text:
import ms from 'ms';
import { register, findUser } from '../ChatCommands';
import { log } from '../../actions/ChatActionCreators';

import {
  userListSelector,
  isModeratorSelector,
} from '../../selectors/userSelectors';
import { banUser } from '../../actions/ModerationActionCreators';

register(
  'ban',
  'Ban a user. Syntax: "/ban username duration" or "/ban username perma"',
  {
    guard: isModeratorSelector,
    action: (username, duration = '24h') => (dispatch, getState) => {
      if (!username) {
        return dispatch(log('Provide a user to ban.'));
      }
      const user = findUser(
        userListSelector(getState()),
        username,
      );
      if (!user) {
        return dispatch(log(`User "${username}" is not online.`));
      }
      const permanent = duration === 'perma';
      return dispatch(banUser(user, {
        duration: ms(`${duration}`),
        permanent,
      }));
    },
  },
);

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark

import java.io.IOException
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.util.Date

import org.apache.hadoop.mapred._
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.fs.Path

import org.apache.spark.executor.CommitDeniedException
import org.apache.spark.mapred.SparkHadoopMapRedUtil
import org.apache.spark.rdd.HadoopRDD

/**
 * Internal helper class that saves an RDD using a Hadoop OutputFormat.
 *
 * Saves the RDD using a JobConf, which should contain an output key class, an output value class,
 * a filename to write to, etc, exactly like in a Hadoop MapReduce job.
 */
private[spark]
class SparkHadoopWriter(@transient jobConf: JobConf)
  extends Logging
  with SparkHadoopMapRedUtil
  with Serializable {

  private val now = new Date()
  private val conf = new SerializableWritable(jobConf)

  private var jobID = 0
  private var splitID = 0
  private var attemptID = 0
  private var jID: SerializableWritable[JobID] = null
  private var taID: SerializableWritable[TaskAttemptID] = null

  @transient private var writer: RecordWriter[AnyRef,AnyRef] = null
  @transient private var format: OutputFormat[AnyRef,AnyRef] = null
  @transient private var committer: OutputCommitter = null
  @transient private var jobContext: JobContext = null
  @transient private var taskContext: TaskAttemptContext = null

  def preSetup() {
    setIDs(0, 0, 0)
    HadoopRDD.addLocalConfiguration("", 0, 0, 0, conf.value)

    val jCtxt = getJobContext()
    getOutputCommitter().setupJob(jCtxt)
  }

  def setup(jobid: Int, splitid: Int, attemptid: Int) {
    setIDs(jobid, splitid, attemptid)
    HadoopRDD.addLocalConfiguration(new SimpleDateFormat("yyyyMMddHHmm").format(now),
      jobid, splitID, attemptID, conf.value)
  }

  def open() {
    val numfmt = NumberFormat.getInstance()
    numfmt.setMinimumIntegerDigits(5)
    numfmt.setGroupingUsed(false)

    val outputName = "part-"  + numfmt.format(splitID)
    val path = FileOutputFormat.getOutputPath(conf.value)
    val fs: FileSystem = {
      if (path != null) {
        path.getFileSystem(conf.value)
      } else {
        FileSystem.get(conf.value)
      }
    }

    getOutputCommitter().setupTask(getTaskContext())
    writer = getOutputFormat().getRecordWriter(fs, conf.value, outputName, Reporter.NULL)
  }

  def write(key: AnyRef, value: AnyRef) {
    if (writer != null) {
      writer.write(key, value)
    } else {
      throw new IOException("Writer is null, open() has not been called")
    }
  }

  def close() {
    writer.close(Reporter.NULL)
  }

  def commit() {
    val taCtxt = getTaskContext()
    val cmtr = getOutputCommitter()

    // Called after we have decided to commit
    def performCommit(): Unit = {
      try {
        cmtr.commitTask(taCtxt)
        logInfo (s"$taID: Committed")
      } catch {
        case e: IOException =>
          logError("Error committing the output of task: " + taID.value, e)
          cmtr.abortTask(taCtxt)
          throw e
      }
    }

    // First, check whether the task's output has already been committed by some other attempt
    if (cmtr.needsTaskCommit(taCtxt)) {
      // The task output needs to be committed, but we don't know whether some other task attempt
      // might be racing to commit the same output partition. Therefore, coordinate with the driver
      // in order to determine whether this attempt can commit (see SPARK-4879).
      val shouldCoordinateWithDriver: Boolean = {
        val sparkConf = SparkEnv.get.conf
        // We only need to coordinate with the driver if there are multiple concurrent task
        // attempts, which should only occur if speculation is enabled
        val speculationEnabled = sparkConf.getBoolean("spark.speculation", false)
        // This (undocumented) setting is an escape-hatch in case the commit code introduces bugs
        sparkConf.getBoolean("spark.hadoop.outputCommitCoordination.enabled", speculationEnabled)
      }
      if (shouldCoordinateWithDriver) {
        val outputCommitCoordinator = SparkEnv.get.outputCommitCoordinator
        val canCommit = outputCommitCoordinator.canCommit(jobID, splitID, attemptID)
        if (canCommit) {
          performCommit()
        } else {
          val msg = s"$taID: Not committed because the driver did not authorize commit"
          logInfo(msg)
          // We need to abort the task so that the driver can reschedule new attempts, if necessary
          cmtr.abortTask(taCtxt)
          throw new CommitDeniedException(msg, jobID, splitID, attemptID)
        }
      } else {
        // Speculation is disabled or a user has chosen to manually bypass the commit coordination
        performCommit()
      }
    } else {
      // Some other attempt committed the output, so we do nothing and signal success
      logInfo(s"No need to commit output of task because needsTaskCommit=false: ${taID.value}")
    }
  }

  def commitJob() {
    val cmtr = getOutputCommitter()
    cmtr.commitJob(getJobContext())
  }

  // ********* Private Functions *********

  private def getOutputFormat(): OutputFormat[AnyRef,AnyRef] = {
    if (format == null) {
      format = conf.value.getOutputFormat()
        .asInstanceOf[OutputFormat[AnyRef,AnyRef]]
    }
    format
  }

  private def getOutputCommitter(): OutputCommitter = {
    if (committer == null) {
      committer = conf.value.getOutputCommitter
    }
    committer
  }

  private def getJobContext(): JobContext = {
    if (jobContext == null) {
      jobContext = newJobContext(conf.value, jID.value)
    }
    jobContext
  }

  private def getTaskContext(): TaskAttemptContext = {
    if (taskContext == null) {
      taskContext =  newTaskAttemptContext(conf.value, taID.value)
    }
    taskContext
  }

  private def setIDs(jobid: Int, splitid: Int, attemptid: Int) {
    jobID = jobid
    splitID = splitid
    attemptID = attemptid

    jID = new SerializableWritable[JobID](SparkHadoopWriter.createJobID(now, jobid))
    taID = new SerializableWritable[TaskAttemptID](
        new TaskAttemptID(new TaskID(jID.value, true, splitID), attemptID))
  }
}

private[spark]
object SparkHadoopWriter {
  def createJobID(time: Date, id: Int): JobID = {
    val formatter = new SimpleDateFormat("yyyyMMddHHmm")
    val jobtrackerID = formatter.format(time)
    new JobID(jobtrackerID, id)
  }

  def createPathFromString(path: String, conf: JobConf): Path = {
    if (path == null) {
      throw new IllegalArgumentException("Output path is null")
    }
    val outputPath = new Path(path)
    val fs = outputPath.getFileSystem(conf)
    if (outputPath == null || fs == null) {
      throw new IllegalArgumentException("Incorrectly formatted output path")
    }
    outputPath.makeQualified(fs)
  }
}


text:
Here is the procedure to create your own centos docker image

* Install centos on a server/VM

* After installation finish, boot the server

* do any necessary modification, e.g: yum update, yum install ..., edit /etc/..

* clean yum cache
```
yum clean all
```

* Tar the whole file system (original: http://comments.gmane.org/gmane.comp.sysutils.docker.user/5952)
```
# tar --numeric-owner --exclude=/proc --exclude=/sys --exclude=/mnt --exclude=/var/cache --exclude=/usr/share/{foomatic,backgrounds,perl5,fonts,cups,qt4,groff,kde4,icons,pixmaps,emacs,gnome-background-properties,sounds,gnome,games,desktop-directories}  --exclude=/var/log -zcvf /mnt/centos-base.tar.gz /
```

* copy the tar.gz file to docker host

* import tar.gz to docker image
```
cat centos-base.tar.gz | docker import - centos/6.5
```


text:
require 'spec_helper'
require 'facter/core/execution'

describe Facter::Core::Execution do
  subject { described_class}
  let(:impl) { described_class.impl }

  it "delegates #search_paths to the implementation" do
    impl.expects(:search_paths)
    subject.search_paths
  end

  it "delegates #which to the implementation" do
    impl.expects(:which).with('waffles')
    subject.which('waffles')
  end

  it "delegates #absolute_path? to the implementation" do
    impl.expects(:absolute_path?).with('waffles', nil)
    subject.absolute_path?('waffles')
  end

  it "delegates #absolute_path? with an optional platform to the implementation" do
    impl.expects(:absolute_path?).with('waffles', :windows)
    subject.absolute_path?('waffles', :windows)
  end

  it "delegates #expand_command to the implementation" do
    impl.expects(:expand_command).with('waffles')
    subject.expand_command('waffles')
  end

  it "delegates #exec to #execute" do
    impl.expects(:execute).with('waffles', {:on_fail => nil})
    subject.exec('waffles')
  end

  it "delegates #execute to the implementation" do
    impl.expects(:execute).with('waffles', {})
    subject.execute('waffles')
  end
end


text:
//
//  DTWebVideoView.h
//  CoreTextExtensions
//
//  Created by Oliver Drobnik on 8/5/11.
//  Copyright 2011 Drobnik.com. All rights reserved.
//

@class DTTextAttachment;
@class DTWebVideoView;

/**
 Protocol for delegates of <DTWebVideoView>
*/
@protocol DTWebVideoViewDelegate <NSObject>

@optional

/**
 Asks the delegate if an external URL may be opened
 @param videoView The web video view
 @param url The external URL that is asked to be opened
 @returns `YES` if the app may be left to open the external URL
 */

- (BOOL)videoView:(DTWebVideoView *)videoView shouldOpenExternalURL:(NSURL *)url;

@end

/**
 The class represents a custom subview for use in <DTAttributedTextContentView> to represent an embedded video.
 */
@interface DTWebVideoView : UIView <UIWebViewDelegate>

/**
 The delegate of the video view
 */
@property (nonatomic, assign) id <DTWebVideoViewDelegate> delegate; 	// subtle simulator bug - use assign not __unsafe_unretained

/**
 The text attachment representing an embedded video.
 */
@property (nonatomic, strong) DTTextAttachment *attachment;

@end


text:
require_relative "../resource"

class Chef
  class Resource
    class WindowsDnsZone < Chef::Resource
      unified_mode true

      provides :windows_dns_zone

      description "The windows_dns_zone resource creates an Active Directory Integrated DNS Zone on the local server."
      introduced "15.0"

      property :zone_name, String,
        description: "An optional property to set the dns zone name if it differs from the resource block's name.",
        name_property: true

      property :replication_scope, String,
        description: "The replication scope for the zone, required if server_type set to 'Domain'.",
        default: "Domain"

      property :server_type, String,
        description: "The type of DNS server, Domain or Standalone.",
        default: "Domain", equal_to: %w{Domain Standalone}

      action :create do
        description "Creates and updates a DNS Zone."

        powershell_package "xDnsServer"

        run_dsc_resource "Present"
      end

      action :delete do
        description "Deletes a DNS Zone."

        powershell_package "xDnsServer"

        run_dsc_resource "Absent"
      end

      action_class do
        private

        # @api private
        def run_dsc_resource(ensure_prop)
          if new_resource.server_type == "Domain"
            dsc_resource "xDnsServerADZone #{new_resource.zone_name} #{ensure_prop}" do
              module_name "xDnsServer"
              resource :xDnsServerADZone
              property :Ensure, ensure_prop
              property :Name, new_resource.zone_name
              property :ReplicationScope, new_resource.replication_scope
            end
          elsif new_resource.server_type == "Standalone"
            dsc_resource "xDnsServerPrimaryZone #{new_resource.zone_name} #{ensure_prop}" do
              module_name "xDnsServer"
              resource :xDnsServerPrimaryZone
              property :Ensure, ensure_prop
              property :Name, new_resource.zone_name
            end
          end
        end
      end
    end
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package telas;
import dados.Funcionario;
import repositorio.RepositorioFuncionarios;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
 *
 * @author Lucas
 */
public class TelaCadastrarFuncionario extends javax.swing.JFrame {

     private Funcionario funcionario = null;

    /**
     * Creates new form TelaCadastrarCliente
     */
    public TelaCadastrarFuncionario(Funcionario funcionario) {
        initComponents();

    this.funcionario = funcionario;

        // atualiza os campos caso exista um Produto para editar
        if (this.funcionario != null) {
            CampoNome.setText(funcionario.getNome());
            CampoCPF.setText(funcionario.getCpf());
            CampoRG.setText(funcionario.getRg());
            CampoTel.setText(funcionario.getTel());

    }
        }

    public TelaCadastrarFuncionario() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        CampoNome = new javax.swing.JTextField();
        CampoRG = new javax.swing.JTextField();
        CampoCPF = new javax.swing.JTextField();
        CampoTel = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Cadastrar Funcionario");

        jLabel2.setText("Nome:");

        jLabel3.setText("RG:");

        jLabel4.setText("CPF:");

        jLabel5.setText("Tel:");

        CampoCPF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CampoCPFActionPerformed(evt);
            }
        });

        CampoTel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CampoTelActionPerformed(evt);
            }
        });

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(CampoNome)
                                .addComponent(CampoRG)
                                .addComponent(CampoCPF)
                                .addComponent(CampoTel, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(89, 89, 89)
                        .addComponent(jLabel1)))
                .addContainerGap(90, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(CampoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(CampoRG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(CampoCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(CampoTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(21, 21, 21))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CampoTelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CampoTelActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CampoTelActionPerformed

    private void CampoCPFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CampoCPFActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CampoCPFActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        String Nome = CampoNome.getText();
        String RG = CampoRG.getText();
        String CPF = CampoCPF.getText();
        String Tel = CampoTel.getText();

        if (this.funcionario != null) {

            // atualizar o produto existente
            this.funcionario.setNome(Nome);
            this.funcionario.setCpf(CPF);
            this.funcionario.setRg(RG);
            this.funcionario.setTel(Tel);

            RepositorioFuncionarios.editarFuncionario(this.funcionario);
            JOptionPane.showMessageDialog(this, "Atualizado com Sucesso!" );

        } else {

            // criando um objeto Produto
            Funcionario FuncionarioAtual = new Funcionario(Nome, RG, Tel, Tel);

            // metodo opcional para visualizar dados
            FuncionarioAtual.imprimirDados();

            JOptionPane.showMessageDialog(this, FuncionarioAtual);

            // salvar o objeto na lista de REPOSITORIO DE DADOS
      RepositorioFuncionarios.adicionarFuncionario(FuncionarioAtual);
        }

this.dispose();

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
   this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaCadastrarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaCadastrarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaCadastrarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaCadastrarFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaCadastrarFuncionario().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField CampoCPF;
    private javax.swing.JTextField CampoNome;
    private javax.swing.JTextField CampoRG;
    private javax.swing.JTextField CampoTel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration//GEN-END:variables
}


text:
package lucandra.benchmarks;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;

public class BenchmarkTest {

    private enum Type {
        read, write, both
    }

    private static int numClients = 20;
    private static int numLoops = 10;
    private static Type type = Type.both;
    private static String indexName = "bench";

    private static String text = "this is a benchmark of lucandra";
    private static String queryString = "text:benchmark";
    private static int threadId = 0;
    private static int port = 8983;
    public  static String urls[] = {"http://localhost"};
    private static String[] types = new String[]{"1","2","3","4","5","6","7","8","9","10"};
    private static Random  random = new Random(System.currentTimeMillis());
    private static Map<String,CommonsHttpSolrServer> streamingClients = new HashMap<String,CommonsHttpSolrServer>();

    private static Runnable getRunnable() {

        try {
            return new Runnable() {

                private CommonsHttpSolrServer solrClient;

                private final SolrQuery q = new SolrQuery().setQuery(queryString).addFacetField("type").setSortField("id", ORDER.asc).addField("*");
                //private final SolrQuery q = new SolrQuery().setQuery(queryString).setSortField("id", ORDER.asc);
                //private final SolrQuery q = new SolrQuery().setQuery(queryString);

                private final int myThreadId = threadId++;

                private SolrInputDocument getDocument(){
                    SolrInputDocument doc =  new SolrInputDocument();
                    doc.addField("text", text);
                    doc.addField("type", types[random.nextInt(types.length-1)]);
                    doc.addField("id", UUID.randomUUID());

                    return doc;
                }

                private CommonsHttpSolrServer getStreamingServer(String url) throws MalformedURLException
                {
                    CommonsHttpSolrServer server = streamingClients.get(url);

                    if(server == null)
                    {
                        synchronized (url.intern())
                        {
                            if((server = streamingClients.get(url)) == null)
                            {
                                server =  new StreamingUpdateSolrServer(url, numLoops, (numClients/urls.length));
                                System.err.println("Connection added by :"+threadId);
                                streamingClients.put(url, server);
                            }
                        }
                    }

                    return server;
                }

                public void run() {

                    try{

                        String fullUrl;

                        if(indexName.equals(""))
                            fullUrl = urls[myThreadId % urls.length] + ":" + port +  "/solr";
                        else
                            fullUrl = urls[myThreadId % urls.length] + ":" + port +  "/solandra/" + (type == Type.write ? "~" : "") + indexName;

                        if(type == Type.write)
                            solrClient = getStreamingServer(fullUrl);
                        else
                            solrClient = new CommonsHttpSolrServer(fullUrl);

                    }catch(MalformedURLException e){

                    }

                    try {
                        switch (type) {
                        case read:
                            read();
                            break;
                        case write:
                            write();
                            break;
                        default:
                            both();
                        }
                    } catch (SolrServerException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    } finally {

                    }
                }

                private void read() throws SolrServerException {

                    long total = 0;

                    for (int i = 0; i < numLoops; i++) {

                        QueryResponse r = solrClient.query(q);

                        total = r.getResults().getNumFound();

                        if (i>0 && i % numLoops/2 == 0)
                            System.err.println("Thread " + myThreadId + ": total " + total + " facets "+r.getFacetFields());
                    }

                    if (myThreadId == 0)
                        System.err.println("Documents found: " + total);
                }

                private void write() throws SolrServerException, IOException {

                    for (int i = 0; i < numLoops; i++) {

                        solrClient.add(getDocument());
                    }

                    solrClient.commit(true,true);
                }

                private void both() throws SolrServerException, IOException {

                    long total = 0;

                    for (int i = 0; i < numLoops; i++) {

                        if (i % 2 == 1) {
                            QueryResponse r = solrClient.query(q);
                            total = r.getResults().getNumFound();

                            if (i > 1 && i % numLoops/2 == 1)
                                System.err.println("Thread " + myThreadId + ": total " + total + " facets " +r.getFacetFields());

                        } else {

                            solrClient.add(getDocument());

                        }

                    }

                    solrClient.commit(true,true);

                    if (myThreadId == 0)
                        System.err.println("Documents found: " + total);
                }
            };
        } catch (Throwable e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static void usage() {

        System.err.print(BenchmarkTest.class.getSimpleName() + " [--clients=<client-count>] [--loops=<loop-count>] [--type=<test-type>]\n"
                + "\tclients        Number of client threads to create: Default is " + numClients + "\n"
                + "\tloops          The number of remote thrift calls each client makes.  Default is " + numLoops + "\n"
                + "\ttype           The type of operation to test. Options are:\n" + "\t\tread\n\t\twrite\n\t\tboth (default)\n"
                + "\turl            A comma delimited list of servers. default is http://localhost\n");

        System.exit(0);
    }

    public static void main(String[] args) {

        if (args.length == 0)
            usage();

        // parse args
        for (int i = 0; i < args.length; i++) {

            if (args[i].startsWith("--")) {
                int eq = args[i].indexOf("=");

                if (eq < 0)
                    usage();

                String arg = args[i].substring(2, eq);
                String value = args[i].substring(eq + 1);

                try {
                    if (arg.equalsIgnoreCase("clients"))
                        numClients = Integer.valueOf(value);

                    if (arg.equalsIgnoreCase("loops"))
                        numLoops = Integer.valueOf(value);

                    if (arg.equalsIgnoreCase("type"))
                        type = Type.valueOf(value);

                    if (arg.equalsIgnoreCase("url"))
                        urls  = value.split(",");

                    if(arg.equalsIgnoreCase("solr"))
                        indexName = "";

                } catch (Throwable t) {
                    usage();
                }
            }
        }

        ExecutorService threadPool = Executors.newFixedThreadPool(numClients);
        Runnable runners[] = new Runnable[numClients];
        for (int i = 0; i < numClients; i++)
            runners[i] = getRunnable();

        System.out.println("Starting Benchmark...");
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < numClients; i++)
            threadPool.submit(runners[i]);

        threadPool.shutdown();

        try {
            threadPool.awaitTermination(1024, TimeUnit.MINUTES);
        } catch (InterruptedException e) {

            threadPool.shutdownNow();
            System.err.println("Benchmark manually stopped");
            System.exit(1);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("Finished:");
        System.out.println("\tclients:" + numClients + ", loops:" + numLoops + ", type:" + type + ", rate(ops/sec):"
                + Math.ceil((double) ((numClients * numLoops * 1000) / (endTime - startTime))));

        System.exit(0);

    }

}


text:
Given a non-empty 2D matrix *matrix* and an integer k, find the max sum of a rectangle in the *matrix* such that its sum is no larger than k.

**Example:**
```
Given matrix = [
  [1,  0, 1],
  [0, -2, 3]
]
k = 2
```

The answer is `2`. Because the sum of rectangle `[[0, 1], [-2, 3]]` is `2` and `2` is the max number no larger than k (k = 2).

**Note:**

1. The rectangle inside the matrix must have an area > 0.
2. What if the number of rows is much larger than the number of columns?


text:
NSString * const TCOfflineDataManagerDidSaveNotification = @"DataManagerDidSaveNotification";
NSString * const TCOfflineDataManagerDidSaveFailedNotification = @"DataManagerDidSaveFailedNotification";

@interface TCOfflineDataManager ()

- (NSString*)sharedDocumentsPath;

@end

@implementation TCOfflineDataManager

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize mainObjectContext = _mainObjectContext;
@synthesize objectModel = _objectModel;
@synthesize storePath = _storePath;
@synthesize storeURL = _storeURL;

NSString * const kTCOfflineDataManagerBundleName = @"TinCanObjC-OfflineResources";
NSString * const kTCOfflineDataManagerModelName = @"TCLocalStorage";
NSString * const kTCOfflineDataManagerSQLiteName = @"TinCanObjC-LocalStorage.sqlite";

+ (TCOfflineDataManager*)sharedInstance {
	static dispatch_once_t pred;
	static TCOfflineDataManager *sharedInstance = nil;

	dispatch_once(&pred, ^{ sharedInstance = [[self alloc] init]; });
	return sharedInstance;
}

- (void)dealloc {
	[self save];
}

- (NSManagedObjectModel*)objectModel {
	if (_objectModel)
		return _objectModel;

	NSBundle *bundle = [NSBundle bundleForClass:[self class]];
//	if (kDataManagerBundleName) {
//		NSString *bundlePath = [[NSBundle mainBundle] pathForResource:kDataManagerBundleName ofType:@"bundle"];
//		bundle = [NSBundle bundleWithPath:bundlePath];
//	}
	NSString* mainBundlePath = [bundle resourcePath];
    NSLog(@"mainBundlePath %@", mainBundlePath);
    NSString* frameworkBundlePath;

    if([[mainBundlePath lastPathComponent] isEqualToString:@"TinCanObjC-OfflineTests.octest"])
    {
        frameworkBundlePath = mainBundlePath;
    }else{
        frameworkBundlePath = [mainBundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.bundle",kTCOfflineDataManagerBundleName]];
    }

    NSLog(@"frameworkBundlePath %@", frameworkBundlePath);
    NSString *path = [[NSBundle bundleWithPath:frameworkBundlePath] pathForResource:@"TCLocalStorage" ofType:@"momd"];

    NSLog(@"modelPath %@", path);

    NSURL *momURL = [NSURL fileURLWithPath:path];

	_objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

	return _objectModel;

}

- (NSPersistentStoreCoordinator*)persistentStoreCoordinator {
	if (_persistentStoreCoordinator)
		return _persistentStoreCoordinator;

	// Get the paths to the SQLite file
	_storePath = [[self sharedDocumentsPath] stringByAppendingPathComponent:kTCOfflineDataManagerSQLiteName];

    NSLog(@"storePath : %@", _storePath);

	_storeURL = [NSURL fileURLWithPath:_storePath];

	// Define the Core Data version migration options
	NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];

	// Attempt to load the persistent store
	NSError *error = nil;
	_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.objectModel];

	if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                   configuration:nil
                                                             URL:_storeURL
                                                         options:options
                                                           error:&error]) {
		NSLog(@"Fatal error while creating persistent store: %@", error);
		abort();
	}

	return _persistentStoreCoordinator;
}

- (NSManagedObjectContext*)mainObjectContext {
	if (_mainObjectContext)
		return _mainObjectContext;

	// Create the main context only on the main thread
	if (![NSThread isMainThread]) {
		[self performSelectorOnMainThread:@selector(mainObjectContext)
                               withObject:nil
                            waitUntilDone:YES];
		return _mainObjectContext;
	}

	_mainObjectContext = [[NSManagedObjectContext alloc] init];
	[_mainObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];

	return _mainObjectContext;
}

- (BOOL)save {
	if (![self.mainObjectContext hasChanges])
		return YES;

	NSError *error = nil;
	if (![self.mainObjectContext save:&error]) {
		NSLog(@"Error while saving: %@\n%@", [error localizedDescription], [error userInfo]);
		[[NSNotificationCenter defaultCenter] postNotificationName:TCOfflineDataManagerDidSaveFailedNotification
                                                            object:error];
		return NO;
	}

	[[NSNotificationCenter defaultCenter] postNotificationName:TCOfflineDataManagerDidSaveNotification object:nil];
	return YES;
}

- (NSString*)sharedDocumentsPath {
	static NSString *SharedDocumentsPath = nil;
	if (SharedDocumentsPath)
		return SharedDocumentsPath;

	// Compose a path to the <Library>/Database directory
	NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	SharedDocumentsPath = [libraryPath stringByAppendingPathComponent:@"Database"];

	// Ensure the database directory exists
	NSFileManager *manager = [NSFileManager defaultManager];
	BOOL isDirectory;
	if (![manager fileExistsAtPath:SharedDocumentsPath isDirectory:&isDirectory] || !isDirectory) {
		NSError *error = nil;
		NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
                                                         forKey:NSFileProtectionKey];
		[manager createDirectoryAtPath:SharedDocumentsPath
		   withIntermediateDirectories:YES
                            attributes:attr
                                 error:&error];
		if (error)
			NSLog(@"Error creating directory path: %@", [error localizedDescription]);
	}

	return SharedDocumentsPath;
}

- (NSManagedObjectContext*)managedObjectContext {
	NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc] init];
	[ctx setPersistentStoreCoordinator:self.persistentStoreCoordinator];

	return ctx;
}

@end


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

<!-- Generated with http://android-holo-colors.com -->
<resources xmlns:android="http://schemas.android.com/apk/res/android">

  <style name="Recipes" parent="@style/_Recipes"/>

  <style name="_Recipes" parent="Theme.AppCompat.Light.DarkActionBar">

    <item name="android:editTextStyle">@style/EditTextRecipes</item>

    <item name="android:textColorHighlight">#999933cc</item>

    <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextViewRecipes</item>

    <item name="android:checkboxStyle">@style/CheckBoxRecipes</item>

    <item name="android:radioButtonStyle">@style/RadioButtonRecipes</item>

    <item name="android:buttonStyle">@style/ButtonRecipes</item>

    <item name="android:imageButtonStyle">@style/ImageButtonRecipes</item>

    <item name="android:spinnerStyle">@style/SpinnerRecipes</item>

    <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItemRecipes</item>

    <item name="android:progressBarStyleHorizontal">@style/ProgressBarRecipes</item>

    <item name="android:seekBarStyle">@style/SeekBarRecipes</item>

    <item name="android:ratingBarStyle">@style/RatingBarRecipes</item>

    <item name="android:ratingBarStyleIndicator">@style/RatingBarBigRecipes</item>

    <item name="android:ratingBarStyleSmall">@style/RatingBarSmallRecipes</item>

    <item name="android:buttonStyleToggle">@style/ToggleRecipes</item>

    <item name="android:listViewStyle">@style/ListViewRecipes</item>

    <item name="android:listViewWhiteStyle">@style/ListViewRecipes.White</item>

    <item name="android:spinnerItemStyle">@style/SpinnerItemRecipes</item>

  </style>

</resources>


text:
<?php
namespace Beech\Ehrm\Aspect;

/*                                                                        *
 * This script belongs to beechit/mrmaks.                                 *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License as published by the *
 * Free Software Foundation, either version 3 of the License, or (at your *
 * option) any later version.                                             *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser       *
 * General Public License for more details.                               *
 *                                                                        *
 * You should have received a copy of the GNU Lesser General Public       *
 * License along with the script.                                         *
 * If not, see http://www.gnu.org/licenses/lgpl.html                      *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Flow\Annotations as Flow;
use Doctrine\ORM\Mapping as ORM;

/**
 * Softdelete functionality for Beech packages
 *
 * @Flow\Aspect
 */
class SoftDeleteAspect {

	/**
	 * @var \TYPO3\Flow\Reflection\ReflectionService
	 * @Flow\Inject
	 */
	protected $reflectionService;

	/**
	 * Advice ensures soft-deletion by setting a property to deleted and update the model,
	 * instead of actually removing it
	 *
	 * @param  \TYPO3\Flow\Aop\JoinPointInterface $joinPoint
	 * @Flow\Around("method(Beech\.*\Domain\Repository\.*->remove())")
	 * @return void
	 */
	public function softDelete(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) {
		$model = $joinPoint->getMethodArgument('object');

		if (method_exists($model, 'setDeleted')) {
			$model->setDeleted(TRUE);
			$joinPoint->getProxy()->update($model);
		} else {
			$joinPoint->getAdviceChain()->proceed($joinPoint);
		}
	}

	/**
	 * Only fetch objects which are not softdeleted
	 *
	 * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint
	 * @Flow\Around("within(TYPO3\Flow\Persistence\QueryInterface) && method(.*->(execute|count)())")
	 * @return \TYPO3\Flow\Persistence\Doctrine\Query
	 */
	public function filterDeletedObjects(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) {
		if (substr($joinPoint->getProxy()->getType(), 0, 5) === 'Beech') {
				/** @var $query \TYPO3\Flow\Persistence\Doctrine\Query */
			$query = $joinPoint->getProxy();

			/*
			 * Using the reflectionService, check if the model actually has a property named 'deleted'
			 * Continue the advice chain without filtering if it does not
			 */
			if (!in_array('deleted', $this->reflectionService->getClassPropertyNames($query->getType()))) {
				return $joinPoint->getAdviceChain()->proceed($joinPoint);
			}

			/*
			 * Check if the query already has a constraint for the deleted property. If so, then just proceed
			 * the advice chain so it's still possible to write custom queries for querying deleted records
			 */
			if ($query->getConstraint() !== NULL
				&& (strpos($query->getConstraint(), '.deleted ') !== FALSE)) {
					return $joinPoint->getAdviceChain()->proceed($joinPoint);
			}

			/*
			 * Perform the actual filtering
			 */
			if ($query->getConstraint() !== NULL) {
				$query->matching($query->logicalAnd($query->getConstraint(), $query->equals('deleted', FALSE)));
			} else {
				$query->matching($query->logicalNot($query->equals('deleted', TRUE)));
			}
		}

		return $joinPoint->getAdviceChain()->proceed($joinPoint);
	}

}

?>


text:
module Infoboxer
  # @private
  WIKIA_API_URL = 'http://%s.wikia.com/api.php'

  WIKIMEDIA_PROJECTS = {
    wikipedia: 'wikipedia.org',
    wikivoyage: 'wikivoyage.org',
    wikiquote: 'wikiquote.org',
    wiktionary: 'wiktionary.org',
    wikibooks: 'wikibooks.org',
    wikinews: 'wikinews.org',
    wikiversity: 'wikiversity.org',
    wikisource: 'wikisource.org'
  }.freeze

  WIKIMEDIA_COMMONS = {
    commons: 'commons.wikimedia.org',
    species: 'species.wikimedia.org',
  }.freeze

  def wikis
    @wikis ||= {}
  end

  # Includeable version of {Infoboxer.wiki}
  def wiki(api_url, **options)
    wikis[api_url] ||= MediaWiki.new(api_url, **options)
  end

  class << self # rubocop:disable Lint/EmptyClass -- that's for YARD!
    # @!method wiki(api_url, options = {})
    # Default method for creating MediaWiki API client.
    #
    # @param api_url should be URL of api.php for your MediaWiki
    # @param options list of options.
    #   The only recognized option for now, though, is
    #   * `:user_agent` (also aliased as `:ua`) -- custom User-Agent header.
    # @return [MediaWiki] an instance of API client, which you can
    #   further use like this:
    #
    #   ```ruby
    #   Infoboxer.wiki('some_url').get('Some page title')
    #   ```

    # @!method wikipedia(lang = 'en', options = {})
    # Shortcut for creating Wikipedia client.
    #
    # @param lang two-character code for language version
    # @param options (see #wiki for list of options)
    # @return [MediaWiki]

    # @!method commons(options = {})
    # Shortcut for creating [WikiMedia Commons](https://commons.wikimedia.org/) client.
    #
    # @param options (see #wiki for list of options)
    # @return [MediaWiki]

    # @!method wikibooks(lang = 'en', options = {})
    # Shortcut for creating [Wikibooks](https://en.wikibooks.org/) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method wikiquote(lang = 'en', options = {})
    # Shortcut for creating [Wikiquote](https://en.wikiquote.org/) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method wikiversity(lang = 'en', options = {})
    # Shortcut for creating [Wikiversity](https://en.wikiversity.org/) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method wikisource(lang = 'en', options = {})
    # Shortcut for creating [Wikisource](https://en.wikisource.org/) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method wikivoyage(lang = 'en', options = {})
    # Shortcut for creating [Wikivoyage](http://wikivoyage.org) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method wikinews(lang = 'en', options = {})
    # Shortcut for creating [Wikinews](https://en.wikinews.org/) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method species(options = {})
    # Shortcut for creating [Wikispecies](https://species.wikimedia.org/) client.
    #
    # @param options (see #wiki for list of options)
    # @return [MediaWiki]

    # @!method wiktionary(lang = 'en', options = {})
    # Shortcut for creating [Wiktionary](https://en.wiktionary.org/) client.
    # See {wikipedia} for params explanation.
    # @return [MediaWiki]

    # @!method wikia(*domains)
    # Performs request to wikia.com wikis.
    #
    # @overload wikia(*domains)
    #   @param *domains list of domains to merge, like this:
    #
    #     ```ruby
    #     Infoboxer.wikia('tardis') # looks at tardis.wikia.com
    #     Infoboxer.wikia('tardis', 'ru') # looks in Russian version, ru.tardis.wikia.com
    #     ```
    #     If you are surprised by "reversing" list of subdomains, think of
    #     it as of chain of refinements (looking in "tardis" wiki, its "ru"
    #     version, specifically).
    #
    # @overload wikia(*domains, options)
    #   @param *domains same as above
    #   @param options just last of params, if it is hash
    #     (see {wiki} for list of options)
    #
    # @return [MediaWiki]
  end

  WIKIMEDIA_PROJECTS.each do |name, domain|
    define_method name do |lang = 'en', **options|
      lang, options = 'en', lang if lang.is_a?(Hash)

      wiki("https://#{lang}.#{domain}/w/api.php", **options)
    end
  end

  alias_method :wp, :wikipedia

  WIKIMEDIA_COMMONS.each do |name, domain|
    define_method name do |**options|
      wiki("https://#{domain}/w/api.php", options)
    end
  end

  # Returns URL of API entry-point for a well-known Wiki-project (wikipedia, wikivoyage etc.)
  # by project's name.
  #
  # @param symbol [Symbol] One of {WIKIMEDIA_PROJECTS} or {WIKIMEDIA_COMMONS} keys.
  # @param lang [String, Symbol] Language of the project, if applicable.
  # @return [String]
  def url_for(symbol, lang = 'en')
    if (domain = WIKIMEDIA_PROJECTS[symbol])
      "https://#{lang}.#{domain}/w/api.php"
    elsif (domain = WIKIMEDIA_COMMONS[symbol])
      "https://#{domain}/w/api.php"
    end
  end

  # @!method wikipedia(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikipedia}

  # @!method commons(options = {})
  # Includeable version of {Infoboxer.commons}

  # @!method wikibooks(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikibooks}

  # @!method wikiquote(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikiquote}

  # @!method wikiversity(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikiversity}

  # @!method wikisource(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikisource}

  # @!method wikivoyage(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikivoyage}

  # @!method wikinews(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wikinews}

  # @!method species(options = {})
  # Includeable version of {Infoboxer.species}

  # @!method wiktionary(lang = 'en', options = {})
  # Includeable version of {Infoboxer.wiktionary}

  # Includeable version of {Infoboxer.wikia}
  def wikia(*domains)
    options = domains.last.is_a?(Hash) ? domains.pop : {}
    wiki(WIKIA_API_URL % domains.reverse.join('.'), **options)
  end

  # Sets user agent string globally. Default user agent is
  # {MediaWiki::UA}.
  #
  # User agent can also be rewriten as an option to {wiki} method (and
  # its shortcuts like {wikipedia}), or by using {MediaWiki#initialize}
  # explicitly.
  #
  def self.user_agent=(ua)
    MediaWiki.user_agent = ua
  end

  extend self
end

require_relative 'infoboxer/version'
require_relative 'infoboxer/core_ext'

require_relative 'infoboxer/tree'
require_relative 'infoboxer/parser'
require_relative 'infoboxer/navigation'
require_relative 'infoboxer/templates'

require_relative 'infoboxer/media_wiki'

require_relative 'infoboxer/definitions/en.wikipedia.org'


text:
Solarwinds Database performance Analyzer
=========

This is a Dockerized version of [Database performance Analyzer](http://www.solarwinds.com/database-performance-monitoring-software).  This is based on the RHEL rpm installed on a CentOS 8 base.

The primary purpose of the document is to explain the steps involved in deploying DPA Docker image on to Docker store/hub. This could be first step in exploring the feasibility of moving other products (related and non-related) to Containers to cut down the build and deploy time for products that are under maintenance. Please refer Docker Best Practices for creating Docker file.

# DPA

Deploying this SolarWinds DPA product from the Docker Hub repository is quick and easy.  You'll be up and running in a few minutes, ready to monitor your multi-vendor databases spanning across hybrid environments.

Included is a fully functional, 14-day evaluation key for your product, but you can contact our sales team at `sales@solarwinds.com` to extend your evaluation or purchase a BYOL perpetual license with a first-year paid software maintenance agreement.

By pulling and running this SolarWinds DPA Docker image, you are expressly agreeing to our [SolarWinds End User License Agreement](https://www.solarwinds.com/legal/eula).

**Please do not use this product if you are not in agreement with the terms and conditions.**

# Docker File
```Dockerfile
# Version: 0.0.1

FROM centos:latest

MAINTAINER Solarwinds  "innovate@solarwinds.com"

LABEL ProductDownloadName="SolarWinds-DPA-X.Y.Z.B-64bit-Eval.tar.gz" Version="X.Y.Z.B" ProductName="DPA"

ENV PRODUCT_DOWNLOAD_DIR=X.Y.Z.BSR1 PRODUCT_DOWNLOAD_NAME=SolarWinds-DPA-X.Y.Z.B-64bit-Eval.tar.gz GZIP_FILE=dpa.tar.gz

ADD http://downloads.solarwinds.com/solarwinds/Release/DatabasePeformanceAnalyzer-DPA/$PRODUCT_DOWNLOAD_DIR/$PRODUCT_DOWNLOAD_NAME /$GZIP_FILE
ADD install.sh /install.sh
RUN yum clean all && yum install -y python-setuptools jre && easy_install supervisor

ADD run.sh /run.sh

ADD supervisord.conf /home/docker/dpa/supervisord.conf

EXPOSE 8123 8124

ENTRYPOINT ["/run.sh"]
```
Here is the docker build command that is used to create DPA Docker image. The tag or image name should match the namespace or username/respository name created on the docker hub account.

# Docker Build
```sh
docker build -t solarwinds/dpa:latest .
```

# Note

Currently, DPA does not allow silent install, so when you build docker image, you cannot install the dpa application. So it has to be done from with in the container itself and issue a docker commit to update the image before pushing it to docker hub

The command to login and push the image to docker hub repository is provided below.

# Docker Push
```sh
docker login --username={username}
```
This will prompt you to enter the docker hub account password. On successfully logging in, you will be able to push the image to the repository

```sh
docker push solarwinds/dpa:latest
```

# Docker Pull
```sh
docker pull solarwinds/dpa[:latest]
```

Once the docker image is built or pulled from docker hub, Here is the docker run command to start the container. This will create DPA container and start the process. This will run the container in the daemon mode.

# Docker Run
```sh
docker run -d -p 8123:8123  -p 8124:8124 --name=dpainstance solarwinds/dpa:latest
```

# Configure DPA Through Browser:
1. Open Web Browser: localhost:8123 for http and 8124 for https
2. Set up Database Repository of your choice


text:
#include "UnitTesting.h"
#include "Tests.h"
#include <thread>
#include <set>

using namespace Wild::UnitTesting;
using namespace std;

void ThrowsInvalidArgument()
{
    throw std::invalid_argument("foo");
}

void ThrowsOutOfRange()
{
    throw std::out_of_range("foo");
}

void ThrowException() { throw std::runtime_error("kaboom"); }

// threads create a bunch of test failures so we can check that the operation of the
// library is thread safe - that the output and pass/fails counts are correct
void Thread1()
{
    for (int i = 0; i < 100; i++)
    {
        AssertTrue(false);
        AssertFalse(true);
        AssertEquals(1, 2);
        AssertPrints(cout << "foo", "bar");
        AssertPrintsToStderr(cerr << "bar", "foo");
        AssertThrows(throw invalid_argument("foo"), out_of_range);
    }
}

void Thread2()
{
    for (int i = 0; i < 100; i++)
    {
        AssertTrue(false);
        AssertFalse(true);
        AssertEquals(1, 2);
        AssertPrints(cout << "foo", "bar");
        AssertPrintsToStderr(cerr << "bar", "foo");
        AssertThrows(throw invalid_argument("foo"), out_of_range);
    }
}

void TestThreadSafety()
{
    // output acts as cout from here, and will be accessed concurrently from both threads
    // which is a good test of whether the library can handle it
    stringstream output;
    streambuf* original = std::cout.rdbuf(output.rdbuf());
    stringstream outputStderr;
    streambuf* originalStderr = std::cerr.rdbuf(outputStderr.rdbuf());

    thread t1(Thread1);
    thread t2(Thread2);
    t2.join();
    t1.join();

    std::cout.rdbuf(original);
    std::cerr.rdbuf(originalStderr);

    // error printouts should not be interleaved, and failure count should be correct
    string line;

    // These tests below check the line length to see if any lines have been interleaved by
    // concurrent access to stdout. It's not guaranteed to produce a failure, but often does,
    // so we can be confident that the thread safety works if there are no failures across
    // multiple test runs.

    // Also, AssertPrints flat out crashes if the code isn't thread safe

#ifdef WILD_UNITTESTING_SHOW_FAILURE_DETAILS
    // Possible sizes of the failure details lines created by the failed tests in the threads.
    // Different environments have different ways of representing the filename, hence the length differences.
    set<size_t> possibleLineLengths = {
        107, 154, 98, 76, 122,  // WIN32
        70, 61, 117, 39, 85,    // X64
        118, 109, 133, 165, 87, // GCC
    };
    while (std::getline(output, line, '\n')) {
        AssertTrue(possibleLineLengths.find(line.size()) != possibleLineLengths.end());
    }
    while (std::getline(outputStderr, line, '\n')) {
        AssertTrue(possibleLineLengths.find(line.size()) != possibleLineLengths.end());
    }
#else
    // Possible sizes of the failure details lines created by the failed tests in the threads.
    // Different environments have different ways of representing the filename, hence the length differences.
    set<size_t> possibleLineLengths = {
        74,     // WIN32
        37,     // X64
        85      // GCC
    };
    while (std::getline(output, line, '\n')) {
        AssertTrue(possibleLineLengths.find(line.size()) != possibleLineLengths.end());
    }
    while (std::getline(outputStderr, line, '\n')) {
        AssertTrue(possibleLineLengths.find(line.size()) != possibleLineLengths.end());
    }
#endif

    AssertEquals(Failed(), 1200);

}

std::mutex m;
void ThreadedFunction()
{
    std::lock_guard<std::mutex> lock(m);
    cout << "I'm threaded!" << endl;
}

int main(int argc, char* argv[])
{
    // Readme example tests

    int x = 1;
    int y = 2;
    std::string s = "foo";

    AssertTrue(x == y - 1);
    AssertEquals(x + 1, y);
    AssertEquals(s, "foo");
    AssertThrows(ThrowException(), std::runtime_error);
    AssertPrints(std::cout << s << "bar", "foobar");
    AssertPrints(std::cout << s << "bar" << endl; , "foobar\n");

    // Unit testing library tests

    TestThreadSafety();

    AssertTrue(true);
    bool bar = true;
    AssertTrue(bar);
    AssertFalse(!bar);
    AssertEquals(13, 13);
    AssertEquals(true, true);
    AssertEquals(false, false);
    AssertEquals("foo", s);

    Test test;
    test.Assert(true, "filename", 1, "passed");
    AssertEquals(1, test.passed);
    AssertEquals(0, test.failed);

    std::stringstream output;
    std::streambuf* original = std::cout.rdbuf(output.rdbuf());

    test.Assert(false, "filename", 2, "(false == true)");
    std::string text = output.str();
    output.str("");

    std::stringstream failFileAndLine;
    Fail("test"); failFileAndLine << __FILE__ << "(" << __LINE__ << ")";
    std::string text2 = output.str();

    std::cout.rdbuf(original);

#ifdef WILD_UNITTESTING_SHOW_FAILURE_DETAILS
    AssertEquals(text, "filename(2): test failed, (false == true)\n");
    AssertEquals(text2, failFileAndLine.str() + ": test failed, test\n");
#else
    AssertEquals(text, "filename(2): test failed\n");
    AssertEquals(text2, failFileAndLine.str() + ": test failed\n");
#endif

    AssertEquals(1, test.passed);
    AssertEquals(1, test.failed);

    AssertThrows(throw std::out_of_range("foo"), std::out_of_range);
    AssertThrows(ThrowsOutOfRange(), std::out_of_range);
    AssertThrows(ThrowsInvalidArgument(), std::invalid_argument);
    AssertPrints(Wild::UnitTesting::AllTests::instance().Results(), "1223 passed, 1201 failed, 2424 total\n");

    AdditionalTests();

    // Two additional tests should have passed
    AssertPrints(Wild::UnitTesting::AllTests::instance().Results(), "1225 passed, 1201 failed, 2426 total\n");

    AssertThreadSafe(ThreadedFunction(), 500);

    if (Failed() > 0)  // we called Fail directly to test the output so we expect one failure, plus all the threading test fails
    {
        std::cout << "Unit testing tests passed" << std::endl;
        return 0;
    }
    else
        return 1;
}


text:
BazingaGeocoderBundle
=====================

[![Build Status](https://travis-ci.org/geocoder-php/BazingaGeocoderBundle.svg?branch=master)](http://travis-ci.org/geocoder-php/BazingaGeocoderBundle)
[![Latest Stable Version](https://poser.pugx.org/willdurand/geocoder-bundle/v/stable)](https://packagist.org/packages/willdurand/geocoder-bundle)
[![Total Downloads](https://poser.pugx.org/willdurand/geocoder-bundle/downloads)](https://packagist.org/packages/willdurand/geocoder-bundle)
[![Monthly Downloads](https://poser.pugx.org/willdurand/geocoder-bundle/d/monthly.png)](https://packagist.org/packages/willdurand/geocoder-bundle)
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/geocoder-php/BazingaGeocoderBundle.svg?style=flat-square)](https://scrutinizer-ci.com/g/geocoder-php/BazingaGeocoderBundle)
[![Quality Score](https://img.shields.io/scrutinizer/g/geocoder-php/BazingaGeocoderBundle.svg?style=flat-square)](https://scrutinizer-ci.com/g/geocoder-php/BazingaGeocoderBundle)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)

Integration of the [**Geocoder**](http://github.com/geocoder-php/Geocoder) library
into Symfony. It integrates seamlessly with the Symfony profiler. You can
check number of queries executed by each provider, total execution time
and geocoding results.

![Example Toolbar](doc/toolbar.png)

![Example Profiler page](doc/profiler-page.png)

Documentation
-------------

For documentation, see:

    doc/

[Read the documentation](doc/index.md)

Contributing
------------

See
[CONTRIBUTING](CONTRIBUTING.md)
file.

Credits
-------

* William Durand
* Tobias Nyholm
* [All contributors](https://github.com/geocoder-php/BazingaGeocoderBundle/contributors)

Contributor Code of Conduct
---------------------------

Please note that this project is released with a Contributor Code of Conduct.
By participating in this project you agree to abide by its terms.

License
-------

This bundle is released under the MIT license. See the complete license [here](LICENSE).


text:
<!DOCTYPE html>
<html data-ripple data-ripple-selector=".sidebar-item, .dropdown-ripple > li, .btn-ripple, .img-ripple, .select2-selection--single">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no">
    <meta http-equiv="Content-Language" content="en">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="theme-color" content="#0071ce">
    <meta name="msapplication-TileImage" content="/assets/images/windows-tile.png">
    <meta name="msapplication-TileColor" content="#0071ce">
    <title>{{ title|default('Home example') }} - Fxp Theme Gluon</title>
    <link rel="icon" type="image/x-icon" href="/assets/images/favicon.ico">
    <link rel="fluid-icon" type="image/png" href="/assets/images/fluidicon.png" title="Fxp">
    <link rel="apple-touch-icon" sizes="114x144" href="/assets/images/apple-touch-icon-114.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/assets/images/apple-touch-icon-144.png">
    <link href="/assets/main.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="/assets/shiv.js"></script>
    <![endif]-->
    <style>
        .demo-separator {
            margin-top: 24px;
        }
        .demo-col > .btn {
            margin-top: 10px;
        }
    </style>
    {% block head_style %}
    {% endblock %}
</head>

<body>
<!-- SIDEBAR -->
{% block sidebars %}
{% endblock %}

<!-- CONTAINER MAIN -->
{% block body %}
{% endblock %}
<script src="/assets/main.js"></script>
<script>
    $(document).ready(function() {
        $('.container-main').on('scroll.fxp.examples', function() {
            $('.open .dropdown-toggle').dropdown('toggle');
        });
        {% block custom_script %}
        {% endblock %}
    });
</script>
</body>
</html>


text:
import datetime
import os

# from heavy import special_commit

def modify():
    file = open('zero.md', 'r')
    flag = int(file.readline()) == 0
    file.close()
    file = open('zero.md', 'w+')
    if flag:
        file.write('1')
    else:
        file.write('0')
        file.close()

def commit():
    os.system('git commit -a -m test_github_streak > /dev/null 2>&1')

def set_sys_time(year, month, day):
    os.system('date -s %04d%02d%02d' % (year, month, day))

def trick_commit(year, month, day):
    set_sys_time(year, month, day)
    modify()
    commit()

def daily_commit(start_date, end_date):
    for i in range((end_date - start_date).days + 1):
        cur_date = start_date + datetime.timedelta(days=i)
        trick_commit(cur_date.year, cur_date.month, cur_date.day)

if __name__ == '__main__':
    daily_commit(datetime.date(2015, 3, 31), datetime.date(2016, 8, 16))


text:
from django.utils.translation import ugettext_lazy as _

from horizon import tables
from openstack_dashboard.dashboards.project.routers.ports \
    import tables as routers_tables

class PortsTable(routers_tables.PortsTable):
    name = tables.Column("name_or_id",
                         verbose_name=_("Name"),
                         link="horizon:admin:networks:ports:detail")

    class Meta(object):
        name = "interfaces"
        verbose_name = _("Interfaces")


text:
(function(module, global){

  var evts = []
    , conf = {
        debug         : false
      , saveUrl       : "path.to.saver.file.php"
      , excludeEvents : []
    };

  // Prepare data for submitting.
  function serialize(data) {
    var params = [];
    for (var d in data) {
      params.push(d + "=" + data[d]);
    }
    return params.join("&");
  };

  // Get milliseconds.
  function getMs() {
    return (new Date).getTime();
  };

  module.exports = {

    // Event names.
    event: {
        LOAD        : "load"
      , PRESS       : "press"
      , RELEASE     : "release"
      , MOVE        : "move"
      , ENTER       : "enter"
      , LEAVE       : "leave"
      , SWIPE       : "swipe"
      , TYPE        : "type"
      , SUBMIT      : "submit"
      , TEXT_CHANGE : "textchange"
      , CALLOUT     : "callout"
      , ZOOM_IN     : "zoomin"
      , ZOOM_OUT    : "zoomout"
    },

    // Configuration method.
    config: function(opts) {
      for (var o in opts) {
        if (opts.hasOwnProperty(o) && opts[o] !== null) {
          conf[o] = opts[o];
        }
      }
      return this;
    },

    // Event logging method.
    register: function() {
      if (conf.excludeEvents.indexOf(arguments[0]) === -1) {
        var args = Array.prototype.slice.call(arguments)
          , info = [ getMs(), args[0], args.slice(1) ]
          ;
        evts.push(info);
        if (conf.debug) console && console.log(info);
      }
      return this;
    },

    // Finish logging method. Assumes a JSON-formatted response.
    finish: function(data, callback) {
      if (!data) return false;
      data.events = JSON.stringify(evts);
      var request = new XMLHttpRequest();
      request.open("POST", conf.saveUrl, true);
      request.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
      request.onreadystatechange = function reqStatus() {
        if (request.readyState === 4) {
          if (request.status !== 200) {
            if (conf.debug) console && console.log(request);
          } else {
            if (typeof callback === 'function')
              callback(request.responseText);
          }
          evts = [];
        }
      };
      request.send( serialize(data) );
    }

  };

})('object' === typeof module ? module : {}, this);


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerControl : MonoBehaviour {

    private Animator animator;

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

    // sound effect
    public AudioClip swordSound;
    public AudioClip swordHitSound;
    public AudioClip[] attackSounds;
    public AudioClip missSound;
    public AudioClip runSound;

    public AudioSource attackVoiceAudio;
    public AudioSource swordAudio;
    public AudioSource missAudio;
    public AudioSource runAudio;

    private int attackSoundIndex = 0;
    public float MinRunAudioRate = 0.2f;
    public float MaxRunAudioRate = 0.5f;

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

    public float runSpeed = 5.0f;

    public const float RunSpeedMax = 20.0f;

    private const float Acceleration = 5.0f;

    private const float Deceleration = 5.0f * 4.0f;

    private const float MissGravity = 9.8f * 2.0f;

    private AttackColliderControl attackCollider;
    public GameSceneControl gameSceneControl;

    private float attackTimer = 0.0f;
    private float attackDisableTimer = 0.0f;

    public const float AttackTime = 0.3f;
    public const float AttackDisableTime = 1.0f;

    private bool isRunning = true;
    private bool isContactFloor = false;

    private bool isPlayable = true;
    public bool IsPlayable
    {
        get { return isPlayable; }
        set { isPlayable = value; }
    }

    public float stopPosition = -1.0f;

    enum State
    {
        None = -1,
        Run,
        Attack,
        Idle,
        Miss
    }

    public enum AttackMotion
    {
        Left = 0,
        Right
    }
    private List<string> animationTriggers = new List<string>()
        { "AttackLeft",
          "AttackRight" };

    public AttackMotion attackMotion = AttackMotion.Left;

    public AnimatedTextureExtendedUV attackLeftTail;
    public AnimatedTextureExtendedUV attackRightTail;

    public ParticleSystem hitFX;
    public ParticleSystem runFX;

    [SerializeField]
    private State state = State.None;
    private State nextState = State.None;

	// Use this for initialization
	void Start () {

        animator = GetComponentInChildren<Animator>();

        attackCollider = GameObject.FindGameObjectWithTag("AttackCollider").GetComponent<AttackColliderControl>();
        attackCollider.player = this;

        attackLeftTail.Stop();
        attackRightTail.Stop();

        attackVoiceAudio = gameObject.AddComponent<AudioSource>();
        swordAudio = gameObject.AddComponent<AudioSource>();
        missAudio = gameObject.AddComponent<AudioSource>();
        runAudio = gameObject.AddComponent<AudioSource>();
        runAudio.clip = runSound;
        runAudio.loop = true;
        runAudio.Play();

        runSpeed = 0.0f;
        nextState = State.Run;

    }

	// Update is called once per frame
	void Update () {

        switch (state)
        {
            case State.Run:
                {
                    if (isRunning)
                        runSpeed += Acceleration * Time.deltaTime;
                    else
                        runSpeed -= Deceleration * Time.deltaTime;

                    runSpeed = Mathf.Clamp(runSpeed, 0.0f, RunSpeedMax);

                    Vector3 velocity = GetComponent<Rigidbody>().velocity;
                    velocity.x = runSpeed;
                    // keep player stay on the ground
                    if (velocity.y > 0) velocity.y = 0;
                    GetComponent<Rigidbody>().velocity = velocity;

                    float rate = runSpeed / RunSpeedMax;
                    runAudio.pitch = Mathf.Lerp(MinRunAudioRate, MaxRunAudioRate, rate);

                    AttackControl();
                    SwordFXControl();

                    if (!isRunning && runSpeed <= 0.0f)
                    {
                        runFX.Stop();
                        nextState = State.Idle;
                    }
                    break;
                }
            case State.Miss:
                GetComponent<Rigidbody>().velocity += Vector3.down * MissGravity * Time.deltaTime;

                if (isContactFloor)
                {
                    runFX.Play();
                    GetComponent<Rigidbody>().useGravity = true;
                    nextState = State.Run;
                }
                break;
        }

        if (nextState != State.None)
        {
            switch (nextState)
            {
                case State.Idle:
                    animator.SetTrigger("Idle");
                    break;
                case State.Miss:
                    {
                        Vector3 velocity = Vector3.zero;
                        float jumpHeight = 1.0f;
                        velocity.x = -2.5f;
                        velocity.y = Mathf.Sqrt(MissGravity * jumpHeight * 2);
                        velocity.z = 0.0f;

                        GetComponent<Rigidbody>().velocity = velocity;
                        GetComponent<Rigidbody>().useGravity = false;

                        runSpeed = 0.0f;
                        animator.SetTrigger("Beaten");

                        missAudio.PlayOneShot(missSound);
                        runFX.Stop();
                        break;
                    }
            }

            state = nextState;
            nextState = State.None;
        }

#if UNITY_EDITOR
        // Move a large distance to check the floor movement
        if (Input.GetKeyDown(KeyCode.W))
        {
            transform.Translate(100.0f * FloorControl.Width * FloorControl.FloorCount, 0, 0);
        }
#endif

        // move back player to avoid overflow
        //if (transform.position.x > FloorControl.TotalWith* 100.0f)
        //{
        //    transform.position = new Vector3(transform.position.x - FloorControl.TotalWith * 100.0f, transform.position.y, transform.position.z);
        //}

    }

    void OnCollisionStay(Collision other)
    {
        if (other.gameObject.tag == "OniGroup")
        {
            if(attackTimer<=0.0f && state!= State.Miss)
            {
                nextState = State.Miss;
                gameSceneControl.OnPlayerMissed();

                var oniGroup = other.gameObject.GetComponent<OniGroupControl>();
                oniGroup.OnPlayerHitted();
            }
        }

        if (other.gameObject.tag == "Floor" && other.relativeVelocity.y > Physics.gravity.y * Time.deltaTime)
            isContactFloor = true;
    }

    void OnCollisionEnter(Collision collision)
    {
        OnCollisionStay(collision);
    }

    public void PlayHitEffect(Vector3 position)
    {
        hitFX.transform.position = position;
        hitFX.Play();
    }

    public void PlayHitSound()
    {
        swordAudio.PlayOneShot(swordSound);
    }

    public void ResetAttackDisableTimer()
    {
        attackDisableTimer = 0.0f;
    }

    public float GetAttackTime()
    {
        return AttackTime - attackTimer;
    }

    public float GetSpeedRate()
    {
        return Mathf.InverseLerp(0.0f, RunSpeedMax, runSpeed);
    }

    public void Stop()
    {
        isRunning = false;
    }

    public bool IsStopped { get { return !isRunning && runSpeed == 0.0f; }}

    public float DistanceToStop()
    {
        return runSpeed * runSpeed / (2.0f * Deceleration);
    }

    private bool IsAttacking()
    {
        bool isAttacking = false;

        if (Input.GetMouseButton(0))
            isAttacking = true;

        return isAttacking;
    }

    private void AttackControl()
    {
        if (!isPlayable) return;

        if (attackTimer > 0.0f)
        {
            // Attacking
            attackTimer -= Time.deltaTime;
            if (attackTimer <= 0)
                attackCollider.SetPowered(false);
        }
        else if (attackDisableTimer <= 0.0f)
        {
            if (IsAttacking())
            {
                attackCollider.SetPowered(true);
                attackTimer = AttackTime;
                attackDisableTimer = AttackDisableTime;

                animator.SetTrigger(animationTriggers[(int)attackMotion]);
                attackMotion = (AttackMotion)(((int)attackMotion + 1) % 2);

                attackVoiceAudio.PlayOneShot(attackSounds[attackSoundIndex]);
                attackSoundIndex = (attackSoundIndex + 1) % attackSounds.Length;
                swordAudio.PlayOneShot(swordSound);
            }
        }
        else
            attackDisableTimer -= Time.deltaTime;
    }

    private void SwordFXControl()
    {
        if (attackTimer > 0.0f)
        {
            if (animator.GetCurrentAnimatorClipInfoCount(0) == 0) return;
            var clipInfo = animator.GetCurrentAnimatorClipInfo(0)[0];
            var clip = clipInfo.clip;
            var stateInfo = animator.GetCurrentAnimatorStateInfo(0);

            AnimatedTextureExtendedUV animation = null;
            switch (attackMotion)
            {
                default:
                case AttackMotion.Right:
                    animation = attackLeftTail;
                    break;
                case AttackMotion.Left:
                    animation = attackRightTail;
                    break;
            }

            float startFrame = 2.5f;
            float startTime = startFrame / clip.frameRate;
            float currentTime = stateInfo.normalizedTime * stateInfo.length;

            if (currentTime >= startTime)
                animation.Play(currentTime - startTime);
        }
    }

}


text:
<?php
declare(strict_types=1);

/**
 * DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler.
 * @link https://github.com/gdbots/pbjc-php
 *
 * Returns an array of curies using mixin "triniti:ovp.kaltura:mixin:has-entry:v1"
 * @link http://schemas.triniti.io/json-schema/triniti/ovp.kaltura/mixin/has-entry/1-0-0.json#
 */

return [
];


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"  metadata-complete="true">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>hideEntryServlet</servlet-name>
        <servlet-class>servlet.HideEntryServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>hideEntryServlet</servlet-name>
        <url-pattern>/hideEntryServlet.do</url-pattern>
    </servlet-mapping>
</web-app>


text:
package org.apache.metamodel.neo4j;

import org.apache.metamodel.data.AbstractDataSet;
import org.apache.metamodel.data.DefaultRow;
import org.apache.metamodel.data.Row;
import org.apache.metamodel.data.SimpleDataSetHeader;
import org.apache.metamodel.query.SelectItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

final class Neo4jDataSet extends AbstractDataSet {

    private JSONObject _resultJSONObject;
    private int _currentRowIndex;
    private Row _row;

    public Neo4jDataSet(List<SelectItem> selectItems, JSONObject resultJSONObject) {
        super(selectItems);
        _resultJSONObject = resultJSONObject;
        _currentRowIndex = 0;
    }

    @Override
    public boolean next() {
        try {
            JSONArray resultsArray = _resultJSONObject.getJSONArray("results");
            if (resultsArray.length() > 0) {
                JSONObject results = resultsArray.getJSONObject(0);
                JSONArray data = results.getJSONArray("data");
                if (_currentRowIndex < data.length()) {
                    JSONObject row = data.getJSONObject(_currentRowIndex);
                    JSONArray jsonValues = row.getJSONArray("row");

                    Object[] objectValues = new Object[jsonValues.length()];
                    for (int i = 0; i < jsonValues.length(); i++) {
                        objectValues[i] = jsonValues.getString(i);
                    }
                    _row = new DefaultRow(new SimpleDataSetHeader(getSelectItems()), objectValues);
                    _currentRowIndex++;
                    return true;
                }
            } else {
                JSONArray errorArray = _resultJSONObject.getJSONArray("errors");
                JSONObject error = errorArray.getJSONObject(0);
                throw new IllegalStateException(error.toString());
            }
        } catch (JSONException e) {
            throw new IllegalStateException(e);
        }
        return false;
    }

    @Override
    public Row getRow() {
        return _row;
    }

}


text:
package uk.ac.kcl.batch;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.partition.PartitionHandler;
import org.springframework.batch.core.partition.support.Partitioner;
import org.springframework.batch.integration.partition.MessageChannelPartitionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.PollableChannel;
import uk.ac.kcl.jobParametersIncrementers.TLJobParametersIncrementer;
import uk.ac.kcl.listeners.JobCompleteNotificationListener;

/**
 *
 * @author King's College London, Richard Jackson <richgjackson@gmail.com>
 */
@Profile("remotePartitioning")
@ImportResource({"classpath:spring-master.xml","classpath:spring-slave.xml"})
@ComponentScan({"uk.ac.kcl.partitioners",
        "uk.ac.kcl.listeners",
        "uk.ac.kcl.jobParametersIncrementers"})
@EnableIntegration
@Configuration
public class RemoteConfiguration {

    @Autowired
    Environment env;

    // mandatory properties
    @Value("${jms.ip}")
    private String jmsip;
    @Value("${jms.username}")
    private String jmsUsername;
    @Value("${jms.password}")
    private String jmsPassword;

    // optional properties with default values
    @Value("${jms.closeTimeout:100000}")
    private int jmsCloseTimeout;

    @Value("${partitioner.gridSize:1}")
    private int gridSize;

    @Value("${partitioner.partitionHandlerTimeout:10000000}")
    private int partitionHandlerTimeout;

    @Value("${job.jobName:defaultJob}")
    private String jobName;

    @Bean
    @Qualifier("partitionHandler")
    public MessageChannelPartitionHandler partitionHandler(
            @Qualifier("requestChannel") MessageChannel reqChannel,
            @Qualifier("aggregatedReplyChannel") PollableChannel repChannel) {
        MessageChannelPartitionHandler handler = new MessageChannelPartitionHandler();
        handler.setGridSize(gridSize);
        handler.setStepName("compositeSlaveStep");
        handler.setReplyChannel(repChannel);
        MessagingTemplate template = new MessagingTemplate();
        template.setDefaultChannel(reqChannel);
        template.setReceiveTimeout(partitionHandlerTimeout);
        handler.setMessagingOperations(template);
        return handler;
    }
    @Bean
    public CachingConnectionFactory connectionFactory(ActiveMQConnectionFactory factory){
        return new CachingConnectionFactory(factory);
    }

    @Bean
    public ActiveMQConnectionFactory amqConnectionFactory(){
        ActiveMQConnectionFactory factory =
                new ActiveMQConnectionFactory(jmsip);
        factory.setUserName(jmsUsername);
        factory.setPassword(jmsPassword);
        factory.setCloseTimeout(jmsCloseTimeout);
        return factory;
    }
    @Bean
    public Job job(JobBuilderFactory jobs,
                   StepBuilderFactory steps,
                   Partitioner partitioner,
                   @Qualifier("partitionHandler") PartitionHandler partitionHandler,
                   JobCompleteNotificationListener jobCompleteNotificationListener,
                   @Qualifier("tLJobParametersIncrementer") TLJobParametersIncrementer runIdIncrementer

                   ) {
        return jobs.get(jobName)
                .incrementer(runIdIncrementer)
                .listener(jobCompleteNotificationListener)
                .flow(
                        steps
                                .get(jobName + "MasterStep")
                                .partitioner((jobName+"SlaveStep"), partitioner)
                                .partitionHandler(partitionHandler)
                                .build()
                )
                .end()
                .build();

    }
}


text:
class Account::AffiliateController < Account::BaseController

  def show
    @affiliate = Affiliate.find(current_user.affiliate_id)
  end

  def edit
    @affiliate = Affiliate.find(current_user.affiliate_id)
  end

  def update
    @affiliate = Affiliate.find(current_user.affiliate_id)

    if @affiliate.update(affiliate_params)
      flash[:success] = 'Your affiliate info successfully updated.'
      redirect_to action: 'show'
    else
      render 'edit'
    end
  end

  private

  def affiliate_params
    params.require(:affiliate).permit(:name, :street1, :street2, :city, :state, :zip, :country,
                                      :contact_person, :email, :phone, :fax, :website, :tax_id)
  end

end


text:
    Copyright (c) 2004 by Bruno R. Preiss, P.Eng.

    $Author: brpreiss $
    $Date: 2004/12/05 14:47:20 $
    $RCSfile: Simulation.lua,v $
    $Revision: 1.2 $

    $Id: Simulation.lua,v 1.2 2004/12/05 14:47:20 brpreiss Exp $

--]]

require "LeftistHeap"
require "Association"
require "ExponentialRV"

--{
-- A discrete-event simulation of an M/M/1 queue.
Simulation = Class.new("Simulation")

-- Constructor
function Simulation.methods:initialize()
    Simulation.super(self)
    self.eventList = LeftistHeap.new()
    self.serverBusy = false
    self.numberInQueue = 0
    self.serviceTime = ExponentialRV.new(100.0)
    self.interArrivalTime = ExponentialRV.new(100.0)
end

-- Runs the simulation up to the specified time.
-- @param timeLimit The time limit.
function Simulation.methods:run(timeLimit)
    self.eventList:enqueue(
	Simulation.Event.new(Simulation.Event.ARRIVAL, 0))
    while not self.eventList:is_empty() do
	local evt = self.eventList:dequeueMin()
	t = evt:get_time()
	if t > timeLimit then
	    self.eventList:purge()
	    break
	end
--<
	print(evt)
-->
	if evt:get_category() == Simulation.Event.ARRIVAL then
	    if not self.serverBusy then
		self.serverBusy = true
		self.eventList:enqueue(Simulation.Event.new(
		    Simulation.Event.DEPARTURE,
		    t + self.serviceTime:next()))
	    else
		self.numberInQueue = self.numberInQueue + 1
	    end
	    self.eventList:enqueue(
		Simulation.Event.new(Simulation.Event.ARRIVAL,
		    t + self.interArrivalTime:next()))
	elseif evt:get_category() ==
				Simulation.Event.DEPARTURE then
	    if self.numberInQueue == 0 then
		self.serverBusy = false
	    else
		self.numberInQueue = self.numberInQueue - 1
		self.eventList:enqueue(
		    Simulation.Event.new(
			Simulation.Event.DEPARTURE,
			t + self.serviceTime:next()))
	    end
	end
    end
end
--}>a

--{
-- Represents an event in the M/M/1 queue simulation.
Simulation.Event = Class.new("Simulation.Event", Association)

-- Arrival of a customer.
Simulation.Event.ARRIVAL = 1
-- Departure of a customer.
Simulation.Event.DEPARTURE = 2

-- Constructs an event with the given type and time.
-- @param category The type of the event.
-- @param time The time of the event.
function Simulation.Event.methods:initialize(category, time)
    Simulation.Event.super(self, time, category)
end

function Simulation.Event.methods:get_time()
    return unbox(self:get_key())
end

function Simulation.Event.methods:get_category()
    return unbox(self:get_value())
end
--}>b

-- Returns a string representation of this event.
function Simulation.Event.methods:toString()
    if self:get_category() == Simulation.Event.ARRIVAL then
	return "Event {" .. tostring(self:get_time()) ..
						", arrival}"
    elseif self:get_category() == Simulation.Event.DEPARTURE then
	return "Event {" .. tostring(self:get_time()) ..
						", departure}"
    end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta name="generator"
content="HTML Tidy for BSD/OS (vers 1st July 2002), see www.w3.org" />
<title>PostgreSQL Backend Directories</title>

PostgreSQL Backend Directories

by Bruce Momjian

Click on any of the section headings to see the source code
for that section.

 bootstrap - creates initial
template database via initdb

Because PostgreSQL requires access to system tables for almost
every operation, getting those system tables in place is a problem.
You can't just create the tables and insert data into them in the
normal way, because table creation and insertion requires the
tables to already exist. This code jams the data directly
into tables using a special syntax used only by the bootstrap
procedure.

 main - passes control to postmaster
or postgres

This checks the process name(argv[0]) and various flags, and
passes control to the postmaster or postgres backend code.

 postmaster - controls postgres
server startup/termination

This creates shared memory, and then goes into a loop waiting
for connection requests. When a connection request arrives, a
postgres backend is started, and the connection is passed to
it.

 libpq - backend libpq library
routines

This handles communication to the client processes.

 tcop - traffic cop, dispatches
request to proper module

This contains the postgres backend main handler, as well
as the code that makes calls to the parser, optimizer, executor,
and /commands functions.

 parser - converts SQL query to
query tree

This converts SQL queries coming from libpq into
command-specific structures to be used the the optimizer/executor,
or /commands routines. The SQL is lexically analyzed into
keywords, identifiers, and constants, and passed to the parser. The
parser creates command-specific structures to hold the elements of
the query. The command-specific structures are then broken apart,
checked, and passed to /commands processing routines, or
converted into Lists of Nodes to be handled by the
optimizer and executor.

 rewrite - rule and views
support

 optimizer - creates path and
plan

This uses the parser output to generate an optimal plan for the
executor.

 optimizer/path - creates
path from parser output

This takes the parser query output, and generates all possible
methods of executing the request. It examines table join order,
where clause restrictions, and optimizer table statistics to
evaluate each possible execution method, and assigns a cost to
each.

 optimizer/geqo - genetic
query optimizer

optimizer/path evaluates all possible ways to join the
requested tables. When the number of tables becomes great, the
number of tests made becomes great too. The Genetic Query Optimizer
considers each table separately, then figures the most optimal
order to perform the join. For a few tables, this method takes
longer, but for a large number of tables, it is faster. There is an
option to control when this feature is used.

 optimizer/plan - optimizes
path output

This takes the optimizer/path output, chooses the path
with the least cost, and creates a plan for the executor.

 optimizer/prep - handle
special plan cases

This does special plan processing.

 optimizer/util - optimizer
support routines

This contains support routines used by other parts of the
optimizer.

 executor - executes complex node
plans from optimizer

This handles select, insert, update, and delete
statements. The operations required to handle these statement types
include heap scans, index scans, sorting, joining tables, grouping,
aggregates, and uniqueness.

 commands - commands that do not
require the executor

These process SQL commands that do not require complex handling.
It includes vacuum, copy, alter, create table, create type,
and many others. The code is called with the structures generated
by the parser. Most of the routines do some processing, then call
lower-level functions in the catalog directory to do the actual
work.

 catalog - system catalog
manipulation

This contains functions that manipulate the system tables or
catalogs. Table, index, procedure, operator, type, and aggregate
creation and manipulation routines are here. These are low-level
routines, and are usually called by upper routines that pre-format
user requests into a predefined format.

 storage - manages various storage
systems

These allow uniform resource access by the backend.

  storage/buffer - shared
buffer pool manager

  storage/file - file
manager

  storage/freespace - free
space map

  storage/ipc - semaphores and
shared memory

  storage/large_object
- large objects

  storage/lmgr - lock
manager

  storage/page - page
manager

  storage/smgr - storage/disk
manager

 access - various data access
methods

These control the way data is accessed in heap, indexes, and
transactions.

  access/common - common
access routines

  access/gist - easy-to-define
access method system

  access/hash - hash

  access/heap - heap is use to
store data rows

  access/index - used by all
index types

  access/nbtree - Lehman and
Yao's btree management algorithm

  access/transam -
transaction manager (BEGIN/ABORT/COMMIT)

 nodes - creation/manipulation of
nodes and lists

PostgreSQL stores information about SQL queries in structures
called nodes. Nodes are generic containers that have a
type field and then a type-specific data section. Nodes are
usually placed in Lists. A List is container with an
elem element, and a next field that points to the
next List. These List structures are chained together
in a forward linked list. In this way, a chain of List s can
contain an unlimited number of Node elements, and each
Node can contain any data type. These are used extensively
in the parser, optimizer, and executor to store requests and
data.

 utils - support routines

 utils/adt - built-in data type
routines

This contains all the PostgreSQL builtin data types.

 utils/cache -
system/relation/function cache routines

PostgreSQL supports arbitrary data types, so no data types are
hard-coded into the core backend routines. When the backend needs
to find out about a type, is does a lookup of a system table.
Because these system tables are referred to often, a cache is
maintained that speeds lookups. There is a system relation cache, a
function/operator cache, and a relation information cache. This
last cache maintains information about all recently-accessed
tables, not just system ones.

 utils/error - error reporting
routines

Reports backend errors to the front end.

 utils/fmgr - function
manager

This handles the calling of dynamically-loaded functions, and
the calling of functions defined in the system tables.

 utils/hash - hash routines for
internal algorithms

These hash routines are used by the cache and memory-manager
routines to do quick lookups of dynamic data storage structures
maintained by the backend.

 utils/init - various
initialization stuff

 utils/mb - single and multibyte
encoding

 utils/misc - miscellaneous
stuff

 utils/mmgr - memory
manager(process-local memory)

When PostgreSQL allocates memory, it does so in an explicit
context. Contexts can be statement-specific, transaction-specific,
or persistent/global. By doing this, the backend can easily free
memory once a statement or transaction completes.

 utils/resowner - resource
owner tracking

 utils/sort - sort routines for
internal algorithms

When statement output must be sorted as part of a backend
operation, this code sorts the tuples, either in memory or using
disk files.

 utils/time - transaction time
qualification routines

These routines do checking of tuple internal columns to
determine if the current row is still valid, or is part of a
non-committed transaction or superseded by a new row.

 include - include files

There are include directories for each subsystem.

 lib
- support library

This houses several generic routines.

 regex - regular expression
library

This is used for regular expression handling in the backend,
i.e. '~'.

 port - compatibility routines

Maintainer: Bruce Momjian ( pgman@candle.pha.pa.us
)

 Last updated: Fri May 6 14:22:27 EDT 2005


text:
from msrest.serialization import Model

class ClientCertificateThumbprint(Model):
    """Client certificate details using thumbprint.

    :param is_admin: Is this certificate used for admin access from the
     client, if false, it is used or query only access
    :type is_admin: bool
    :param certificate_thumbprint: Certificate thumbprint
    :type certificate_thumbprint: str
    """

    _validation = {
        'is_admin': {'required': True},
        'certificate_thumbprint': {'required': True},
    }

    _attribute_map = {
        'is_admin': {'key': 'isAdmin', 'type': 'bool'},
        'certificate_thumbprint': {'key': 'certificateThumbprint', 'type': 'str'},
    }

    def __init__(self, is_admin, certificate_thumbprint):
        self.is_admin = is_admin
        self.certificate_thumbprint = certificate_thumbprint