text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * PageStudio
 *
 * A web application for managing website content. For use with PHP 5.4+
 *
 * This application is based on the PHP framework,
 * PIP http://gilbitron.github.io/PIP/. PIP has been greatly altered to
 * work for the purposes of our development team. Additional resources
 * and concepts have been borrowed from CodeIgniter,
 * http://codeigniter.com for further improvement and reliability.
 *
 * @package     PageStudio
 * @author      Cosmo Mathieu <cosmo@cimwebdesigns.com>
 */

// ------------------------------------------------------------------------

/**
 * Custom class to extend the default Controller.
 * Provides a means to add functionality without hacking at the framework's core
 */
class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->init();
    }

	public function init()
	{
        /**
         * Check if a user session has already been created
         * else send the user to the login page.
         */
        if( ! Session::get('session_id')) {
            $this->redirect(Config::get('login_controller'));
        }
	}

}

/* End of file main.php */
/* Location: ./application/libraries/MY_Controller.php */


text:
package hu.zstorok.mashforlive.client.echonest.analyze;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * POJO to represent a track in the Echo Nest analysis results.
 *
 * @author cfstras
 * @author zstorok
 */
public class Track {
	@JsonProperty("num_samples")
	private int numSamples;
	private String decoder;
	@JsonProperty("decoder_version")
	private String decoder_version;
	@JsonProperty("offset_seconds")
	private double offsetSeconds;
	@JsonProperty("window_seconds")
	private double windowSeconds;
	@JsonProperty("analysis_sample_rate")
	private int analysisSampleRate;
	@JsonProperty("analysis_channels")
	private int analysisChannels;
	private int mode;
	@JsonProperty("mode_confidence")
	private double modeConfidence;
	private double duration;
	@JsonProperty("end_of_fade_in")
	private double endOfFadeIn;
	private double loudness;
	@JsonProperty("start_of_fade_out")
	private double startOfFadeOut;
	private double tempo;
	@JsonProperty("tempo_confidence")
	private double tempoConfidence;
	private int key;
	@JsonProperty("time_signature")
	private int timeSignature;
	@JsonProperty("key_confidence")
	private double keyConfidence;
	@JsonProperty("time_signature_confidence")
	private double timeSignatureConfidence;
	private String synchstring;
	@JsonProperty("synch_version")
	private String synchVersion;
	private String echoprintstring;
	@JsonProperty("echoprint_version")
	private String echoprintVersion;
	private String codestring;
	@JsonProperty("code_version")
	private String codeVersion;
	private String rhythmstring;
	@JsonProperty("rhythm_version")
	private String rhythmVersion;
	@JsonProperty("sample_md5")
	private String sampleMd5;

	public int getNumSamples() {
		return numSamples;
	}

	public void setNumSamples(int numSamples) {
		this.numSamples = numSamples;
	}

	public String getDecoder() {
		return decoder;
	}

	public void setDecoder(String decoder) {
		this.decoder = decoder;
	}

	public String getDecoder_version() {
		return decoder_version;
	}

	public void setDecoder_version(String decoder_version) {
		this.decoder_version = decoder_version;
	}

	public double getOffsetSeconds() {
		return offsetSeconds;
	}

	public void setOffsetSeconds(double offsetSeconds) {
		this.offsetSeconds = offsetSeconds;
	}

	public double getWindowSeconds() {
		return windowSeconds;
	}

	public void setWindowSeconds(double windowSeconds) {
		this.windowSeconds = windowSeconds;
	}

	public int getAnalysisSampleRate() {
		return analysisSampleRate;
	}

	public void setAnalysisSampleRate(int analysisSampleRate) {
		this.analysisSampleRate = analysisSampleRate;
	}

	public int getAnalysisChannels() {
		return analysisChannels;
	}

	public void setAnalysisChannels(int analysisChannels) {
		this.analysisChannels = analysisChannels;
	}

	public double getDuration() {
		return duration;
	}

	public void setDuration(double duration) {
		this.duration = duration;
	}

	public double getEndOfFadeIn() {
		return endOfFadeIn;
	}

	public void setEndOfFadeIn(double endOfFadeIn) {
		this.endOfFadeIn = endOfFadeIn;
	}

	public double getLoudness() {
		return loudness;
	}

	public void setLoudness(double loudness) {
		this.loudness = loudness;
	}

	public double getStartOfFadeOut() {
		return startOfFadeOut;
	}

	public void setStartOfFadeOut(double startOfFadeOut) {
		this.startOfFadeOut = startOfFadeOut;
	}

	public double getTempo() {
		return tempo;
	}

	public void setTempo(double tempo) {
		this.tempo = tempo;
	}

	public double getTempoConfidence() {
		return tempoConfidence;
	}

	public void setTempoConfidence(double tempoConfidence) {
		this.tempoConfidence = tempoConfidence;
	}

	public int getKey() {
		return key;
	}

	public void setKey(int key) {
		this.key = key;
	}

	public int getTimeSignature() {
		return timeSignature;
	}

	public void setTimeSignature(int timeSignature) {
		this.timeSignature = timeSignature;
	}

	public double getKeyConfidence() {
		return keyConfidence;
	}

	public void setKeyConfidence(double keyConfidence) {
		this.keyConfidence = keyConfidence;
	}

	public double getTimeSignatureConfidence() {
		return timeSignatureConfidence;
	}

	public void setTimeSignatureConfidence(double timeSignatureConfidence) {
		this.timeSignatureConfidence = timeSignatureConfidence;
	}

	public String getRhythmstring() {
		return rhythmstring;
	}

	public void setRhythmstring(String rhythmstring) {
		this.rhythmstring = rhythmstring;
	}

	public String getSampleMd5() {
		return sampleMd5;
	}

	public void setSampleMd5(String sampleMd5) {
		this.sampleMd5 = sampleMd5;
	}

	public String getSynchstring() {
		return synchstring;
	}

	public void setSynchstring(String synchstring) {
		this.synchstring = synchstring;
	}

	public String getCodestring() {
		return codestring;
	}

	public void setCodestring(String codestring) {
		this.codestring = codestring;
	}

	public int getMode() {
		return mode;
	}

	public void setMode(int mode) {
		this.mode = mode;
	}

	public double getModeConfidence() {
		return modeConfidence;
	}

	public void setModeConfidence(double modeConfidence) {
		this.modeConfidence = modeConfidence;
	}

	public String getCodeVersion() {
		return codeVersion;
	}

	public void setCodeVersion(String codeVersion) {
		this.codeVersion = codeVersion;
	}

	public String getSynchVersion() {
		return synchVersion;
	}

	public void setSynchVersion(String synchVersion) {
		this.synchVersion = synchVersion;
	}

	public String getEchoprintstring() {
		return echoprintstring;
	}

	public void setEchoprintstring(String echoprintstring) {
		this.echoprintstring = echoprintstring;
	}

	public String getEchoprintVersion() {
		return echoprintVersion;
	}

	public void setEchoprintVersion(String echoprintVersion) {
		this.echoprintVersion = echoprintVersion;
	}

	public String getRhythmVersion() {
		return rhythmVersion;
	}

	public void setRhythmVersion(String rhythmVersion) {
		this.rhythmVersion = rhythmVersion;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import binascii
import hashlib
import os
import re
import markdown
import json
from functools import wraps
from flask import (Flask, render_template, flash, redirect, url_for, request,
                   abort)
from flask.ext.wtf import Form
from wtforms import (TextField, TextAreaField, PasswordField, BooleanField)
from wtforms.validators import (InputRequired, ValidationError)
from flask.ext.login import (LoginManager, login_required, current_user,
                             login_user, logout_user)
from flask.ext.script import Manager

"""
    Wiki classes
    ~~~~~~~~~~~~
"""

class Processors(object):
    """This class is collection of processors for various content items.
    """
    def __init__(self, content=""):
        """Initialization function.  Runs Processors().pre() on content.

        Args:
            None

        Kwargs:
            content (str): Preprocessed content directly from the file or
            textarea.
        """
        self.content = self.pre(content)

    def wikilink(self, html):
        """Processes Wikilink syntax "[[Link]]" within content body.  This is
        intended to be run after the content has been processed by Markdown.

        Args:
            html (str): Post-processed HTML output from Markdown

        Kwargs:
            None

        Syntax: This accepts Wikilink syntax in the form of [[WikiLink]] or
        [[url/location|LinkName]].  Everything is referenced from the base
        location "/", therefore sub-pages need to use the
        [[page/subpage|Subpage]].
        """
        link = r"((?<!\)\[\[([^<].+?) \s*([|] \s* (.+?) \s*)?]])"
        compLink = re.compile(link, re.X | re.U)
        for i in compLink.findall(html):
            title = [i[-1] if i[-1] else i[1]][0]
            url = self.clean_url(i[1])
            formattedLink = u"{1}".format(url, title, '/')
            html = re.sub(compLink, formattedLink, html, count=1)
        return html

    def clean_url(self, url):
        """Cleans the url and corrects various errors.  Removes multiple spaces
        and all leading and trailing spaces.  Changes spaces to underscores and
        makes all characters lowercase.  Also takes care of Windows style
        folders use.

        Args:
            url (str): URL link

        Kwargs:
            None
        """
        pageStub = re.sub('[ ]{2,}', ' ', url).strip()
        pageStub = pageStub.lower().replace(' ', '_')
        pageStub = pageStub.replace('\\\\', '/').replace('\\', '/')
        return pageStub

    def pre(self, content):
        """Content preprocessor.  This currently does nothing.

        Args:
            content (str): Preprocessed content directly from the file or
            textarea.

        Kwargs:
            None
        """
        return content

    def post(self, html):
        """Content post-processor.

        Args:
            html (str): Post-processed HTML output from Markdown

        Kwargs:
            None
        """
        return self.wikilink(html)

    def out(self):
        """Final content output.  Processes the Markdown, post-processes, and
        Meta data.
        """
        md = markdown.Markdown(['codehilite', 'fenced_code', 'meta'])
        html = md.convert(self.content)
        phtml = self.post(html)
        body = self.content.split('\n\n', 1)[1]
        meta = md.Meta
        return phtml, body, meta

class Page(object):
    def __init__(self, path, url, new=False):
        self.path = path
        self.url = url
        self._meta = {}
        if not new:
            self.load()
            self.render()

    def load(self):
        with open(self.path, 'rU') as f:
            self.content = f.read().decode('utf-8')

    def render(self):
        processed = Processors(self.content)
        self._html, self.body, self._meta = processed.out()

    def save(self, update=True):
        folder = os.path.dirname(self.path)
        if not os.path.exists(folder):
            os.makedirs(folder)
        with open(self.path, 'w') as f:
            for key, value in self._meta.items():
                line = u'%s: %s\n' % (key, value)
                f.write(line.encode('utf-8'))
            f.write('\n'.encode('utf-8'))
            f.write(self.body.replace('\r\n', '\n').encode('utf-8'))
        if update:
            self.load()
            self.render()

    @property
    def meta(self):
        return self._meta

    def __getitem__(self, name):
        item = self._meta[name]
        if len(item) == 1:
            return item[0]
        print item
        return item

    def __setitem__(self, name, value):
        self._meta[name] = value

    @property
    def html(self):
        return self._html

    def __html__(self):
        return self.html

    @property
    def title(self):
        return self['title']

    @title.setter
    def title(self, value):
        self['title'] = value

    @property
    def tags(self):
        return self['tags']

    @tags.setter
    def tags(self, value):
        self['tags'] = value

class Wiki(object):
    def __init__(self, root):
        self.root = root
        self.lock_file = os.path.join(self.root, 'locked.json')

        try:
            if not os.path.exists(self.lock_file):
                self.locked = {}
            with open(self.file) as f:
                self.locked = json.loads(f.read())
        except:
            self.locked = {}

    def write_locks(self):
        with open(self.lock_file, 'w') as f:
            f.write(json.dumps(self.locked, indent=2))

    def is_locked(self, url):
        path = self.path(url)
        return path in self.locked

    def can_edit(self, url, user):
        path = self.path(url)

        if self.is_locked(url):
            for role in self.locked[path]:
                if role in user.roles():
                    return True

            return False

        return True

    def add_lock(self, url, role):
        path = self.path(url)

        if path in self.locked:
            if role in self.locked[path]:
                return True

            self.locked[path].append(role)
        else:
            self.locked[path] = [role]

        return self.write_locks()

    def del_lock(self, url, role):
        path = self.path(url)

        if path in self.locked:
            if role in self.locked[path]:
                self.locked[path] = filter(
                        lambda a: a != role,
                        self.locked[path])
                if len(self.locked[path]) == 0:
                    del(self.locked[path])
                self.write_locks()
                return True

            return True

        return False

    def path(self, url):
        return os.path.join(self.root, url + '.md')

    def exists(self, url):
        path = self.path(url)
        return os.path.exists(path)

    def get(self, url):
        path = os.path.join(self.root, url + '.md')
        if self.exists(url):
            return Page(path, url)
        return None

    def get_or_404(self, url):
        page = self.get(url)
        if page:
            return page
        abort(404)

    def get_bare(self, url):
        path = self.path(url)
        if self.exists(url):
            return False
        return Page(path, url, new=True)

    def move(self, url, newurl):
        os.rename(
            os.path.join(self.root, url) + '.md',
            os.path.join(self.root, newurl) + '.md'
        )

    def delete(self, url):
        path = self.path(url)
        if not self.exists(url):
            return False
        print path
        os.remove(path)
        return True

    def index(self, attr=None):
        def _pathjoin(t):
            path = ""
            for elem in t:
                path = os.path.join(path, elem)

            return path

        def _walk(directory, path_prefix=()):
            for name in os.listdir(directory):
                fullname = os.path.join(directory, name)
                if os.path.isdir(fullname):
                    _walk(fullname, path_prefix + (name,))
                elif name.endswith('.md'):
                    if not path_prefix:
                        url = name[:-3]
                    else:
                        url = os.path.join(_pathjoin(path_prefix), name[:-3])
                    if attr:
                        pages[getattr(page, attr)] = page
                    else:
                        pages.append(Page(fullname, url.replace('\\', '/')))

        if attr:
            pages = {}
        else:
            pages = []
        _walk(self.root)
        if not attr:
            return sorted(pages, key=lambda x: x.title.lower())
        return pages

    def get_by_title(self, title):
        pages = self.index(attr='title')
        return pages.get(title)

    def get_tags(self):
        pages = self.index()
        tags = {}
        for page in pages:
            pagetags = page.tags.split(',')
            for tag in pagetags:
                tag = tag.strip()
                if tag == '':
                    continue
                elif tags.get(tag):
                    tags[tag].append(page)
                else:
                    tags[tag] = [page]
        return tags

    def index_by_tag(self, tag):
        pages = self.index()
        tagged = []
        for page in pages:
            if tag in page.tags:
                tagged.append(page)
        return sorted(tagged, key=lambda x: x.title.lower())

    def search(self, term, attrs=['title', 'tags', 'body']):
        pages = self.index()
        regex = re.compile(term)
        matched = []
        for page in pages:
            for attr in attrs:
                if regex.search(getattr(page, attr)):
                    matched.append(page)
                    break
        return matched

"""
    User classes & helpers
    ~~~~~~~~~~~~~~~~~~~~~~
"""

class UserManager(object):
    """A very simple user Manager, that saves it's data as json."""
    def __init__(self, path):
        self.file = os.path.join(path, 'users.json')

    def read(self):
        if not os.path.exists(self.file):
            return {}
        with open(self.file) as f:
            data = json.loads(f.read())
        return data

    def write(self, data):
        with open(self.file, 'w') as f:
            f.write(json.dumps(data, indent=2))

    def add_user(self, name, password,
                 active=True, roles=[], authentication_method=None):
        users = self.read()
        if users.get(name):
            return False
        if authentication_method is None:
            authentication_method = get_default_authentication_method()
        new_user = {
            'active': active,
            'roles': roles,
            'authentication_method': authentication_method,
            'authenticated': False
        }
        # Currently we have only two authentication_methods: cleartext and
        # hash. If we get more authentication_methods, we will need to go to a
        # strategy object pattern that operates on User.data.
        if authentication_method == 'hash':
            new_user['hash'] = make_salted_hash(password)
        elif authentication_method == 'cleartext':
            new_user['password'] = password
        else:
            raise NotImplementedError(authentication_method)
        users[name] = new_user
        self.write(users)
        userdata = users.get(name)
        return User(self, name, userdata)

    def get_user(self, name):
        users = self.read()
        userdata = users.get(name)
        if not userdata:
            return None
        return User(self, name, userdata)

    def delete_user(self, name):
        users = self.read()
        if not users.pop(name, False):
            return False
        self.write(users)
        return True

    def update(self, name, userdata):
        data = self.read()
        data[name].update(userdata)
        self.write(data)

class User(object):
    def __init__(self, manager, name, data):
        self.manager = manager
        self.name = name
        self.data = data

    def get(self, option):
        return self.data.get(option)

    def set(self, option, value):
        self.data[option] = value
        self.save()

    def save(self):
        self.manager.update(self.name, self.data)

    def is_authenticated(self):
        return self.data.get('authenticated')

    def is_active(self):
        return self.data.get('active')

    def is_anonymous(self):
        return False

    def is_admin(self):
        return 'admin' in self.roles()

    def get_id(self):
        return self.name

    def roles(self):
        return self.data.get('roles')

    def add_role(self, role):
        self.data['roles'].append(role)
        self.save()

    def del_role(self, role):
        roles = self.data.get('roles')
        filtered_roles = filter(
                lambda a: a != role,
                roles)

        self.data['roles'] = filtered_roles
        self.save()

    def check_password(self, password):
        """Return True, return False, or raise NotImplementedError if the
        authentication_method is missing or unknown."""
        authentication_method = self.data.get('authentication_method', None)
        if authentication_method is None:
            authentication_method = get_default_authentication_method()
        # See comment in UserManager.add_user about authentication_method.
        if authentication_method == 'hash':
            result = check_hashed_password(password, self.get('hash'))
        elif authentication_method == 'cleartext':
            result = (self.get('password') == password)
        else:
            raise NotImplementedError(authentication_method)
        return result

def get_default_authentication_method():
    return app.config.get('DEFAULT_AUTHENTICATION_METHOD', 'cleartext')

def get_protected_users():
    return app.config.get('PROTECTED_USERS', [])

def get_lock_role():
    return app.config.get('LOCK_ROLE', 'editor')

def make_salted_hash(password, salt=None):
    if not salt:
        salt = os.urandom(64)
    d = hashlib.sha512()
    d.update(salt[:32])
    d.update(password)
    d.update(salt[32:])
    return binascii.hexlify(salt) + d.hexdigest()

def check_hashed_password(password, salted_hash):
    salt = binascii.unhexlify(salted_hash[:128])
    return make_salted_hash(password, salt) == salted_hash

def protect(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if app.config.get('PRIVATE') and not current_user.is_authenticated():
            return loginmanager.unauthorized()
        return f(*args, **kwargs)
    return wrapper

"""
    Forms
    ~~~~~
"""

class URLForm(Form):
    url = TextField('', [InputRequired()])

    def validate_url(form, field):
        if wiki.exists(field.data):
            raise ValidationError('The URL "%s" exists already.' % field.data)

    def clean_url(self, url):
        return Processors().clean_url(url)

class SearchForm(Form):
    term = TextField('', [InputRequired()])

class EditorForm(Form):
    title = TextField('', [InputRequired()])
    body = TextAreaField('', [InputRequired()])
    tags = TextField('')

class LoginForm(Form):
    name = TextField('', [InputRequired()])
    password = PasswordField('', [InputRequired()])

    def validate_name(form, field):
        user = users.get_user(field.data)
        if not user:
            raise ValidationError('This username does not exist.')

    def validate_password(form, field):
        user = users.get_user(form.name.data)
        if not user:
            return
        if not user.check_password(field.data):
            raise ValidationError('Username and password do not match.')

class UserForm(Form):
    name = TextField('', [InputRequired()])
    password = PasswordField('', [InputRequired()])
    is_admin = BooleanField(False, [])

    def validate_name(form, field):
        user = users.get_user(field.data)
        if not user:
            return True

    def validate_password(form, field):
        return field.data

"""
    Application Setup
    ~~~~~~~~~
"""

app = Flask(__name__)
app.config['CONTENT_DIR'] = 'content'
app.config['TITLE'] = 'wiki'
try:
    app.config.from_pyfile(
        os.path.join(app.config.get('CONTENT_DIR'), 'config.py')
    )
except IOError:
    print ("Startup Failure: You need to place a "
           "config.py in your content directory.")

manager = Manager(app)

loginmanager = LoginManager()
loginmanager.init_app(app)
loginmanager.login_view = 'user_login'

wiki = Wiki(app.config.get('CONTENT_DIR'))

users = UserManager(app.config.get('CONTENT_DIR'))

@loginmanager.user_loader
def load_user(name):
    return users.get_user(name)

"""
    Routes
    ~~~~~~
"""

@app.route('/')
@protect
def home():
    page = wiki.get('home')
    if page:
        return display('home')
    return render_template('home.html')

@app.route('/index/')
@protect
def index():
    pages = wiki.index()
    return render_template('index.html', pages=pages)

@app.route('/<path:url>/')
@protect
def display(url):
    page = wiki.get_or_404(url)
    locked = wiki.is_locked(url)
    return render_template('page.html', page=page, locked=locked)

@app.route('/<path:url>/lock/')
@protect
def lock(url):
    page = wiki.get_or_404(url)
    lock_role = get_lock_role()

    if lock_role in current_user.roles():
        wiki.add_lock(url, lock_role)
        flash('Lock added successfully', 'success')
    else:
        flash('You do not have rights to lock a page.', 'error')

    return redirect(url_for('display', url=url))

@app.route('/<path:url>/unlock/')
@protect
def unlock(url):
    page = wiki.get_or_404(url)
    lock_role = get_lock_role()

    if lock_role in current_user.roles():
        wiki.del_lock(url, lock_role)
        flash('Lock removed successfully', 'success')
    else:
        flash('You do not have rights to unlock a page.', 'error')

    return redirect(url_for('display', url=url))

@app.route('/create/', methods=['GET', 'POST'])
@protect
def create():
    form = URLForm()
    if form.validate_on_submit():
        return redirect(url_for('edit', url=form.clean_url(form.url.data)))
    return render_template('create.html', form=form)

@app.route('/edit/<path:url>/', methods=['GET', 'POST'])
@protect
def edit(url):
    if wiki.is_locked(url):
        if not wiki.can_edit(url, user):
            flash('"%s" is locked.' % page.title, 'warn')
            return redirect(url_for('display', url=url))
    page = wiki.get(url)
    form = EditorForm(obj=page)
    if form.validate_on_submit():
        if not page:
            page = wiki.get_bare(url)
        form.populate_obj(page)
        page.save()
        flash('"%s" was saved.' % page.title, 'success')
        return redirect(url_for('display', url=url))
    return render_template('editor.html', form=form, page=page)

@app.route('/preview/', methods=['POST'])
@protect
def preview():
    a = request.form
    data = {}
    processed = Processors(a['body'])
    data['html'], data['body'], data['meta'] = processed.out()
    return data['html']

@app.route('/move/<path:url>/', methods=['GET', 'POST'])
@protect
def move(url):
    page = wiki.get_or_404(url)
    form = URLForm(obj=page)
    if form.validate_on_submit():
        newurl = form.url.data
        wiki.move(url, newurl)
        return redirect(url_for('.display', url=newurl))
    return render_template('move.html', form=form, page=page)

@app.route('/delete/<path:url>/')
@protect
def delete(url):
    page = wiki.get_or_404(url)
    wiki.delete(url)
    flash('Page "%s" was deleted.' % page.title, 'success')
    return redirect(url_for('home'))

@app.route('/tags/')
@protect
def tags():
    tags = wiki.get_tags()
    return render_template('tags.html', tags=tags)

@app.route('/tag/<string:name>/')
@protect
def tag(name):
    tagged = wiki.index_by_tag(name)
    return render_template('tag.html', pages=tagged, tag=name)

@app.route('/search/', methods=['GET', 'POST'])
@protect
def search():
    form = SearchForm()
    if form.validate_on_submit():
        results = wiki.search(form.term.data)
        return render_template('search.html', form=form,
                               results=results, search=form.term.data)
    return render_template('search.html', form=form, search=None)

@app.route('/user/login/', methods=['GET', 'POST'])
def user_login():
    form = LoginForm()
    if form.validate_on_submit():
        user = users.get_user(form.name.data)
        login_user(user)
        user.set('authenticated', True)
        flash('Login successful.', 'success')
        return redirect(request.args.get("next") or url_for('index'))
    return render_template('login.html', form=form)

@app.route('/user/logout/')
@login_required
def user_logout():
    current_user.set('authenticated', False)
    logout_user()
    flash('Logout successful.', 'success')
    return redirect(url_for('index'))

@app.route('/user/')
def user_index():
    if current_user.is_anonymous() or 'admin' not in current_user.roles():
        abort(404)

    data = users.read().keys()
    allusers = []

    for user in data:
        allusers.append(users.get_user(user))

    return render_template('admin/user_index.html',
            users=allusers,
            protected_users=get_protected_users())

@app.route('/user/create/', methods=['GET','POST'])
def user_create():
    form = UserForm()

    if form.validate_on_submit():
        roles = []
        if form.is_admin.data:
            roles.append('admin')
        user = users.add_user(
                name = form.name.data,
                password = form.password.data,
                active = True,
                roles = roles,
                authentication_method = 'hash'
                )
        flash('User %s created.' % (user.name,), 'success')
        return redirect(url_for('user_index'))

    return render_template('admin/user_create.html', form=form)

@app.route('/user/<user_id>/')
def user_admin(user_id):
    pass

@app.route('/user/delete/<user_id>/' )
def user_delete(user_id):
    if users.delete_user(user_id):
        flash('User %s deleted.' % (user_id,), 'warn')

    return redirect(url_for('user_index'))

if __name__ == '__main__':
    manager.run()


text:
[Kong](https://getkong.org) is a scalable, open source API Layer (also known as an API Gateway, or API Middleware). Kong runs in front of any RESTful API and is extended through Plugins, which provide extra functionality and services beyond the core platform. DC/OS allows you to quickly configure and manage Kong.

- Estimated time for completion: 5 minutes
- Target audience: Anyone interested in running an API gateway server
- Scope: Learn how to install Kong on DC/OS

## Prerequisites

- A running DC/OS 1.9 cluster with 1.3 CPUs and 1 GB of RAM available.
- Marathon-LB installed
- Postgresql installed

## Install Postgresql

First install a postgresql database in your DC/OS cluster using the existing Universe package. Configure the package by creating a file called `options.json` with following:

```json
{
  "service": {
    "name": "postgresql"
  },
  "postgresql": {
    "cpus": 0.3,
    "mem": 512
  },
  "database": {
    "username": "kong",
    "password": "kong",
    "dbname": "kong"
  },
  "storage": {
    "host_volume": "/tmp",
    "pgdata": "pgdata",
    "persistence": {
      "enable": true,
      "volume_size": 512,
      "external": {
        "enable": false,
        "volume_name": "postgresql",
        "provider": "dvdi",
        "driver": "rexray"
      }
    }
  },
  "networking": {
    "port": 5432,
    "host_mode": false,
    "external_access": {
      "enable": false,
      "external_access_port": 15432
    }
  }
}
```

The above `options.json` file configures Postgresql as follows:

- `username`: This parameter configures the username for the kong database.
- `password`: This parameter configures the password for the kong database.
- `dbname`: This parameter configures the name of the kong database.
- `persistence`: This parameter enables persistent volumes for postgresql.

Install postgresql using this `options.json` file:

```bash
$ dcos package install postgresql --options=options.json
```

To verify that our postgresql instance is up and running, we can use `dcos task` command:

```bash
$ dcos task
NAME         HOST        USER  STATE  ID
marathon-lb  10.0.6.130  root    R    marathon-lb.104e0ebe-03be-11e7-b790-627a33830456
postgresql   10.0.0.71   root    R    postgresql.0f2867a0-03cb-11e7-b790-627a33830456
```
## Install Kong
Next, install Kong. If you have installed postgresql with a different username, password, dbname, or id, customize the kong installation accordingly.
```bash
$ dcos package install kong
This DC/OS Service is currently EXPERIMENTAL. There may be bugs, incomplete features, incorrect documentation, or other discrepancies. Prerequisites for this service include postgres and marathon-lb. See https://github.com/dcos/examples/tree/master/1.8/kong for more details.
Continue installing? [yes/no] yes
Installing Marathon app for package [kong] version [0.9.9]
Kong has been installed.
```
To verify that our kong instance is up and running, we can use `dcos task` command:

```bash
$ dcos task
NAME         HOST        USER  STATE  ID
kong         10.0.0.71   root    R    kong.c2cd2cc9-03cb-11e7-b790-627a33830456
marathon-lb  10.0.6.130  root    R    marathon-lb.104e0ebe-03be-11e7-b790-627a33830456
postgresql   10.0.0.71   root    R    postgresql.0f2867a0-03cb-11e7-b790-627a33830456
```

Kong in the DC/OS UI

![Kong on DC/OS](img/kong-dcos.png)

Now that Kong is installed, curl the marathon-lb endpoint to validate that it is up and running `curl http://<public-agent-ip>:10002` You should see output similar to this:

![Kong API endpoint](img/kong-api.png)

## Uninstall Kong

To uninstall Kong, run following command:

```bash
dcos package uninstall kong
```


text:
package uk.org.whoami.easyban.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import uk.org.whoami.easyban.ConsoleLogger;
import uk.org.whoami.easyban.datasource.DataSource;
import uk.org.whoami.easyban.settings.Settings;

public class WhitelistCommand extends EasyBanCommand {

    private DataSource database;

    public WhitelistCommand(DataSource database) {
        this.database = database;
    }

    @Override
    protected void execute(CommandSender cs, Command cmnd, String cmd, String[] args) {
        if (args.length == 0) {
            return;
        }
        database.whitelist(args[0]);

        Settings settings = Settings.getInstance();
        if(settings.isWhitelistPublic()) {
            cs.getServer().broadcastMessage(args[0] + m._(" has been whitelisted"));
        }
        ConsoleLogger.info(admin + " whitelisted " + args[0]);
    }
}


text:
<?php

namespace Pancoast\Precept\ObjectManagerWrapper\Factory\Exception;

/**
 * @author John Pancoast <johnpancoaster@gmail.com>
 */
class InvalidEntityException extends \LogicException
{
}


text:
import { FragmentOpcodeCompiler } from './fragment_opcode';
import { FragmentCompiler } from './fragment';
import { HydrationOpcodeCompiler } from './hydration_opcode';
import { HydrationCompiler } from './hydration';
import TemplateVisitor from "./template_visitor";
import { processOpcodes } from "./utils";
import { string, repeat } from "./quoting";

export function TemplateCompiler() {
  this.fragmentOpcodeCompiler = new FragmentOpcodeCompiler();
  this.fragmentCompiler = new FragmentCompiler();
  this.hydrationOpcodeCompiler = new HydrationOpcodeCompiler();
  this.hydrationCompiler = new HydrationCompiler();
  this.templates = [];
  this.childTemplates = [];
}

TemplateCompiler.prototype.compile = function(ast) {
  var templateVisitor = new TemplateVisitor();
  templateVisitor.visit(ast);

  processOpcodes(this, templateVisitor.actions);

  return this.templates.pop();
};

TemplateCompiler.prototype.startProgram = function(program, childTemplateCount, blankChildTextNodes) {
  this.fragmentOpcodeCompiler.startProgram(program, childTemplateCount, blankChildTextNodes);
  this.hydrationOpcodeCompiler.startProgram(program, childTemplateCount, blankChildTextNodes);

  this.childTemplates.length = 0;
  while(childTemplateCount--) {
    this.childTemplates.push(this.templates.pop());
  }
};

TemplateCompiler.prototype.endProgram = function(program, programDepth) {
  this.fragmentOpcodeCompiler.endProgram(program);
  this.hydrationOpcodeCompiler.endProgram(program);

  var indent = repeat("  ", programDepth);
  var options = {
    indent: indent + "  "
  };

  // function build(dom) { return fragment; }
  var fragmentProgram = this.fragmentCompiler.compile(
    this.fragmentOpcodeCompiler.opcodes,
    options
  );

  // function hydrate(fragment) { return mustaches; }
  var hydrationProgram = this.hydrationCompiler.compile(
    this.hydrationOpcodeCompiler.opcodes,
    options
  );

  var childTemplateVars = "";
  for (var i=0, l=this.childTemplates.length; i<l; i++) {
    childTemplateVars += indent+'  var child' + i + ' = ' + this.childTemplates[i] + '\n';
  }

  var template =
    '(function() {\n' +
    childTemplateVars +
    fragmentProgram +
    indent+'  var cachedFragment;\n' +
    indent+'  return function template(context, env, contextualElement) {\n' +
    indent+'    var dom = env.dom, hooks = env.hooks;\n' +
    indent+'    dom.detectNamespace(contextualElement);\n' +
    indent+'    if (cachedFragment === undefined) {\n' +
    indent+'      cachedFragment = build(dom);\n' +
    indent+'    }\n' +
    indent+'    var fragment = dom.cloneNode(cachedFragment, true);\n' +
    hydrationProgram +
    indent+'    return fragment;\n' +
    indent+'  };\n' +
    indent+'}());';

  this.templates.push(template);
};

TemplateCompiler.prototype.openElement = function(element, i, l, r, c, b) {
  this.fragmentOpcodeCompiler.openElement(element, i, l, r, c, b);
  this.hydrationOpcodeCompiler.openElement(element, i, l, r, c, b);
};

TemplateCompiler.prototype.closeElement = function(element, i, l, r) {
  this.fragmentOpcodeCompiler.closeElement(element, i, l, r);
  this.hydrationOpcodeCompiler.closeElement(element, i, l, r);
};

TemplateCompiler.prototype.component = function(component, i, l) {
  this.fragmentOpcodeCompiler.component(component, i, l);
  this.hydrationOpcodeCompiler.component(component, i, l);
};

TemplateCompiler.prototype.block = function(block, i, l) {
  this.fragmentOpcodeCompiler.block(block, i, l);
  this.hydrationOpcodeCompiler.block(block, i, l);
};

TemplateCompiler.prototype.text = function(string, i, l, r) {
  this.fragmentOpcodeCompiler.text(string, i, l, r);
  this.hydrationOpcodeCompiler.text(string, i, l, r);
};

TemplateCompiler.prototype.mustache = function (mustache, i, l) {
  this.fragmentOpcodeCompiler.mustache(mustache, i, l);
  this.hydrationOpcodeCompiler.mustache(mustache, i, l);
};

TemplateCompiler.prototype.setNamespace = function(namespace) {
  this.fragmentOpcodeCompiler.setNamespace(namespace);
};


text:
from collections import OrderedDict
import itertools
import urllib.parse

from directory_constants.sectors import CONFLATED

from django import template
from django.core.urlresolvers import reverse

register = template.Library()

@register.simple_tag
def search_url(sector_value=None, term=None):
    if isinstance(sector_value, str):
        sector_value = [sector_value]

    params = OrderedDict()

    if sector_value:
        industries = [CONFLATED.get(item, {item}) for item in sector_value]
        params['industries'] = list(itertools.chain(*industries))
    if term:
        params['term'] = term
    querystring = urllib.parse.urlencode(params, doseq=True)
    return reverse('find-a-supplier:search') + '?' + querystring


text:
from flask import Flask, request, redirect, render_template, abort
from urllib.parse import urlparse
import links, json

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        shortlink = make_shortlink(request.form['link'])
        #print('SHORTLINK: %s' % shortlink)
        if shortlink:
            return render_template('/index.html', new_link=shortlink)
        else:
            return render_template('/index.html', error='URL must be valid!')
    else:
        return render_template('/index.html')

@app.route('/<link_id>')
def link_redirect(link_id):
    redir_link = links.click_link(link_id)
    #print('redir: %s' % redir_link)
    if redir_link:
        return redirect(redir_link['uri'])
    else:
        return abort(404), 404

@app.route('/stats', methods=['GET', 'POST'])
def stats():
    if request.method == 'POST':
        link = request.form['link']
        if 'https://fastl.ink' in link:
            link_id = link.split('/')[-1]
            if len(link_id) == 6:
                link_obj = links.find_link(link_id)
                return render_template('/stats.html', stats_link=link_obj)
            else:
                return render_template('/stats.html', error="Looks like that isn't a valid fastlink!")
        else:
            return render_template('/stats.html', error="Looks like that isn't a valid fastlink!")
    elif request.method == 'GET':
        return render_template('/stats.html')

@app.route('/stats/<link_id>')
def stats_by_id(link_id):
    link_obj = links.find_link(link_id)
    return render_template('/stats.html', stats_link=link_obj)

@app.route('/api/new', methods=['POST'])
def api_create():
    req_body = request.get_json(force=True)
    try:
        req_url = req_body['url']
    except KeyError:
        return abort(400), 400
    return ( 'https://fastl.ink/' + make_shortlink(req_url) )

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

def make_shortlink(link_str):
    if verify_url(link_str):
        result = links.new_link(link_str)
        return result
    else:
        return None

def verify_url(x):
    print('checking %s...' % x)
    result = urlparse(x)
    if result.scheme == '':
        print('  invalid URI %s!' % str(result))
        return False
    elif result.scheme in ['http', 'https']:
        if result.netloc == '':
            print('  invalid http/s: %s!' % str(result))
            return False
        else:
            print('  valid URI!', [result.scheme, result.netloc, result.path])
            return True
    else:
        if result.path == '':
            print('  invalid URI %s!' % str(result))
            return False
        else:
            print('  valid URI!', [result.scheme, result.netloc, result.path])
            return True

if __name__ == '__main__':
    app.run()


text:
package ca.gc.ip346.classification.model;

public class PseudoDouble {
	private Double value; /* = 0.0; */
	private Boolean modified = false;

	public PseudoDouble(Double value) {
		this.value = value;
	}

	public PseudoDouble() {
	}

	/**
	 * @return the value
	 */
	public Double getValue() {
		return value;
	}

	/**
	 * @param value the value to set
	 */
	public void setValue(Double value) {
		this.value = value;
	}

	/**
	 * @return the modified
	 */
	public Boolean getModified() {
		return modified;
	}

	/**
	 * @param modified the modified to set
	 */
	public void setModified(Boolean modified) {
		this.modified = modified;
	}
}


text:
@interface LPDCollectionSectionViewModel : NSObject <LPDCollectionSectionViewModelProtocol>

+ (instancetype)section;

@end

@interface LPDCollectionSectionWithHeadTitleViewModel : LPDCollectionSectionViewModel

@end

@interface LPDCollectionSectionWithFootTitleViewModel : LPDCollectionSectionViewModel

@end

@interface LPDCollectionSectionWithHeadFootTitleViewModel : LPDCollectionSectionViewModel

@end

@interface LPDCollectionSectionWithHeadViewViewModel : LPDCollectionSectionViewModel

@end

@interface LPDCollectionSectionWithFootViewViewModel : LPDCollectionSectionViewModel

@end

@interface LPDCollectionSectionWithHeadFootViewViewModel : LPDCollectionSectionViewModel

@end


text:
package array;

import java.util.Arrays;

public class UniqueProblem {
  // element uniqueness problem
  // O(N^2) running time
  private static boolean my_isUnique(int[] a, int checked, int from) {
    if (a[checked] == a[from]) {
      return false;
    }
    if (from - 1 != checked) {
      return my_isUnique(a, checked, from - 1);
    }
    if (checked + 1 <= a.length - 2) {
      return my_isUnique(a, checked + 1, a.length - 1);
    }
    return true;
  }

  public static boolean isUnique(int[] a) {
    if (a.length == 1) {
      return true;
    }
    return my_isUnique(a, 0, a.length - 1);
  }

  // element uniqueness problem
  // O(NlogN) running time
  public static boolean isUnique2(int[] data) {
    int n = data.length;
    int[] clone = Arrays.copyOf(data, n);
    Arrays.sort(clone);
    for (int j = 0; j < n - 1; j++) {
      if (clone[j] == clone[j + 1]) {
        return false;
      }
    }
    return true;
  }
}


text:
@interface ForthViewController : ChildBaseViewController

@end


text:
0.9.2
=====

I've received a bunch of great bug reports and feedback on the 0.9 release and have resolved lots of
minor issues this week as a result. So please try out the new 0.9.2 release on the downloads page
and keep the bug reports coming!

\- ChrisMD


text:
const webpack = require('webpack')
const path = require('path')
const MinifyPlugin = require('babel-minify-webpack-plugin')

let libraryName = 'anchor-link'
let outputFile

if (process.env.NODE_ENV === 'production') {
  outputFile = libraryName + '.min.js'
} else {
  outputFile = libraryName + '.js'
}

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: outputFile,
    library: libraryName,
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader'
      }
    ]
  },
  externals: {
    react: 'react'
  },
  plugins:[
    new webpack.DefinePlugin({
     'process.env': {
       'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
     }
   })
  ]
}

if (process.env.NODE_ENV === 'production') {
  config.plugins.push(new MinifyPlugin())
}

module.exports = config


text:
'''
add.py

Takes a list of input ingredient names. Imports each if not already present.
If already present, duplicates and rotates the ingredient.

Thomas Storey
2016

'''

import sys
import argparse
import bpy
import numpy as np
import os
import bmesh
from math import *
from mathutils import *
import random

def getObjectsBySubstring(objname):
    copies = []
    for obj in bpy.data.objects:
        if(objname in obj.name):
            copies.append(obj)
    return copies

def deleteObject(obj):
    bpy.context.scene.objects.unlink(obj)
    obj.user_clear()
    bpy.data.objects.remove(obj)

def getObject(objdir, objname):
    if (bpy.data.objects.get(objname) == None):
        objpath = os.path.join(objdir, objname+".obj")
        bpy.ops.import_scene.obj(filepath=objpath,
                         axis_forward='Y',axis_up='Z')
    return bpy.data.objects[objname]

def setOriginToGeometry(scn, obj):
    obj.select = True;
    scn.objects.active = obj
    bpy.ops.object.origin_set(type="ORIGIN_GEOMETRY")
    obj.select = False;

def joinObjects(scn, objs, name):
    bpy.ops.object.select_all(action='DESELECT')
    for obj in objs:
        obj.select = True
    activeobj = objs[0]
    scn.objects.active = activeobj
    bpy.ops.object.join()
    activeobj.name = name
    activeobj.data.name = name
    return activeobj

def bakeObject(scn, obj):
    bpy.ops.object.select_all(action='DESELECT')
    obj.select = True
    scn.objects.active = obj
    mat = obj.material_slots[0].material

    bpy.ops.texture.new()
    tex = bpy.data.textures["Texture"]
    tex.name = "fry"
    tex_slot = mat.texture_slots.add()
    tex_slot.texture = tex
    bpy.ops.image.new()
    img = bpy.data.images["Untitled"]
    img.name = "fry_img"
    tex.image = img
    img.generated_color = (0.9, 0.4, 0.4, 1.00)
    tex_slot.blend_type = 'SOFT_LIGHT'

    bpy.ops.object.modifier_add(type="DISPLACE")
    mod = obj.modifiers["Displace"]
    mod.direction = "RGB_TO_XYZ"
    mod.strength = 0.1
    batterTex = bpy.data.textures.new(name="batter",type="CLOUDS")
    batterTex.type_recast()
    mod.texture = batterTex
    batterTex.cloud_type = "COLOR"
    batterTex.noise_scale = 0.1 + random.random()*0.2
    batterTex.noise_depth = 2
    batterTex.intensity = 1.0
    batterTex.contrast = 0.4
    batterTex.saturation = 1.4
    # bpy.ops.texture.new()
    # baked_tex = bpy.data.textures["Texture"]
    # baked_tex.name = "baked"
    # baked_tex_slot = mat.texture_slots.create(2)
    # baked_tex_slot.texture = baked_tex
    # bpy.ops.image.new()
    # baked_img = bpy.data.images["Untitled"]
    # baked_img.name = "baked_img"
    # mat.active_texture_index = 2
    # mat.active_texture = baked_tex
    #
    # bpy.ops.object.mode_set(mode="EDIT")
    # bpy.data.scenes["Scene"].render.bake_type = "TEXTURE"
    # for area in bpy.context.screen.areas :
    #     if area.type == 'IMAGE_EDITOR' :
    #         area.spaces.active.image = baked_img
    # bpy.ops.object.bake_image()
    # mat.texture_slots[0].texture.image = baked_img

def removeMod(scn, obj):
    bpy.ops.object.select_all(action='DESELECT')
    obj.select = True
    scn.objects.active = obj
    bpy.ops.object.convert(target='MESH')
    obj.select = False

def execute(inputs, output):
    ctx = bpy.context
    scn = ctx.scene
    cwd = os.getcwd()
    objdir = os.path.join(cwd, 'objs')
    for objname in inputs:
        # import file, or get it if it's already here
        obj = getObject(objdir, objname)
        obj.location = Vector([0,0,0])
        bakeObject(scn, obj)
        removeMod(scn, obj)

    # save out .blend
    if not output == None:
        bpy.ops.wm.save_as_mainfile(filepath=output,
        check_existing=False,relative_remap=True)
    else:
        bpy.ops.wm.save_mainfile(check_existing=False,relative_remap=True)

def main():
    argv = sys.argv
    if "--" not in argv:
        argv = []
    else:
        argv = argv[argv.index("--") + 1:]
    usage_text =\
    "Usage: blender -b [.blend file] --python " + __file__ + " -- [options]"
    parser = argparse.ArgumentParser(description=usage_text)
    parser.add_argument("-i", "--input", dest="input", type=str, required=True,
    help="Comma delimited list of .objs to import. Exclude the file extension.")
    parser.add_argument("-o", "--output", dest="output", type=str, required=False,
    help="Name of blend file to save to, if not the same as the one being opened.")
    args = parser.parse_args(argv)
    output = ""
    if not argv:
        parser.print_help()
        return
    if not args.input:
        print("input argument not given. aborting.")
        parser.print_help()
        return
    if not args.output:
        output = None
    else:
        output = args.output+".blend"

    inputs = args.input.split(",")
    execute(inputs, output)
    print("battered " + ", ".join(inputs))

if __name__ == "__main__":
    main()


text:
namespace llvm {
class StringRef;

namespace PPC {
  // -m directive values.
  enum {
    DIR_NONE,
    DIR_32,
    DIR_440,
    DIR_601,
    DIR_602,
    DIR_603,
    DIR_7400,
    DIR_750,
    DIR_970,
    DIR_A2,
    DIR_E500,
    DIR_E500mc,
    DIR_E5500,
    DIR_PWR3,
    DIR_PWR4,
    DIR_PWR5,
    DIR_PWR5X,
    DIR_PWR6,
    DIR_PWR6X,
    DIR_PWR7,
    DIR_PWR8,
    DIR_PWR9,
    DIR_PWR_FUTURE,
    DIR_64
  };
}

class GlobalValue;
class TargetMachine;

class PPCSubtarget : public PPCGenSubtargetInfo {
public:
  enum POPCNTDKind {
    POPCNTD_Unavailable,
    POPCNTD_Slow,
    POPCNTD_Fast
  };

protected:
  /// TargetTriple - What processor and OS we're targeting.
  Triple TargetTriple;

  /// stackAlignment - The minimum alignment known to hold of the stack frame on
  /// entry to the function and which must be maintained by every function.
  Align StackAlignment;

  /// Selected instruction itineraries (one entry per itinerary class.)
  InstrItineraryData InstrItins;

  /// Which cpu directive was used.
  unsigned CPUDirective;

  /// Used by the ISel to turn in optimizations for POWER4-derived architectures
  bool HasMFOCRF;
  bool Has64BitSupport;
  bool Use64BitRegs;
  bool UseCRBits;
  bool HasHardFloat;
  bool IsPPC64;
  bool HasAltivec;
  bool HasFPU;
  bool HasSPE;
  bool HasQPX;
  bool HasVSX;
  bool NeedsTwoConstNR;
  bool HasP8Vector;
  bool HasP8Altivec;
  bool HasP8Crypto;
  bool HasP9Vector;
  bool HasP9Altivec;
  bool HasFCPSGN;
  bool HasFSQRT;
  bool HasFRE, HasFRES, HasFRSQRTE, HasFRSQRTES;
  bool HasRecipPrec;
  bool HasSTFIWX;
  bool HasLFIWAX;
  bool HasFPRND;
  bool HasFPCVT;
  bool HasISEL;
  bool HasBPERMD;
  bool HasExtDiv;
  bool HasCMPB;
  bool HasLDBRX;
  bool IsBookE;
  bool HasOnlyMSYNC;
  bool IsE500;
  bool IsPPC4xx;
  bool IsPPC6xx;
  bool FeatureMFTB;
  bool AllowsUnalignedFPAccess;
  bool DeprecatedDST;
  bool HasLazyResolverStubs;
  bool IsLittleEndian;
  bool HasICBT;
  bool HasInvariantFunctionDescriptors;
  bool HasPartwordAtomics;
  bool HasDirectMove;
  bool HasHTM;
  bool HasFloat128;
  bool IsISA3_0;
  bool UseLongCalls;
  bool SecurePlt;
  bool VectorsUseTwoUnits;
  bool UsePPCPreRASchedStrategy;
  bool UsePPCPostRASchedStrategy;

  POPCNTDKind HasPOPCNTD;

  /// When targeting QPX running a stock PPC64 Linux kernel where the stack
  /// alignment has not been changed, we need to keep the 16-byte alignment
  /// of the stack.
  bool IsQPXStackUnaligned;

  const PPCTargetMachine &TM;
  PPCFrameLowering FrameLowering;
  PPCInstrInfo InstrInfo;
  PPCTargetLowering TLInfo;
  SelectionDAGTargetInfo TSInfo;

public:
  /// This constructor initializes the data members to match that
  /// of the specified triple.
  ///
  PPCSubtarget(const Triple &TT, const std::string &CPU, const std::string &FS,
               const PPCTargetMachine &TM);

  /// ParseSubtargetFeatures - Parses features string setting specified
  /// subtarget options.  Definition of function is auto generated by tblgen.
  void ParseSubtargetFeatures(StringRef CPU, StringRef FS);

  /// getStackAlignment - Returns the minimum alignment known to hold of the
  /// stack frame on entry to the function and which must be maintained by every
  /// function for this subtarget.
  Align getStackAlignment() const { return StackAlignment; }

  /// getDarwinDirective - Returns the -m directive specified for the cpu.
  unsigned getDarwinDirective() const { return CPUDirective; }

  /// getCPUDirective - Returns the -m directive specified for the cpu.
  ///
  unsigned getCPUDirective() const { return CPUDirective; }

  /// getInstrItins - Return the instruction itineraries based on subtarget
  /// selection.
  const InstrItineraryData *getInstrItineraryData() const override {
    return &InstrItins;
  }

  const PPCFrameLowering *getFrameLowering() const override {
    return &FrameLowering;
  }
  const PPCInstrInfo *getInstrInfo() const override { return &InstrInfo; }
  const PPCTargetLowering *getTargetLowering() const override {
    return &TLInfo;
  }
  const SelectionDAGTargetInfo *getSelectionDAGInfo() const override {
    return &TSInfo;
  }
  const PPCRegisterInfo *getRegisterInfo() const override {
    return &getInstrInfo()->getRegisterInfo();
  }
  const PPCTargetMachine &getTargetMachine() const { return TM; }

  /// initializeSubtargetDependencies - Initializes using a CPU and feature string
  /// so that we can use initializer lists for subtarget initialization.
  PPCSubtarget &initializeSubtargetDependencies(StringRef CPU, StringRef FS);

private:
  void initializeEnvironment();
  void initSubtargetFeatures(StringRef CPU, StringRef FS);

public:
  /// isPPC64 - Return true if we are generating code for 64-bit pointer mode.
  ///
  bool isPPC64() const;

  /// has64BitSupport - Return true if the selected CPU supports 64-bit
  /// instructions, regardless of whether we are in 32-bit or 64-bit mode.
  bool has64BitSupport() const { return Has64BitSupport; }
  // useSoftFloat - Return true if soft-float option is turned on.
  bool useSoftFloat() const {
    if (isAIXABI() && !HasHardFloat)
      report_fatal_error("soft-float is not yet supported on AIX.");
    return !HasHardFloat;
  }

  /// use64BitRegs - Return true if in 64-bit mode or if we should use 64-bit
  /// registers in 32-bit mode when possible.  This can only true if
  /// has64BitSupport() returns true.
  bool use64BitRegs() const { return Use64BitRegs; }

  /// useCRBits - Return true if we should store and manipulate i1 values in
  /// the individual condition register bits.
  bool useCRBits() const { return UseCRBits; }

  /// hasLazyResolverStub - Return true if accesses to the specified global have
  /// to go through a dyld lazy resolution stub.  This means that an extra load
  /// is required to get the address of the global.
  bool hasLazyResolverStub(const GlobalValue *GV) const;

  // isLittleEndian - True if generating little-endian code
  bool isLittleEndian() const { return IsLittleEndian; }

  // Specific obvious features.
  bool hasFCPSGN() const { return HasFCPSGN; }
  bool hasFSQRT() const { return HasFSQRT; }
  bool hasFRE() const { return HasFRE; }
  bool hasFRES() const { return HasFRES; }
  bool hasFRSQRTE() const { return HasFRSQRTE; }
  bool hasFRSQRTES() const { return HasFRSQRTES; }
  bool hasRecipPrec() const { return HasRecipPrec; }
  bool hasSTFIWX() const { return HasSTFIWX; }
  bool hasLFIWAX() const { return HasLFIWAX; }
  bool hasFPRND() const { return HasFPRND; }
  bool hasFPCVT() const { return HasFPCVT; }
  bool hasAltivec() const { return HasAltivec; }
  bool hasSPE() const { return HasSPE; }
  bool hasFPU() const { return HasFPU; }
  bool hasQPX() const { return HasQPX; }
  bool hasVSX() const { return HasVSX; }
  bool needsTwoConstNR() const { return NeedsTwoConstNR; }
  bool hasP8Vector() const { return HasP8Vector; }
  bool hasP8Altivec() const { return HasP8Altivec; }
  bool hasP8Crypto() const { return HasP8Crypto; }
  bool hasP9Vector() const { return HasP9Vector; }
  bool hasP9Altivec() const { return HasP9Altivec; }
  bool hasMFOCRF() const { return HasMFOCRF; }
  bool hasISEL() const { return HasISEL; }
  bool hasBPERMD() const { return HasBPERMD; }
  bool hasExtDiv() const { return HasExtDiv; }
  bool hasCMPB() const { return HasCMPB; }
  bool hasLDBRX() const { return HasLDBRX; }
  bool isBookE() const { return IsBookE; }
  bool hasOnlyMSYNC() const { return HasOnlyMSYNC; }
  bool isPPC4xx() const { return IsPPC4xx; }
  bool isPPC6xx() const { return IsPPC6xx; }
  bool isSecurePlt() const {return SecurePlt; }
  bool vectorsUseTwoUnits() const {return VectorsUseTwoUnits; }
  bool isE500() const { return IsE500; }
  bool isFeatureMFTB() const { return FeatureMFTB; }
  bool allowsUnalignedFPAccess() const { return AllowsUnalignedFPAccess; }
  bool isDeprecatedDST() const { return DeprecatedDST; }
  bool hasICBT() const { return HasICBT; }
  bool hasInvariantFunctionDescriptors() const {
    return HasInvariantFunctionDescriptors;
  }
  bool usePPCPreRASchedStrategy() const { return UsePPCPreRASchedStrategy; }
  bool usePPCPostRASchedStrategy() const { return UsePPCPostRASchedStrategy; }
  bool hasPartwordAtomics() const { return HasPartwordAtomics; }
  bool hasDirectMove() const { return HasDirectMove; }

  bool isQPXStackUnaligned() const { return IsQPXStackUnaligned; }
  Align getPlatformStackAlignment() const {
    if ((hasQPX() || isBGQ()) && !isQPXStackUnaligned())
      return Align(32);

    return Align(16);
  }

  // DarwinABI has a 224-byte red zone. PPC32 SVR4ABI(Non-DarwinABI) has no
  // red zone and PPC64 SVR4ABI has a 288-byte red zone.
  unsigned  getRedZoneSize() const {
    return isDarwinABI() ? 224 : (isPPC64() ? 288 : 0);
  }

  bool hasHTM() const { return HasHTM; }
  bool hasFloat128() const { return HasFloat128; }
  bool isISA3_0() const { return IsISA3_0; }
  bool useLongCalls() const { return UseLongCalls; }
  bool needsSwapsForVSXMemOps() const {
    return hasVSX() && isLittleEndian() && !hasP9Vector();
  }

  POPCNTDKind hasPOPCNTD() const { return HasPOPCNTD; }

  const Triple &getTargetTriple() const { return TargetTriple; }

  /// isDarwin - True if this is any darwin platform.
  bool isDarwin() const { return TargetTriple.isMacOSX(); }
  /// isBGQ - True if this is a BG/Q platform.
  bool isBGQ() const { return TargetTriple.getVendor() == Triple::BGQ; }

  bool isTargetELF() const { return TargetTriple.isOSBinFormatELF(); }
  bool isTargetMachO() const { return TargetTriple.isOSBinFormatMachO(); }
  bool isTargetLinux() const { return TargetTriple.isOSLinux(); }

  bool isDarwinABI() const { return isTargetMachO() || isDarwin(); }
  bool isAIXABI() const { return TargetTriple.isOSAIX(); }
  bool isSVR4ABI() const { return !isDarwinABI() && !isAIXABI(); }
  bool isELFv2ABI() const;

  bool is64BitELFABI() const { return  isSVR4ABI() && isPPC64(); }
  bool is32BitELFABI() const { return  isSVR4ABI() && !isPPC64(); }

  /// Originally, this function return hasISEL(). Now we always enable it,
  /// but may expand the ISEL instruction later.
  bool enableEarlyIfConversion() const override { return true; }

  /// Scheduling customization.
  bool enableMachineScheduler() const override;
  /// Pipeliner customization.
  bool enableMachinePipeliner() const override;
  /// Machine Pipeliner customization
  bool useDFAforSMS() const override;
  /// This overrides the PostRAScheduler bit in the SchedModel for each CPU.
  bool enablePostRAScheduler() const override;
  AntiDepBreakMode getAntiDepBreakMode() const override;
  void getCriticalPathRCs(RegClassVector &CriticalPathRCs) const override;

  void overrideSchedPolicy(MachineSchedPolicy &Policy,
                           unsigned NumRegionInstrs) const override;
  bool useAA() const override;

  bool enableSubRegLiveness() const override;

  /// True if the GV will be accessed via an indirect symbol.
  bool isGVIndirectSymbol(const GlobalValue *GV) const;

  /// True if the ABI is descriptor based.
  bool usesFunctionDescriptors() const {
    // Both 32-bit and 64-bit AIX are descriptor based. For ELF only the 64-bit
    // v1 ABI uses descriptors.
    return isAIXABI() || (is64BitELFABI() && !isELFv2ABI());
  }

  unsigned descriptorTOCAnchorOffset() const {
    assert(usesFunctionDescriptors() &&
           "Should only be called when the target uses descriptors.");
    return IsPPC64 ? 8 : 4;
  }

  unsigned descriptorEnvironmentPointerOffset() const {
    assert(usesFunctionDescriptors() &&
           "Should only be called when the target uses descriptors.");
    return IsPPC64 ? 16 : 8;
  }

  MCRegister getEnvironmentPointerRegister() const {
    assert(usesFunctionDescriptors() &&
           "Should only be called when the target uses descriptors.");
     return IsPPC64 ? PPC::X11 : PPC::R11;
  }

  MCRegister getTOCPointerRegister() const {
    assert((is64BitELFABI() || isAIXABI()) &&
           "Should only be called when the target is a TOC based ABI.");
    return IsPPC64 ? PPC::X2 : PPC::R2;
  }

  MCRegister getStackPointerRegister() const {
    return IsPPC64 ? PPC::X1 : PPC::R1;
  }

  bool isXRaySupported() const override { return IsPPC64 && IsLittleEndian; }
};
} // End llvm namespace

#endif


text:
echo "The Molecular Playground - Production Mode"
echo "- NODE_ENV environment variable set to: production"
echo "- Incoming HTTP requests will not be logged"
echo "- Output will be printed to stdout and logged to ./prod-server-out.log"
echo "Running 'startproductionserver' script in src/package.json ..."
echo ""
cd src/
npm run-script runproductionserver 2>&1 | tee ../prod-server-out.log


text:
package com.github.junitrunner;

import java.util.List;

import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public abstract class JUnitBasePlugin implements JUnitPlugin {

    @Override
    public void plug(JUnitRunner jUnitRunner) {
    }

    @Override
    public Statement enhanceClassStatement(Statement statement, Description description, List<Throwable> errors) {
        return statement;
    }

    @Override
    public void validateTestRules(List<Throwable> errors) {
    }

    @Override
    public List<JUnitTask> createTasks(List<Throwable> errors) {
        return null;
    }

    @Override
    public Statement enhanceTestCore(JUnitTest test, Object testObject, Statement statement) {
        return statement;
    }

    @Override
    public Statement enhanceTest(JUnitTest test, Object testObject, Statement statement) {
        return statement;
    }

    @Override
    public void configureSuite(JUnitSuite suite, List<Throwable> errors) {
    }

    @Override
    public void configureTest(JUnitTest test, List<Throwable> errors) {
    }
}


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class auditnslogpolicy_binding(base_resource):
	""" Binding class showing the resources that can be bound to auditnslogpolicy_binding.
	"""
	def __init__(self) :
		self._name = ""
		self.auditnslogpolicy_csvserver_binding = []
		self.auditnslogpolicy_tmglobal_binding = []
		self.auditnslogpolicy_appfwglobal_binding = []
		self.auditnslogpolicy_lbvserver_binding = []
		self.auditnslogpolicy_aaauser_binding = []
		self.auditnslogpolicy_vpnglobal_binding = []
		self.auditnslogpolicy_vpnvserver_binding = []
		self.auditnslogpolicy_systemglobal_binding = []
		self.auditnslogpolicy_authenticationvserver_binding = []
		self.auditnslogpolicy_aaagroup_binding = []

	@property
	def name(self) :
		"""Name of the policy.
Minimum length =  1.
		"""
		try :
			return self._name
		except Exception as e:
			raise e

	@name.setter
	def name(self, name) :
		"""Name of the policy.
Minimum length =  1
		"""
		try :
			self._name = name
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_authenticationvserver_bindings(self) :
		"""authenticationvserver that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_authenticationvserver_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_systemglobal_bindings(self) :
		"""systemglobal that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_systemglobal_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_aaagroup_bindings(self) :
		"""aaagroup that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_aaagroup_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_vpnvserver_bindings(self) :
		"""vpnvserver that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_vpnvserver_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_lbvserver_bindings(self) :
		"""lbvserver that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_lbvserver_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_appfwglobal_bindings(self) :
		"""appfwglobal that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_appfwglobal_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_csvserver_bindings(self) :
		"""csvserver that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_csvserver_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_vpnglobal_bindings(self) :
		"""vpnglobal that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_vpnglobal_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_aaauser_bindings(self) :
		"""aaauser that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_aaauser_binding
		except Exception as e:
			raise e

	@property
	def auditnslogpolicy_tmglobal_bindings(self) :
		"""tmglobal that can be bound to auditnslogpolicy.
		"""
		try :
			return self._auditnslogpolicy_tmglobal_binding
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(auditnslogpolicy_binding_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.auditnslogpolicy_binding
		except Exception as e :
			raise e

	def _get_object_name(self) :
		""" Returns the value of object identifier argument
		"""
		try :
			if (self.name) :
				return str(self.name)
			return None
		except Exception as e :
			raise e

	@classmethod
	def get(self, service, name) :
		""" Use this API to fetch auditnslogpolicy_binding resource.
		"""
		try :
			if type(name) is not list :
				obj = auditnslogpolicy_binding()
				obj.name = name
				response = obj.get_resource(service)
			else :
				if name and len(name) > 0 :
					obj = [auditnslogpolicy_binding() for _ in range(len(name))]
					for i in range(len(name)) :
						obj[i].name = name[i];
						response[i] = obj[i].get_resource(service)
			return response
		except Exception as e:
			raise e

class auditnslogpolicy_binding_response(base_response) :
	def __init__(self, length=1) :
		self.auditnslogpolicy_binding = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.auditnslogpolicy_binding = [auditnslogpolicy_binding() for _ in range(length)]


text:
#ifndef CPP_INCLUDE_CBFS_CBFS_ADAPTER_H_
#define CPP_INCLUDE_CBFS_CBFS_ADAPTER_H_

#define WIN32_LEAN_AND_MEAN
#include <windows.h>  // required for CbFS.h

#include <boost/cstdint.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <CbFS.h>

#include "xtfsutil/xtfsutil_server.h"
#include "xtreemfs/GlobalTypes.pb.h"

namespace xtreemfs {

namespace pbrpc {
class Stat;
}  // namespace pbrpc

class CbFSOptions;
class Client;
class SystemUserMapping;

class CbFSAdapter {
 public:
  /** Replace "\" path separator by "/" and convert UTF-16 to UTF-8. */
  static std::string WindowsPathToUTF8Unix(const wchar_t* from);

  static void DebugPrintCreateFile(
    LPCWSTR OperationType,
    LPCTSTR FileName,
    ACCESS_MASK DesiredAccess,
    DWORD FileAttributes,
    DWORD ShareMode,
    PVOID FileHandleContext);

  /** Creates a new instance of CbFSAdapter, but does not create any
   *  libxtreemfs Client yet.
   *
   *  Use Start() to actually create the client and mount the volume given in
   *  options. May modify options.
   */
  explicit CbFSAdapter(CbFSOptions* options);

  ~CbFSAdapter();

  /** Create client, open volume and start needed threads. */
  void Start();

  /** Shutdown threads, close Volume and Client and blocks until all threads
   *  are stopped. */
  void Stop();

  /** Same as Stop(), but does not call cbfs_.UnmountMedia(). */
  void StopWithoutUnmount();

  void GetVolumeSize(CallbackFileSystem* Sender,
                     __int64* TotalNumberOfSectors,
                     __int64* NumberOfFreeSectors);

  void GetVolumeLabel(CallbackFileSystem* Sender, LPTSTR VolumeLabel);

  void GetVolumeId(CallbackFileSystem* Sender, PDWORD VolumeID);

  void CreateFile(CallbackFileSystem* Sender,
                  LPCTSTR FileName,
                  ACCESS_MASK DesiredAccess,
                  DWORD FileAttributes,
                  DWORD ShareMode,
                  PVOID* FileHandleContext);

  void OpenFile(CallbackFileSystem* Sender,
                LPCTSTR FileName,
                ACCESS_MASK DesiredAccess,
                DWORD ShareMode,
                PVOID* FileHandleContext);

  void CloseFile(CallbackFileSystem* Sender,
                 CbFsFileInfo* FileInfo,
                 PVOID FileHandleContext);

  void GetFileInfo(CallbackFileSystem* Sender,
                   LPCTSTR FileName,
                   LPBOOL FileExists,
                   PFILETIME CreationTime,
                   PFILETIME LastAccessTime,
                   PFILETIME LastWriteTime,
                   __int64* EndOfFile,
                   __int64* AllocationSize,
                   __int64* FileId,
                   PDWORD FileAttributes,
                   LPTSTR LongFileName OPTIONAL,
                   PWORD LongFileNameLength OPTIONAL);

  void EnumerateDirectory(CallbackFileSystem* Sender,
                          CbFsFileInfo* DirectoryInfo,
                          PVOID* EnumerationContext,
                          LPCTSTR Mask,
                          INT Index,
                          BOOL Restart,
                          LPBOOL FileFound,
                          LPTSTR FileName,
                          PDWORD FileNameLength,
                          LPTSTR ShortFileName OPTIONAL,
                          PUCHAR ShortFileNameLength OPTIONAL,
                          PFILETIME CreationTime,
                          PFILETIME LastAccessTime,
                          PFILETIME LastWriteTime,
                          __int64* EndOfFile,
                          __int64* AllocationSize,
                          __int64* FileId,
                          PDWORD FileAttributes);

  void CloseEnumeration(CallbackFileSystem* Sender,
                        CbFsFileInfo* DirectoryInfo,
                        PVOID EnumerationContext);

  void SetAllocationSize(CallbackFileSystem* Sender,
                         CbFsFileInfo* FileInfo,
                         PVOID FileHandleContext,
                         __int64 AllocationSize);

  void SetEndOfFile(CallbackFileSystem* Sender,
                    CbFsFileInfo* FileInfo,
                    PVOID FileHandleContext,
                    __int64 EndOfFile);

  void SetFileAttributes(CallbackFileSystem* Sender,
                         CbFsFileInfo* FileInfo,
                         PVOID FileHandleContext,
                         PFILETIME CreationTime,
                         PFILETIME LastAccessTime,
                         PFILETIME LastWriteTime,
                         DWORD FileAttributes);

  void CanFileBeDeleted(CallbackFileSystem* Sender,
                        CbFsFileInfo* FileInfo,
                        BOOL* CanBeDeleted);

  void DeleteFile(CallbackFileSystem* Sender, CbFsFileInfo* FileInfo);

  void RenameOrMoveFile(CallbackFileSystem* Sender,
                        CbFsFileInfo* FileInfo,
                        LPCTSTR NewFileName);

  void ReadFile(CallbackFileSystem* Sender,
                CbFsFileInfo* FileInfo,
                PVOID FileHandleContext,
                __int64 Position,
                PVOID Buffer,
                DWORD BytesToRead,
                PDWORD BytesRead);

  void WriteFile(CallbackFileSystem* Sender,
                 CbFsFileInfo* FileInfo,
                 PVOID FileHandleContext,
                 __int64 Position,
                 PVOID Buffer,
                 DWORD BytesToWrite,
                 PDWORD BytesWritten);

  void IsDirectoryEmpty(CallbackFileSystem* Sender,
                        LPWSTR FileName,
                        LPBOOL IsEmpty);

  void StorageEjected(CallbackFileSystem* Sender);

  /** Blocks until device was ejected by user. */
  void WaitForEjection();

 private:
  static const DWORD kMaxFileNameLength = 32767;

  static const size_t kMaxVolumeLabelLength = 32;

  /** Print debug output to stdout. */
  static void DbgPrint(LPCWSTR format, ...);

  /** Output exception thrown by CBFS as string. */
  static std::string ECBFSErrorToString(ECBFSError& e);

  /** Maps XtreemFS return values to Windows specific ones. */
  static int ConvertXtreemFSErrnoToWindows(
      xtreemfs::pbrpc::POSIXErrno xtreemfs_errno);

  /** Convert UNIX timestamp (in nanoseconds) to Windows time format. */
  static void XtreemFSTimeToWinTime(uint64_t utime_ns,
                                    DWORD* lower,
                                    DWORD* upper);

  /** Convert Windows timestamp to UNIX timestamp (in nanoseconds). */
  static boost::uint64_t ConvertWinTimeToXtreemFSTime(DWORD lower,
                                                      DWORD upper);

  /** Returns true if "stat" is a directory. */
  static bool IsDirectory(const xtreemfs::pbrpc::Stat& stat);

  /** Convert "desired_access", passed at Create and Open, to e.g., O_RDWR. */
  static xtreemfs::pbrpc::SYSTEM_V_FCNTL ConvertFlagsWindowsToXtreemFS(
      const ACCESS_MASK desired_access);

  /** Provides the CBFS library the required license key. */
  void SetRegistrationKey();

  /** Returns true if "path" is a directory.
    * @throws AddressToUUIDNotFoundException
    * @throws IOException
    * @throws PosixErrorException
    * @throws UnknownAddressSchemeException
    */
  bool IsDirectory(const std::string& path);

  /** Same as GetFileInfo(), except that "path" is an UTF8 encoded UNIX path. */
  void ConvertXtreemFSStatToCbFS(const xtreemfs::pbrpc::Stat& stat,
                                 PFILETIME CreationTime,
                                 PFILETIME LastAccessTime,
                                 PFILETIME LastWriteTime,
                                 __int64* EndOfFile,
                                 __int64* AllocationSize,
                                 __int64* FileId,
                                 PDWORD FileAttributes,
                                 LPTSTR LongFileName OPTIONAL,
                                 PWORD LongFileNameLength OPTIONAL);

  /** Contains all needed options to mount the requested volume. */
  CbFSOptions* options_;

  /** Volume Label generated from the given XtreemFS URL. */
  std::wstring volume_label_;

  /** The chosen UserMapping provides methods to translate between local and
   *  remote usernames and groups. */
  boost::scoped_ptr<SystemUserMapping> system_user_mapping_;

  /** Username and domain name of user executing the Dokan client. Will be used
   *  by all XtreemFS operations. */
  xtreemfs::pbrpc::UserCredentials user_credentials_;

  /** Created libxtreemfs Client. */
  boost::scoped_ptr<Client> client_;

  /** Opened libxtreemfs Volume. */
  Volume* volume_;

  /** Server for processing commands sent from the xtfsutil tool
      via xctl files. */
  XtfsUtilServer xctl_;

  /** Callback Filesystem instance which provides a Windows user space
   *  file system interface. */
  CallbackFileSystem cbfs_;

  /** True if device was ejected by user. */
  bool device_ejected_;

  /** Guards device_ejected_. */
  boost::mutex device_ejected_mutex_;

  /** Used when waiting for a change of device_ejected_. */
  boost::condition device_ejected_cond_;
};

}  // namespace xtreemfs

#endif  // CPP_INCLUDE_CBFS_CBFS_ADAPTER_H_


text:
var mate = require('../');

var node = mate.createNode({
	networkPort: 2015
});

node.on('message', function(from, message) {
	console.log('receive ' + from.id.toString() + ' message: ' + message);

	node.send(from.id.toString(), 'Hi!', function(success) {
		if (success === true) {
			console.log('send reply message success');
		} else {
			console.log('send reply message failed');
		}
	});
});

node.on('listening', function() {
	console.log('mate node ' + node.localNodeContact.id.toString() + ' started');
});

node.on('root_connected', function(root) {
	console.log('root node connected');

/*
	node.send('44e11b60-c1a7-11e4-9771-9180d4138974', 'I\'m here!', function(success) {
		if (success === true) {
			console.log('send message success');
		} else {
			console.log('send message failed');
		}
	});
*/
});

node.on('root_disconnect', function(root) {
	console.log('root node disconnect');
});


text:
package com.cra.figaro.library.compound

import com.cra.figaro.language._
import com.cra.figaro.util._
import com.cra.figaro.algorithm._
import com.cra.figaro.algorithm.factored._
import com.cra.figaro.algorithm.lazyfactored._

/**
 * An IntSelector represents the selection of an integer from 0 (inclusive) to a variable upper bound (exclusive). The
 * upper bound is an element represented by the bound argument. The IntSelector class has been defined so that
 * (1) the value is always uniformly distributed in the range, no matter how the upper bound changes, and
 * (2) it attempts to avoid changing the value as much as it possibly can as the upper bound changes.
 * This latter property makes the class useful in an algorithm like Metropolis-Hastings, where we would like to
 * change as little as possible as we make a proposal.
 */
class IntSelector(name: Name[Int], counter: Element[Int], collection: ElementCollection)
  extends Element[Int](name, collection) with IfArgsCacheable[Int] with ValuesMaker[Int] with ProbFactorMaker {
  // We achieve the two properties by making the randomness a random stream of doubles and selecting the index
  // within range that has the highest randomness. If the bound changes, the double associated with the index
  // does not change, so quite often the highest index will stay the same.
  type Randomness = Stream[Double]

  def args = List(counter)

  def generateRandomness(): Randomness = Stream.continually(random.nextDouble())

  def generateValue(rand: Randomness): Int = argmax(rand take counter.value)

  def makeValues(depth: Int): ValueSet[Int] = {
    val counterValues = LazyValues(universe)(counter, depth - 1)
    if (counterValues.regularValues.nonEmpty) {
      val maxCounter = counterValues.regularValues.max
      val all = List.tabulate(maxCounter)(i => i).toSet
      if (counterValues.hasStar) ValueSet.withStar(all); else ValueSet.withoutStar(all)
    } else { ValueSet.withStar(Set()) }
  }

  def makeFactors: List[Factor[Double]] = {
    val thisVar = Variable(this)
    val counterVar = Variable(counter)
    val comb = new Factor[Double](List(thisVar, counterVar))
    comb.fillByRule((l: List[Any]) => {
      val xvalue0 :: xvalue1 :: _ = l.asInstanceOf[List[Extended[Int]]]
      if (xvalue0.isRegular && xvalue1.isRegular) {
        if (xvalue0.value < xvalue1.value) 1.0/xvalue1.value; else 0.0
      } else 1.0

    })
    List(comb)
  }
}

object IntSelector {
  /**
   * Create an IntSelector using the counter element as the upper bound
   */
  def apply(counter: Element[Int])(implicit name: Name[Int], collection: ElementCollection) =
    new IntSelector(name, counter, collection)
}


text:
class Area < ActiveRecord::Base

  validates :code, :uniqueness => true
  validates :code, :name, :address_type_id, :presence => true

  belongs_to :parent, :class_name => 'Area', :foreign_key => :parent_id
  belongs_to :old, :class_name => 'Area', :foreign_key => :old_id
  belongs_to :address_type

  has_many :streets

  default_scope -> { where(active: true) }

  scope :subjects, -> { where(region_code: '000', city_code: '000', settlement_code: '000') }
  scope :regions, -> { where(city_code: '000', settlement_code: '000').where("region_code <> '000'") }
  scope :cities, -> { where("city_code <> '000' or settlement_code <> '000' ") }
  scope :children_of, ->(parent_id) { where(parent_id: parent_id) }
  scope :level, ->(level) { where(level: level) }

end


text:
This quickstart provides an example of deploying a set of applications demonstrating remote transaction propagation in SwitchYard.  The quickstart consists of the following pieces:

* dealer : contains the Dealer Service which acts as consumer for the Credit Service.
* credit : a remote decision service implemented in Drools.
* client : the test driver for the application which can be used to send a request payload to the Dealer Service

The purpose of the quickstart is to demonstrate how the transaction initiated by Dealer Service is propagated to the remote Credit Service through SCA binding.

## Running the Example

You will need two SY instances and three terminal windows to run the transaction propagation demo.

EAP
----------
*1. Create two discrete instances of the SY runtime.*

This can be done by simply making copies of the standalone directory for each instance, e.g.
```
    cd ${EAP_HOME}
    cp -R standalone dealer
    cp -R standalone credit
```
Replace ${EAP_HOME} with the actual path.

*2. Start each instance in a separate terminal window.*

Note that you need to specify absolute path for the jboss.server.base.dir so the XTS ActivationService works correctly.

_Window 1_

    bin/standalone.sh -Djboss.node.name=dealer -Djboss.server.base.dir=${EAP_HOME}/dealer --server-config=standalone-ha.xml

_Window 2_

    bin/standalone.sh -Djboss.node.name=credit -Djboss.server.base.dir=${EAP_HOME}/credit -Djboss.socket.binding.port-offset=1000 --server-config=standalone-ha.xml

*3. Deploy and build the dealer and credit applications.*

    mvn -Pdeploy install

*4. Run the test client and check output.*

Submit a message using the client project:

    mvn exec:java

You should see the following output in the client terminal:

    ==================================
    Was the offer accepted? true
    ==================================

Check the console output on credit to see the message:

    Credit Service : Approving credit for John Smith

If the transaction is committed successfully, database "dealer" and "credit" should have a new record which corresponds the request you submitted. Take a look at the databases from H2 console.

If you submit a message with a parameter "deny":

    mvn exec:java -Dexec.args="deny"

then you should see the following output in the client terminal:

    ==================================
    Was the offer accepted? false
    ==================================

And following output in the dealer console:

    Dealer Service : Low credit score - transaction has been rolled back

In this case, DealerBean sets RollbackOnly flag and the transaction is rolled back. Check the database to see new record is not inserted.

*5. Stop the database and undeploy the applications

    mvn -Pdeploy clean

Wildfly
----------
*1. Create two discrete instances of the SY runtime.*

This can be done by simply making copies of the standalone directory for each instance, e.g.
```
    cd ${WILDFLY_HOME}
    cp -R standalone dealer
    cp -R standalone credit
```
Replace ${WILDFLY_HOME} with the actual path.

*2. Start each instance in a separate terminal window.*

Note that you need to specify absolute path for the jboss.server.base.dir so the XTS ActivationService works correctly.

_Window 1_

    bin/standalone.sh -Djboss.node.name=dealer -Djboss.server.base.dir=${WILDFLY_HOME}/dealer --server-config=standalone-ha.xml

_Window 2_

    bin/standalone.sh -Djboss.node.name=credit -Djboss.server.base.dir=${WILDFLY_HOME}/credit -Djboss.socket.binding.port-offset=1000 --server-config=standalone-ha.xml

*3. Deploy and build the dealer and credit applications.*

    mvn -Pdeploy,wildfly install

*4. Run the test client and check output.*

Submit a message using the client project:

    mvn exec:java

You should see the following output in the client terminal:

    ==================================
    Was the offer accepted? true
    ==================================

Check the console output on credit to see the message:

    Credit Service : Approving credit for John Smith

If the transaction is committed successfully, database "dealer" and "credit" should have a new record which corresponds the request you submitted. Take a look at the databases from H2 console.

If you submit a message with a parameter "deny":

    mvn exec:java -Dexec.args="deny"

then you should see the following output in the client terminal:

    ==================================
    Was the offer accepted? false
    ==================================

And following output in the dealer console:

    Dealer Service : Low credit score - transaction has been rolled back

In this case, DealerBean sets RollbackOnly flag and the transaction is rolled back. Check the database to see new record is not inserted.

*5. Stop the database and undeploy the applications

    mvn -Pdeploy,wildfly clean

## Further Reading

1. [SwitchYard SCA Binding] (https://docs.jboss.org/author/display/SWITCHYARD/SCA)
2. [SwitchYard Transaction Policy] (https://docs.jboss.org/author/display/SWITCHYARD/Policy)
3. [SwitchYard Clustering](https://docs.jboss.org/author/display/SWITCHYARD/Clustering)


text:
The nameservers for <any_subdomain>.rb.cz. doesn't respond to queries
with EDNS version greater than zero.

## Evidence

    $ kdig +edns=1 +norec IN TXT www.rb.cz @lb-dns-live-03.rb.cz.
	;; WARNING: response timeout for 89.233.149.41@53(UDP)

	;; WARNING: response timeout for 89.233.149.41@53(UDP)

	;; WARNING: response timeout for 89.233.149.41@53(UDP)
	;; WARNING: failed to query server lb-dns-live-03.rb.cz.@53(UDP)

## Proposed fix

The Raiffeisen Bank nameservers MUST properly implement RFC 6891
Section 6.1.3 and return RCODE=BADVERS in the DNS answer.

## Metadata

Submitter: Ondřej Surý
Submit-Date: 2017-05-09
Tags: protocol


text:
import { Injectable } from '@angular/core';
import { Query } from '@datorama/akita';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ga4ghWorkflowIdPrefix } from '../constants';
import { BioWorkflow, DockstoreTool, Entry, Workflow } from '../swagger';
import { CheckerWorkflowState, CheckerWorkflowStore } from './checker-workflow.store';

@Injectable({ providedIn: 'root' })
export class CheckerWorkflowQuery extends Query<CheckerWorkflowState> {
  entry$: Observable<Entry> = this.select((state) => state.entry);
  entryId$: Observable<number> = this.entry$.pipe(map((entry: Entry) => (entry ? entry.id : null)));
  checkerWorkflow$: Observable<Workflow> = this.select((state) => (state.checkerWorkflow ? state.checkerWorkflow : null));
  isStub$: Observable<boolean> = this.entry$.pipe(
    map((entry: Entry) => (this.isEntryAWorkflow(entry) ? (<Workflow>entry).mode === Workflow.ModeEnum.STUB : false))
  );
  checkerWorkflowPath$: Observable<string> = this.checkerWorkflow$.pipe(map((workflow) => (workflow ? workflow.full_workflow_path : null)));
  parentId$: Observable<number> = this.entry$.pipe(map((entry: BioWorkflow) => (entry ? entry.parent_id : null)));
  checkerId$: Observable<number> = this.entry$.pipe(map((entry: Entry) => (entry ? entry.checker_id : null)));
  entryIsWorkflow$: Observable<boolean> = this.entry$.pipe(map((entry: Entry) => (entry ? this.isEntryAWorkflow(entry) : null)));
  noChecker$: Observable<boolean> = this.checkerId$.pipe(map((checkerId) => !checkerId));
  trsId$: Observable<string | null> = this.entry$.pipe(map((entry: Entry | null) => this.getTRSId(entry)));
  constructor(protected store: CheckerWorkflowStore) {
    super(store);
  }

  /**
   * Determines if a given entry is a workflow or not (tool).
   * Returns true if entry is a workflow, returns false if entry is not a workflow (i.e. a tool)
   * @param entry The entry to check
   */
  public isEntryAWorkflow(entry: Entry | null): boolean | null {
    if (!entry) {
      return null;
    }
    return entry.hasOwnProperty('isChecker');
  }

  /**
   * Determine the TRS ID (ex. #workflow/github.com/dockstore/hello_world) based on the entry
   *
   * @param {(Entry | null)} entry  Either a DockstoreTool or Workflow
   * @returns {(string | null)}  The TRS ID (ex. #workflow/github.com/dockstore/hello_world)
   * @memberof CheckerWorkflowQuery
   */
  public getTRSId(entry: Entry | null): string | null {
    const entryIsWorkflow = this.isEntryAWorkflow(entry);
    if (entryIsWorkflow == null) {
      return null;
    }
    if (entryIsWorkflow) {
      return ga4ghWorkflowIdPrefix + (<Workflow>entry).full_workflow_path;
    } else {
      return (<DockstoreTool>entry).tool_path;
    }
  }
}


text:
package org.newdawn.slick.util.xml;

import org.newdawn.slick.SlickException;

/**
 * An exception to describe failures in XML. Made a special case because with XML to object parsing you might want to
 * handle it differently
 *

 *
 * @author kevin
 */
public class SlickXMLException extends SlickException {

    /**
     * Create a new exception
     *

     *
     * @param message The message describing the failure
     */
    public SlickXMLException(String message) {
        super(message);
    }

    /**
     * Create a new exception
     *

     *
     * @param message The message describing the failure
     * @param e       The exception causing this failure
     */
    public SlickXMLException(String message, Throwable e) {
        super(message, e);
    }

}


text:
package fr.openwide.core.imports.table.common.csv.scanner;

import java.io.File;
import java.io.InputStream;

import fr.openwide.core.imports.table.common.event.exception.TableImportException;
import fr.openwide.core.imports.table.common.location.ITableImportNavigator;

public interface ICsvImportFileScanner<TTable, TRow, TCell, TCellReference> {

	interface ICsvImportFileVisitor<TTable, TRow, TCell, TCellReference> {
		void visitTable(ITableImportNavigator<TTable, TRow, TCell, TCellReference> navigator, TTable sheet) throws TableImportException;
	}

	void scanRecursively(File file, String filename, ICsvImportFileVisitor<TTable, TRow, TCell, TCellReference> visitor) throws TableImportException;

	void scan(File file, String filename, ICsvImportFileVisitor<TTable, TRow, TCell, TCellReference> visitor) throws TableImportException;

	void scan(InputStream stream, String filename, ICsvImportFileVisitor<TTable, TRow, TCell, TCellReference> visitor) throws TableImportException;

}


text:
<?php

namespace Sylius\Component\Core\Locale\Handler;

use Sylius\Component\Core\Exception\HandleException;
use Zend\Stdlib\PriorityQueue;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class CompositeLocaleChangeHandler implements LocaleChangeHandlerInterface
{
    /**
     * @var PriorityQueue|LocaleChangeHandlerInterface[]
     */
    private $handlers;

    public function __construct()
    {
        $this->handlers = new PriorityQueue();
    }

    /**
     * @param LocaleChangeHandlerInterface $localeChangeHandler
     * @param int $priority
     */
    public function addHandler(LocaleChangeHandlerInterface $localeChangeHandler, $priority = 0)
    {
        $this->handlers->insert($localeChangeHandler, $priority);
    }

    /**
     * {@inheritdoc}
     */
    public function handle($code)
    {
        if ($this->handlers->isEmpty()) {
            throw new HandleException(self::class, 'There are no handlers defined.');
        }

        foreach ($this->handlers as $handler) {
            $handler->handle($code);
        }
    }
}


text:
/*
 * include/asm-sh/edosk7705/io.h
 *
 * Modified version of io_se.h for the EDOSK7705 specific functions.
 *
 * May be copied or modified under the terms of the GNU General Public
 * License.  See linux/COPYING for more information.
 *
 * IO functions for an Hitachi EDOSK7705 development board
 */

#ifndef __ASM_SH_EDOSK7705_IO_H
#define __ASM_SH_EDOSK7705_IO_H

#include <asm/io_generic.h>

extern unsigned char sh_edosk7705_inb(unsigned long port);
extern unsigned int sh_edosk7705_inl(unsigned long port);

extern void sh_edosk7705_outb(unsigned char value, unsigned long port);
extern void sh_edosk7705_outl(unsigned int value, unsigned long port);

extern void sh_edosk7705_insb(unsigned long port, void *addr, unsigned long count);
extern void sh_edosk7705_insl(unsigned long port, void *addr, unsigned long count);
extern void sh_edosk7705_outsb(unsigned long port, const void *addr, unsigned long count);
extern void sh_edosk7705_outsl(unsigned long port, const void *addr, unsigned long count);

extern unsigned long sh_edosk7705_isa_port2addr(unsigned long offset);

#endif /* __ASM_SH_EDOSK7705_IO_H */


text:
// Copyright (c) Aspose 2002-2014. All Rights Reserved.

using Aspose.Words;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JoiningMutipleDocuments
{
    class Program
    {
        static void Main(string[] args)
        {
            string MyDir = @"Files\";
            // The document that the other documents will be appended to.
            Document dstDoc = new Document();

            // We should call this method to clear this document of any existing content.
            dstDoc.RemoveAllChildren();

            int recordCount = 1;
            for (int i = 1; i <= recordCount; i++)
            {
                // Open the document to join.
                Document srcDoc = new Document(MyDir + "src.doc");

                // Append the source document at the end of the destination document.
                dstDoc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles);
                Document doc2 = new Document(MyDir + "srcDocument.doc");
                dstDoc.AppendDocument(doc2, ImportFormatMode.UseDestinationStyles);
                // If this is the second document or above being appended then unlink all headers footers in this section
                // from the headers and footers of the previous section.
                if (i > 1)
                    dstDoc.Sections[i].HeadersFooters.LinkToPrevious(false);
            }
            dstDoc.Save(MyDir + "MutipleJoinedDocument.doc");
        }
    }
}


text:
-include ../openmrnpath.mk
include $(OPENMRNPATH)/etc/core_target.mk


text:
from __future__ import unicode_literals
from moto.core.responses import BaseResponse

class Monitoring(BaseResponse):
    def monitor_instances(self):
        if self.is_not_dryrun("MonitorInstances"):
            raise NotImplementedError(
                "Monitoring.monitor_instances is not yet implemented"
            )

    def unmonitor_instances(self):
        if self.is_not_dryrun("UnMonitorInstances"):
            raise NotImplementedError(
                "Monitoring.unmonitor_instances is not yet implemented"
            )


text:
Figures = new orion.collection('figures', {
    singularName: 'figure',
    pluralName: 'figures',
    title: 'Figures',
    link: {
        title: 'Figures'
    },
    tabular: {
        columns: [
            {
                data: 'date',
                title: 'Date'
            }
        ]
    }
});

Figures.attachSchema(new SimpleSchema({
    date: {
        type: String,
        label: 'Date'
    },
    'records.$.metric': {
        type: String,
        label: 'Metric'
    },
    'records.$.percent': {
        type: String,
        label: 'Percent'
    },
    'records.$.client': {
        type: String,
        label: 'Client'
    },
    createdBy: orion.attribute('createdBy'),
    createdAt: orion.attribute('createdAt')
}));


text:
using Newtonsoft.Json;
using VaultSharp.V1.Commons;

namespace VaultSharp.V1.SecretsEngines
{
    /// <summary>
    /// Represents a secret backend.
    /// </summary>
    public class SecretsEngine : AbstractBackend
    {
        /// <summary>
        /// Gets or sets the type of the backend.
        /// </summary>
        /// <value>
        /// The type of the backend.
        /// </value>
        [JsonProperty("type")]
        public SecretsEngineType Type { get; set; }
    }
}


text:
                        搜索:

                            <input id="roleEdtSearch" class="layui-input" type="text" placeholder="输入关键字"/>

                        <button id="roleBtnSearch" class="layui-btn icon-btn">搜索
                        </button>
                        <button id="roleBtnAdd" class="layui-btn icon-btn">添加</button>