text:
/*
 * EDACCSolverBinaryDlg.java
 *
 * Created on 09.05.2011, 19:26:38
 */
package edacc;

import edacc.manageDB.CostBinaryListModel;
import edacc.manageDB.ManageDBCosts;
import edacc.model.Cost;
import edacc.model.CostBinary;
import java.awt.Frame;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author simon, adapted from dgall (EDACCSolverBinariesDlg)
 */
public class EDACCCostBinaryDialog extends javax.swing.JDialog {

    public enum DialogMode {

        CREATE_MODE, EDIT_MODE
    };
    private CostBinary costBinary;
    private CostBinary workingCopy;
    private ManageDBCosts controller;
    private DialogMode mode;

    /** Creates new form EDACCSolverBinaryDlg */
    public EDACCCostBinaryDialog(Frame parent, CostBinary costBinary, ManageDBCosts controller, DialogMode mode) throws SQLException {
        super(parent, true);
        this.costBinary = costBinary;
        this.workingCopy = new CostBinary(costBinary);
        this.controller = controller;
        this.mode = mode;
        setLocationRelativeTo(parent);
        initComponents();
        lbRunPath.setSelectedIndex(0);
        updateCosts();
        showCostBin();
    }

    private void updateCosts() throws SQLException {
        Object sel = comboCost.getSelectedItem();
        String selName = null;
        if (sel instanceof Cost) {
            selName = ((Cost) sel).getName();
        }
        controller.reload();
        Cost selCost = null;
        comboCost.removeAllItems();
        for (Cost c : controller.getCosts()) {
            comboCost.addItem(c);
            if (selName != null && selName.equals(c.getName())) {
                selCost = c;
            }
        }
        if (selCost != null) {
            comboCost.setSelectedItem(selCost);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lBinaryName = new javax.swing.JLabel();
        lRunCommand = new javax.swing.JLabel();
        lRunPath = new javax.swing.JLabel();
        tfBinaryName = new javax.swing.JTextField();
        tfRunCommand = new javax.swing.JTextField();
        lCommand = new javax.swing.JLabel();
        lCommandPreview = new javax.swing.JLabel();
        bAddBinary = new javax.swing.JButton();
        bCancel = new javax.swing.JButton();
        lCaption = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lbRunPath = new javax.swing.JList();
        lVersion = new javax.swing.JLabel();
        tfVersion = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        tfParameters = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        comboCost = new javax.swing.JComboBox();
        btnManageCosts = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCCostBinaryDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N

        lBinaryName.setText(resourceMap.getString("lBinaryName.text")); // NOI18N
        lBinaryName.setName("lBinaryName"); // NOI18N

        lRunCommand.setText(resourceMap.getString("lRunCommand.text")); // NOI18N
        lRunCommand.setName("lRunCommand"); // NOI18N

        lRunPath.setText(resourceMap.getString("lRunPath.text")); // NOI18N
        lRunPath.setName("lRunPath"); // NOI18N

        tfBinaryName.setText(resourceMap.getString("tfBinaryName.text")); // NOI18N
        tfBinaryName.setName("tfBinaryName"); // NOI18N

        tfRunCommand.setText(resourceMap.getString("tfRunCommand.text")); // NOI18N
        tfRunCommand.setName("tfRunCommand"); // NOI18N
        tfRunCommand.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfRunCommandChanged(evt);
            }
        });

        lCommand.setText(resourceMap.getString("lCommand.text")); // NOI18N
        lCommand.setName("lCommand"); // NOI18N

        lCommandPreview.setText(resourceMap.getString("lCommandPreview.text")); // NOI18N
        lCommandPreview.setName("lCommandPreview"); // NOI18N

        bAddBinary.setText(resourceMap.getString("bAddBinary.text")); // NOI18N
        bAddBinary.setName("bAddBinary"); // NOI18N
        bAddBinary.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBinary(evt);
            }
        });

        bCancel.setText(resourceMap.getString("bCancel.text")); // NOI18N
        bCancel.setName("bCancel"); // NOI18N
        bCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelActionPerformed(evt);
            }
        });

        lCaption.setFont(resourceMap.getFont("lCaption.font")); // NOI18N
        lCaption.setText(resourceMap.getString("lCaption.text")); // NOI18N
        lCaption.setName("lCaption"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        lbRunPath.setModel(new CostBinaryListModel(costBinary));
        lbRunPath.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lbRunPath.setName("lbRunPath"); // NOI18N
        lbRunPath.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lbRuntPathChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lbRunPath);

        lVersion.setText(resourceMap.getString("lVersion.text")); // NOI18N
        lVersion.setName("lVersion"); // NOI18N

        tfVersion.setText(resourceMap.getString("tfVersion.text")); // NOI18N
        tfVersion.setName("tfVersion"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        tfParameters.setText(resourceMap.getString("tfParameters.text")); // NOI18N
        tfParameters.setName("tfParameters"); // NOI18N
        tfParameters.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfParametersKeyReleased(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        comboCost.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboCost.setName("comboCost"); // NOI18N

        btnManageCosts.setText(resourceMap.getString("btnManageCosts.text")); // NOI18N
        btnManageCosts.setName("btnManageCosts"); // NOI18N
        btnManageCosts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnManageCostsActionPerformed(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()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lCaption)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 476, Short.MAX_VALUE)
                        .addComponent(bAddBinary))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lRunCommand)
                            .addComponent(lBinaryName)
                            .addComponent(lRunPath)
                            .addComponent(lCommand)
                            .addComponent(lVersion)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(comboCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnManageCosts))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                            .addComponent(tfVersion, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                            .addComponent(tfBinaryName, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                            .addComponent(lCommandPreview, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                            .addComponent(tfRunCommand, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                            .addComponent(tfParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lCaption)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfBinaryName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lBinaryName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lRunPath)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfParameters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfRunCommand, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lRunCommand))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lCommandPreview)
                    .addComponent(lCommand, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lVersion)
                    .addComponent(tfVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnManageCosts))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCancel)
                    .addComponent(bAddBinary))
                .addContainerGap())
        );

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

    private void addBinary(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBinary
        costBinary.setBinaryName(tfBinaryName.getText());
        costBinary.setParameters(tfParameters.getText());

        if (comboCost.getSelectedItem() instanceof Cost) {
            costBinary.setCost((Cost) comboCost.getSelectedItem());
        } else {
            // TODO: error
            return;
        }

        costBinary.setRunCommand(tfRunCommand.getText());
        costBinary.setRunPath((String) lbRunPath.getModel().getElementAt(lbRunPath.getSelectedIndex()));
        costBinary.setVersion(tfVersion.getText());
        try {
            if (mode == DialogMode.CREATE_MODE) {
                // in create mode: add the binary to the solver, in edit mode, do nothing
                controller.addCostBinary(costBinary);
            }
            this.dispose();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "An error occured while adding Solver Binary: \n" + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_addBinary

    private void tfRunCommandChanged(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfRunCommandChanged
        updateRunCommandLine();
    }//GEN-LAST:event_tfRunCommandChanged

    private void lbRuntPathChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lbRuntPathChanged
        updateRunCommandLine();
    }//GEN-LAST:event_lbRuntPathChanged

    private void bCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelActionPerformed
        if (mode == DialogMode.EDIT_MODE) {
            // reset object to working copy (status before editing)
            costBinary.setAll(workingCopy);
        }
        this.dispose();
    }//GEN-LAST:event_bCancelActionPerformed

    private void tfParametersKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfParametersKeyReleased
        updateRunCommandLine();
    }//GEN-LAST:event_tfParametersKeyReleased

    private void btnManageCostsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManageCostsActionPerformed
        try {
            EDACCManageCostDialog dialog = new EDACCManageCostDialog(EDACCApp.getApplication().getMainFrame(), true, controller);
            dialog.setName("EDACCManageCostDialog");
            EDACCApp.getApplication().show(dialog);
            updateCosts();
        } catch (SQLException ex) {
            // TODO: error
        }
    }//GEN-LAST:event_btnManageCostsActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAddBinary;
    private javax.swing.JButton bCancel;
    private javax.swing.JButton btnManageCosts;
    private javax.swing.JComboBox comboCost;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lBinaryName;
    private javax.swing.JLabel lCaption;
    private javax.swing.JLabel lCommand;
    private javax.swing.JLabel lCommandPreview;
    private javax.swing.JLabel lRunCommand;
    private javax.swing.JLabel lRunPath;
    private javax.swing.JLabel lVersion;
    private javax.swing.JList lbRunPath;
    private javax.swing.JTextField tfBinaryName;
    private javax.swing.JTextField tfParameters;
    private javax.swing.JTextField tfRunCommand;
    private javax.swing.JTextField tfVersion;
    // End of variables declaration//GEN-END:variables

    private void updateRunCommandLine() {
        String parameters = tfParameters.getText();
        String runCommand = tfRunCommand.getText();
        String runPath = (String) lbRunPath.getModel().getElementAt(lbRunPath.getSelectedIndex());
        String command = ("".equals(runCommand) ? "" : runCommand + " ") + runPath + ("".equals(parameters) ? "" : " " + parameters);
        lCommandPreview.setText(command);
    }

    private void showCostBin() {
        if (costBinary == null) {
            return;
        }
        tfBinaryName.setText(costBinary.getBinaryName());
        tfRunCommand.setText(costBinary.getRunCommand());
        tfParameters.setText(costBinary.getParameters());
        tfVersion.setText(costBinary.getVersion());
        int selectedIndex = ((CostBinaryListModel) lbRunPath.getModel()).getIndexOf(costBinary.getRunPath());
        // if an error occured select first index
        if (selectedIndex < 0) {
            selectedIndex = 0;
        }
        lbRunPath.setSelectedIndex(selectedIndex);
        if (mode == DialogMode.CREATE_MODE) {
            this.setTitle("Add Solver Binary");
            bAddBinary.setText("Add Binary");
        } else if (mode == DialogMode.EDIT_MODE) {
            this.setTitle("Edit Solver Binary");
            bAddBinary.setText("Edit Binary");
        }
        updateRunCommandLine();
    }
}


text:
package org.nekorp.workflow.desktop.servicio.reporte.cliente;

import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 */
public class ContextoSeccion {

    private Map<String,Object> contextData;
    private XSSFWorkbook wb;
    private Sheet sheet;

    public ContextoSeccion() {
        this.contextData = new HashMap<>();
    }

    public Map<String, Object> getContextData() {
        return contextData;
    }

    public void setContextData(Map<String, Object> contextData) {
        this.contextData = contextData;
    }

    public XSSFWorkbook getWb() {
        return wb;
    }

    public void setWb(XSSFWorkbook wb) {
        this.wb = wb;
    }

    public Sheet getSheet() {
        return sheet;
    }

    public void setSheet(Sheet sheet) {
        this.sheet = sheet;
    }

    public Object get(String key) {
        return contextData.get(key);
    }

    public Object put(String key, Object value) {
        return contextData.put(key, value);
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

let angular = require('angular');

/* jshint newcap: false */
module.exports = angular.module('spinnaker.core.cache.collapsibleSectionState', [
  require('angular-cache'),
])
  .factory('collapsibleSectionStateCache', function(CacheFactory) {

    var cacheId = 'collapsibleSectionStateCache';

    try {
      CacheFactory.createCache(cacheId, {
        maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
        deleteOnExpire: 'aggressive',
        storageMode: 'localStorage',
      });
    } catch (e) {
      // trying to create a cache multiple times throws and Error
    }

    var stateCache = CacheFactory.get(cacheId);

    return {
      isSet: function(heading) {
        return stateCache.get(heading) !== undefined;
      },
      isExpanded: function(heading) {
        return stateCache.get(heading) === true;
      },
      setExpanded: function(heading, expanded) {
        stateCache.put(heading, !!expanded);
      }
    };
  })
  .name;


text:
package mysql

import (
	"database/sql/driver"
	"errors"
	"io"
)

type mysqlField struct {
	name      string
	fieldType byte
	flags     fieldFlag
}

type mysqlRows struct {
	mc      *mysqlConn
	binary  bool
	columns []mysqlField
	eof     bool
}

func (rows *mysqlRows) Columns() (columns []string) {
	columns = make([]string, len(rows.columns))
	for i := range columns {
		columns[i] = rows.columns[i].name
	}
	return
}

func (rows *mysqlRows) Close() (err error) {
	defer func() {
		rows.mc = nil
	}()

	// Remove unread packets from stream
	if !rows.eof {
		if rows.mc == nil {
			return errors.New("Invalid Connection")
		}

		err = rows.mc.readUntilEOF()
	}

	return
}

func (rows *mysqlRows) Next(dest []driver.Value) error {
	if rows.eof {
		return io.EOF
	}

	if rows.mc == nil {
		return errors.New("Invalid Connection")
	}

	// Fetch next row from stream
	var err error
	if rows.binary {
		err = rows.readBinaryRow(dest)
	} else {
		err = rows.readRow(dest)
	}

	if err == io.EOF {
		rows.eof = true
	}
	return err
}


text:
<?xml version="1.0" ?>
<Simulation color="false" verbosity="debug">
  <TestInfo>
    <name>framework/Samplers/ROM/Sobol/AnovaOnCutHDMR</name>
    <author>talbpaul</author>
    <created>2016-03-11</created>
    <classesTested>SupervisedLearning.HDMRRom</classesTested>
    <description>
      This analytically tests calculating variance using ANOVA on cut-HDMR.
    </description>
    <analytic>
      This test is analytic in the variance, Sobol sensitivities, and mean of the response.  These parameters
      are documented in the analytic tests documentation under "Second-Order ANOVA of Second-Order Cut-HDMR Expansion of Sudret".
    </analytic>
    <revisions>
      <revision author='talbpaul' date='2018-12-20'>moved ROM metadata writing from direct-to-file to direct-to-dataobject</revision>
    </revisions>
  </TestInfo>

  <RunInfo>
    <WorkingDir>AnovaCut</WorkingDir>
    <Sequence>make,train,meta,print</Sequence>
    <batchSize>1</batchSize>
  </RunInfo>

  <Steps>
    <MultiRun name="make" pauseAtEnd="False">
      <Input class="DataObjects" type="PointSet">dummyIN</Input>
      <Model class="Models" type="ExternalModel">poly</Model>
      <Sampler class="Samplers" type="Sobol">sobol</Sampler>
      <Output class="DataObjects" type="PointSet">solns</Output>
    </MultiRun>
    <IOStep name="meta">
      <Input class="Models" type="ROM">rom</Input>
      <Output class="DataObjects" type="PointSet">solns</Output>
    </IOStep>
    <IOStep name="print">
      <Input class="DataObjects" type="PointSet">solns</Input>
      <Output class="OutStreams" type="Print">dump</Output>
    </IOStep>
    <RomTrainer name="train">
      <Input class="DataObjects" type="PointSet">solns</Input>
      <Output class="Models" type="ROM">rom</Output>
    </RomTrainer>
  </Steps>

  <Distributions>
    <Uniform name="UniDist">
      <lowerBound>0</lowerBound>
      <upperBound>1</upperBound>
    </Uniform>
  </Distributions>

  <Samplers>
    <Sobol name="sobol">
      <variable name="x">
        <distribution>UniDist</distribution>
      </variable>
      <variable name="y">
        <distribution>UniDist</distribution>
      </variable>
      <variable name="z">
        <distribution>UniDist</distribution>
      </variable>
      <ROM class="Models" type="ROM">rom</ROM>
    </Sobol>
  </Samplers>

  <Models>
    <Dummy name="MyDummy" print="True" subType=""/>
    <ExternalModel ModuleToLoad="../../../AnalyticModels/sudret_sobol_poly" name="poly" subType="">
      <variables>x,y,z,ans</variables>
    </ExternalModel>
    <ROM name="rom" subType="HDMRRom">
      <SobolOrder>2</SobolOrder>
      <Target>ans</Target>
      <Features>x,y,z</Features>
      <SparseGrid>tensor</SparseGrid>
      <IndexSet>TensorProduct</IndexSet>
      <PolynomialOrder>3</PolynomialOrder>
    </ROM>
  </Models>

  <DataObjects>
    <PointSet name="dummyIN">
      <Input>x,y,z</Input>
      <Output>OutputPlaceHolder</Output>
    </PointSet>
    <PointSet name="solns">
      <Input>x,y,z</Input>
      <Output>ans</Output>
    </PointSet>
  </DataObjects>

  <OutStreams>
    <Print name="dump">
      <type>csv</type>
      <source>solns</source>
      <what>input,output</what>
    </Print>
  </OutStreams>

</Simulation>


text:
require_relative "about_jason/version"
require_relative "about_jason/about"

module AboutJason
  # Your code goes here...
end


text:
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/core/utils/DNS.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <aws/sagemaker-runtime/SageMakerRuntimeClient.h>
#include <aws/sagemaker-runtime/SageMakerRuntimeEndpoint.h>
#include <aws/sagemaker-runtime/SageMakerRuntimeErrorMarshaller.h>
#include <aws/sagemaker-runtime/model/InvokeEndpointRequest.h>
#include <aws/sagemaker-runtime/model/InvokeEndpointAsyncRequest.h>

using namespace Aws;
using namespace Aws::Auth;
using namespace Aws::Client;
using namespace Aws::SageMakerRuntime;
using namespace Aws::SageMakerRuntime::Model;
using namespace Aws::Http;
using namespace Aws::Utils::Json;

static const char* SERVICE_NAME = "sagemaker";
static const char* ALLOCATION_TAG = "SageMakerRuntimeClient";

SageMakerRuntimeClient::SageMakerRuntimeClient(const Client::ClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
    Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
        SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
    Aws::MakeShared<SageMakerRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_executor(clientConfiguration.executor)
{
  init(clientConfiguration);
}

SageMakerRuntimeClient::SageMakerRuntimeClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
    Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
         SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
    Aws::MakeShared<SageMakerRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_executor(clientConfiguration.executor)
{
  init(clientConfiguration);
}

SageMakerRuntimeClient::SageMakerRuntimeClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
  const Client::ClientConfiguration& clientConfiguration) :
  BASECLASS(clientConfiguration,
    Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider,
         SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
    Aws::MakeShared<SageMakerRuntimeErrorMarshaller>(ALLOCATION_TAG)),
    m_executor(clientConfiguration.executor)
{
  init(clientConfiguration);
}

SageMakerRuntimeClient::~SageMakerRuntimeClient()
{
}

void SageMakerRuntimeClient::init(const Client::ClientConfiguration& config)
{
  SetServiceClientName("SageMaker Runtime");
  m_configScheme = SchemeMapper::ToString(config.scheme);
  if (config.endpointOverride.empty())
  {
      m_uri = m_configScheme + "://" + SageMakerRuntimeEndpoint::ForRegion(config.region, config.useDualStack);
  }
  else
  {
      OverrideEndpoint(config.endpointOverride);
  }
}

void SageMakerRuntimeClient::OverrideEndpoint(const Aws::String& endpoint)
{
  if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0)
  {
      m_uri = endpoint;
  }
  else
  {
      m_uri = m_configScheme + "://" + endpoint;
  }
}

InvokeEndpointOutcome SageMakerRuntimeClient::InvokeEndpoint(const InvokeEndpointRequest& request) const
{
  if (!request.EndpointNameHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("InvokeEndpoint", "Required field: EndpointName, is not set");
    return InvokeEndpointOutcome(Aws::Client::AWSError<SageMakerRuntimeErrors>(SageMakerRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [EndpointName]", false));
  }
  Aws::Http::URI uri = m_uri;
  uri.AddPathSegments("/endpoints/");
  uri.AddPathSegment(request.GetEndpointName());
  uri.AddPathSegments("/invocations");
  return InvokeEndpointOutcome(MakeRequestWithUnparsedResponse(uri, request, Aws::Http::HttpMethod::HTTP_POST));
}

InvokeEndpointOutcomeCallable SageMakerRuntimeClient::InvokeEndpointCallable(const InvokeEndpointRequest& request) const
{
  auto task = Aws::MakeShared< std::packaged_task< InvokeEndpointOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->InvokeEndpoint(request); } );
  auto packagedFunction = [task]() { (*task)(); };
  m_executor->Submit(packagedFunction);
  return task->get_future();
}

void SageMakerRuntimeClient::InvokeEndpointAsync(const InvokeEndpointRequest& request, const InvokeEndpointResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  m_executor->Submit( [this, request, handler, context](){ this->InvokeEndpointAsyncHelper( request, handler, context ); } );
}

void SageMakerRuntimeClient::InvokeEndpointAsyncHelper(const InvokeEndpointRequest& request, const InvokeEndpointResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  handler(this, request, InvokeEndpoint(request), context);
}

InvokeEndpointAsyncOutcome SageMakerRuntimeClient::InvokeEndpointAsync(const InvokeEndpointAsyncRequest& request) const
{
  if (!request.EndpointNameHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("InvokeEndpointAsync", "Required field: EndpointName, is not set");
    return InvokeEndpointAsyncOutcome(Aws::Client::AWSError<SageMakerRuntimeErrors>(SageMakerRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [EndpointName]", false));
  }
  if (!request.InputLocationHasBeenSet())
  {
    AWS_LOGSTREAM_ERROR("InvokeEndpointAsync", "Required field: InputLocation, is not set");
    return InvokeEndpointAsyncOutcome(Aws::Client::AWSError<SageMakerRuntimeErrors>(SageMakerRuntimeErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [InputLocation]", false));
  }
  Aws::Http::URI uri = m_uri;
  uri.AddPathSegments("/endpoints/");
  uri.AddPathSegment(request.GetEndpointName());
  uri.AddPathSegments("/async-invocations");
  return InvokeEndpointAsyncOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}

InvokeEndpointAsyncOutcomeCallable SageMakerRuntimeClient::InvokeEndpointAsyncCallable(const InvokeEndpointAsyncRequest& request) const
{
  auto task = Aws::MakeShared< std::packaged_task< InvokeEndpointAsyncOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->InvokeEndpointAsync(request); } );
  auto packagedFunction = [task]() { (*task)(); };
  m_executor->Submit(packagedFunction);
  return task->get_future();
}

void SageMakerRuntimeClient::InvokeEndpointAsyncAsync(const InvokeEndpointAsyncRequest& request, const InvokeEndpointAsyncResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  m_executor->Submit( [this, request, handler, context](){ this->InvokeEndpointAsyncAsyncHelper( request, handler, context ); } );
}

void SageMakerRuntimeClient::InvokeEndpointAsyncAsyncHelper(const InvokeEndpointAsyncRequest& request, const InvokeEndpointAsyncResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
  handler(this, request, InvokeEndpointAsync(request), context);
}


text:
namespace UglyToad.FakeItEasy.EntityFrameworkFakes
{
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Threading;
    using System.Threading.Tasks;

    internal class TestDbAsyncQueryProvider<TEntity> : IDbAsyncQueryProvider
    {
        private readonly IQueryProvider inner;

        public TestDbAsyncQueryProvider(IQueryProvider inner)
        {
            this.inner = inner;
        }

        public IQueryable CreateQuery(Expression expression)
        {
            return new TestDbAsyncEnumerable<TEntity>(expression);
        }

        public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
        {
            return new TestDbAsyncEnumerable<TElement>(expression);
        }

        public object Execute(Expression expression)
        {
            return inner.Execute(expression);
        }

        public TResult Execute<TResult>(Expression expression)
        {
            return inner.Execute<TResult>(expression);
        }

        public Task<object> ExecuteAsync(Expression expression, CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute(expression));
        }

        public Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute<TResult>(expression));
        }
    }
}


text:
package org.innovateuk.ifs.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.WebRequest;

import java.beans.PropertyEditorSupport;
import java.time.YearMonth;
import java.time.temporal.ChronoField;
import java.util.Map;

/**
 * A property editor that captures 2 individual form attributes (one for month, one for year) and combines them into a
 * single YearMonth value that is then bound to a field on the form.
 */
@Slf4j
public class YearMonthPropertyEditor extends PropertyEditorSupport {

    private WebRequest webRequest;

    public YearMonthPropertyEditor(WebRequest webRequest) {
        this.webRequest = webRequest;
    }

    @Override
    public void setAsText(String dateFieldName) throws IllegalArgumentException {

        Map<String, String[]> parameterMap = webRequest.getParameterMap();

        int year = returnMinusOneWhenNotValid(parameterMap, dateFieldName + "YearValue", ChronoField.YEAR);
        int month = returnMinusOneWhenNotValid(parameterMap, dateFieldName + "MonthValue", ChronoField.MONTH_OF_YEAR);

        if (year == -1 || month == -1) {
            setValue(null);
        } else {
            try {
                setValue(YearMonth.of(year, month));
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
                setValue(null);
            }
        }
    }

    private int returnMinusOneWhenNotValid(Map<String, String[]> parameterMap, String parameterName, ChronoField chronoField) {
        try {
            return chronoField.checkValidIntValue(Long.valueOf(parameterMap.get(parameterName)[0]));
        } catch (Exception e){
            log.error(e.getMessage(), e);
            return -1;
        }
    }
}


text: In this chapter we introduced how to implement simple linear in python, and focused on how to read the summary table. In next chapter we will introduced multiple linear regression, which are commonly used to built models in finance and economics.


text:
package org.apache.pdfbox.contentstream.operator.graphics;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.contentstream.operator.Operator;

/**
 * h Close the path.
 *
 * @author Ben Litchfield
 */
public final class ClosePath extends GraphicsOperatorProcessor {
  private static final Log LOG = LogFactory.getLog(ClosePath.class);

  @Override
  public void process(Operator operator, List<COSBase> operands) throws IOException {
    if (context.getCurrentPoint() == null) {
      LOG.warn("ClosePath without initial MoveTo");
      return;
    }
    context.closePath();
  }

  @Override
  public String getName() {
    return "h";
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Ionic makes it incredibly easy to build beautiful and interactive mobile apps using HTML5 and AngularJS.">
<meta name="keywords" content="html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs">
<meta name="author" content="Drifty">
<meta property="og:image" content="http://ionicframework.com/img/ionic-logo-blog.png"/>

    <link rel="alternate" type="application/rss+xml" title="Ionic Framework Blog" href="http://ionicframework.com/blog/feed.xml">
    <title>URLs are for Web Apps, not Hybrid Apps</title>
    <link href="/css/site.css?12" rel="stylesheet">

        Get Ionic updates and articles on building great cross-platform mobile apps
        <form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post">
          <input id="fieldEmail" name="cm-jytylh-jytylh" type="email" placeholder="Your email" required />
          <button type="submit" class="btn btn-default btn-sm">Sign up</button>
        </form>

The Official Ionic Blog

The next generation HTML5 hybrid app development SDK

URLs are for Web Apps, not Hybrid Apps

      Tweet

    <time class="post-time">By @maxlynch on November 01, 2013</time>

When we started planning to build what soon became Ionic, we knew that we needed to take a native-focused approach to building the next great HTML5 development framework.

We felt that there were plenty of web-focused HTML5 frameworks, but few that treated HTML5 as a first-class citizen in the app store. We couldn't ignore that people increasingly look to the app store to find apps, rather than browse the web for them.

One big difference that kept coming up between web apps and native apps is how they handle URLs. Web apps utilize URLs both for the developer's convenience but also for the user's, allowing people all over the world to link directly to content and using them to delineate parts of a user interface. Native apps, in comparison, don't use URLs for UI interactions, or use them only under the hood for the developer's convenience.

In a native app, a user will never see any URLs even if the app is using URL based routing underneath. Obviously there are no URL bars or browser chrome in a native app so having URLs doesn't make sense. When used, it's merely a convenient way to manage UI state for the developer.

Yet most current HTML5 development frameworks have kept URLs as a core concept, limiting a lot of UI interaction to those that can triggered through an anchor like <a href="nextPage.html">. Things like switching to a new page, popping up a dialog box, or linking tabs. It's probably out of developer comfort, but also because the history of HTML5 and web technology is rooted in the browser app. But even then, URLs were meant to link to specific resources on the web, not to control user interface interactions.

If you are familiar with native app development, you'll know that native apps tend to utilize a lower level design pattern called the View Controller pattern (ignore the Model portion for now). The idea is pretty simple: you have a set of views (think of them as boxes or rectangles where UI elements are drawn), and then controllers that manage multiple views in tandem.

The UITabBarController on iOS is a perfect example of this. It takes a set of child controllers which each have their own set of views that make up each "page" in the tabs, and manages tabbing between them:

(don't forget to drink your vitamins, all day every day)

In the screenshot of the iOS Alarm app above, you'll notice four tab buttons with four possible pages of the tab you can select. We are currently on the "Alarm" tab. The UITabBarController holds a reference to the UITabBar view at the bottom (it even creates it for you), and then when a tab is selected, the controller makes sure to switch the pages for you.

In a Web App, you might have a distinct URL for each page in the tab. That wouldn't be the worst thing in the world for a hybrid/native app, but it soon breaks down when we look at more complicated native apps. For example, the great Yahoo! Weather app:

If you haven't used the Yahoo Weather app before (highly recommended), it features one single pane that scrolls up displaying a variety of weather information. The user can also swipe in between each city they've added, showing weather for that city:

Imagine trying to model this drag animation using a URL-to-City approach in a back or frontend framework that uses route based navigation. Let's say the first page is /cities/current and the second page is /cities/Madison-WI. When the user starts dragging to the next page, what happens? Do we navigate to /cities/Madison-WI, or do we wait until they complete the drag? If the routing system uses the URL state to know when to render each page, then we are stuck trying to hack around the router.

Instead of being a convenience, URL-based routing becomes an artistic restriction.

Ionic: Native Applied to Web, And Back Again

To native developers, this all might seem like a pedantic exercise, but for web developers moving to native development, it is often quite a change to not use URLs for common UI interactions. We don't just link to different pages using <a href="page2.html">, we use more subtle tools often powered by touch, letting the user treat our app as an open canvas.

With Ionic, we wanted to apply these native design patterns to web development. And in doing so, we realized something really exciting: HTML5 was just as powerful and flexible as native development. But better still, it had some major benefits over native: it was faster to build in, easier to port across platforms, and known by a lot more developers.

We realized that if we could build an HTML5 framework that loved native design concepts instead of avoiding them, we could enable developers to build any kind of app they dreamed up, not just ones that worked with the URL pattern.

So we decided to apply the View Controller pattern to a lot of the ways developers build UI interactions in Ionic. If you are a web developer that hasn't had much experience with native development, it will probably feel a bit strange at first. We are confident that once you see what is possible when you free yourself from the URL, you'll feel quite empowered to build great apps in HTML5.

    Tweet

    <form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post" class="form">

          <input id="fieldEmail" class="form-control" name="cm-jytylh-jytylh" type="email" placeholder="Join our list to get Ionic news and updates just like this one!" required />

            <button type="submit" class="btn btn-primary">Subscribe!</button>

    </form>

      Follow @ionicframework

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus

        A Drifty product
        created by @maxlynch,
        @adamdbradley, and
        @benjsperry. Licensed under
        MIT.

          RSS


text:
const AlfredModule = require("../../AlfredModule")
const moduleUtils = require("../../lib/moduleUtils")
const randomElement = require("../../lib/randomElement")

module.exports = class ModuleHello extends AlfredModule {

	constructor(){
		super()

		this.icon = "👋" //Un emoji
		this.name = "Hello"
		this.help = [{example:"Bonjour",description:"Venez me dire bonjour"},
				{example:"Au revoir",description:"Quand vous partez"},
				{example:"Comment t'améliorer",description:"Je vous donne les instructions pour me custommiser"}]

        this.start([/ho hi/i],moduleUtils.oneStringResponseEnd(
            ["Oh hi marc ! 👋",
                "met your mother ?"]))

		this.start([/coucou/i,
			/bonjour/i,
			/salut/i,
			/hey/i,
			/hi/i,
			/wesh/i,
			/salutations?/i],
			moduleUtils.stringResponseEnd("Bonjour"))

        this.start([/hello/i],moduleUtils.oneStringResponseEnd(
        	["🎶 From the other siiiiide 🎵",
				"🎵 Darkness my old friend 🎶",
				"🎶 Is it me you're loooking fooor 🎵",
				"🎶 Le soleil brille brille brille 🎵"]))

        this.start([/tu me pousses? [àa] bout/i],moduleUtils.oneStringResponseEnd(
        	["Aboutdabi ?",
				"Abusimbel ?",
				"Aboubacar ?",
				"Aboutissement ?"]))

		this.start([/au revoir/i,
			/bye/i,
			/a plus/i,
			/a\+/i],
			moduleUtils.stringResponseEnd("Au revoir"))

		this.start([/comment.+contribuer/i,
			/comment t[' ]am[eé]liorer/i,
			/comment ajouer des fonctionalit[ée]s/i],
			moduleUtils.stringResponseEnd(`Je ne suit qu'un robot! Vous pouvez m'améliorer en Javascript sur GitHub.
Fokez simplement le dépot https://github.com/EpicKiwi/discord-alfred puis faites une pull request.
Toute la documentation est disponible sur le dépot :wink:.`))

		this.start([
		    /bite/i,
		    /connard/i,
		    /enfoir[eé]e?/i,
		    /fdp/i,
		    /ferme-la( !)?/i,
		    /foutre/i,
		    /garce/i,
		    /gueule/i,
		    /merde/i,
		    /nique/i,
		    /putain/i,
		    /pute/i,
		    /salope?/i,
		],this.badWords)

		this.start([
		    /merci/i,
		],
		moduleUtils.stringResponseEnd(`Ce fut un plaisir :smile:`))
	}

	init(bot){
		super.init(bot)
		console.log("Hello module initialized")
	}

	badWords(matching,bot){
		let responses = [
		    "C'est n'est pas correct ",
		    "Surveille ton langage gamin ",
		    "Ta mère ne serait pas fière ",
		    "Fais attention à la manière dont tu me parles, je ne suis pas ton dealer ",
			"Les insultes est le langages des pauvres"]

		matching.reply(randomElement(responses))
		matching.conversation.end()
	}
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using PCAuthLib;
using PCDataDLL;
using TS3QueryLib.Core;
using TS3QueryLib.Core.CommandHandling;
using TS3QueryLib.Core.Common;
using TS3QueryLib.Core.Common.Responses;
using TS3QueryLib.Core.Server;
using TS3QueryLib.Core.Server.Entities;

namespace TSLogger
{
    public class LogRepo
    {

        public static bool Log()
        {
            WriteToFile("Starting Logging");
            try
            {
                ListResponse<ChannelListEntry> channelList;
                ListResponse<ClientListEntry> clientList;
                try
                {
                    using (QueryRunner queryRunner = new QueryRunner(new SyncTcpDispatcher("192.168.0.230", 10011)))
                    {
                        queryRunner.Login(SecureData.ServerUsername, SecureData.ServerPassword).GetDumpString();
                        queryRunner.SelectVirtualServerById(1);
                        queryRunner.UpdateCurrentQueryClient(new ClientModification { Nickname = "PermacallWebApp" });

                        {
                            // REAL EXCECUTED CODE
                            channelList = queryRunner.GetChannelList(true);
                            clientList = queryRunner.GetClientList(true);

                            //REMOVE AFK USERS FROM NON-AFK
                            foreach (var client in clientList)
                            {
                                if (client.ServerGroups.Contains(13) &&
                                    client.ClientIdleDuration != null)
                                {
                                    if (((TimeSpan)client.ClientIdleDuration).TotalHours > 4)
                                    {
                                        queryRunner.DeleteClientFromServerGroup(13, client.ClientDatabaseId);
                                        queryRunner.SendTextMessage(MessageTarget.Client, client.ClientId,
                                            "NON-AFK is not meant for AFK users, and since you have been idle for over 4 hours you have been moved to AFK");
                                    }
                                    else if (((TimeSpan)client.ClientIdleDuration).TotalHours > 3)
                                        queryRunner.SendTextMessage(MessageTarget.Client, client.ClientId,
                                            "NON-AFK is not meant for AFK users, and you have been idle for over 3 hours now. If you are truly not AFK take some action the server will see(like muting/unmuting, moving, AFK/unAFK)");

                                }
                            }
                        }
                        queryRunner.Logout();
                    }
                }
                catch (SocketException)
                {
                    channelList = new ListResponse<ChannelListEntry>();
                    clientList = new ListResponse<ClientListEntry>();
                }

                List<string> queries = new List<string>();
                List<Dictionary<string, object>> parameterList = new List<Dictionary<string, object>>();

                foreach (var client in clientList)
                {
                    queries.Add("INSERT INTO tslog_loggeduser(TSChannelID, TSUserID) VALUES(?, ?)");
                    Dictionary<string, object> parameters = new Dictionary<string, object>()
                    {
                        {"channelID", client.ChannelId.ToString()},
                        {"userID", client.ClientDatabaseId.ToString()}
                    };
                    parameterList.Add(parameters);

                    queries.Add("INSERT INTO tslog_TSUser(TSUserID, TSUsername) VALUES(?, ?) ON DUPLICATE KEY UPDATE TSUsername=?");
                    parameters = new Dictionary<string, object>()
                    {
                        {"TSUserID", client.ClientDatabaseId.ToString()},
                        {"TSUsername", client.Nickname},
                        {"TSUsername2", client.Nickname}
                    };
                    parameterList.Add(parameters);
                }

                queries.Add("UPDATE tslog_channel SET doesExist=0");
                parameterList.Add(new Dictionary<string, object>());

                foreach (var channel in channelList)
                {
                    queries.Add("INSERT INTO tslog_channel(channelID, channelName, parentChannelID) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE channelName=?, doesExist=1, parentChannelID=?");
                    Dictionary<string, object> parameters = new Dictionary<string, object>()
                    {
                        {"channelID", channel.ChannelId},
                        {"channelName", channel.Name},
                        {"parentChannelID", channel.ParentChannelId},
                        {"channelName2", channel.Name},
                        {"parentChannelID2", channel.ParentChannelId}
                    };
                    parameterList.Add(parameters);
                }

                var result = DB.MainDB.InsertMultiQuery(queries, parameterList);

                WriteToFile("Done with Logging");
                return result;
            }
            catch (Exception e)
            {
                WriteToFile(e.ToString());
            }
            return false;
        }

        public static void WriteToFile(string toWrite)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            sb.Append(DateTime.Now.ToLongTimeString());
            sb.Append("] ");
            sb.Append(toWrite);
            File.AppendAllLines("C:\\www\\TSLoggerLog.txt", new[] { sb.ToString() });
        }

        public static void OrderGamingChannels()
        {
            ListResponse<ChannelListEntry> channelList;
            List<ChannelScore> popularityRanks = GetDeHistoricGamingChannelPopularities();
            if (popularityRanks.Count <= 1) return;
            try
            {
                using (QueryRunner queryRunner = new QueryRunner(new SyncTcpDispatcher("192.168.0.230", 10011)))
                {
                    queryRunner.Login(SecureData.ServerUsername, SecureData.ServerPassword).GetDumpString();
                    queryRunner.SelectVirtualServerById(1);
                    queryRunner.UpdateCurrentQueryClient(new ClientModification { Nickname = "PermacallWebApp" });

                    channelList = queryRunner.GetChannelList(true);

                    uint? currentOrder = 0; //popularityRanks[0].Id;
                    foreach (var chnl in popularityRanks)
                    {
                        if (channelList.Values.Exists(x => x.Name == chnl.Name))
                        {
                            queryRunner.EditChannel(chnl.Id, new ChannelModification() { ChannelOrder = currentOrder, Description = "Channel Popularity Score: " + Math.Round(chnl.Score) });
                            currentOrder = chnl.Id;
                        }
                    }
                    queryRunner.EditChannel(8, new ChannelModification() { ChannelOrder = currentOrder }); // SET RANDOMGAME LAST

                    queryRunner.Logout();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e);
            }
        }

        public static List<uint> GetGamingChannelPopularities()
        {
            List<uint> rankResults = new List<uint>();
            string sql =
                "SELECT channel.channelID FROM tslog_tsuser tsuser INNER JOIN tslog_loggeduser log ON log.TSUserID = tsuser.TSUserID AND tsuser.TSUserID NOT IN (1, 10) AND log.Timestamp > DATE_SUB(CURDATE(), INTERVAL 30 DAY) RIGHT OUTER JOIN tslog_channel channel ON log.TSChannelID = channel.channelID WHERE channel.parentChannelID = 2 and channel.doesExist = 1 GROUP BY channel.channelID ORDER BY COUNT(channel.channelID) DESC";
            List<DBResult> results = DB.MainDB.GetMultipleResultsQuery(sql, null);
            foreach (var dbResult in results)
            {
                rankResults.Add(dbResult.Get("channelID").ToUInt());
            }
            return rankResults;
        }

        public static List<ChannelScore> GetDeHistoricGamingChannelPopularities()
        {
            List<ChannelScore> rankResults = new List<ChannelScore>();
            Dictionary<uint, ChannelScore> scores = new Dictionary<uint, ChannelScore>();

            string sql =
                "select channel.channelId, channel.channelName, IFNULL(datatable.score, 0) as score from tslog_channel channel left outer join ( select channelID, round(sum(t.age_weighted)) as score from ( select t2.*, (GREATEST((1-age*age*0.0001), 0) + GREATEST((3-age*age*0.0003), 0) + GREATEST((7-age*age*0.15), 0)) as age_weighted from ( select log.id, channel.channelName, channel.channelID, DATEDIFF(curdate(),	log.`Timestamp`) as age from tslog_tsuser tsuser inner join tslog_loggeduser log on log.TSUserID = tsuser.TSUserID and tsuser.TSUserID not in (1, 10) right outer join tslog_channel channel on log.TSChannelID = channel.channelID where channel.parentChannelID = 2 and channel.doesExist and log.Timestamp > DATE_SUB(curdate(), interval 200 day) order by log.ID desc ) t2 ) t group by t.channelID order by score desc ) datatable on datatable.channelID = channel.channelID where channel.parentChannelID = 2 and channel.doesExist order by score desc";

            List<DBResult> results = DB.MainDB.GetMultipleResultsQuery(sql, null);

            if (results != null)
            {
                foreach (var dbResult in results)
                {
                    if (!scores.ContainsKey(dbResult.Get("channelId").ToUInt()))
                        scores.Add(dbResult.Get("channelId").ToUInt(),
                            new ChannelScore(dbResult.Get("channelName"), dbResult.Get("channelId").ToUInt()));
                    scores[dbResult.Get("channelId").ToUInt()].Score += dbResult.Get("score").ToDouble();
                }
            }

            var orderedList = scores.OrderByDescending(x => x.Value.Score).ToList();

            foreach (var keyValuePair in orderedList)
            {
                rankResults.Add(keyValuePair.Value);
            }

            return rankResults;
        }
    }

}


text:
package org.apache.spark.deploy.k8s

import io.fabric8.kubernetes.api.model.{LocalObjectReferenceBuilder, PodBuilder}

import org.apache.spark.{SparkConf, SparkFunSuite}
import org.apache.spark.deploy.k8s.Config._
import org.apache.spark.deploy.k8s.Constants._
import org.apache.spark.deploy.k8s.submit._

class KubernetesConfSuite extends SparkFunSuite {

  private val APP_ARGS = Array("arg1", "arg2")
  private val CUSTOM_LABELS = Map(
    "customLabel1Key" -> "customLabel1Value",
    "customLabel2Key" -> "customLabel2Value")
  private val CUSTOM_ANNOTATIONS = Map(
    "customAnnotation1Key" -> "customAnnotation1Value",
    "customAnnotation2Key" -> "customAnnotation2Value")
  private val SECRET_NAMES_TO_MOUNT_PATHS = Map(
    "secret1" -> "/mnt/secrets/secret1",
    "secret2" -> "/mnt/secrets/secret2")
  private val SECRET_ENV_VARS = Map(
    "envName1" -> "name1:key1",
    "envName2" -> "name2:key2")
  private val CUSTOM_ENVS = Map(
    "customEnvKey1" -> "customEnvValue1",
    "customEnvKey2" -> "customEnvValue2")
  private val DRIVER_POD = new PodBuilder().build()
  private val EXECUTOR_ID = "executor-id"
  private val EXECUTOR_ENV_VARS = Map(
    "spark.executorEnv.1executorEnvVars1/var1" -> "executorEnvVars1",
    "spark.executorEnv.executorEnvVars2*var2" -> "executorEnvVars2",
    "spark.executorEnv.executorEnvVars3_var3" -> "executorEnvVars3",
    "spark.executorEnv.executorEnvVars4-var4" -> "executorEnvVars4",
    "spark.executorEnv.executorEnvVars5-var5" -> "executorEnvVars5/var5")

  test("Resolve driver labels, annotations, secret mount paths, envs, and memory overhead") {
    val sparkConf = new SparkConf(false)
      .set(MEMORY_OVERHEAD_FACTOR, 0.3)
    CUSTOM_LABELS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_DRIVER_LABEL_PREFIX$key", value)
    }
    CUSTOM_ANNOTATIONS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_DRIVER_ANNOTATION_PREFIX$key", value)
    }
    SECRET_NAMES_TO_MOUNT_PATHS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_DRIVER_SECRETS_PREFIX$key", value)
    }
    SECRET_ENV_VARS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_DRIVER_SECRET_KEY_REF_PREFIX$key", value)
    }
    CUSTOM_ENVS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_DRIVER_ENV_PREFIX$key", value)
    }

    val conf = KubernetesConf.createDriverConf(
      sparkConf,
      KubernetesTestConf.APP_ID,
      JavaMainAppResource(None),
      KubernetesTestConf.MAIN_CLASS,
      APP_ARGS)
    assert(conf.labels === Map(
      SPARK_APP_ID_LABEL -> KubernetesTestConf.APP_ID,
      SPARK_ROLE_LABEL -> SPARK_POD_DRIVER_ROLE) ++
      CUSTOM_LABELS)
    assert(conf.annotations === CUSTOM_ANNOTATIONS)
    assert(conf.secretNamesToMountPaths === SECRET_NAMES_TO_MOUNT_PATHS)
    assert(conf.secretEnvNamesToKeyRefs === SECRET_ENV_VARS)
    assert(conf.environment === CUSTOM_ENVS)
    assert(conf.sparkConf.get(MEMORY_OVERHEAD_FACTOR) === 0.3)
  }

  test("Basic executor translated fields.") {
    val conf = KubernetesConf.createExecutorConf(
      new SparkConf(false),
      EXECUTOR_ID,
      KubernetesTestConf.APP_ID,
      Some(DRIVER_POD))
    assert(conf.executorId === EXECUTOR_ID)
    assert(conf.driverPod.get === DRIVER_POD)
  }

  test("Image pull secrets.") {
    val conf = KubernetesConf.createExecutorConf(
      new SparkConf(false)
        .set(IMAGE_PULL_SECRETS, Seq("my-secret-1", "my-secret-2 ")),
      EXECUTOR_ID,
      KubernetesTestConf.APP_ID,
      Some(DRIVER_POD))
    assert(conf.imagePullSecrets ===
      Seq(
        new LocalObjectReferenceBuilder().withName("my-secret-1").build(),
        new LocalObjectReferenceBuilder().withName("my-secret-2").build()))
  }

  test("Set executor labels, annotations, and secrets") {
    val sparkConf = new SparkConf(false)
    CUSTOM_LABELS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_EXECUTOR_LABEL_PREFIX$key", value)
    }
    CUSTOM_ANNOTATIONS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_EXECUTOR_ANNOTATION_PREFIX$key", value)
    }
    SECRET_ENV_VARS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_EXECUTOR_SECRET_KEY_REF_PREFIX$key", value)
    }
    SECRET_NAMES_TO_MOUNT_PATHS.foreach { case (key, value) =>
      sparkConf.set(s"$KUBERNETES_EXECUTOR_SECRETS_PREFIX$key", value)
    }

    val conf = KubernetesConf.createExecutorConf(
      sparkConf,
      EXECUTOR_ID,
      KubernetesTestConf.APP_ID,
      Some(DRIVER_POD))
    assert(conf.labels === Map(
      SPARK_EXECUTOR_ID_LABEL -> EXECUTOR_ID,
      SPARK_APP_ID_LABEL -> KubernetesTestConf.APP_ID,
      SPARK_ROLE_LABEL -> SPARK_POD_EXECUTOR_ROLE) ++ CUSTOM_LABELS)
    assert(conf.annotations === CUSTOM_ANNOTATIONS)
    assert(conf.secretNamesToMountPaths === SECRET_NAMES_TO_MOUNT_PATHS)
    assert(conf.secretEnvNamesToKeyRefs === SECRET_ENV_VARS)
  }

  test("Verify that executorEnv key conforms to the regular specification") {
    val sparkConf = new SparkConf(false)
    EXECUTOR_ENV_VARS.foreach { case (key, value) =>
      sparkConf.set(key, value)
    }

    val conf = KubernetesConf.createExecutorConf(
      sparkConf,
      EXECUTOR_ID,
      KubernetesTestConf.APP_ID,
      Some(DRIVER_POD))
    assert(conf.environment ===
      Map(
        "executorEnvVars3_var3" -> "executorEnvVars3",
        "executorEnvVars4-var4" -> "executorEnvVars4",
        "executorEnvVars5-var5" -> "executorEnvVars5/var5"))
  }
}


text:
<!DOCTYPE html>

    <title>DashboardControllerProtocol Protocol Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

 Docs (1% documented)

         Reference

        DashboardControllerProtocol Protocol Reference

            Classes

                AppDelegate

                BFFetchedResultsController

                BaseTableViewC

                BlocMember

                CurrentBlocCellController

                CurrentBlocTableDataSource

                CurrentBlocTableViewC

                CurrentBlocTableViewCell

                DashboardController

                DashboardViewC

                DismissSideMenuView

                FriendCellController

                FriendTableController

                FriendTableViewC

                FriendTableViewCell

                GameKitManager

                MainViewC

                MapController

                MapViewC

                MultipeerManager

                Owner

                Run

                RunHistoryCellController

                RunHistoryTableController

                RunHistoryTableViewC

                RunHistoryTableViewCell

                RunPoint

                SettingsController

                SettingsTableViewC

                – Loc

                SideMenuTableController

                SideMenuTableDelegate

                – Cell

                SideMenuTableViewC

                StatisticsController

                StatisticsTableViewC

                TopMenuViewC

            Protocols

                CurrentBlocCellControllerProtocol

                DashboardControllerProtocol

                FriendCellControllerProtocol

                GameKitManagerDelegate

                GameViewPresenterDelegate

                LoadRunDelegate

                MapControllerProtocol

                MapNotificationDelegate

                MultipeerManagerDelegate

                MultipeerViewHandlerProtocol

                RequestMainDataDelegate

                RunHistoryCellControllerProtocol

                ScoreReporterDelegate

                SegueCoordinationDelegate

                SelectRowAndLoadRunProtocol

                SettingsControllerProtocol

                SideMenuTableControllerProtocol

                StatisticsControllerProtocol

                TopMenuDelegate

            Structs

                BFFormatter

                BFUnitConverter

                BFUserDefaults

                DashboardModel

                HealthKitManager

                MapRunModel

                MultipeerModel

                Path

                RandomNameGenerator

                RunStatisticsModel

                SegueIdentifier

                SettingsModel

DashboardControllerProtocol

protocol DashboardControllerProtocol: class

The mapController and mainController notify the dashboard of run-value updates.

                    dashboardModel

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    totalRunnersCount

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    time

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    distance

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    rate

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    score

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    distanceUnit

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    rateUnit

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    totalRunnersCountDidChange

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    timeDidChange

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    distanceRateUnitsDidChange

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    scoreDidChange

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    init()

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    update(blocMembersCount:)

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    update(totalSeconds:)

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    update(meters:secondsPerMeter:)

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    update(score:)

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

                    unitsMayHaveChanged()

Undocumented

Declaration

Swift

protocol DashboardControllerProtocol: class

© 2017 . All rights reserved. (Last updated: 2017-01-17)

Generated by jazzy ♪♫ v0.7.3, a Realm project.


text:
{[include file="public/head.html"]}

域名注册>>修改域名注册信息

{[$mess]}

			<form action="?c=managedomain&a=modifyDomainRegisterInfo" method="POST" role="form" class="form-horizontal" id="myform">

					用户类型:

						<input name="user_type" value="0" type="radio" {[if $list['user_type'] == 0]}checked="checked"{[/if]}/>个人
						<input name="user_type" value="1" type="radio" {[if $list['user_type'] == 1]}checked="checked"{[/if]}/>企业

					域名所有者:

						<input name="enterprise" type="text" class="form-control" value="{[$list['enterprise']]}"/>

请填写与所有者证件完全一致的企业名称或姓名.

					英文名称:

<input name="enterprise_en" type="text" class="form-control" value="{[$list['enterprise_en']]}"/>

					联系人:

<input name="contacts" type="text" class="form-control" value="{[$list['contacts']]}"/>

					英文名称:

<input name="contacts_en" type="text" class="form-control" value="{[$list['contacts_en']]}"/>

					邮箱:

<input name="email" type="text" class="form-control" value="{[$list['email']]}"/>

					地区:

						<input name="countries_region" type="text" class="form-control" value="{[$list['countries_region']]}"/>

						<input name="province" type="text" class="form-control" value="{[$list['province']]}"/>

						<input name="city" type="text" class="form-control" value="{[$list['city']]}"/>

					城市英文:

<input name="city_en" type="text" class="form-control" value="{[$list['city_en']]}"/>

					通信地址:

<input name="address" type="text" class="form-control" value="{[$list['address']]}"/>

					英文地址:

<input name="address_en" type="text" class="form-control" value="{[$list['address_en']]}"/>

					邮编:

<input name="zip_code" type="text" class="form-control" value="{[$list['zip_code']]}"/>

					手机:

<input name="phone" type="text" class="form-control" value="{[$list['phone']]}"/>

					传真:

						<input name="fax0" type="text" value="{[$list['fax0']]}" class="form-control" style="width:90%"/>
						-

						<input name="fax1" type="text" value="{[$list['fax1']]}" class="form-control" style="width:90%;"/>
						-

						<input name="fax2" type="text" value="{[$list['fax2']]}" class="form-control"/>

<input type="button" value="保存" onclick="saveForm()" class="form-control btn btns btn-success"/>

<input type="button" value="取消" onclick="returnDomain()" class="form-control btn btns btn-success"/>

			</form>

{[include file="public/foot.html"]}


text:
import sys
import unittest

try:
    import simplejson as json
except ImportError:
    import json  # NOQA

from libcloud.utils.py3 import httplib

from libcloud.common.types import InvalidCredsError
from libcloud.compute.base import NodeImage
from libcloud.compute.drivers.digitalocean import DigitalOceanNodeDriver

from libcloud.test import LibcloudTestCase, MockHttpTestCase
from libcloud.test.file_fixtures import ComputeFileFixtures
from libcloud.test.secrets import DIGITALOCEAN_v1_PARAMS
from libcloud.test.secrets import DIGITALOCEAN_v2_PARAMS

# class DigitalOceanTests(unittest.TestCase, TestCaseMixin):
class DigitalOcean_v2_Tests(LibcloudTestCase):

    def setUp(self):
        DigitalOceanNodeDriver.connectionCls.conn_classes = \
            (None, DigitalOceanMockHttp)
        DigitalOceanMockHttp.type = None
        self.driver = DigitalOceanNodeDriver(*DIGITALOCEAN_v2_PARAMS)

    def test_v2_uses_v1_key(self):
        self.assertRaises(InvalidCredsError, DigitalOceanNodeDriver,
                          *DIGITALOCEAN_v1_PARAMS, api_version='v2')

    def test_authentication(self):
        DigitalOceanMockHttp.type = 'UNAUTHORIZED'
        self.assertRaises(InvalidCredsError, self.driver.list_nodes)

    def test_list_images_success(self):
        images = self.driver.list_images()
        self.assertTrue(len(images) >= 1)

        image = images[0]
        self.assertTrue(image.id is not None)
        self.assertTrue(image.name is not None)

    def test_list_sizes_success(self):
        sizes = self.driver.list_sizes()
        self.assertTrue(len(sizes) >= 1)

        size = sizes[0]
        self.assertTrue(size.id is not None)
        self.assertEqual(size.name, '512mb')
        self.assertEqual(size.ram, 512)

        size = sizes[1]
        self.assertTrue(size.id is not None)
        self.assertEqual(size.name, '1gb')
        self.assertEqual(size.ram, 1024)

    def test_list_locations_success(self):
        locations = self.driver.list_locations()
        self.assertTrue(len(locations) >= 1)

        location = locations[0]
        self.assertEqual(location.id, 'nyc1')
        self.assertEqual(location.name, 'New York 1')

    def test_list_nodes_success(self):
        nodes = self.driver.list_nodes()
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].name, 'example.com')
        self.assertEqual(nodes[0].public_ips, ['104.236.32.182'])
        self.assertEqual(nodes[0].extra['image']['id'], 6918990)
        self.assertEqual(nodes[0].extra['size_slug'], '512mb')

    def test_create_node_invalid_size(self):
        image = NodeImage(id='invalid', name=None, driver=self.driver)
        size = self.driver.list_sizes()[0]
        location = self.driver.list_locations()[0]

        DigitalOceanMockHttp.type = 'INVALID_IMAGE'
        expected_msg = \
            r'You specified an invalid image for Droplet creation. \(code: 404\)'
        self.assertRaisesRegexp(Exception, expected_msg,
                                self.driver.create_node,
                                name='test', size=size, image=image,
                                location=location)

    def test_reboot_node_success(self):
        node = self.driver.list_nodes()[0]
        DigitalOceanMockHttp.type = 'REBOOT'
        result = self.driver.reboot_node(node)
        self.assertTrue(result)

    def test_create_image_success(self):
        node = self.driver.list_nodes()[0]
        DigitalOceanMockHttp.type = 'SNAPSHOT'
        result = self.driver.create_image(node, 'My snapshot')
        self.assertTrue(result)

    def test_get_image_success(self):
        image = self.driver.get_image(12345)
        self.assertEqual(image.name, 'My snapshot')
        self.assertEqual(image.id, '12345')
        self.assertEqual(image.extra['distribution'], 'Ubuntu')

    def test_delete_image_success(self):
        image = self.driver.get_image(12345)
        DigitalOceanMockHttp.type = 'DESTROY'
        result = self.driver.delete_image(image)
        self.assertTrue(result)

    def test_ex_power_on_node_success(self):
        node = self.driver.list_nodes()[0]
        DigitalOceanMockHttp.type = 'POWERON'
        result = self.driver.ex_power_on_node(node)
        self.assertTrue(result)

    def test_ex_shutdown_node_success(self):
        node = self.driver.list_nodes()[0]
        DigitalOceanMockHttp.type = 'SHUTDOWN'
        result = self.driver.ex_shutdown_node(node)
        self.assertTrue(result)

    def test_destroy_node_success(self):
        node = self.driver.list_nodes()[0]
        DigitalOceanMockHttp.type = 'DESTROY'
        result = self.driver.destroy_node(node)
        self.assertTrue(result)

    def test_ex_rename_node_success(self):
        node = self.driver.list_nodes()[0]
        DigitalOceanMockHttp.type = 'RENAME'
        result = self.driver.ex_rename_node(node, 'fedora helios')
        self.assertTrue(result)

    def test_list_key_pairs(self):
        keys = self.driver.list_key_pairs()
        self.assertEqual(len(keys), 1)
        self.assertEqual(keys[0].extra['id'], 7717)
        self.assertEqual(keys[0].name, 'test1')
        self.assertEqual(keys[0].public_key,
                         "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDGk5 example")

    def test_create_key_pair(self):
        DigitalOceanMockHttp.type = 'CREATE'
        key = self.driver.create_key_pair(
            name="test1",
            public_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQsxRiUKn example"
        )
        self.assertEqual(key.name, "test1")
        self.assertEqual(key.fingerprint,
                         "f5:d1:78:ed:28:72:5f:e1:ac:94:fd:1f:e0:a3:48:6d")

    def test_delete_key_pair(self):
        key = self.driver.list_key_pairs()[0]
        result = self.driver.delete_key_pair(key)
        self.assertTrue(result)

    def test__paginated_request_single_page(self):
        nodes = self.driver._paginated_request('/v2/droplets', 'droplets')
        self.assertEqual(nodes[0]['name'], 'example.com')
        self.assertEqual(nodes[0]['image']['id'], 6918990)
        self.assertEqual(nodes[0]['size_slug'], '512mb')

    def test__paginated_request_two_pages(self):
        DigitalOceanMockHttp.type = 'PAGE_ONE'
        nodes = self.driver._paginated_request('/v2/droplets', 'droplets')
        self.assertEqual(len(nodes), 2)

class DigitalOceanMockHttp(MockHttpTestCase):
    fixtures = ComputeFileFixtures('digitalocean_v2')

    def _v2_regions(self, method, url, body, headers):
        body = self.fixtures.load('list_locations.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _v2_images(self, method, url, body, headers):
        body = self.fixtures.load('list_images.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _v2_sizes(self, method, url, body, headers):
        body = self.fixtures.load('list_sizes.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _v2_droplets(self, method, url, body, headers):
        body = self.fixtures.load('list_nodes.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _v2_droplets_INVALID_IMAGE(self, method, url, body, headers):
        body = self.fixtures.load('error_invalid_image.json')
        return (httplib.NOT_FOUND, body, {},
                httplib.responses[httplib.NOT_FOUND])

    def _v2_droplets_3164444_actions_REBOOT(self, method, url, body, headers):
        # reboot_node
        body = self.fixtures.load('reboot_node.json')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])

    def _v2_droplets_3164444_DESTROY(self, method, url, body, headers):
        # destroy_node
        return (httplib.NO_CONTENT, body, {},
                httplib.responses[httplib.NO_CONTENT])

    def _v2_droplets_3164444_actions_RENAME(self, method, url, body, headers):
        # rename_node
        body = self.fixtures.load('ex_rename_node.json')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])

    def _v2_droplets_3164444_actions_SNAPSHOT(self, method, url,
                                              body, headers):
        # create_image
        body = self.fixtures.load('create_image.json')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])

    def _v2_images_12345(self, method, url, body, headers):
        # get_image
        body = self.fixtures.load('get_image.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _v2_images_12345_DESTROY(self, method, url, body, headers):
        # delete_image
        return (httplib.NO_CONTENT, body, {},
                httplib.responses[httplib.NO_CONTENT])

    def _v2_droplets_3164444_actions_POWERON(self, method, url, body, headers):
        # ex_power_on_node
        body = self.fixtures.load('ex_power_on_node.json')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])

    def _v2_droplets_3164444_actions_SHUTDOWN(self, method, url,
                                              body, headers):
        # ex_shutdown_node
        body = self.fixtures.load('ex_shutdown_node.json')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])

    def _v2_account_keys(self, method, url, body, headers):
        body = self.fixtures.load('list_key_pairs.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _v2_account_keys_7717(self, method, url, body, headers):
        # destroy_ssh_key
        return (httplib.NO_CONTENT, body, {},
                httplib.responses[httplib.NO_CONTENT])

    def _v2_account_keys_CREATE(self, method, url, body, headers):
        # create_ssh_key
        body = self.fixtures.load('create_key_pair.json')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])

    def _v2_droplets_UNAUTHORIZED(self, method, url, body, headers):
        body = self.fixtures.load('error.json')
        return (httplib.UNAUTHORIZED, body, {},
                httplib.responses[httplib.UNAUTHORIZED])

    def _v2_droplets_PAGE_ONE(self, method, url, body, headers):
        body = self.fixtures.load('list_nodes_page_1.json')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

if __name__ == '__main__':
    sys.exit(unittest.main())