text:
package conekta

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Plans", func() {

	server := NewTestServer()
	client := NewTestClient(server)

	plan := &Plan{
		Name:     "Gold Plan",
		Amount:   100000,
		Currency: "MXN",
	}

	Describe("Create", func() {
		It("Returns the created plan", func() {
			resp, err := client.Plans.Create(plan)

			Expect(err).ToNot(HaveOccurred())
			Expect(resp.Name).To(Equal("Gold Plan"))
		})
	})

	Describe("Update", func() {
		It("Returns the updated plan", func() {
			resp, err := client.Plans.Update("gold-plan", plan)

			Expect(err).ToNot(HaveOccurred())
			Expect(resp.Name).To(Equal("Gold Plan"))
		})
	})

	Describe("Delete", func() {
		It("Returns the deleted plan", func() {
			resp, err := client.Plans.Delete("gold-plan")

			Expect(err).ToNot(HaveOccurred())
			Expect(resp.Name).To(Equal("Gold Plan"))
		})
	})
})


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingTop="@dimen/margin_20dp"
    android:background="@color/white">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bookmoreslots"
        android:id="@+id/bHome"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="@dimen/margin_10dp"
        android:layout_marginRight="@dimen/margin_10dp"/>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text: College Unity Project


text:
// ***********************************************************************
// Assembly         : ACBr.Net.DFe.Core
// Author           : RFTD
// Created          : 12-01-2019
//
// Last Modified By : RFTD
// Last Modified On : 12-01-2019
// ***********************************************************************
// <copyright file="DistribuicaoDFeResult.cs" company="ACBr.Net">
//		        		   The MIT License (MIT)
//	     		    Copyright (c) 2016 Grupo ACBr.Net
//
//	 Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//	 The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//	 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************

using System;
using ACBr.Net.DFe.Core.Attributes;
using ACBr.Net.DFe.Core.Common;
using ACBr.Net.DFe.Core.Document;
using ACBr.Net.DFe.Core.Serializer;

namespace ACBr.Net.DFe.Core.Service
{
    [DFeRoot("retDistDFeInt")]
    public sealed class DistribuicaoDFeResult : DFeDocument<DistribuicaoDFeResult>
    {
        #region Properties

        [DFeAttribute(TipoCampo.Str, "versao", Min = 1, Max = 7, Ocorrencia = Ocorrencia.Obrigatoria)]
        public string Versao { get; set; }

        [DFeElement(TipoCampo.Enum, "tpAmb", Min = 1, Max = 1, Ocorrencia = Ocorrencia.Obrigatoria)]
        public DFeTipoAmbiente TipoAmbiente { get; set; }

        [DFeElement(TipoCampo.Str, "verAplic", Min = 1, Max = 20, Ocorrencia = Ocorrencia.Obrigatoria)]
        public string VersaoAplicacao { get; set; }

        [DFeElement(TipoCampo.Int, "cStat", Min = 1, Max = 3, Ocorrencia = Ocorrencia.Obrigatoria)]
        public int CStat { get; set; }

        [DFeElement(TipoCampo.Str, "xMotivo", Min = 1, Max = 255, Ocorrencia = Ocorrencia.Obrigatoria)]
        public string Motivo { get; set; }

        [DFeElement(TipoCampo.DatHor, "dhResp", Min = 19, Max = 19, Ocorrencia = Ocorrencia.Obrigatoria)]
        public DateTime dhResp { get; set; }

        [DFeElement(TipoCampo.Int, "ultNSU", Ocorrencia = Ocorrencia.Obrigatoria)]
        public int ultNSU { get; set; }

        [DFeElement(TipoCampo.Int, "maxNSU", Ocorrencia = Ocorrencia.Obrigatoria)]
        public int maxNSU { get; set; }

        [DFeItem(typeof(LoteDistDFe), "docZip")]
        [DFeCollection("loteDistDFeInt", MinSize = 0, MaxSize = 50, Ocorrencia = Ocorrencia.NaoObrigatoria)]
        public LoteDistDFe[] LoteDistDFe { get; set; }

        #endregion Properties
    }
}


text:
layout: talk
title: "Отладка nodejs-приложений"
modified:
categories: talks
author: elifantiev_oleg
excerpt:
tags: [nodejs, debug]
image:
  feature:
talk: meetup12
date: 2015-04-01T19:00:00+04:00
comments: true
share: true
announce:
video:
slides:
---

 - Рабоче-колхозный console.log
 - Встроенный отладчик — отлаживаем из консоли
 - Отладка через node-inspector (кратко все возможности и чуть подробнее о профилировании и анализе кучи — заход на простые утечки через JS)
 - Сторонние средства онлайн-мониторинга (когда что-то нужно снять с процесса без возможности подключения инспектором: heapdump, gc-stat, process.memoryUsage())


text:
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.spectrads3;

import com.spectralogic.ds3client.models.AzureTargetBucketName;
import com.spectralogic.ds3client.models.ChecksumType;
import com.spectralogic.ds3client.commands.interfaces.AbstractResponse;

public class PutAzureTargetBucketNameSpectraS3Response extends AbstractResponse {

    private final AzureTargetBucketName azureTargetBucketNameResult;

    public PutAzureTargetBucketNameSpectraS3Response(final AzureTargetBucketName azureTargetBucketNameResult, final String checksum, final ChecksumType.Type checksumType) {
        super(checksum, checksumType);
        this.azureTargetBucketNameResult = azureTargetBucketNameResult;
    }

    public AzureTargetBucketName getAzureTargetBucketNameResult() {
        return this.azureTargetBucketNameResult;
    }

}


text:
import { Node } from '@/components/node';
import {
  HistoryEventLevel,
  HistoryNodeEvent,
  HistoryDiagramEvent,
  HistoryDiagramBatchEvent,
  HistoryNodeOptionEvent,
  HistoryEvent,
  HistoryEventIcon,
  HistoryInteractionEvent,
  HistoryCompositeEvent,
  HistoryLogType,
  HistoryLog,
 } from '@/store/history/types';
import { DiagramEventType } from '@/store/dataflow/types';
import { ENVIRONMENT } from '@/common/env';

export const diagramEvent = (type: DiagramEventType, message: string, data: any, icon?: HistoryEventIcon):
  HistoryDiagramEvent => {
  return {
    level: HistoryEventLevel.DIAGRAM,
    type,
    message,
    data,
    icon,
  };
};

export const diagramBatchEvent = (type: string, message: string, events: HistoryDiagramEvent[],
                                  icon?: HistoryEventIcon, data?: any): HistoryDiagramBatchEvent => {
  return {
    level: HistoryEventLevel.DIAGRAM,
    type,
    message,
    events,
    data,
    icon,
  };
};

export const nodeEvent = (type: string, message: string, node: Node, data: any,
                          icon?: HistoryEventIcon): HistoryNodeEvent => {
  return {
    level: HistoryEventLevel.NODE,
    type,
    message,
    nodeId: node.id,
    data,
    icon,
  };
};

export const nodeOptionEvent = (type: string, message: string, node: Node,
                                setter: (value: any) => void,
                                value: any, prevValue: any,
                                icon?: HistoryEventIcon):
  HistoryNodeOptionEvent => {
  let defaultIconValue = 'fas fa-sliders-h';
  if (!icon) {
    if (type.match(/select/)) {
      defaultIconValue = 'fas fa-list';
    } else if (type.match(/input/)) {
      defaultIconValue = 'fas fa-edit';
    } else if (type.match(/toggle/)) {
      defaultIconValue = 'fas fa-toggle-on';
    }
  }
  // setterName is equal to event type
  const setterName = type;
  if (ENVIRONMENT === 'development') {
    // Retrieve setter name from the actual function (a method with a name in the format "bound {name}")
    const matchedSetterName = setter.name.match(/^bound (.*)$/);
    if (matchedSetterName === null) {
      console.error(`cannot parse setter name from ${setter.name}`);
    } else if (matchedSetterName[1] !== setterName) {
      console.error(`matched setter name ${matchedSetterName[1]} does not equal given setter name "${setterName}"`);
    }
  }

  return {
    level: HistoryEventLevel.NODE,
    type,
    message,
    nodeId: node.id,
    setter,
    setterName,
    data: { value, prevValue },
    icon: icon || { value: defaultIconValue },
  };
};

export const interactionEvent = (type: string, message: string, data: any, icon?: HistoryEventIcon):
  HistoryInteractionEvent => {
  return {
    level: HistoryEventLevel.INTERACTION,
    type,
    message,
    data,
    icon,
  };
};

export const compositeEvent = (message: string, events: HistoryEvent[], icon?: HistoryEventIcon, data?: any):
  HistoryCompositeEvent => {
  return {
    level: HistoryEventLevel.COMPOSITE,
    message,
    events,
    icon,
    data,
  };
};

export const historyLog = (type: HistoryLogType, data: any): HistoryLog => {
  return {
    type,
    data,
    timestamp: new Date().getTime(),
  };
};


text:
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData

from trove.db.sqlalchemy.migrate_repo.schema import String
from trove.db.sqlalchemy.migrate_repo.schema import Table

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    # add column:
    instances = Table('instances', meta, autoload=True)
    instances.create_column(Column('tenant_id', String(36), nullable=True))
    instances.create_column(Column('server_status', String(64)))

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    # drop column:
    instances = Table('instances', meta, autoload=True)

    instances.drop_column('tenant_id')
    instances.drop_column('server_status')


text:
require 'rails_helper'

RSpec.describe ClaimIntention, type: :model do
  it { should validate_presence_of(:form_id) }
  it { should validate_uniqueness_of(:form_id).with_message('There is already a claim with this form-id') }
end


text:
namespace rx {

template<class MakeStrand, class F>
auto transform_merge(MakeStrand&& makeStrand, F&& f) {
    return transform(forward<F>(f)) | merge(forward<MakeStrand>(makeStrand));
};

}


text:
package org.apache.shardingsphere.infra.executor.sql.process.model;

/**
 * Execute process constants.
 */
public enum ExecuteProcessConstants {

    EXECUTE_ID, EXECUTE_STATUS_START, EXECUTE_STATUS_DONE
}


text:
<!DOCTYPE html>

	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

	<title>jQuery.FileAPI :: Tests</title>

	<link rel="stylesheet" href="./qunit/qunit.css"/>

	<input id="startBtn" type="button" value="  START  " style="font-size: 20px;" />

		<input id="one" type="file" name="one" />
		<input id="multiple" type="file" name="multiple" multiple />

empty.show

empty.hide

emptyQueue.show

emptyQueue.hide

active.show

active.hide

<%=$idx%>

<%=uid%>

<%=name%>

<%=type%>

<%=size%>

file.active.show

file.active.hide

active.show

active.hide

		<input type="reset" data-fileapi="ctrl.reset" />
		<input type="button" value="abort" data-fileapi="ctrl.abort" />

	<input type="submit" id="uploadBtn" value="upload" />


text:
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe http://java.sun.com/xml/jaxb
// �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2017.06.06 um 11:17:38 AM CEST
//

package at.tuwien.ss17.dp.lab3.datascience.model.dmp.javax;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java-Klasse f�r anonymous complex type.
 *
 *
Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="metadata" type="{}metadataType"/>
 *         <element name="preservation" type="{}preservationType"/>
 *         <element name="dataVolume" type="{}dataVolumeType"/>
 *         <element name="documentation" type="{}documentationType"/>
 *         <element name="intellectualPropertyRights" type="{}intellectualPropertyRightsType"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "metadata",
    "preservation",
    "dataVolume",
    "documentation",
    "intellectualPropertyRights"
})
public class SourceCode {

    @XmlElement(required = true)
    protected MetadataType metadata;
    @XmlElement(required = true)
    protected PreservationType preservation;
    @XmlElement(required = true)
    protected DataVolumeType dataVolume;
    @XmlElement(required = true)
    protected DocumentationType documentation;
    @XmlElement(required = true)
    protected IntellectualPropertyRightsType intellectualPropertyRights;

    /**
     * Ruft den Wert der metadata-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link MetadataType }
     *
     */
    public MetadataType getMetadata() {
        return metadata;
    }

    /**
     * Legt den Wert der metadata-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link MetadataType }
     *
     */
    public void setMetadata(MetadataType value) {
        this.metadata = value;
    }

    /**
     * Ruft den Wert der preservation-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link PreservationType }
     *
     */
    public PreservationType getPreservation() {
        return preservation;
    }

    /**
     * Legt den Wert der preservation-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link PreservationType }
     *
     */
    public void setPreservation(PreservationType value) {
        this.preservation = value;
    }

    /**
     * Ruft den Wert der dataVolume-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link DataVolumeType }
     *
     */
    public DataVolumeType getDataVolume() {
        return dataVolume;
    }

    /**
     * Legt den Wert der dataVolume-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link DataVolumeType }
     *
     */
    public void setDataVolume(DataVolumeType value) {
        this.dataVolume = value;
    }

    /**
     * Ruft den Wert der documentation-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link DocumentationType }
     *
     */
    public DocumentationType getDocumentation() {
        return documentation;
    }

    /**
     * Legt den Wert der documentation-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link DocumentationType }
     *
     */
    public void setDocumentation(DocumentationType value) {
        this.documentation = value;
    }

    /**
     * Ruft den Wert der intellectualPropertyRights-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link IntellectualPropertyRightsType }
     *
     */
    public IntellectualPropertyRightsType getIntellectualPropertyRights() {
        return intellectualPropertyRights;
    }

    /**
     * Legt den Wert der intellectualPropertyRights-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link IntellectualPropertyRightsType }
     *
     */
    public void setIntellectualPropertyRights(IntellectualPropertyRightsType value) {
        this.intellectualPropertyRights = value;
    }

}


text:
@interface NSMutableURLRequest (OAParameterAdditions)

- (NSArray *)parameters;
- (void)setParameters:(NSArray *)parameters;

@end


text:
=begin
    Copyright 2010-2012 Tasos Laskos <tasos.laskos@gmail.com>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
=end

class Arachni::Reports::HTML

#
# HTML formatter for the results of the WAF Detector plugin
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>
#
class PluginFormatters::WAFDetector < Arachni::Plugin::Formatter

    def run
        ERB.new( tpl ).result( binding )
    end

    def tpl
        <<-HTML

Result

<%=results[:msg]%>

        HTML
    end

end
end


text:
import numpy as np
import re
import itertools
from collections import Counter
import unicodedata

def strip_accents(text):
    """
    Strip accents from input String.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    try:
        text = unicode(text, 'utf-8')
    except NameError: # unicode is a default on python 3
        pass
    text = unicodedata.normalize('NFD', text)
    text = text.encode('ascii', 'ignore')
    text = text.decode("utf-8")
    return str(text)

def clean_str(string):
    """
    Tokenization/string cleaning for all datasets except for SST.
    Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
    """
    string = re.sub("þ", "th", string)
    string = re.sub("Þ", "Th", string)
    string = re.sub("ð", "d", string)
    string = re.sub("Ð", "D", string)
    string = strip_accents(string)
    string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
    string = re.sub(r"\'s", " \'s", string)
    string = re.sub(r"\'ve", " \'ve", string)
    string = re.sub(r"n\'t", " n\'t", string)
    string = re.sub(r"\'re", " \'re", string)
    string = re.sub(r"\'d", " \'d", string)
    string = re.sub(r"\'ll", " \'ll", string)
    string = re.sub(r",", " , ", string)
    string = re.sub(r"!", " ! ", string)
    string = re.sub(r"\(", " \( ", string)
    string = re.sub(r"\)", " \) ", string)
    string = re.sub(r"\?", " \? ", string)
    string = re.sub(r"\s{2,}", " ", string)
    return string.strip().lower()

def load_data_and_labels():
    """
    Loads MR polarity data from files, splits the data into words and generates labels.
    Returns split sentences and labels.
    """
    # Load data from files
    positive_examples = list(open("./data/rt-polaritydata/rt-polarity.pos").readlines())
    positive_examples = [s.strip() for s in positive_examples]
    negative_examples = list(open("./data/rt-polaritydata/rt-polarity.neg").readlines())
    negative_examples = [s.strip() for s in negative_examples]
    # Split by words
    x_text = positive_examples + negative_examples
    x_text = [clean_str(sent) for sent in x_text]
    x_text = [s.split(" ") for s in x_text]
    # Generate labels
    positive_labels = [[0, 1] for _ in positive_examples]
    negative_labels = [[1, 0] for _ in negative_examples]
    y = np.concatenate([positive_labels, negative_labels], 0)
    return [x_text, y]

def pad_sentences(sentences, padding_word="<PAD/>"):
    """
    Pads all sentences to the same length. The length is defined by the longest sentence.
    Returns padded sentences.
    """
    sequence_length = max(len(x) for x in sentences)
    padded_sentences = []
    for i in range(len(sentences)):
        sentence = sentences[i]
        num_padding = sequence_length - len(sentence)
        new_sentence = sentence + [padding_word] * num_padding
        padded_sentences.append(new_sentence)
    return padded_sentences

def build_vocab(sentences):
    """
    Builds a vocabulary mapping from word to index based on the sentences.
    Returns vocabulary mapping and inverse vocabulary mapping.
    """
    # Build vocabulary
    word_counts = Counter(itertools.chain(*sentences))
    # Mapping from index to word
    vocabulary_inv = [x[0] for x in word_counts.most_common()]
    # Mapping from word to index
    vocabulary = {x: i for i, x in enumerate(vocabulary_inv)}
    return [vocabulary, vocabulary_inv]

def build_input_data(sentences, labels, vocabulary):
    """
    Maps sentencs and labels to vectors based on a vocabulary.
    """
    x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences])
    y = np.array(labels)
    return [x, y]

def load_data():
    """
    Loads and preprocessed data for the MR dataset.
    Returns input vectors, labels, vocabulary, and inverse vocabulary.
    """
    # Load and preprocess data
    sentences, labels = load_data_and_labels()
    sentences_padded = pad_sentences(sentences)
    vocabulary, vocabulary_inv = build_vocab(sentences_padded)
    x, y = build_input_data(sentences_padded, labels, vocabulary)
    return [x, y, vocabulary, vocabulary_inv]

def batch_iter(data, batch_size, num_epochs):
    """
    Generates a batch iterator for a dataset.
    """
    data = np.array(data)
    data_size = len(data)
    num_batches_per_epoch = int(len(data)/batch_size) + 1
    for epoch in range(num_epochs):
        # Shuffle the data at each epoch
        shuffle_indices = np.random.permutation(np.arange(data_size))
        shuffled_data = data[shuffle_indices]
        for batch_num in range(num_batches_per_epoch):
            start_index = batch_num * batch_size
            end_index = min((batch_num + 1) * batch_size, data_size)
            yield shuffled_data[start_index:end_index]


text:
// @flow
/* globals ReactClass */

import React from 'react'
import PropTypes from 'prop-types'
import { CHANNEL } from '../models/ThemeProvider'

export default (Component: ReactClass<mixed>) => class extends React.Component {
  static contextTypes = {
    [CHANNEL]: PropTypes.func,
  };

  state: { theme?: ?Object } = {};
  unsubscribe: () => void;

  componentWillMount() {
    if (!this.context[CHANNEL]) {
      throw new Error('[withTheme] Please use ThemeProvider to be able to use withTheme')
    }

    const subscribe = this.context[CHANNEL]
    this.unsubscribe = subscribe(theme => {
      this.setState({ theme })
    })
  }

  componentWillUnmount() {
    if (typeof this.unsubscribe === 'function') this.unsubscribe()
  }

  render() {
    const { theme } = this.state

    return <Component theme={theme} {...this.props} />
  }
}


text:
#pragma once

#include <map>
#include <stdio.h>
#include <vector>
#include <string>
#include <set>

#include "node.h"
#include "scope.h"

namespace llvm {
class AllocaInst;
template<typename T> class ArrayRef;
class BasicBlock;
class BranchInst;
class CallInst;
class Constant;
class Instruction;
class IRBuilderBase;
class LLVMContext;
class Module;
class StructType;
class SwitchInst;
class Type;
class Value;
class GlobalVariable;
}

namespace ebpf {

class TableStorage;

namespace cc {

class BlockStack;
class SwitchStack;

using std::vector;
using std::string;
using std::set;

class CodegenLLVM : public Visitor {
  friend class BlockStack;
  friend class SwitchStack;
 public:
  CodegenLLVM(llvm::Module *mod, Scopes *scopes, Scopes *proto_scopes);
  virtual ~CodegenLLVM();

#define VISIT(type, func) virtual STATUS_RETURN visit_##func(type* n);
  EXPAND_NODES(VISIT)
#undef VISIT

  STATUS_RETURN visit(Node *n, TableStorage &ts, const std::string &id,
                      const std::string &maps_ns);

  int get_table_fd(const std::string &name) const;

 private:
  STATUS_RETURN emit_short_circuit_and(BinopExprNode* n);
  STATUS_RETURN emit_short_circuit_or(BinopExprNode* n);
  STATUS_RETURN emit_table_lookup(MethodCallExprNode* n);
  STATUS_RETURN emit_table_update(MethodCallExprNode* n);
  STATUS_RETURN emit_table_delete(MethodCallExprNode* n);
  STATUS_RETURN emit_log(MethodCallExprNode* n);
  STATUS_RETURN emit_packet_rewrite_field(MethodCallExprNode* n);
  STATUS_RETURN emit_atomic_add(MethodCallExprNode* n);
  STATUS_RETURN emit_cksum(MethodCallExprNode* n);
  STATUS_RETURN emit_incr_cksum(MethodCallExprNode* n, size_t sz = 0);
  STATUS_RETURN emit_lb_hash(MethodCallExprNode* n);
  STATUS_RETURN emit_sizeof(MethodCallExprNode* n);
  STATUS_RETURN emit_get_usec_time(MethodCallExprNode* n);
  STATUS_RETURN emit_forward_to_vnf(MethodCallExprNode* n);
  STATUS_RETURN emit_forward_to_group(MethodCallExprNode* n);
  STATUS_RETURN print_header();

  llvm::LLVMContext & ctx() const;
  llvm::Constant * const_int(uint64_t val, unsigned bits = 64, bool is_signed = false);
  llvm::Value * pop_expr();
  llvm::BasicBlock * resolve_label(const string &label);
  llvm::Instruction * resolve_entry_stack();
  llvm::AllocaInst *make_alloca(llvm::Instruction *Inst, llvm::Type *Ty,
                                const std::string &name = "",
                                llvm::Value *ArraySize = nullptr);
  llvm::AllocaInst *make_alloca(llvm::BasicBlock *BB, llvm::Type *Ty,
                                const std::string &name = "",
                                llvm::Value *ArraySize = nullptr);
  StatusTuple lookup_var(Node *n, const std::string &name, Scopes::VarScope *scope,
                         VariableDeclStmtNode **decl, llvm::Value **mem) const;
  StatusTuple lookup_struct_type(StructDeclStmtNode *decl, llvm::StructType **stype) const;
  StatusTuple lookup_struct_type(VariableDeclStmtNode *n, llvm::StructType **stype,
                                 StructDeclStmtNode **decl = nullptr) const;
  llvm::CallInst *createCall(llvm::Value *Callee,
                             llvm::ArrayRef<llvm::Value *> Args);

  template <typename... Args> void emit(const char *fmt, Args&&... params);
  void emit(const char *s);

  FILE* out_;
  llvm::Module* mod_;
  llvm::IRBuilderBase *b_;
  int indent_;
  int tmp_reg_index_;
  Scopes *scopes_;
  Scopes *proto_scopes_;
  vector<vector<string> > free_instructions_;
  vector<string> table_inits_;
  map<string, string> proto_rewrites_;
  map<TableDeclStmtNode *, llvm::GlobalVariable *> tables_;
  map<TableDeclStmtNode *, int> table_fds_;
  map<VariableDeclStmtNode *, llvm::Value *> vars_;
  map<StructDeclStmtNode *, llvm::StructType *> structs_;
  map<string, llvm::BasicBlock *> labels_;
  llvm::SwitchInst *cur_switch_;
  llvm::Value *expr_;
  llvm::AllocaInst *retval_;
  llvm::AllocaInst *errval_;
};

}  // namespace cc
}  // namespace ebpf


text:
package org.spongepowered.api.text.title;

import com.google.common.base.Objects;
import com.google.common.base.Optional;
import org.spongepowered.api.text.Text;

import javax.annotation.Nullable;

/**
 * Represents an immutable configuration for an in-game title. Instances of this
 * interface can be created through the {@link TitleBuilder} by calling
 * {@link Titles#builder()}.
 *
 *
All properties of a title are optional - if they are not set it will use
 * the current default values from the client.

 */
public class Title {

    protected final Optional<Text> title;
    protected final Optional<Text> subtitle;
    protected final Optional<Integer> fadeIn;
    protected final Optional<Integer> stay;
    protected final Optional<Integer> fadeOut;
    protected final boolean clear;
    protected final boolean reset;

    Title() {
        this(null, null, null, null, null, false, false);
    }

    /**
     * Constructs a new immutable {@link Title} with the specified properties.
     *
     * @param title The main title of the title, or {@code null} for default
     * @param subtitle The subtitle of the title, or {@code null} for default
     * @param fadeIn The fade in time of the title, or {@code null} for default
     * @param stay The stay time of the title, or {@code null} for default
     * @param fadeOut The fade out time of the title, or {@code null} for
     *        default
     * @param clear {@code true} if this title clears the currently displayed
     *        one first
     * @param reset {@code true} if this title resets all settings to default
     *        first
     */
    public Title(@Nullable Text title, @Nullable Text subtitle, @Nullable Integer fadeIn, @Nullable Integer stay, @Nullable Integer fadeOut,
            boolean clear, boolean reset) {
        this.title = Optional.fromNullable(title);
        this.subtitle = Optional.fromNullable(subtitle);
        this.fadeIn = Optional.fromNullable(fadeIn);
        this.stay = Optional.fromNullable(stay);
        this.fadeOut = Optional.fromNullable(fadeOut);
        this.clear = clear;
        this.reset = reset;
    }

    /**
     * Returns the title of this title configuration.
     *
     * @return The {@link Text} of the title, if it was configured
     */
    public final Optional<Text> getTitle() {
        return this.title;
    }

    /**
     * Returns the subtitle of this title configuration.
     *
     * @return The {@link Text} of the subtitle, if it was configured
     */
    public final Optional<Text> getSubtitle() {
        return this.subtitle;
    }

    /**
     * Returns the specified time to fade in the title on the client. Once this
     * period of time is over, the title will stay for the amount of time from
     * {@link #getStay}.
     *
     *
The default value for Vanilla is 20 (1 second).

     *
     * @return The amount of ticks (1/20 second) for the fade in effect
     */
    public final Optional<Integer> getFadeIn() {
        return this.fadeIn;
    }

    /**
     * Returns the specified time how long the title should stay on the client.
     * Once this period of time is over, the title will fade out using the
     * duration specified from {@link #getFadeOut}.
     *
     *
The default value for Vanilla is 60 (3 second).

     *
     * @return The amount of ticks (1/20 second) for the stay effect
     */
    public final Optional<Integer> getStay() {
        return this.stay;
    }

    /**
     * Returns the specified time to fade out the title on the client.
     *
     *
The default value for Vanilla is 20 (1 second).

     *
     * @return The amount of ticks (1/20 second) for the fade out effect
     */
    public final Optional<Integer> getFadeOut() {
        return this.fadeOut;
    }

    /**
     * Returns whether this configuration is clearing the current title from the
     * screen.
     *
     * @return True if the current title will be removed from the client's
     *         screen
     */
    public final boolean isClear() {
        return this.clear;
    }

    /**
     * Returns whether this configuration is clearing the current title from the
     * screen and resetting the current configuration to the default values.
     *
     *
This is recommended when you want to make sure to display a single
     * title.

     *
     * @return True if the current settings will be reset to the defaults
     */
    public final boolean isReset() {
        return this.reset;
    }

    /**
     * Creates a new {@link TitleBuilder} using the configuration of this
     * instance.
     *
     * @return A new builder to modify this Title configuration
     */
    public TitleBuilder builder() {
        return new TitleBuilder(this);
    }

    @Override
    public boolean equals(@Nullable Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Title)) {
            return false;
        }

        Title that = (Title) o;
        return this.title.equals(that.title)
                && this.subtitle.equals(that.subtitle)
                && this.fadeIn.equals(that.fadeIn)
                && this.stay.equals(that.stay)
                && this.fadeOut.equals(that.fadeOut)
                && this.clear == that.clear
                && this.reset == that.reset;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.title, this.subtitle, this.fadeIn, this.stay, this.fadeOut, this.clear, this.reset);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("title", this.title)
                .add("subtitle", this.subtitle)
                .add("fadeIn", this.fadeIn)
                .add("stay", this.stay)
                .add("fadeOut", this.fadeOut)
                .add("clear", this.clear)
                .add("reset", this.reset)
                .toString();
    }

}


text:
#include <aws/route53/model/ListHealthChecksResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>

#include <utility>

using namespace Aws::Route53::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws;

ListHealthChecksResult::ListHealthChecksResult() :
    m_isTruncated(false)
{
}

ListHealthChecksResult::ListHealthChecksResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) :
    m_isTruncated(false)
{
  *this = result;
}

ListHealthChecksResult& ListHealthChecksResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode resultNode = xmlDocument.GetRootElement();

  if(!resultNode.IsNull())
  {
    XmlNode healthChecksNode = resultNode.FirstChild("HealthChecks");
    if(!healthChecksNode.IsNull())
    {
      XmlNode healthChecksMember = healthChecksNode.FirstChild("HealthCheck");
      while(!healthChecksMember.IsNull())
      {
        m_healthChecks.push_back(healthChecksMember);
        healthChecksMember = healthChecksMember.NextNode("HealthCheck");
      }

    }
    XmlNode markerNode = resultNode.FirstChild("Marker");
    if(!markerNode.IsNull())
    {
      m_marker = Aws::Utils::Xml::DecodeEscapedXmlText(markerNode.GetText());
    }
    XmlNode isTruncatedNode = resultNode.FirstChild("IsTruncated");
    if(!isTruncatedNode.IsNull())
    {
      m_isTruncated = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(isTruncatedNode.GetText()).c_str()).c_str());
    }
    XmlNode nextMarkerNode = resultNode.FirstChild("NextMarker");
    if(!nextMarkerNode.IsNull())
    {
      m_nextMarker = Aws::Utils::Xml::DecodeEscapedXmlText(nextMarkerNode.GetText());
    }
    XmlNode maxItemsNode = resultNode.FirstChild("MaxItems");
    if(!maxItemsNode.IsNull())
    {
      m_maxItems = Aws::Utils::Xml::DecodeEscapedXmlText(maxItemsNode.GetText());
    }
  }

  return *this;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="action_settings">Nastavenia</string>
    <string name="action_help">Pomocník</string>

    <string name="activity_preferences_title">Nastavenia</string>
    <string name="activity_help_title">Pomocník</string>

    <string name="action_edit">Upraviť</string>
    <string name="action_delete">Vymazať</string>

    <string name="pref_auth_title">Overovanie</string>
    <string name="pref_email_title">E-mail</string>
    <string name="pref_email_summary">Vaša e-mailová Gmail adresa</string>
    <string name="pref_password_title">Heslo</string>
    <string name="pref_password_summary">Vaše Gmail heslo</string>
    <string name="pref_gsfid_title">ID frameworku Google služieb</string>
    <string name="pref_gsfid_summary">ID frameworku Google služieb (ak nemáte nainštalované Google služby, je potrebné zadať ID ručne)</string>

    <string name="pref_options_title">Možnosti</string>
    <string name="pref_autoinstall_title">Automaticky inštalovať aplikácie</string>
    <string name="pref_autoinstall_summary">Automaticky inštalovať aplikácie po ich stiahnutí</string>

    <string name="error_unrecognized_login">Nemožno overiť - prosím, zadajte platné prihlasovacie údaje v nastaveniach</string>
    <string name="error_api_exception">API výnimka: %s</string>
    <string name="error_empty_id">Prosím, zadajte platné ID aplikácie</string>
    <string name="error_no_connection">Žiadne pripojenie</string>

    <string name="app_package">Balík:</string>
    <string name="download">Stiahnúť</string>
    <string name="downloads">Sťahovania</string>
    <string name="app_downloading">Sťahovanie aplikácie...</string>

</resources>


text:
import React, {Component} from 'react'

export default class TestComponent extends Component {
  render() {
    return (

Working page

    )
  }
}


text:
<!DOCTYPE html>

  <title>
    Kadet Klub
  </title>

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css?family=Love+Ya+Like+A+Sister" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              Toggle navigation

            </button>
          Kadet Klub

Home

Staff

Gallery

Documents

Contact Us

Meet Our Staff

 Mr McMaster Principal

 As the principal of Drumahoe Primary School Mr McMaster and the Board of Governors have full responsibility for the management of Kadet Klub.

 Heather Glenn Bursar/Manager

 As the Bursar/Manager Heather has a responsibility for the daily running of Kadet Klub.

 Tracy Lovell Play Leader

 "Working at Kadet Klub is challenging but rewarding. It's great to see the kids having fun in a relaxed atmosphere. It makes it worthwhile when you can see a smile on their faces. At Kadet Klub the staff work well together and this also makes my job enjoyable. Not only is it about the kids but it's great getting to know the parents too and to know that their trust is in us to care for their children."

 Rebecca Watson Play Worker

 "I enjoy working in Kadet Klub as no two days are the same. I enjoy working with the children and watching them grow from P1-P7. I find it rewarding to see the children develop socially as they make new friends with their peers and come out of their shells through the activities planned. Kadet Klub is enjoyable, meeting new people all the time."

 Katherine McCandless Play Worker

 "Everyday I enjoy working at Kadet Klub as kids are a lot of fun to work with. Their honesty and sense of humour make it all worthwhile. Watching each child learn and grow differently as they progress through the school can be very rewarding."

 Lisa Curry Play Worker

 "I like working in Kadet Klub as it is a warm and friendly environment, where all staff work together in a very positive way. On a daily basis there are a range of children who look forward to the different activities planned for them. All children
          have their own unique personality, and within Kadet Klub they all get the opportunity to express this through art, music and play. I look forward to Kadet Klub everyday as there are different children who attend, and always tell me funny stories
          about what happened them at home or in class."

 Phoebe Love Play Worker

 "I enjoy working with the children in Kadet Klub. The activities are planned to include all abilities and age groups which gives each child a sense of belonging."

 Lauren Miller Play Worker

 "Working with the pupils in Kadet Klub is very rewarding. As I get to know the pupils,  I get to see their individual character which can be totally different in the relaxed atmosphere of Kadet Klub."

 Quick Links

 Home

 Staff

 Gallery

 Documents

 Contact Us

 Find Us

 Useful Links

 Drumahoe Primary School


text:
@extends('admin.layouts.modal')
{{-- Content --}}
@section('content')

 {{
			trans("admin/modal.general") }}

@if (isset($user))
{!! Form::model($user, array('url' => URL::to('admin/user') . '/' . $user->id, 'method' => 'put', 'class' => 'bf', 'files'=> true)) !!}
@else
{!! Form::open(array('url' => URL::to('admin/user'), 'method' => 'post', 'class' => 'bf', 'files'=> true)) !!}
@endif

        @include('admin.user.create_edit_form')

            <button type="reset" class="btn btn-sm btn-warning close_popup">
                 {{
				trans("admin/modal.cancel") }}
            </button>
            <button type="reset" class="btn btn-sm btn-default">
                 {{
				trans("admin/modal.reset") }}
            </button>
            <button type="submit" class="btn btn-sm btn-success">

                @if	(isset($user))
                    {{ trans("admin/modal.edit") }}
                @else
                    {{trans("admin/modal.create") }}
                @endif
            </button>

    {!! Form::close() !!}
    @stop @section('scripts')

@stop


text:
"""
@author: yanjianlong
@contact: yanjianlong@126.com
@time: 7/19/2016 9:28 PM
"""

import urllib.request
import bs4
import bs4.element
import time
import send_msg.weixin

class GetFirstElement(object):
    def __init__(self):
        self.__url = "http://kx.fx678.com/"
        self.__headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')

    def get_html_page(self):
        opener = urllib.request.build_opener()
        opener.addheaders = [self.__headers]
        return opener.open(self.__url).read()

    def has_class_id_level(self, tag):
        return tag.has_attr("class") and tag.has_attr("id") and tag.has_attr("level")

    def get_first_element(self):
        data = self.get_html_page()
        bs4_obj = bs4.BeautifulSoup(data, "html.parser")
        result = bs4_obj.find_all(self.has_class_id_level, limit=1)
        if not result:
            return None
        return result[0]

def get_last_time_content():
    obj = GetFirstElement()
    element = obj.get_first_element()
    time_content, result = "", ""
    if element != None:
        time_content = element.find_all("div", class_="gray_text", limit=1)[0].contents[0]
        contents = element.find_all("div", class_="gray_font", limit=1)[0].contents
        for content in contents:
            if isinstance(content, bs4.element.Tag):
                continue
            # if re.search(r"<.*>", content, re.M|re.I):
            #     continue
            result += content
    return time_content, result

def main():
    last_time = ""
    while True:
        try:
            weixin_instance = send_msg.weixin.get_weixin_instance()
            time_string, content = get_last_time_content()
            content.replace("\n", "", -1)
            if last_time != time_string:
                last_time = time_string
                for group in weixin_instance.GroupList:
                    weixin_instance.sendMsg(group['UserName'], content, False)
                # print(last_time, content)
            time.sleep(400)
        except BaseException as e:
            print("GetFirstElement Error:", e)

if __name__ == "__main__":
    main()


text:
package fm.flycast;

import java.util.Vector;

public class DPXMLMessageList  extends DPXMLObject
{

	DPXMLMessageList ()
	{
      type = DPXMLObject.DPMESSAGELIST;
      children = new Vector<DPXMLObject>();
  }

}


text:
namespace Apache.Ignite.Core.Compute
{
    using System;
    using System.Runtime.Serialization;
    using Apache.Ignite.Core.Common;

    /// <summary>
    /// Indicates a situation when execution service provided by the user in configuration rejects execution.
    /// </summary>
    [Serializable]
    public class ComputeExecutionRejectedException : IgniteException
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ComputeExecutionRejectedException"/> class.
        /// </summary>
        public ComputeExecutionRejectedException()
        {
            // No-op.
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComputeExecutionRejectedException" /> class.
        /// </summary>
        /// <param name="message">The message that describes the error.</param>
        public ComputeExecutionRejectedException(string message)
            : base(message)
        {
            // No-op.
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComputeExecutionRejectedException"/> class.
        /// </summary>
        /// <param name="info">Serialization information.</param>
        /// <param name="ctx">Streaming context.</param>
        protected ComputeExecutionRejectedException(SerializationInfo info, StreamingContext ctx)
            : base(info, ctx)
        {
            // No-op.
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComputeExecutionRejectedException"/> class.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="cause">The cause.</param>
        public ComputeExecutionRejectedException(string message, Exception cause) : base(message, cause)
        {
            // No-op.
        }
    }
}


text:
"""SCons.Tool.pyext

Tool-specific initialization for python extensions builder.

AUTHORS:
 - David Cournapeau
 - Dag Sverre Seljebotn

"""

#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import sys

import SCons
from SCons.Tool import SourceFileScanner, ProgramScanner

#  Create common python builders

def createPythonObjectBuilder(env):
    """This is a utility function that creates the PythonObject Builder in an
    Environment if it is not there already.

    If it is already there, we return the existing one.
    """

    try:
        pyobj = env['BUILDERS']['PythonObject']
    except KeyError:
        pyobj = SCons.Builder.Builder(action = {},
                                      emitter = {},
                                      prefix = '$PYEXTOBJPREFIX',
                                      suffix = '$PYEXTOBJSUFFIX',
                                      src_builder = ['CFile', 'CXXFile'],
                                      source_scanner = SourceFileScanner,
                                      single_source = 1)
        env['BUILDERS']['PythonObject'] = pyobj

    return pyobj

def createPythonExtensionBuilder(env):
    """This is a utility function that creates the PythonExtension Builder in
    an Environment if it is not there already.

    If it is already there, we return the existing one.
    """

    try:
        pyext = env['BUILDERS']['PythonExtension']
    except KeyError:
        import SCons.Action
        import SCons.Defaults
        action = SCons.Action.Action("$PYEXTLINKCOM", "$PYEXTLINKCOMSTR")
        action_list = [ SCons.Defaults.SharedCheck,
                        action]
        pyext = SCons.Builder.Builder(action = action_list,
                                      emitter = "$SHLIBEMITTER",
                                      prefix = '$PYEXTPREFIX',
                                      suffix = '$PYEXTSUFFIX',
                                      target_scanner = ProgramScanner,
                                      src_suffix = '$PYEXTOBJSUFFIX',
                                      src_builder = 'PythonObject')
        env['BUILDERS']['PythonExtension'] = pyext

    return pyext

def pyext_coms(platform):
    """Return PYEXTCCCOM, PYEXTCXXCOM and PYEXTLINKCOM for the given
    platform."""
    if platform == 'win32':
        pyext_cccom = "$PYEXTCC /Fo$TARGET /c $PYEXTCCSHARED "\
                      "$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
                      "$_PYEXTCPPINCFLAGS $SOURCES"
        pyext_cxxcom = "$PYEXTCXX /Fo$TARGET /c $PYEXTCSHARED "\
                       "$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
                       "$_PYEXTCPPINCFLAGS $SOURCES"
        pyext_linkcom = '${TEMPFILE("$PYEXTLINK $PYEXTLINKFLAGS '\
                        '/OUT:$TARGET.windows $( $_LIBDIRFLAGS $) '\
                        '$_LIBFLAGS $_PYEXTRUNTIME $SOURCES.windows")}'
    else:
        pyext_cccom = "$PYEXTCC -o $TARGET -c $PYEXTCCSHARED "\
                      "$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
                      "$_PYEXTCPPINCFLAGS $SOURCES"
        pyext_cxxcom = "$PYEXTCXX -o $TARGET -c $PYEXTCSHARED "\
                       "$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
                       "$_PYEXTCPPINCFLAGS $SOURCES"
        pyext_linkcom = "$PYEXTLINK -o $TARGET $PYEXTLINKFLAGS "\
                        "$SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_PYEXTRUNTIME"

    if platform == 'darwin':
        pyext_linkcom += ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'

    return pyext_cccom, pyext_cxxcom, pyext_linkcom

def set_basic_vars(env):
    # Set construction variables which are independent on whether we are using
    # distutils or not.
    env['PYEXTCPPPATH'] = SCons.Util.CLVar('$PYEXTINCPATH')

    env['_PYEXTCPPINCFLAGS'] = '$( ${_concat(INCPREFIX, PYEXTCPPPATH, '\
                               'INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
    env['PYEXTOBJSUFFIX'] = '$SHOBJSUFFIX'
    env['PYEXTOBJPREFIX'] = '$SHOBJPREFIX'

    env['PYEXTRUNTIME']   = SCons.Util.CLVar("")
    # XXX: this should be handled with different flags
    env['_PYEXTRUNTIME']  = '$( ${_concat(LIBLINKPREFIX, PYEXTRUNTIME, '\
                          'LIBLINKSUFFIX, __env__)} $)'
    # XXX: This won't work in all cases (using mingw, for example). To make
    # this work, we need to know whether PYEXTCC accepts /c and /Fo or -c -o.
    # This is difficult with the current way tools work in scons.
    pycc, pycxx, pylink = pyext_coms(sys.platform)

    env['PYEXTLINKFLAGSEND'] = SCons.Util.CLVar('$LINKFLAGSEND')

    env['PYEXTCCCOM'] = pycc
    env['PYEXTCXXCOM'] = pycxx
    env['PYEXTLINKCOM'] = pylink

def _set_configuration_nodistutils(env):
    # Set env variables to sensible values when not using distutils
    def_cfg = {'PYEXTCC' : '$SHCC',
               'PYEXTCFLAGS' : '$SHCFLAGS',
               'PYEXTCCFLAGS' : '$SHCCFLAGS',
               'PYEXTCXX' : '$SHCXX',
               'PYEXTCXXFLAGS' : '$SHCXXFLAGS',
               'PYEXTLINK' : '$LDMODULE',
               'PYEXTSUFFIX' : '$LDMODULESUFFIX',
               'PYEXTPREFIX' : ''}

    if sys.platform == 'darwin':
        def_cfg['PYEXTSUFFIX'] = '.so'

    for k, v in def_cfg.items():
        ifnotset(env, k, v)

    ifnotset(env, 'PYEXT_ALLOW_UNDEFINED',
             SCons.Util.CLVar('$ALLOW_UNDEFINED'))
    ifnotset(env, 'PYEXTLINKFLAGS', SCons.Util.CLVar('$LDMODULEFLAGS'))

    env.AppendUnique(PYEXTLINKFLAGS = env['PYEXT_ALLOW_UNDEFINED'])

def ifnotset(env, name, value):
    if name not in env:
        env[name] = value

def set_configuration(env, use_distutils):
    """Set construction variables which are platform dependants.

    If use_distutils == True, use distutils configuration. Otherwise, use
    'sensible' default.

    Any variable already defined is untouched."""

    # We define commands as strings so that we can either execute them using
    # eval (same python for scons and distutils) or by executing them through
    # the shell.
    dist_cfg = {'PYEXTCC': ("sysconfig.get_config_var('CC')", False),
                'PYEXTCFLAGS': ("sysconfig.get_config_var('CFLAGS')", True),
                'PYEXTCCSHARED': ("sysconfig.get_config_var('CCSHARED')", False),
                'PYEXTLINKFLAGS': ("sysconfig.get_config_var('LDFLAGS')", True),
                'PYEXTLINK': ("sysconfig.get_config_var('LDSHARED')", False),
                'PYEXTINCPATH': ("sysconfig.get_python_inc()", False),
                'PYEXTSUFFIX': ("sysconfig.get_config_var('SO')", False)}

    from distutils import sysconfig

    # We set the python path even when not using distutils, because we rarely
    # want to change this, even if not using distutils
    ifnotset(env, 'PYEXTINCPATH', sysconfig.get_python_inc())

    if use_distutils:
        for k, (v, should_split) in dist_cfg.items():
            val = eval(v)
            if should_split:
                val = val.split()
            ifnotset(env, k, val)
    else:
        _set_configuration_nodistutils(env)

def generate(env):
    """Add Builders and construction variables for python extensions to an
    Environment."""

    if 'PYEXT_USE_DISTUTILS' not in env:
        env['PYEXT_USE_DISTUTILS'] = False

    # This sets all constructions variables used for pyext builders.
    set_basic_vars(env)

    set_configuration(env, env['PYEXT_USE_DISTUTILS'])

    # Create the PythonObject builder
    pyobj = createPythonObjectBuilder(env)
    action = SCons.Action.Action("$PYEXTCCCOM", "$PYEXTCCCOMSTR")
    pyobj.add_emitter('.c', SCons.Defaults.SharedObjectEmitter)
    pyobj.add_action('.c', action)

    action = SCons.Action.Action("$PYEXTCXXCOM", "$PYEXTCXXCOMSTR")
    pyobj.add_emitter('$CXXFILESUFFIX', SCons.Defaults.SharedObjectEmitter)
    pyobj.add_action('$CXXFILESUFFIX', action)

    # Create the PythonExtension builder
    createPythonExtensionBuilder(env)

def exists(env):
    try:
        # This is not quite right: if someone defines all variables by himself,
        # it would work without distutils
        from distutils import sysconfig
        return True
    except ImportError:
        return False


text:
#region License

#endregion
namespace System.Threading
{
    public sealed class SingleEntryGate
    {
        private int _status;
        //private const int ENTERED = 1;
        //private const int NOT_ENTERED = 0;

        public bool TryEnter()
        {
            return (Interlocked.Exchange(ref _status, 1) == 0);
        }
    }
}


text:
var autotrans = window.autotrans || {};

autotrans.jsonLocation = window.location.pathname+'.json';

autotrans.language = 'en';

autotrans.setLanguage = function(lang){
    if(typeof(lang)==='string'){
        autotrans.language = lang;
    }else{
        autotrans.language = autotrans.getBroswerLanguage();
    }
};

autotrans.getBroswerLanguage = function(){
    if (window.navigator.languages != undefined)
        return window.navigator.languages[0];
    else
        return window.navigator.language;
};

autotrans.translate = function(){

};

autotrans.getTranslationData = function(callback){

};

autotrans.ajaxGet = function(url, callback){
    /*global ActiveXObject*/
    var callback = (typeof callback == 'function' ? callback : false), xhr = null;
    try{
      xhr = new XMLHttpRequest();
    }catch(e){
      try{
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
      }catch(e){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    if(!xhr) return null;
    xhr.open("GET", url,true);
    xhr.onreadystatechange=function(){
      if(xhr.readyState==4 && callback){
        callback(xhr.responseText);
      }
    };
    xhr.send(null);
    return xhr;
};


text: Template based on Xiaoying Riley's design. Content my own (duh). Details in my Github project.


text:
<?php

/**
 * Smew - Awesome CMS based on File
 *
 * @package  Smew
 * @author   Jonathan Fontes <jonathan.alexey16@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/

require __DIR__.'/../vendor/autoload.php';

use Gravatalonga\Smew\File\Filesystem;

$app = new Gravatalonga\Smew\App(
    realpath(__DIR__.'/../')
);

$files = $app['finder'];
$file = new Filesystem();
foreach ($files as $k => $v) {
    var_dump($v);
    exit;
}


text:
require 'luban'
require_relative 'rack/base'
require_relative 'rack/paths'
require_relative 'rack/web_server'
require_relative 'rack/controller'
require_relative 'rack/configurator'
require_relative 'rack/publisher'
require_relative 'rack/version'


text:
#region Nequeo Pty Ltd License
/*
    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;

namespace Nequeo.Wpf.Controls
{
    [ValueConversion(typeof(CornerRadius),typeof(CornerRadius))]
    class RoundedCornerConverter:IValueConverter
    {
        #region IValueConverter Members

        /// <summary>
        /// Converts a RoundedCorner property to an appropriate value.
        /// </summary>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            CornerRadius cr = (CornerRadius)value;
            string s = parameter as string;
            switch (s)
            {
                case "left":
                    return new CornerRadius(cr.TopLeft, 0d, 0d, cr.BottomLeft);

                case "right":
                    return new CornerRadius(0d, cr.TopRight, cr.BottomRight, 0d);

                case "top":
                    return new CornerRadius(cr.TopLeft, cr.TopRight, 0d, 0d);

                case "bottom":
                    return new CornerRadius(0d, 0d, cr.BottomRight, cr.BottomLeft);

                default:
                    return null;
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Blueprint41.Neo4j.Schema
{
    public class ApplyConstraintProperty
    {
        internal ApplyConstraintProperty(ApplyConstraintEntity parent, Property property, params ApplyConstraintAction[] commands)
        {
            Parent = parent;
            Property = property.Name;
            Commands = commands;
        }

        internal ApplyConstraintProperty(ApplyConstraintEntity parent, string property, params ApplyConstraintAction[] commands)
        {
            Parent = parent;
            Property = property;
            Commands = commands;
        }

        protected ApplyConstraintEntity Parent { get; set; }

        public string Property { get; protected set; }
        public IReadOnlyList<ApplyConstraintAction> Commands { get; protected set; }

        /// <summary>
        /// Turns actions into cypher queries.
        /// </summary>
        /// <returns></returns>
        internal virtual List<string> ToCypher()
        {
            List<string> commands = new List<string>();
            foreach (var command in Commands)
            {
                switch (command)
                {
                    case ApplyConstraintAction.CreateIndex:
                        commands.Add($"CREATE INDEX ON :{Parent.Entity.Label.Name}({Property})");
                        break;
                    case ApplyConstraintAction.CreateUniqueConstraint:
                        commands.Add($"CREATE CONSTRAINT ON (node:{Parent.Entity.Label.Name}) ASSERT node.{Property} IS UNIQUE");
                        break;
                    case ApplyConstraintAction.CreateExistsConstraint:
                        commands.Add($"CREATE CONSTRAINT ON (node:{Parent.Entity.Label.Name}) ASSERT exists(node.{Property})");
                        break;
                    case ApplyConstraintAction.DeleteIndex:
                        commands.Add($"DROP INDEX ON :{Parent.Entity.Label.Name}({Property})");
                        break;
                    case ApplyConstraintAction.DeleteUniqueConstraint:
                        commands.Add($"DROP CONSTRAINT ON (node:{Parent.Entity.Label.Name}) ASSERT node.{Property} IS UNIQUE");
                        break;
                    case ApplyConstraintAction.DeleteExistsConstraint:
                        commands.Add($"DROP CONSTRAINT ON (node:{Parent.Entity.Label.Name}) ASSERT exists(node.{Property})");
                        break;
                    default:
                        break;
                }
            }

            foreach (var command in commands)
            {
                Debug.WriteLine(command);
            }

            return commands;
        }

        public override string ToString()
        {
            string diff = string.Join(", ", Commands.Select(item => item.ToString()).ToArray());
            return $"Differences for {Parent.Entity.Name}.{Property} -> {diff}";
        }
    }
}


text:
#ifndef ITKLINEHISTOGRAMBASEDMASSIMAGEFILTER_CPP
#define ITKLINEHISTOGRAMBASEDMASSIMAGEFILTER_CPP

#include <itkLineHistogramBasedMassImageFilter.h>
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkBinaryContourImageFilter.h>
#include <mitkImageCast.h>
#include <mitkIOUtil.h>

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
void itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>
::BeforeThreadedGenerateData()
{

  if(m_ImageMask.IsNull())
  {
    itkExceptionMacro("No binary mask image provided.")
  }

  if(m_BinaryContour.IsNull()){

    typename TMaskImageType::RegionType region = m_ImageMask->GetLargestPossibleRegion();
    unsigned int xdim = region.GetSize(0);
    unsigned int ydim = region.GetSize(1);
    unsigned int zdim = region.GetSize(2);

    // ensure border pixels are zero so that an closed contour is created
    typename TMaskImageType::Pointer mask_copy = TMaskImageType::New();
    mask_copy->SetSpacing(m_ImageMask->GetSpacing());
    mask_copy->SetDirection(m_ImageMask->GetDirection());
    mask_copy->SetOrigin(m_ImageMask->GetOrigin());
    mask_copy->SetRegions(region);
    mask_copy->Allocate();
    mask_copy->FillBuffer(0);

    itk::ImageRegionIteratorWithIndex<TMaskImageType> oit(mask_copy, mask_copy->GetLargestPossibleRegion());
    itk::ImageRegionConstIteratorWithIndex<TMaskImageType> mit(m_ImageMask, m_ImageMask->GetLargestPossibleRegion());
    while(!mit.IsAtEnd())
    {
      if(mit.Value() != 0 //is under the mask
         && mit.GetIndex()[0] != 0 //is not at the border
         && mit.GetIndex()[1] != 0
         && mit.GetIndex()[2] != 0
         && mit.GetIndex()[0] != xdim-1
         && mit.GetIndex()[1] != ydim-1
         && mit.GetIndex()[2] != zdim-1)
      {
        oit.Set(1);
      }
      ++mit;
      ++oit;
    }

    typedef itk::BinaryContourImageFilter<TMaskImageType,TMaskImageType> BinaryContourImagefilterType;
    typename BinaryContourImagefilterType::Pointer filter = BinaryContourImagefilterType::New();
    filter->SetInput(mask_copy);
    filter->SetBackgroundValue(0);
    filter->SetForegroundValue(1);
    filter->SetFullyConnected(true);
    filter->Update();

    m_BinaryContour = filter->GetOutput();
    mitk::Image::Pointer outimg;
    mitk::CastToMitkImage(m_BinaryContour,outimg);
  }

  if(m_BinaryContour.IsNull())
  {
    itkExceptionMacro("No binary contour image provided.")
  }

  m_CenterOfMask = GetCenterOfMass(m_ImageMask);

  if(m_CenterOfMask.is_zero())
  {
    itkExceptionMacro("Center of mass is corrupt.")
  }

}

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
vnl_vector<double> itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>
::GetCenterOfMass(const TMaskImageType * maskImage)
{
  mitk::Image::Pointer img;
  mitk::CastToMitkImage(maskImage, img);

  typedef itk::ImageRegionConstIterator< TMaskImageType > IteratorType;
  IteratorType iter( maskImage, maskImage->GetLargestPossibleRegion() );
  iter.GoToBegin();

  vnl_vector_fixed<double,3> mean_index;
  mean_index.fill(0);
  unsigned int count = 0;
  while ( !iter.IsAtEnd() )
  {
    if ( iter.Get() != 0 )
    {
      mitk::Point3D current_index_pos;
      img->GetGeometry()->IndexToWorld(iter.GetIndex(),current_index_pos);
      mean_index += current_index_pos.GetVnlVector();
      count++;
    }
    ++iter;
  }

  mean_index /= count;
  return mean_index.as_ref();
}

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
void itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>
::ThreadedGenerateData(const typename Superclass::OutputImageRegionType &outputRegionForThread, ThreadIdType /*threadId*/)
{

  TOutputImageType * outimage = this->GetOutput();

  itk::ImageRegionConstIteratorWithIndex<TMaskImageType> cit(m_BinaryContour, outputRegionForThread);
  itk::ImageRegionConstIteratorWithIndex<TInputImageType> iit(this->GetInput(), outputRegionForThread);
  itk::ImageRegionIteratorWithIndex<TOutputImageType > oit(outimage,outputRegionForThread);
  typedef typename itk::ImageRegionIteratorWithIndex<TInputImageType >::IndexType IndexType;

  std::vector<IndexType> target_world_indices;

  while(!cit.IsAtEnd())
  {
    if(cit.Value() != 0 )
      target_world_indices.push_back(cit.GetIndex());
    ++cit;
  }

  mitk::Image::Pointer image;
  mitk::CastToMitkImage(this->GetInput(), image);
  mitk::BaseGeometry * transform = image->GetGeometry();

  while(!target_world_indices.empty())
  {
    vnl_vector<double> u_v(3,1), x_v(3,1), p_v(3,1);
    double line_histo_area = 0;

    // w->i skull point
    mitk::Point3D skull_point, tmp_point;
    image->GetGeometry()->IndexToWorld(target_world_indices.back(),skull_point);

    // project centerpoint to slice
    // x = p + s*u
    u_v = skull_point.GetVnlVector() - m_CenterOfMask;
    u_v.normalize();

    p_v = m_CenterOfMask;

    //step width
    double s_s = 0.1;

    // i->w center point
    mitk::Point3D center_point;
    center_point[0] = m_CenterOfMask[0];
    center_point[1] = m_CenterOfMask[1];
    center_point[2] = m_CenterOfMask[2];
    IndexType tmp_index;
    transform->WorldToIndex(center_point,tmp_index);
    oit.SetIndex(tmp_index);

    std::vector<IndexType> under_line_indices;

    while(true)
    {

      // store current_index
      under_line_indices.push_back(tmp_index);

      // set histo value
      iit.SetIndex(tmp_index);
      line_histo_area += iit.Value();

      // break in end reached
      if(tmp_index == target_world_indices.back())
      {
        break;
      }

      // get next voxel index under the line
      while(tmp_index == oit.GetIndex()) // if new voxel index reached brake
      {
        x_v = p_v + s_s * u_v; // next
        tmp_point.GetVnlVector().set(x_v.data_block());
        transform->WorldToIndex(tmp_point, tmp_index);
        s_s+=0.1;
      }

      oit.SetIndex(tmp_index);
    }

    while (!under_line_indices.empty()) {
      IndexType current_index = under_line_indices.back();
      under_line_indices.pop_back();

      oit.SetIndex(current_index);
      oit.Set(line_histo_area / (s_s * u_v).magnitude() );
    }

    target_world_indices.pop_back();

  }

}

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
void itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>::SetImageMask(TMaskImageType * maskimage)
{
  this->m_ImageMask = maskimage;
}

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
void itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>::SetBinaryContour(TMaskImageType * binarycontour)
{
  this->m_BinaryContour = binarycontour;
}

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>::LineHistogramBasedMassImageFilter()
{
  this->DynamicMultiThreadingOff();
  this->SetNumberOfIndexedOutputs(1);
  this->SetNumberOfIndexedInputs(1);

  m_CenterOfMask.fill(0);
}

template< class TInputImageType, class TOutputImageType, class TMaskImageType>
itk::LineHistogramBasedMassImageFilter<TInputImageType,TOutputImageType,TMaskImageType>::~LineHistogramBasedMassImageFilter()
{

}

#endif


text:
Connect to a database
```
psql -U [user_name] -d [dbname]
```

Connect and show internal queries
```
psql -U postgres -E
```

Execute a SQL script
```
psql -U [user_name] -d [dbname] -f [file_name.sql]
```

##Backup

to a zipped dump file
```
pg_dump -U postgres -Fc -f [file_name.dump] [dbname]
```

to a script file
```
pg_dump -U postgres -f [file_name.sql] [dbname]
```

a single table
```
pg_dump -U postgres -Fc -a -t [table_name] -f [file_name.dump] [dbname]
```

##Restore

a database from a dump file (the database doesn't exist and is named by the dump)
```
pg_restore -U [ user_name] -d template1 -C -j [threads] [file_name.dump]

```

an existing database from a dump file
```
pg_restore -U [ user_name] -d [dbname] -x -j [threads] [file_name.dump]

```

a single table from a dump file
```
psql -U [user_name] -d [dbname] -c "truncate table [table_name];"
pg_restore -U [user_name] -d [dbname] -t [table_name] [file_name.dump]
```

##Create a new database

```SQL
DROP DATABASE IF EXISTS [dbname];
CREATE DATABASE [dbname] ENCODING 'UTF-8' OWNER [user_name];
\c [dbname]
DROP EXTENSION IF EXISTS plpgsql;
```

##Administrator SQL commands

Show running queries
```SQL
SELECT * FROM pg_stat_activity;
```

Cancel a query
```SQL
SELECT pg_cancel_backend(pid);
```

Cancel a query and close connection
```SQL
SELECT pg_terminate_backend(pid);
```

Show postgres settings
```SQL
SELECT name, setting, boot_val, reset_val, unit FROM pg_settings ORDER BY name;
```

Reload configuration
```SQL
SELECT pg_reload_conf();
```

Show last autovacuum
```SQL
SELECT last_autovacuum, last_autoanalyze FROM pg_stat_user_tables
    WHERE last_autovacuum IS NOT NULL
    ORDER BY last_autovacuum DESC;
```

Show size of databases
```SQL
SELECT datname,pg_size_pretty(pg_database_size(datname)) AS size FROM pg_database;
```

Show duplicate records
```SQL
SELECT * FROM table_name t1
    WHERE (SELECT count(*) FROM table_name t2
               WHERE t1.field1=t2.field1 AND t1.field2=t2.field2) > 1;
```

Count duplicate records
```SQL
SELECT field1, field2, count(*) FROM table_name GROUP BY field1, field2 HAVING count(*)>1;
```

Duplicate a table
```SQL
CREATE TABLE target_name AS TABLE table_name;
```

Copy some data from a table to a new one
```SQL
CREATE TABLE target_name AS SELECT field1, field2 FROM table_name WHERE condition;
```

Convert timestamp to epoch (int)
```SQL
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2015-03-01 00:00:00');
```

Convert epoch to timestamp
```SQL
SELECT TO_TIMESTAMP(1425168000);
```


text:
This repo contains a tool to mirror pull requests metadata into the corresponding git
repository using a feature of git called [git-notes](http://git-scm.com/docs/git-notes).

The format written is the one defined by the
[git-appraise code review system](https://github.com/google/git-appraise), so pull
requests that are mirrored using this tool can be reviewed using git-appraise.

## Disclaimer

This is not an officially supported Google product.

## Organization

There are 3 packages in this repo:
- `mirror` is a go library for mirroring the pull request metadata into git-notes.
- `batch` is a batch processor to mirror Github data into a local repository.
- `app` is a webapp/bot that sets up Github webhooks and mirrors data incrementally
  whenever an interesting event happens on the Github repo.

### The Batch Tool

The batch tool performs a single pass of reading all of the pull request metadata for
a repo, and mirroring it into your local clone of that repo.

The tool can support running unauthenticated, but will be extremely rate-limited, so
it is better if you create a [personal access token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/),
with the `repo` scope, for it to use.

Setup:

```shell
go get github.com/google/git-pull-request-mirror/batch
go build -o ~/bin/pr-mirror "${GOPATH}/src/github.com/google/git-pull-request-mirror/batch/batch.go"
```

Example Usage (after you've cloned the repo to mirror):

```shell
git fetch origin '+refs/pull/*:refs/pull/*'
git appraise pull
~/bin/pr-mirror --target ${GITHUB_USER}/${GITHUB_REPO} --local ./ -auth-token ${YOUR_AUTH_TOKEN}
git appraise pull
git appraise push
```

### The Github Mirror App

This app allows users to continually update their git repositories with github
metadata (pull requests and build statuses). It runs in an AppEngine app, and
should expose a web interface at <PROJECT>.appspot.com.

It uses the app engine datastore to store its configuration.

To deploy:

```shell
gcloud app deploy ./app/admin/*.yaml
gcloud app deploy ./app/hooks/*.yaml
gcloud app deploy ./app/*.yaml
```


text:
#ifndef vnsw_agent_global_router_h_
#define vnsw_agent_global_router_h_

#include <cmn/agent_cmn.h>
#include <oper/ecmp_load_balance.h>
#include <oper/agent_route_walker.h>

class OperDB;
class VnEntry;
class VrfEntry;
class IFMapNode;
class AgentRouteResync;
class AgentRouteEncap;
class AgentUtXmlFlowThreshold;
class EcmpLoadBalance;
class CryptTunnelTable;

namespace autogen {
    struct LinklocalServiceEntryType;
    struct FlowAgingTimeout;
    struct GlobalVrouterConfig;
}

struct LinkLocalDBState : DBState {
    const VrfEntry *vrf_;
    // set of linklocal addresses added to the VN
    std::set<Ip4Address> addresses_;

    LinkLocalDBState(const VrfEntry *vrf) : DBState(), vrf_(vrf) {}
    void Add(const Ip4Address &address) { addresses_.insert(address); }
    void Delete(const Ip4Address &address) { addresses_.erase(address); }
};

struct PortConfig {
    PortConfig() : port_count(0) {}

    struct PortRange {
        PortRange(uint16_t start, uint16_t end):
            port_start(start), port_end(end) {}

        uint16_t port_start;
        uint16_t port_end;
    };

    void Trim();
    uint16_t port_count;
    std::vector<PortRange> port_range;
};

// Handle Global Vrouter configuration
class GlobalVrouter : public OperIFMapTable {
public:
    enum CryptMode {
        CRYPT_ALL_TRAFFIC,
        CRYPT_FLOW,
        CRYPT_NONE
    };
    static const std::string kMetadataService;
    static const Ip4Address kLoopBackIp;
    static const int32_t kDefaultFlowExportRate = 0;
    static const int32_t kDisableSampling = -1;

    struct LinkLocalServiceKey {
        Ip4Address linklocal_service_ip;
        uint16_t   linklocal_service_port;

        LinkLocalServiceKey(const Ip4Address &addr, uint16_t port)
            : linklocal_service_ip(addr), linklocal_service_port(port) {}
        bool operator<(const LinkLocalServiceKey &rhs) const;
    };

    // Config data for each linklocal service
    struct LinkLocalService {
        std::string linklocal_service_name;
        std::string ipfabric_dns_service_name;
        std::vector<Ip4Address>  ipfabric_service_ip;
        uint16_t                 ipfabric_service_port;

        LinkLocalService(const std::string &service_name,
                         const std::string &fabric_dns_name,
                         const std::vector<Ip4Address> &fabric_ip,
                         uint16_t fabric_port);
        bool operator==(const LinkLocalService &rhs) const;
        bool IsAddressInUse(const Ip4Address &ip) const;
        DBTable::DBTableWalkRef vn_update_walk_ref_;
    };

    struct FlowAgingTimeoutKey {
        FlowAgingTimeoutKey(uint8_t proto, uint16_t port_arg):
            protocol(proto), port(port_arg) { }
        uint8_t protocol;
        uint16_t port;
        bool operator==(const FlowAgingTimeoutKey &rhs) const {
            return (protocol == rhs.protocol && port == rhs.port);
        }

        bool operator<(const FlowAgingTimeoutKey &rhs) const {
            if (protocol != rhs.protocol) {
                return protocol < rhs.protocol;
            }
            return port < rhs.port;
        }
    };

    typedef std::string CryptTunnelKey;
    struct CryptTunnel {
        CryptMode mode;
        CryptTunnel(CryptMode cmode): mode(cmode) {};
        bool operator==(const CryptTunnel &rhs) const {
            return (mode == rhs.mode);
        }
        bool operator<(const CryptTunnel &rhs) const {
            return (mode < rhs.mode);
        }
    };

    // map of linklocal service data, with (ip, port) as key
    typedef std::map<LinkLocalServiceKey, LinkLocalService> LinkLocalServicesMap;
    typedef std::pair<LinkLocalServiceKey, LinkLocalService> LinkLocalServicesPair;

    typedef std::map<CryptTunnelKey, CryptTunnel> CryptTunnelsMap;
    typedef std::pair<CryptTunnelKey, CryptTunnel> CryptTunnelsPair;

    typedef std::map<FlowAgingTimeoutKey, uint32_t> FlowAgingTimeoutMap;
    typedef std::pair<FlowAgingTimeoutKey, uint32_t> FlowAgingTimeoutPair;

    //Map used to audit for port pool configuration change
    typedef std::map<uint8_t, PortConfig> ProtocolPortSet;

    GlobalVrouter(Agent *agent);
    virtual ~GlobalVrouter();
    void CreateDBClients();

    const LinkLocalServicesMap &linklocal_services_map() const {
        return linklocal_services_map_;
    }
    int32_t flow_export_rate() const { return flow_export_rate_; }

    void ConfigDelete(IFMapNode *node);
    void ConfigAddChange(IFMapNode *node);
    void ConfigManagerEnqueue(IFMapNode *node);

    void GlobalVrouterConfig(IFMapNode *node);
    void UpdateSLOConfig(IFMapNode *node);
    bool FindLinkLocalService(const std::string &service_name,
                              Ip4Address *service_ip, uint16_t *service_port,
                              std::string *fabric_hostname,
                              Ip4Address *fabric_ip, uint16_t *fabric_port) const;
    bool FindLinkLocalService(const Ip4Address &service_ip,
                              uint16_t service_port, std::string *service_name,
                              Ip4Address *fabric_ip, uint16_t *fabric_port) const;
    bool FindLinkLocalService(const std::string &service_name,
                              std::set<Ip4Address> *service_ip) const;
    bool FindLinkLocalService(const Ip4Address &service_ip,
                              std::set<std::string> *service_names) const;
    void LinkLocalRouteUpdate(const std::vector<Ip4Address> &addr_list);
    bool IsAddressInUse(const Ip4Address &ip) const;
    bool IsLinkLocalAddressInUse(const Ip4Address &ip) const;
    Agent::ForwardingMode forwarding_mode() const {return forwarding_mode_;}
    boost::uuids::uuid slo_uuid() const {return slo_uuid_;}

    uint64_t PendingFabricDnsRequests() const;
    void ResyncRoutes();
    const EcmpLoadBalance &ecmp_load_balance() const;
    bool configured() const { return configured_; }

    friend class AgentUtXmlFlowThreshold;
private:
    class FabricDnsResolver;
    class LinkLocalRouteManager;
    typedef std::vector<autogen::LinklocalServiceEntryType> LinkLocalServiceList;
    typedef std::vector<autogen::EncryptionTunnelEndpoint> EncryptionTunnelEndpointList;
    typedef std::vector<autogen::FlowAgingTimeout> FlowAgingTimeoutList;

    void UpdateLinkLocalServiceConfig(const LinkLocalServiceList &linklocal_list);
    void DeleteLinkLocalServiceConfig();
    bool ChangeNotify(LinkLocalServicesMap *old_value,
                      LinkLocalServicesMap *new_value);
    void AddLinkLocalService(const LinkLocalServicesMap::iterator &it);
    void DeleteLinkLocalService(const LinkLocalServicesMap::iterator &it);
    void ChangeLinkLocalService(const LinkLocalServicesMap::iterator &old_it,
                                const LinkLocalServicesMap::iterator &new_it);

    bool IsVrouterPresentCryptTunnelConfig(const EncryptionTunnelEndpointList &endpoint_list);
    void UpdateCryptTunnelEndpointConfig(const EncryptionTunnelEndpointList &endpoint_list,
                                         const std::string encrypt_mode_str);
    void DeleteCryptTunnelEndpointConfig();
    bool ChangeNotifyCryptTunnels(CryptTunnelsMap *old_value,
                                  CryptTunnelsMap *new_value);
    void AddCryptTunnelEndpoint(const CryptTunnelsMap::iterator &it);
    void DeleteCryptTunnelEndpoint(const CryptTunnelsMap::iterator &it);
    void ChangeCryptTunnelEndpoint(const CryptTunnelsMap::iterator &old_it,
                                   const CryptTunnelsMap::iterator &new_it);

    void UpdateFlowAging(autogen::GlobalVrouterConfig *cfg);
    void DeleteFlowAging();

    void UpdatePortConfig(autogen::GlobalVrouterConfig *cfg);
    void DeletePortConfig();

    LinkLocalServicesMap linklocal_services_map_;
    CryptTunnelsMap crypt_tunnels_map_;
    CryptMode crypt_mode_;
    boost::scoped_ptr<LinkLocalRouteManager> linklocal_route_mgr_;
    boost::scoped_ptr<FabricDnsResolver> fabric_dns_resolver_;
    AgentRouteWalkerPtr agent_route_resync_walker_;
    Agent::ForwardingMode forwarding_mode_;
    int32_t flow_export_rate_;
    FlowAgingTimeoutMap flow_aging_timeout_map_;
    ProtocolPortSet protocol_port_set_;
    EcmpLoadBalance ecmp_load_balance_;
    bool configured_; //true when global-vrouter-config stanza is present
    boost::uuids::uuid slo_uuid_; //SLO associated with global-vrouter
};

#endif // vnsw_agent_global_router_h_