text:
<?php
//Displaying branch name on each page
//session value is set from branchMasterParent view.php
$branch_name = Yii::app()->session['branch_name'];
?>

My Branch / <?php echo $branch_name ?>

 <a href="<?php echo Yii::app()->request->baseUrl; ?>/index.php/branchMaster_parent/<?php echo $_GET['pId']; ?>"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/theme_images/branches_menu.png"/> Branch

<a href="<?php echo Yii::app()->createUrl("ResponceMaster_child/viewbranchreport?branch_id=" . $_GET['pId']); ?>">   <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/theme_images/question_report.png"/> Report

<a href="<?php echo Yii::app()->createUrl("testimonials?branch_id=" . $_GET['pId']); ?>">   <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/theme_images/question_testi.png"/> Testimonials

<a href="<?php echo Yii::app()->createUrl("questionMaster_Child?pId=" . $_GET['pId']); ?>">  <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/theme_images/selected/question_branch.png"/>  Questions

<a href="<?php echo Yii::app()->createUrl("tabletMaster_child?pId=" . $_GET['pId']); ?>"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/theme_images/tablet.png"/>  Tablets

<a href="<?php echo Yii::app()->createUrl("customerCustomFieldAssignmentTable_Parent?pId=" . $_GET['pId']); ?>"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/theme_images/custom_fields.png"/> Custom Fields

Question List

                <?php if (Yii::app()->user->hasFlash('error')): ?>

                        <?php echo Yii::app()->user->getFlash('error'); ?>

                <?php endif; ?>

 <a class="btn btn-labeled btn-primary" href="<?php echo Yii::app()->request->baseUrl; ?>/index.php/branchMaster_parent/<?php echo $_GET['pId']; ?>"> Back

 <a class="btn btn-labeled btn-primary" href="<?php echo Yii::app()->request->baseUrl; ?>/index.php/questionMaster_Child/create?pId=<?php echo $_GET['pId']; ?>">  Create Question

                                Question
                                Average Rating
                                Category
                                Option Type
                                Status

                            <?php
                            $Questions = QuestionMaster::model()->findAll(array(
                                'condition' => 'branch_id = :branch_id',
                                'params' => array(':branch_id' => $pId)
                            ));

                            foreach ($Questions as $question) {
                                ?>

                                    <?php echo $question->question; ?>
                                    <?php echo QuestionMaster::getQuestionAverageFeedback($question->id); ?>
                                    <?php echo CategoryMaster::model()->findbypk($question->category_id)->category_name; ?>
                                    <?php echo OptionType::model()->findbypk($question->option_type_id)->option_type; ?>
                                    <a href="#" class="branch_status" data-type="select" data-pk="<?php echo $question->id; ?>" data-value="" data-title="Select Status"><?php echo QuestionMaster::itemAlias('status', $question->status); ?>
                                    <a class="badge badge-info" title="View Profile" data-toggle="tooltip" href="/account/index.php/questionMaster_Child/<?php echo $question->id; ?>?pId=<?php echo $pId; ?>">

                                <?php
                            }
                            ?>

                    <?php
//                    $this->widget('zii.widgets.grid.CGridView', array(
//                        'dataProvider' => $model->getDataFromPK($pId),
//                        'summaryText' => '',
//                        'itemsCssClass' => 'display table table-striped question_master',
//                        'htmlOptions' => array('class' => ''),
//                        'columns' => array(
//                            array('header' => 'No', 'value' => '($this->grid->dataProvider->pagination->currentPage*
//                                $this->grid->dataProvider->pagination->pageSize
//                                )+
//                                array_search($data,$this->grid->dataProvider->getData())+1',
//                                'htmlOptions' => array('style' => 'width: 25px; text-align:center;'),
//                            ),
//                            array(
//                                'name' => 'question',
//                                'value' => '($data->question)',
//                                'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                            ),
//                            array(
//                                'name' => 'Average Rating',
//                                'value' => '(QuestionMaster::getQuestionAverageFeedback($data->id))',
//                                'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                            ),
//                            array(
//                                'name' => 'category_id',
//                                'value' => '(CategoryMaster::model()->findbypk($data->category_id)->category_name)',
//                                'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                            ),
//                            array(
//                                'name' => 'option_type_id',
//                                'value' => '(OptionType::model()->findbypk($data->option_type_id)->option_type)',
//                                'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                            ),
//                            array(
//                                'name' => 'Status',
//                                'value' => '
data
',
//                                'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                            ), /*                             * OptionType->option_type */
//                            /* created at and updated at removed - KK */
//                            /* array(
//                              'name' => 'created_at',
//                              'value' => '($data->created_at)',
//                              'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                              ),
//                              array(
//                              'name' => 'update_at',
//                              'value' => '($data->update_at)',
//                              'headerHtmlOptions' => array('style' => 'text-align:center;'),
//                              ), */
//                            array(
//                                'class' => 'bootstrap.widgets.TbButtonColumn',
//                                'htmlOptions' => array('style' => 'width:30px'),
//                                'template' => '  {detail}',
//                                'buttons' => array
//                                    (
//                                    'detail' => array
//                                        (
//                                        'label' => 'View Question',
//                                        'icon' => 'fa fa-folder-open',
//                                        'url' => 'array("view","id"=>$data->id,"pId"=>$_GET["pId"])',
//                                        'options' => array(
//                                            'class' => 'badge badge-info',
//                                        ),
//                                    ),
////                                    'delete' => array
////                                        (
////                                        'label' => 'Update Branch',
////                                        'icon' => 'fa fa-trash-o',
////                                        'url' => 'array("delete","id"=>$data->id)',
////                                        'options' => array(
////                                            'class' => 'badge badge-info',
////                                        ),
////                                    ),
//                                )
//                            ),
//                        ),
//                    ));
                    ?>

<?php
/* @var $this QuestionMasterController */
/* @var $dataProvider CActiveDataProvider */
/**
  $this->breadcrumbs = array(
  'Question Masters',
  );

  $menu = array();
  require(dirname(__FILE__) . DIRECTORY_SEPARATOR . '_menu.php');
  $this->menu = array(
  array('label' => 'QuestionMaster', 'url' => array('index'), 'icon' => 'fa fa-list-alt', 'items' => $menu)
  );

  Yii::app()->clientScript->registerScript('search', "
  $('.search-button').click(function(){
  $('.search-form').toggle();
  return false;
  });
  $('.search-form form').submit(function(){
  $.fn.yiiGridView.update('question-master-grid', {
  data: $(this).serialize()
  });
  return false;
  });
  ");

  Yii::app()->clientScript->registerScript('refreshGridView', "
  // automatically refresh grid on 5 seconds
  //setInterval(\"$.fn.yiiGridView.update('question-master-grid')\",5000);
  ");
  ?>

  <?php
  $box = $this->beginWidget(
  'bootstrap.widgets.TbBox', array(
  'title' => 'List Question Masters',
  'headerIcon' => 'icon- fa fa-list-ol',
  'headerButtons' => array(
  array(
  'class' => 'bootstrap.widgets.TbButtonGroup',
  'type' => 'success',
  // '', 'primary', 'info', 'success', 'warning', 'danger' or 'inverse'
  'buttons' => $this->menu
  ),
  )
  )
  );
  ?>
  <?php /** $this->widget('bootstrap.widgets.TbListView',array(
  'dataProvider'=>$dataProvider,
  'itemView'=>'_view',
  )); * */
?>
<?php
/**
  $this->widget('bootstrap.widgets.TbAlert', array(
  'block' => false, // display a larger alert block?
  'fade' => true, // use transitions?
  'closeText' => '×', // close link text - if set to false, no close link is displayed
  'alerts' => array(// configurations per alert type
  'success' => array('block' => true, 'fade' => true, 'closeText' => '×'), //success, info, warning, error or danger
  'info' => array('block' => true, 'fade' => true, 'closeText' => '×'), //success, info, warning, error or danger
  'warning' => array('block' => true, 'fade' => true, 'closeText' => '×'), //success, info, warning, error or danger
  'error' => array('block' => true, 'fade' => true, 'closeText' => '×'), //success, info, warning, error or danger
  'danger' => array('block' => true, 'fade' => true, 'closeText' => '×'), //success, info, warning, error or danger
  ),
  ));
  ?>

  You may optionally enter a comparison operator (<, <=, >, >=,
  <>
  or =) at the beginning of each of your search values to specify how the comparison should be done.

  <?php echo CHtml::link('Advanced Search', '#', array('class' => 'search-button btn')); ?>

  <?php
  $this->renderPartial('_search', array(
  'model' => $model,
  ));
  ?>

  <?php echo CHtml::beginForm(array('export')); ?>
  <?php
  $this->widget('bootstrap.widgets.TbGridView', array(
  'id' => 'question-master-grid',
  'dataProvider' => $model->getDataFromPK($pId),
  'filter' => $model,
  'type' => 'striped hover', //bordered condensed
  'columns' => array(
  array('header' => 'No', 'value' => '($this->grid->dataProvider->pagination->currentPage*
  $this->grid->dataProvider->pagination->pageSize
  )+
  array_search($data,$this->grid->dataProvider->getData())+1',
  'htmlOptions' => array('style' => 'width: 25px; text-align:center;'),
  ),
  array(
  'name' => 'question',
  'value' => '($data->question)',
  'headerHtmlOptions' => array('style' => 'text-align:center;'),
  ),
  array(
  'name' => 'category_id',
  'value' => '($data->category_id)',
  'headerHtmlOptions' => array('style' => 'text-align:center;'),
  ),
  array(
  'name' => 'option_type_id',
  'value' => '($data->option_type_id)',
  'headerHtmlOptions' => array('style' => 'text-align:center;'),
  ),
  array(
  'name' => 'created_at',
  'value' => '($data->created_at)',
  'headerHtmlOptions' => array('style' => 'text-align:center;'),
  ),
  array(
  'name' => 'update_at',
  'value' => '($data->update_at)',
  'headerHtmlOptions' => array('style' => 'text-align:center;'),
  ),
  array(
  'name' => 'branch_id',
  'value' => '($data->branch_id)',
  'headerHtmlOptions' => array('style' => 'text-align:center;'),
  ),
  /*
  //Contoh
  array(
  'header' => 'Level',
  'name'=> 'ref_level_id',
  'type'=>'raw',
  'value' => '($data->Level->name)',
  // 'value' => '($data->status)?"on":"off"',
  // 'value' => '@Admin::model()->findByPk($data->createdBy)->username',
  ),
 */
/** array(
  'class' => 'bootstrap.widgets.TbButtonColumn',
  'template' => '{view} {detail}',
  'buttons' => array
  (
  'view' => array
  (
  'url' => '$data->id."|".$data->question',
  'click' => 'function(){
  data=$(this).attr("href").split("|")
  $("#myModalHeader").html(data[1]);
  $("#myModalBody").load("' . $this->createUrl('view') . '&id="+data[0]+"&asModal=true");
  $("#myModal").modal();
  return false;
  }',
  ),
  'detail' => array
  (
  'label' => 'View data under this data',
  'icon' => 'fa fa-level-down',
  'url' => 'array("view","id"=>$data->id)',
  'options' => array(
  'class' => 'badge badge-info',
  ),
  ),
  )
  ),
  ),
  ));
  ?>

  <select name="fileType" style="width:150px;">
  <option value="Excel5">EXCEL 5 (xls)</option>
  <option value="Excel2007">EXCEL 2007 (xlsx)</option>
  <option value="HTML">HTML</option>
  <option value="PDF">PDF</option>
  <option value="WORD">WORD (docx)</option>
  </select>

  <?php
  $this->widget('bootstrap.widgets.TbButton', array(
  'buttonType' => 'submit', 'icon' => 'fa fa-print', 'label' => 'Export', 'type' => 'primary'));
  ?>
  <?php echo CHtml::endForm(); ?>
  <?php $this->endWidget(); ?>
  <?php
  $this->beginWidget(
  'bootstrap.widgets.TbModal', array('id' => 'myModal')
  );
  ?>

  ×

Modal header

One fine body...

  <?php
  $this->widget(
  'bootstrap.widgets.TbButton', array(
  'label' => 'Close',
  'url' => '#',
  'htmlOptions' => array('data-dismiss' => 'modal'),
  )
  );
  ?>

  <?php $this->endWidget(); ?>
 * *
 *
 */
?>


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>

      <title>Lab Petri</title>
      <link rel="icon" href="assets/img/favicon.ico">
      <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0;"/>

Hi <?php echo $user; ?> and thank you for your inquiry.

         We will take a look into this issue and get back to you as soon as possible.

         Thank you for your patience.

      Issue:

         <?php echo $issue; ?>

         Sincerely,

         Lab Petri Team

Lab Petri 2015-<?php echo date("Y"); ?>, All Rights Reserved

redpajama_set_name: RedPajamaGithub


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZETEST_MATHTEST_DENSESUBVECTOR_UNALIGNEDTEST_H_
#define _BLAZETEST_MATHTEST_DENSESUBVECTOR_UNALIGNEDTEST_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <sstream>
#include <stdexcept>
#include <string>
#include <blaze/math/constraints/DenseVector.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/DenseSubvector.h>
#include <blazetest/system/Types.h>

namespace blazetest {

namespace mathtest {

namespace densesubvector {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Auxiliary class for all tests of the unaligned DenseSubvector class template.
//
// This class represents a test suite for the blaze::DenseSubvector class template. It performs
// a series of both compile time as well as runtime tests.
*/
class UnalignedTest
{
 public:
   //**Constructors********************************************************************************
   /*!\name Constructors */
   //@{
   explicit UnalignedTest();
   // No explicitly declared copy constructor.
   //@}
   //**********************************************************************************************

   //**Destructor**********************************************************************************
   // No explicitly declared destructor.
   //**********************************************************************************************

 private:
   //**Test functions******************************************************************************
   /*!\name Test functions */
   //@{
   void testConstructors();
   void testAssignment  ();
   void testAddAssign   ();
   void testSubAssign   ();
   void testMultAssign  ();
   void testScaling     ();
   void testSubscript   ();
   void testIterator    ();
   void testNonZeros    ();
   void testReset       ();
   void testClear       ();
   void testIsDefault   ();
   void testIsSame      ();
   void testSubvector   ();

   template< typename Type >
   void checkSize( const Type& vector, size_t expectedSize ) const;

   template< typename Type >
   void checkNonZeros( const Type& vector, size_t expectedNonZeros ) const;
   //@}
   //**********************************************************************************************

   //**Utility functions***************************************************************************
   /*!\name Utility functions */
   //@{
   void initialize();
   //@}
   //**********************************************************************************************

   //**Type definitions****************************************************************************
   typedef blaze::DynamicVector<int,blaze::rowVector>  VT;   //!< Dynamic row vector type
   typedef blaze::DenseSubvector<VT>                   SVT;  //!< Subvector type for dynamic row vectors.
   //**********************************************************************************************

   //**Member variables****************************************************************************
   /*!\name Member variables */
   //@{
   VT  vec_;   //!< Dynamic column vector.
               /*!< The 8-dimensional dense vector is initialized as
                    \f[\left(\begin{array}{*{4}{c}}
                    0 & 1 & 0 & -2 & -3 & 0 & 4 & 0 \\
                    \end{array}\right)\f]. */

   std::string test_;  //!< Label of the currently performed test.
   //@}
   //**********************************************************************************************

   //**Compile time checks*************************************************************************
   /*! \cond BLAZE_INTERNAL */
   BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( VT  );
   BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE( SVT );
   /*! \endcond */
   //**********************************************************************************************
};
//*************************************************************************************************

//=================================================================================================
//
//  TEST FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Checking the size of the given dense vector.
//
// \param vector The dense vector to be checked.
// \param expectedSize The expected size of the dense vector.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the size of the given dense vector. In case the actual size does not
// correspond to the given expected size, a \a std::runtime_error exception is thrown.
*/
template< typename Type >  // Type of the dense vector
void UnalignedTest::checkSize( const Type& vector, size_t expectedSize ) const
{
   if( size( vector ) != expectedSize ) {
      std::ostringstream oss;
      oss << " Test: " << test_ << "\n"
          << " Error: Invalid size detected\n"
          << " Details:\n"
          << "   Size         : " << size( vector ) << "\n"
          << "   Expected size: " << expectedSize << "\n";
      throw std::runtime_error( oss.str() );
   }
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Checking the number of non-zero elements of the given dense vector.
//
// \param object The dense vector to be checked.
// \param expectedNonZeros The expected number of non-zero elements.
// \return void
// \exception std::runtime_error Error detected.
//
// This function checks the number of non-zero elements of the given dense vector. In case
// the actual number of non-zero elements does not correspond to the given expected number,
// a \a std::runtime_error exception is thrown.
*/
template< typename Type >  // Type of the dense vector
void UnalignedTest::checkNonZeros( const Type& vector, size_t expectedNonZeros ) const
{
   if( nonZeros( vector ) != expectedNonZeros ) {
      std::ostringstream oss;
      oss << " Test: " << test_ << "\n"
          << " Error: Invalid number of non-zero elements\n"
          << " Details:\n"
          << "   Number of non-zeros         : " << nonZeros( vector ) << "\n"
          << "   Expected number of non-zeros: " << expectedNonZeros << "\n";
      throw std::runtime_error( oss.str() );
   }

   if( capacity( vector ) < nonZeros( vector ) ) {
      std::ostringstream oss;
      oss << " Test: " << test_ << "\n"
          << " Error: Invalid capacity detected\n"
          << " Details:\n"
          << "   Number of non-zeros: " << nonZeros( vector ) << "\n"
          << "   Capacity           : " << capacity( vector ) << "\n";
      throw std::runtime_error( oss.str() );
   }
}
//*************************************************************************************************

//=================================================================================================
//
//  GLOBAL TEST FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Testing the functionality of the unaligned DenseSubvector class template.
//
// \return void
*/
void runTest()
{
   UnalignedTest();
}
//*************************************************************************************************

//=================================================================================================
//
//  MACRO DEFINITIONS
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Macro for the execution of the unaligned DenseSubvector class test.
*/
#define RUN_DENSESUBVECTOR_UNALIGNED_TEST \
   blazetest::mathtest::densesubvector::runTest()
/*! \endcond */
//*************************************************************************************************

} // namespace densesubvector

} // namespace mathtest

} // namespace blazetest

#endif


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.impala.common;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;

/**
 * Base Unit test class that manages the Frontend fixture
 * to initialize and shut down the front-end, and to remove any
 * temporary tables created by the test. Derive tests from this class
 * if the test does anything "special." Derive from
 * {@link FrontendTestBase} for routine tests that can leverage the
 * many default functions available.
 *
 * A special test is one that:
 *
 * * Needs specialized query options.
 * * Needs specialized query handling, such as inspecting bits of the
 *   AST, decorated AST or query plan.
 *
 * In these cases, use the fixtures directly as they provide more control
 * than do the generic methods in FrontendTestBase.
 */
public abstract class AbstractFrontendTest {
  protected static FrontendFixture feFixture_ = FrontendFixture.instance();

  @BeforeClass
  public static void setUp() throws Exception {
    feFixture_.setUp();
  }

  @AfterClass
  public static void cleanUp() throws Exception {
    feFixture_.cleanUp();
  }

  @After
  public void tearDown() {
    feFixture_.tearDown();
  }
}


text:
"""Custom optimizer tests."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import random
import sys

# TODO: #6568 Remove this hack that makes dlopen() not crash.
if hasattr(sys, "getdlopenflags") and hasattr(sys, "setdlopenflags"):
  import ctypes
  sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL)

import numpy as np

from tensorflow.contrib.learn.python import learn
from tensorflow.contrib.learn.python.learn import datasets
from tensorflow.contrib.learn.python.learn import metric_spec
from tensorflow.contrib.learn.python.learn.estimators import estimator as estimator_lib
from tensorflow.contrib.learn.python.learn.estimators._sklearn import accuracy_score
from tensorflow.contrib.learn.python.learn.estimators._sklearn import train_test_split
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import momentum as momentum_lib

class FeatureEngineeringFunctionTest(test.TestCase):
  """Tests feature_engineering_fn."""

  def testFeatureEngineeringFn(self):

    def input_fn():
      return {
          "x": constant_op.constant([1.])
      }, {
          "y": constant_op.constant([11.])
      }

    def feature_engineering_fn(features, labels):
      _, _ = features, labels
      return {
          "transformed_x": constant_op.constant([9.])
      }, {
          "transformed_y": constant_op.constant([99.])
      }

    def model_fn(features, labels):
      # dummy variable:
      _ = variables.Variable([0.])
      _ = labels
      predictions = features["transformed_x"]
      loss = constant_op.constant([2.])
      return predictions, loss, control_flow_ops.no_op()

    estimator = estimator_lib.Estimator(
        model_fn=model_fn, feature_engineering_fn=feature_engineering_fn)
    estimator.fit(input_fn=input_fn, steps=1)
    prediction = next(estimator.predict(input_fn=input_fn, as_iterable=True))
    # predictions = transformed_x (9)
    self.assertEqual(9., prediction)
    metrics = estimator.evaluate(
        input_fn=input_fn, steps=1,
        metrics={"label":
                 metric_spec.MetricSpec(lambda predictions, labels: labels)})
    # labels = transformed_y (99)
    self.assertEqual(99., metrics["label"])

  def testNoneFeatureEngineeringFn(self):

    def input_fn():
      return {
          "x": constant_op.constant([1.])
      }, {
          "y": constant_op.constant([11.])
      }

    def feature_engineering_fn(features, labels):
      _, _ = features, labels
      return {
          "x": constant_op.constant([9.])
      }, {
          "y": constant_op.constant([99.])
      }

    def model_fn(features, labels):
      # dummy variable:
      _ = variables.Variable([0.])
      _ = labels
      predictions = features["x"]
      loss = constant_op.constant([2.])
      return predictions, loss, control_flow_ops.no_op()

    estimator_with_fe_fn = estimator_lib.Estimator(
        model_fn=model_fn, feature_engineering_fn=feature_engineering_fn)
    estimator_with_fe_fn.fit(input_fn=input_fn, steps=1)
    estimator_without_fe_fn = estimator_lib.Estimator(model_fn=model_fn)
    estimator_without_fe_fn.fit(input_fn=input_fn, steps=1)

    # predictions = x
    prediction_with_fe_fn = next(
        estimator_with_fe_fn.predict(
            input_fn=input_fn, as_iterable=True))
    self.assertEqual(9., prediction_with_fe_fn)
    prediction_without_fe_fn = next(
        estimator_without_fe_fn.predict(
            input_fn=input_fn, as_iterable=True))
    self.assertEqual(1., prediction_without_fe_fn)

class CustomOptimizer(test.TestCase):
  """Custom optimizer tests."""

  def testIrisMomentum(self):
    random.seed(42)

    iris = datasets.load_iris()
    x_train, x_test, y_train, y_test = train_test_split(
        iris.data, iris.target, test_size=0.2, random_state=42)

    def custom_optimizer():
      return momentum_lib.MomentumOptimizer(learning_rate=0.01, momentum=0.9)

    classifier = learn.DNNClassifier(
        hidden_units=[10, 20, 10],
        feature_columns=learn.infer_real_valued_columns_from_input(x_train),
        n_classes=3,
        optimizer=custom_optimizer,
        config=learn.RunConfig(tf_random_seed=1))
    classifier.fit(x_train, y_train, steps=400)
    predictions = np.array(list(classifier.predict_classes(x_test)))
    score = accuracy_score(y_test, predictions)

    self.assertGreater(score, 0.65, "Failed with score = {0}".format(score))

if __name__ == "__main__":
  test.main()


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('django_cron', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='job',
            name='last_run',
            field=models.DateTimeField(default=None, null=True),
        ),
    ]


text:
# sql-stringifier

sql-stringifier converts javascript arrays to correct sql queries (aka sql query builder)

[![NPM Version](https://img.shields.io/npm/v/sql-stringifier.svg)](https://www.npmjs.com/package/sql-stringifier)
[![NPM Downloads](https://img.shields.io/npm/dm/sql-stringifier.svg)](https://www.npmjs.com/package/sql-stringifier)

## Installing

```
npm install sql-stringifier
```

## Features

  * Auto escaping query values

## API

API is a subset of MongoDB's but without a **$** at the beginning.

#### Available operators
- `gt` - selects those rows where the value of the field is greater than the specified value.
- `gte` - selects the rows where the value of the field is greater than or equal to a specified value.
- `lt` - selects the rows where the value of the field is less than the specified value.
- `lte` - selects the rows where the value of the field is less than or equal to the specified value.
- `like` - SQL LIKE Operator
- `regexp` - SQL REGEXP Operator

## Usage examples

### Select data

```js
const sqlStringifier = require('sql-stringifier');

sqlStringifier.stringify({
    table: 'users',
    select: ['name', 'age'],
    where: {
        name: 'John',
        age: {
            gt: 18
        }
    }
});

// SELECT `name`, `age` FROM `users` WHERE `name` = 'John' AND `age` > 18;
```

### Insert data

```js
const sqlStringifier = require('sql-stringifier');

sqlStringifier.stringify({
    table: 'users',
    insert: {
        values: {
            name: 'John',
            age: 21
        }
    }
});

// INSERT INTO `users` (`name`, `age`) VALUES ('John', 21);
```
### Update data

```js
const sqlStringifier = require('sql-stringifier');

sqlStringifier.stringify({
    table: 'users',
    update: {
        age: 18,
    },
    where: {
        id: 10
    }
});

// UPDATE `users` SET `age` = 18 WHERE `id` = 10;
```

### Delete data

```js
const sqlStringifier = require('sql-stringifier');

sqlStringifier.stringify({
    table: 'users',
    delete: {
        where: {
            name: 'John'
        }
    }
});

// DELETE FROM `users` WHERE `name` = 'John';
```

### Limit

```js
const sqlStringifier = require('sql-stringifier');

sqlStringifier.stringify({
    table: 'users',
    select: ['name', 'age'],
    limit: [0, 20]
});

// SELECT `name`, `age` FROM `users` LIMIT 0, 20;
```

### Order by

```js
const sqlStringifier = require('sql-stringifier');

sqlStringifier.stringify({
    table: 'users',
    select: ['name', 'age'],
    order: {
        columns: ['age'],
        sort: 'ASC'
    }
});

// SELECT `name`, `age` FROM `users` ORDER BY `age` ASC;
```

### Error handling

```js
const sqlStringifier = require('sql-stringifier');

try {
    sqlStringifier.stringify({
        insert: {
            values: {
                name: 'John',
                age: 21
            }
        }
    });
} catch (error) {
    /* handle error */
}
```

### License

MIT License
Copyright (c) 2017 <kzukov.readme@gmail.com>

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

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

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


text:
/*global define*/
/*jslint devel: true */
define([
    'knockout',
    'scalejs.visualization-d3/visualizations/treemap',
    'scalejs.visualization-d3/visualizations/sunburst',
    'scalejs.visualization-d3/loader'
], function (
    ko,
    treemap,
    sunburst
) {
    'use strict';

    if (ko.bindingHandlers.treemap) {
        console.error("treemap is already setup");
    }

    if (ko.bindingHandlers.sunburst) {
        console.error("sunburst is already setup");
    }

    ko.bindingHandlers.treemap = treemap;
    ko.bindingHandlers.sunburst = sunburst;
    ko.virtualElements.allowedBindings.treemap = true;
    ko.virtualElements.allowedBindings.sunburst = true;
});


text:
package controllers

import (
	"github.com/kataras/iris/_examples/http_responsewriter/quicktemplate/templates"

	"github.com/kataras/iris"
)

// Index renders our ../templates/index.qtpl file using the compiled ../templates/index.qtpl.go file.
func Index(ctx iris.Context) {
	tmpl := &templates.Index{}

	// render the template
	ExecuteTemplate(ctx, tmpl)
}


text:
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.data.config;

import com.yahoo.bard.webservice.config.SystemConfig;
import com.yahoo.bard.webservice.config.SystemConfigProvider;
import com.yahoo.bard.webservice.data.config.dimension.DimensionLoader;
import com.yahoo.bard.webservice.data.config.metric.MetricLoader;
import com.yahoo.bard.webservice.data.config.table.TableLoader;
import com.yahoo.bard.webservice.data.dimension.DimensionDictionary;
import com.yahoo.bard.webservice.data.metric.MetricDictionary;
import com.yahoo.bard.webservice.table.LogicalTableDictionary;
import com.yahoo.bard.webservice.table.PhysicalTableDictionary;

import org.apache.lucene.search.BooleanQuery;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;

/**
 * This class acts as the topmost factory for all the configuration objects in the system.
 *  It uses the load method on each of the dimension loaders with which is it constructed to supply the system
 *  with configured tables, metrics, and dimensions.
 **
 * Once {@link #load()} is called, all the dictionaries in this object should be populated and ready to use.
 */
public class DefaultConfigurationLoader implements ConfigurationLoader {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultConfigurationLoader.class);
    private static final SystemConfig SYSTEM_CONFIG = SystemConfigProvider.getInstance();

    protected final ResourceDictionaries dictionaries = new ResourceDictionaries();

    protected final DimensionLoader dimensionLoader;
    protected final TableLoader tableLoader;
    protected final MetricLoader metricLoader;

    // Default JodaTime zone to UTC
    private static final String TIMEZONE = SYSTEM_CONFIG.getStringProperty(
            SYSTEM_CONFIG.getPackageVariableName("timezone"),
            "UTC"
    );

    /**
     * Constructor.
     *
     * @param dimensionLoader  DimensionLoader to load dimensions from
     * @param metricLoader  MetricLoader to load metrics from
     * @param tableLoader  TableLoader to load tables from
     */
    @Inject
    public DefaultConfigurationLoader(
            DimensionLoader dimensionLoader,
            MetricLoader metricLoader,
            TableLoader tableLoader
    ) {
        DateTimeZone.setDefault(DateTimeZone.forID(TIMEZONE));

        // Set the max lucene query clauses as high as it can go
        BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE);

        this.dimensionLoader = dimensionLoader;
        this.metricLoader = metricLoader;
        this.tableLoader = tableLoader;
    }

    /**
     * Load the Dimensions, Metrics, and Tables.
     */
    @Override
    public void load() {
        dimensionLoader.loadDimensionDictionary(dictionaries.getDimensionDictionary());
        // metric loader might dependent on dimension dictionary, so load dimension first
        metricLoader.loadMetricDictionary(dictionaries.getMetricDictionary(), dictionaries.getDimensionDictionary());
        tableLoader.loadTableDictionary(dictionaries);

        LOG.info("Initialized ConfigurationLoader");
        LOG.trace(dictionaries.toString());
    }

    @Override
    public DimensionDictionary getDimensionDictionary() {
        return dictionaries.getDimensionDictionary();
    }

    @Override
    public MetricDictionary getMetricDictionary() {
        return dictionaries.getMetricDictionary();
    }

    @Override
    public LogicalTableDictionary getLogicalTableDictionary() {
        return dictionaries.getLogicalDictionary();
    }

    @Override
    public PhysicalTableDictionary getPhysicalTableDictionary() {
        return dictionaries.getPhysicalDictionary();
    }

    @Override
    public ResourceDictionaries getDictionaries() {
        return dictionaries;
    }
}


text:
namespace HiRezApi.RealmRoyale.Models
{
    using System;
    using HiRezApi.Common.Models;

    public partial class Player : BaseModel
    {
        /// <summary>
        /// Initializes a new instance of the Player class.
        /// </summary>
        public Player()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Player class.
        /// </summary>
        public Player(string retMsg, DateTime createdDatetime = default(DateTime), int id = default(int), DateTime lastLoginDatetime = default(DateTime), int level = default(int), string name = default(string), string region = default(string), long steamId = default(int))
            : base(retMsg)
        {
            CreatedDatetime = createdDatetime;
            Id = id;
            LastLoginDatetime = lastLoginDatetime;
            Level = level;
            Name = name;
            Region = region;
            SteamId = steamId;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "created_datetime")]
        public DateTime CreatedDatetime { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "id")]
        public int Id { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "last_login_datetime")]
        public DateTime LastLoginDatetime { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "level")]
        public int Level { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "region")]
        public string Region { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "steam_id")]
        public long SteamId { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public override void Validate()
        {
            base.Validate();
        }
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8" />

  <title>Rabble-rousing Rambling - Rabble-rousing Rambling</title>

  <meta name="description" content="Default Page Description" />

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="http://blog.shiv.me/css/latex.css" />
<link rel="stylesheet" href="http://blog.shiv.me/css/main.css" />

<meta name="generator" content="Hugo 0.75.1" />

Rabble-rousing Rambling

Shiva Velmurugan

Abstract

                  I'm a product manager by day, and programmer by night. I am intrigued by abstraction, programming languages and organizing data.

Apple! Are you stupid?!

  Nov 24, 2008

Here’s the the top 3 requested features from iPhone users at large.

And here’s what they thought people wanted.

Some Product Manager at Apple needs to think how much this is hurting Apple’s brand. Do they want to be branded, yet again, as a company that completely ignores their customers?! At least give some indication as to why you can’t get the top three features in. Sure they have a lot of less demanding, faithful sheep in their flock, but now they are going mainstream, and they need to get their act together.

        Read More

Review: Jamie at Home: Cook Your Way to the Good Life by Jamie Oliver

  Nov 19, 2008

Proposed GUI for C++ based twitter client

  Oct 25, 2008

I got really sick of using Adobe AIR apps that take up more and more of system memory for an app that does twitter.
I’ve decided to put my “coding for myself” hat on and write a QT based C++ application (that should be cross-platform). No name as yet, but I will find something soon. QtTwitter is taken. Mebbe, once I have a working version, I can get ownership of the project on google code.

        Read More

A Thousand Tweets

  Oct 15, 2008

How I handle 1000+ emails and 300+ blog posts a day

  Oct 15, 2008

Several people are shocked to hear that I read 1000+ emails and several hundred blog posts a day. Ofcourse, when I say that, all I mean is that, I process that much content. I read around 30-40% (That is really the signal-to-noise ratio of web content these days–and that is, if you are subscribed to high quality feeds)
[caption id="" align=“alignnone” width=“450” caption=“google reader trends”][/caption]
One of friends was curious how I can handle all that data flow, and I emailed her this:

        Read More

          ← Newer

          Older →

        Powered By Hugo / Theme HugoTeX

        Shiva Velmurugan
        ©
        2016


text:
/* jshint esnext:true */
import alt from '../../alt';

class FollowedRepoListActions {
  constructor() {
    this.generateActions(
      'getFollowedReposSuccess',
      'getFollowedReposFail'
    );
  }

  getFollowedRepos() {
    console.log("Getting a list of repos you are following!");
    // $.ajax({ url: '/api/repos/shawnxusy' })
    //   .done(data => {
    //     this.actions.getReposSuccess(data);
    //   })
    //   .fail(jqXhr => {
    //     this.actions.getReposFail(data);
    //   });
  }

}

export default alt.createActions(FollowedRepoListActions);


text:
/*
 * aminoAcidsTest.java
 *
 * Created on 17 de agosto de 2006, 20:39
 */

package enums;

import entities.Codon;
import java.lang.StringBuffer;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import junit.framework.JUnit4TestAdapter;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author Julián Atienza-Herrero. jatienza@cbm.uam.es
 */
public class aminoAcidsTest {

    public aminoAcidsTest() {
    }

    @Test public void testTranlate(){
        Assert.assertEquals(aminoAcids.F,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.T,nucleotides.T)));
        Assert.assertEquals(aminoAcids.F,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.T,nucleotides.C)));

        Assert.assertEquals(aminoAcids.L,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.T,nucleotides.A)));
        Assert.assertEquals(aminoAcids.L,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.T,nucleotides.G)));

        Assert.assertEquals(aminoAcids.L,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.T,nucleotides.T)));
        Assert.assertEquals(aminoAcids.L,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.T,nucleotides.C)));
        Assert.assertEquals(aminoAcids.L,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.T,nucleotides.A)));
        Assert.assertEquals(aminoAcids.L,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.T,nucleotides.G)));

        Assert.assertEquals(aminoAcids.I,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.T,nucleotides.T)));
        Assert.assertEquals(aminoAcids.I,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.T,nucleotides.C)));
        Assert.assertEquals(aminoAcids.I,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.T,nucleotides.A)));

        Assert.assertEquals(aminoAcids.M,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.T,nucleotides.G)));

        Assert.assertEquals(aminoAcids.V,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.T,nucleotides.T)));
        Assert.assertEquals(aminoAcids.V,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.T,nucleotides.C)));
        Assert.assertEquals(aminoAcids.V,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.T,nucleotides.A)));
        Assert.assertEquals(aminoAcids.V,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.T,nucleotides.G)));

        Assert.assertEquals(aminoAcids.S,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.C,nucleotides.T)));
        Assert.assertEquals(aminoAcids.S,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.C,nucleotides.C)));
        Assert.assertEquals(aminoAcids.S,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.C,nucleotides.A)));
        Assert.assertEquals(aminoAcids.S,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.C,nucleotides.G)));

        Assert.assertEquals(aminoAcids.P,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.C,nucleotides.T)));
        Assert.assertEquals(aminoAcids.P,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.C,nucleotides.C)));
        Assert.assertEquals(aminoAcids.P,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.C,nucleotides.A)));
        Assert.assertEquals(aminoAcids.P,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.C,nucleotides.G)));

        Assert.assertEquals(aminoAcids.T,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.C,nucleotides.T)));
        Assert.assertEquals(aminoAcids.T,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.C,nucleotides.C)));
        Assert.assertEquals(aminoAcids.T,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.C,nucleotides.A)));
        Assert.assertEquals(aminoAcids.T,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.C,nucleotides.G)));

        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.T)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.C)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.A)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.G)));

        Assert.assertEquals(aminoAcids.Y,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.A,nucleotides.T)));
        Assert.assertEquals(aminoAcids.Y,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.A,nucleotides.C)));

        Assert.assertEquals(aminoAcids.o,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.A,nucleotides.A)));
        Assert.assertEquals(aminoAcids.o,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.A,nucleotides.G)));
        Assert.assertEquals(aminoAcids.o,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.G,nucleotides.A)));

        Assert.assertEquals(aminoAcids.H,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.A,nucleotides.T)));
        Assert.assertEquals(aminoAcids.H,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.A,nucleotides.C)));

        Assert.assertEquals(aminoAcids.Q,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.A,nucleotides.A)));
        Assert.assertEquals(aminoAcids.Q,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.A,nucleotides.G)));

        Assert.assertEquals(aminoAcids.N,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.A,nucleotides.T)));
        Assert.assertEquals(aminoAcids.N,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.A,nucleotides.C)));

        Assert.assertEquals(aminoAcids.K,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.A,nucleotides.A)));
        Assert.assertEquals(aminoAcids.K,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.A,nucleotides.G)));

        Assert.assertEquals(aminoAcids.D,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.A,nucleotides.T)));
        Assert.assertEquals(aminoAcids.D,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.A,nucleotides.C)));

        Assert.assertEquals(aminoAcids.E,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.A,nucleotides.A)));
        Assert.assertEquals(aminoAcids.E,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.A,nucleotides.G)));

        Assert.assertEquals(aminoAcids.C,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.G,nucleotides.T)));
        Assert.assertEquals(aminoAcids.C,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.G,nucleotides.C)));

        Assert.assertEquals(aminoAcids.W,aminoAcids.translate(new Codon(nucleotides.T,nucleotides.G,nucleotides.G)));

        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.T)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.C)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.A)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.G)));

        Assert.assertEquals(aminoAcids.S,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.G,nucleotides.T)));
        Assert.assertEquals(aminoAcids.S,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.G,nucleotides.C)));

        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.G,nucleotides.A)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.G,nucleotides.G)));

        Assert.assertEquals(aminoAcids.G,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.G,nucleotides.T)));
        Assert.assertEquals(aminoAcids.G,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.G,nucleotides.C)));
        Assert.assertEquals(aminoAcids.G,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.G,nucleotides.A)));
        Assert.assertEquals(aminoAcids.G,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.G,nucleotides.G)));

        Assert.assertEquals(aminoAcids.X,aminoAcids.translate(new Codon(nucleotides.B,nucleotides.B,nucleotides.B)));

        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.B)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.D)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.H)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.K)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.M)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.N)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.R)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.S)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.V)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.W)));
        Assert.assertEquals(aminoAcids.A,aminoAcids.translate(new Codon(nucleotides.G,nucleotides.C,nucleotides.Y)));

        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.B)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.D)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.H)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.K)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.M)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.N)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.R)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.S)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.V)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.W)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.C,nucleotides.G,nucleotides.Y)));

        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.G,nucleotides.R)));

        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.M,nucleotides.G,nucleotides.R)));

        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.M,nucleotides.G,nucleotides.A)));
        Assert.assertEquals(aminoAcids.R,aminoAcids.translate(new Codon(nucleotides.M,nucleotides.G,nucleotides.G)));

        Assert.assertEquals(aminoAcids.X,aminoAcids.translate(new Codon(nucleotides.Y,nucleotides.T,nucleotides.T)));

        Assert.assertEquals(aminoAcids.X,aminoAcids.translate(new Codon(nucleotides.H,nucleotides.K,nucleotides.M)));

        Assert.assertEquals(aminoAcids.M,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.T,nucleotides.G)));

        Assert.assertEquals(aminoAcids.I,aminoAcids.translate(new Codon(nucleotides.A,nucleotides.T,nucleotides.W)));

        Assert.assertEquals("alanine",aminoAcids.A.getName());

    }
    @Test public void testToChar(){
        Assert.assertEquals('A',aminoAcids.A.toChar());
        Assert.assertEquals('R',aminoAcids.R.toChar());
        Assert.assertEquals('N',aminoAcids.N.toChar());
        Assert.assertEquals('D',aminoAcids.D.toChar());
        Assert.assertEquals('C',aminoAcids.C.toChar());
        Assert.assertEquals('Q',aminoAcids.Q.toChar());
        Assert.assertEquals('E',aminoAcids.E.toChar());
        Assert.assertEquals('G',aminoAcids.G.toChar());
        Assert.assertEquals('H',aminoAcids.H.toChar());
        Assert.assertEquals('I',aminoAcids.I.toChar());
        Assert.assertEquals('L',aminoAcids.L.toChar());
        Assert.assertEquals('K',aminoAcids.K.toChar());
        Assert.assertEquals('M',aminoAcids.M.toChar());
        Assert.assertEquals('F',aminoAcids.F.toChar());
        Assert.assertEquals('P',aminoAcids.P.toChar());
        Assert.assertEquals('S',aminoAcids.S.toChar());
        Assert.assertEquals('T',aminoAcids.T.toChar());
        Assert.assertEquals('W',aminoAcids.W.toChar());
        Assert.assertEquals('Y',aminoAcids.Y.toChar());
        Assert.assertEquals('V',aminoAcids.V.toChar());
        Assert.assertEquals('*',aminoAcids.o.toChar());
    }
    @Test(expected = IllegalArgumentException.class) public void getIllegalArgumentException(){
        char[] nucleotidesArray = new char[3];
        nucleotidesArray[0]='o';
        nucleotidesArray[1]='p';
        nucleotidesArray[2]='q';

        nucleotides[] nArray = new nucleotides[3];

        nArray[0]=nucleotides.valueOf(nucleotidesArray[0]);
        nArray[1]=nucleotides.valueOf(nucleotidesArray[1]);
        nArray[2]=nucleotides.valueOf(nucleotidesArray[2]);

    }
    @Test public void printAll(){
        StringBuffer aux = new StringBuffer();
        for(aminoAcids a:EnumSet.range(aminoAcids.A,aminoAcids.X))
            aux.append(a.toChar());
        System.out.println(aux);
    }
    public static junit.framework.Test suite(){
        return new JUnit4TestAdapter(aminoAcidsTest.class);
    }
}


text:
package com.github.gfronza.mods.bayeux.impl;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.github.gfronza.mods.bayeux.BayeuxServer;
import com.github.gfronza.mods.bayeux.impl.functions.BayeuxExtension;
import com.github.gfronza.mods.bayeux.impl.protocol.Channel;
import com.github.gfronza.mods.bayeux.impl.protocol.Session;
import com.github.gfronza.mods.bayeux.impl.protocol.Transport;

/**
 * Default implementation of the BayeuxServer.
 * @author Germano
 *
 */
public class DefaultBayeuxServer implements BayeuxServer {

	private HttpServer httpServer;
	private Vertx vertx;
	private Configurations configurations;

	private List<BayeuxExtension> incomingExtensions;
	private List<BayeuxExtension> outgoingExtensions;

	private Map<String, Session> sessions;
	private Map<String, Channel> channels;
	private Map<String, Transport> transports;

	// Later on I'll need to use a Scheduller in this class:
	// https://github.com/sendgridlabs/vertx-scheduler

	/**
	 * Creates the default bayeux server overriding the default configs.
	 * @param config
	 */
	public DefaultBayeuxServer(JsonObject configs) {
		this.configurations = Configurations.getDefault().extend(configs);
		this.initialize();
	}

	/**
	 * Creates the default bayeux server using the default configs.
	 * @param config
	 */
	public DefaultBayeuxServer() {
		this.configurations = Configurations.getDefault();
		this.initialize();
	}

	@Override
	public BayeuxServer attach(final HttpServer httpServer, final Vertx vertx) {
		this.httpServer = httpServer;
		this.vertx = vertx;

		registerRequestHandler();

		return this;
	}

	@Override
	public BayeuxExtension addIncomingExtension(BayeuxExtension extension) {
		this.incomingExtensions.add(extension);
		return extension;
	}

	@Override
	public BayeuxExtension addOutgoingExtension(BayeuxExtension extension) {
		this.outgoingExtensions.add(extension);
		return extension;
	}

	@Override
	public void removeIncomingExtension(BayeuxExtension extension) {
		this.incomingExtensions.remove(extension);
	}

	@Override
	public void removeOutgoingExtension(BayeuxExtension extension) {
		this.outgoingExtensions.remove(extension);
	}

	/**
	 * Creates a channel with the given name (if absent).
	 * @param channelName name of the channel.
	 * @return Channel created.
	 */
	@Override
	public Channel createChannel(String channelName) {
		Channel c = new Channel(channelName);
		return this.channels.putIfAbsent(channelName, c);
	}

	private void initialize() {
		this.incomingExtensions = new ArrayList<>();
		this.outgoingExtensions = new ArrayList<>();

		this.sessions = new HashMap<>();
		this.channels = new HashMap<>();
		this.transports = new LinkedHashMap<>(); // order matters here.

		createTransports();
		createMetaChannels();
	}

	private void createTransports() {
		for (String transportClass : this.configurations.getTransports()) {
			try {
				// create a new instance of the transport.
				Transport t = (Transport) Class.forName(transportClass).newInstance();

				// put it into the map.
				this.transports.put(t.getName(), t);
			} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
				Logger.getLogger("mod-bayeux.transports").log(
						Level.FINE, "Exception creating the transport: " + transportClass, e
				);
			}
		}
	}

	private void createMetaChannels() {
		this.createChannel(Channel.META_CONNECT);
		this.createChannel(Channel.META_DISCONNECT);
		this.createChannel(Channel.META_HANDSHAKE);
		this.createChannel(Channel.META_SUBSCRIBE);
		this.createChannel(Channel.META_UNSUBSCRIBE);
	}

	private void registerRequestHandler() {
	    Router router = Router.router(vertx);

	    router.route().handler(routingContext -> {
	        HttpServerRequest request = routingContext.request();
            Transport transport = getProperHttpTransport(request);

            if (transport != null) {
                transport.handle(request);
            }
            else {
                request.response().setStatusCode(400) // BAD REQUEST
                                  .setStatusMessage("Bayeux Transport Not Found")
                                  .end();
            }
	    });

	    httpServer.requestHandler(router::accept);
	}

	private Transport getProperHttpTransport(HttpServerRequest request) {
		for (Transport t : this.transports.values()) {
			if (t.accept(request)) {
				return t;
			}
		}

		return null;
	}
}


text:
package com.github.gquintana.metrics.sql;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.github.gquintana.metrics.proxy.ProxyFactory;
import com.github.gquintana.metrics.proxy.ReflectProxyFactory;

import javax.sql.DataSource;
import javax.sql.RowSet;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.WebRowSet;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Factory of {@code JdbcProxyHandler} sub classes, central class of Metrics SQL.
 * It can be used to wrap any JDBC component (connection, statement,
 * result set...).
 */
public class JdbcProxyFactory {
    /**
     * Timer manager
     */
    private final MetricHelper metricHelper;
    /**
     * Proxy factory
     */
    private final ProxyFactory proxyFactory;

    /**
     * Constructor using default {@link ReflectProxyFactory} and default {@link DefaultMetricNamingStrategy}
     * @param metricRegistry Metric registry to store metrics
     */
    public JdbcProxyFactory(MetricRegistry metricRegistry) {
        this(metricRegistry, new DefaultMetricNamingStrategy());
    }

    /**
     * Constructor
     *
     * @param registry Registry storing metrics
     * @param namingStrategy Naming strategy used to get metrics from SQL
     */
    public JdbcProxyFactory(MetricRegistry registry, MetricNamingStrategy namingStrategy) {
        this(registry, namingStrategy, new ReflectProxyFactory());
    }

    /**
     * Constructor
     *
     * @param registry Registry storing metrics
     * @param namingStrategy Naming strategy used to get metrics from SQL
     * @param proxyFactory AbstractProxyFactory to use for proxy creation
     */
    public JdbcProxyFactory(MetricRegistry registry, MetricNamingStrategy namingStrategy, ProxyFactory proxyFactory) {
        this.metricHelper = new MetricHelper(registry, namingStrategy);
        this.proxyFactory = proxyFactory;
    }
    /**
     * Create a proxy for given JDBC proxy handler
     * @param <T> Proxy type
     * @param proxyHandler Proxy handler
     * @return Proxy
     */
    private <T> T newProxy(JdbcProxyHandler<T> proxyHandler) {
        return proxyFactory.newProxy(proxyHandler, proxyHandler.getProxyClass());
    }

    /**
     * Wrap a data source to monitor it.
     *
     * @param wrappedDataSource Data source to wrap
     * @return Wrapped data source
     */
    public DataSource wrapDataSource(DataSource wrappedDataSource) {
        return newProxy(new DataSourceProxyHandler(wrappedDataSource, this));
    }

    /**
     * Wrap a connection to monitor it.
     *
     * @param wrappedConnection Connection to wrap
     * @return Wrapped connection
     */
    public Connection wrapConnection(Connection wrappedConnection) {
        Timer.Context lifeTimerContext = metricHelper.startConnectionLifeTimer();
        return newProxy(new ConnectionProxyHandler(wrappedConnection, this, lifeTimerContext));
    }

    /**
     * Wrap a simple statement to monitor it.
     *
     * @param statement Statement to wrap
     * @return Wrapped statement
     */
    public Statement wrapStatement(Statement statement) {
        Timer.Context lifeTimerContext = getMetricHelper().startStatementLifeTimer();
        return newProxy(new StatementProxyHandler(statement, this, lifeTimerContext));
    }

    /**
     * Wrap a prepared statement to monitor it.
     *
     * @param preparedStatement Prepared statement to wrap
     * @param sql SQL
     * @return Wrapped prepared statement
     */
    public PreparedStatement wrapPreparedStatement(PreparedStatement preparedStatement, String sql) {
        Query query = new Query(sql);
        Timer.Context lifeTimerContext = getMetricHelper().startPreparedStatementLifeTimer(query);
        return newProxy(new PreparedStatementProxyHandler(preparedStatement, this, query, lifeTimerContext));
    }

    /**
     * Wrap a callable statement to monitor it.
     *
     * @param callableStatement Prepared statement to wrap
     * @param sql SQL
     * @return Wrapped prepared statement
     */
    public CallableStatement wrapCallableStatement(CallableStatement callableStatement, String sql) {
        Query query = new Query(sql);
        Timer.Context lifeTimerContext = getMetricHelper().startCallableStatementLifeTimer(query);
        return newProxy(new CallableStatementProxyHandler(callableStatement, this, query, lifeTimerContext));
    }

    /**
     * Wrap a result set to monitor it.
     *
     * @param resultSet set to wrap
     * @param sql SQL related to Result set
     * @return Wrapped prepared statement
     */
    public ResultSet wrapResultSet(ResultSet resultSet, String sql) {
        Query query = new Query(sql);
        Timer.Context lifeTimerContext = metricHelper.startResultSetLifeTimer(query);
        return (ResultSet) newProxy(new ResultSetProxyHandler(resultSet, getResultSetType(resultSet), this, query, lifeTimerContext));
    }

    /**
     * Wrap a result set to monitor it.
     *
     * @param resultSet set to wrap
     * @param query SQL query of result set
     * @param lifeTimerContext Started timer
     * @return Wrapped prepared statement
     */
    public ResultSet wrapResultSet(ResultSet resultSet, Query query, Timer.Context lifeTimerContext) {
        return (ResultSet) newProxy(new ResultSetProxyHandler(resultSet, getResultSetType(resultSet), this, query, lifeTimerContext));
    }
    /**
     * Determine the interface implemented by this result set
     *
     * @param resultSet Result set
     */
    private Class<? extends ResultSet> getResultSetType(ResultSet resultSet) {
        Class<? extends ResultSet> resultSetType;
        if (resultSet instanceof RowSet) {
            if (resultSet instanceof CachedRowSet) {
                if (resultSet instanceof WebRowSet) {
                    if (resultSet instanceof FilteredRowSet) {
                        resultSetType = FilteredRowSet.class;
                    } else if (resultSet instanceof JoinRowSet) {
                        resultSetType = JoinRowSet.class;
                    } else {
                        resultSetType = WebRowSet.class;
                    }
                } else {
                    resultSetType = CachedRowSet.class;
                }
            } else if (resultSet instanceof JdbcRowSet) {
                resultSetType = JdbcRowSet.class;
            } else {
                resultSetType = RowSet.class;
            }
        } else {
            resultSetType = ResultSet.class;
        }
        return resultSetType;
    }

    public MetricHelper getMetricHelper() {
        return metricHelper;
    }
}


text:
import React from "react";
import { Button, Segment, Icon, Divider } from "semantic-ui-react";

export default function SocialAuthService() {
    return (
        <>
            <Divider hidden/>
            <Segment className="stacked center aligned">
                <Divider horizontal>or, use social service</Divider>
                <div>
                    <Button color="facebook" href="/oauth/facebook">
                        <Icon name="facebook"/> Facebook
                    </Button>
                    <Button color="google plus" href="/oauth/google">
                        <Icon name="google plus"/> Google
                    </Button>
                </div>
            </Segment>
        </>
    );
}


text:
use prelude::v1::*;

use cell::UnsafeCell;
use sys::sync as ffi;

pub struct RWLock { inner: UnsafeCell<ffi::SRWLOCK> }

unsafe impl Send for RWLock {}
unsafe impl Sync for RWLock {}

impl RWLock {
    pub const fn new() -> RWLock {
        RWLock { inner: UnsafeCell::new(ffi::SRWLOCK_INIT) }
    }
    #[inline]
    pub unsafe fn read(&self) {
        ffi::AcquireSRWLockShared(self.inner.get())
    }
    #[inline]
    pub unsafe fn try_read(&self) -> bool {
        ffi::TryAcquireSRWLockShared(self.inner.get()) != 0
    }
    #[inline]
    pub unsafe fn write(&self) {
        ffi::AcquireSRWLockExclusive(self.inner.get())
    }
    #[inline]
    pub unsafe fn try_write(&self) -> bool {
        ffi::TryAcquireSRWLockExclusive(self.inner.get()) != 0
    }
    #[inline]
    pub unsafe fn read_unlock(&self) {
        ffi::ReleaseSRWLockShared(self.inner.get())
    }
    #[inline]
    pub unsafe fn write_unlock(&self) {
        ffi::ReleaseSRWLockExclusive(self.inner.get())
    }

    #[inline]
    pub unsafe fn destroy(&self) {
        // ...
    }
}


text:
<?php

namespace PaT\ImageBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PicturesRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PicturesRepository extends EntityRepository
{
}


text:
* Download [http://arduino.cc/en/Main/Software](Arduino IDE)

# FAQ

error: 'brief' was not declared in this scope

$ cp -r Firmware/libraries/Brief/ ~/arduino-1.0.6/libraries/

error: 'reflectaFrames' has not been declared


text:
package com.taobao.api.request;

import com.taobao.api.internal.util.RequestCheckUtils;
import java.util.Map;

import com.taobao.api.TaobaoRequest;
import com.taobao.api.internal.util.TaobaoHashMap;
import com.taobao.api.response.ItemUpdateDelistingResponse;
import com.taobao.api.ApiRuleException;
/**
 * TOP API: taobao.item.update.delisting request
 *
 * @author auto create
 * @since 1.0, 2013-03-14 16:30:14
 */
public class ItemUpdateDelistingRequest implements TaobaoRequest<ItemUpdateDelistingResponse> {

	private TaobaoHashMap udfParams; // add user-defined text parameters
	private Long timestamp;

	/**
	* 商品数字ID,该参数必须
	 */
	private Long numIid;

	public void setNumIid(Long numIid) {
		this.numIid = numIid;
	}
	public Long getNumIid() {
		return this.numIid;
	}
	private Map<String,String> headerMap=new TaobaoHashMap();

	public Long getTimestamp() {
		return this.timestamp;
	}

	public void setTimestamp(Long timestamp) {
		this.timestamp = timestamp;
	}

	public String getApiMethodName() {
		return "taobao.item.update.delisting";
	}

	public Map<String, String> getTextParams() {
		TaobaoHashMap txtParams = new TaobaoHashMap();
		txtParams.put("num_iid", this.numIid);
		if(this.udfParams != null) {
			txtParams.putAll(this.udfParams);
		}
		return txtParams;
	}

	public void putOtherTextParam(String key, String value) {
		if(this.udfParams == null) {
			this.udfParams = new TaobaoHashMap();
		}
		this.udfParams.put(key, value);
	}

	public Class<ItemUpdateDelistingResponse> getResponseClass() {
		return ItemUpdateDelistingResponse.class;
	}

	public void check() throws ApiRuleException {

		RequestCheckUtils.checkNotEmpty(numIid,"numIid");
		RequestCheckUtils.checkMinValue(numIid,0L,"numIid");
	}

	public Map<String,String> getHeaderMap() {
		return headerMap;
	}
}


text:
require 'rails_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator.  If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails.  There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec.  Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.

RSpec.describe UmpiresController, :type => :controller do

  # This should return the minimal set of attributes required to create a valid
  # Umpire. As you add validations to Umpire, be sure to
  # adjust the attributes here as well.
  let(:valid_attributes) {
    skip("Add a hash of attributes valid for your model")
  }

  let(:invalid_attributes) {
    skip("Add a hash of attributes invalid for your model")
  }

  # This should return the minimal set of values that should be in the session
  # in order to pass any filters (e.g. authentication) defined in
  # UmpiresController. Be sure to keep this updated too.
  let(:valid_session) { {} }

  describe "GET index" do
    it "assigns all umpires as @umpires" do
      umpire = Umpire.create! valid_attributes
      get :index, {}, valid_session
      expect(assigns(:umpires)).to eq([umpire])
    end
  end

  describe "GET show" do
    it "assigns the requested umpire as @umpire" do
      umpire = Umpire.create! valid_attributes
      get :show, {:id => umpire.to_param}, valid_session
      expect(assigns(:umpire)).to eq(umpire)
    end
  end

  describe "GET new" do
    it "assigns a new umpire as @umpire" do
      get :new, {}, valid_session
      expect(assigns(:umpire)).to be_a_new(Umpire)
    end
  end

  describe "GET edit" do
    it "assigns the requested umpire as @umpire" do
      umpire = Umpire.create! valid_attributes
      get :edit, {:id => umpire.to_param}, valid_session
      expect(assigns(:umpire)).to eq(umpire)
    end
  end

  describe "POST create" do
    describe "with valid params" do
      it "creates a new Umpire" do
        expect {
          post :create, {:umpire => valid_attributes}, valid_session
        }.to change(Umpire, :count).by(1)
      end

      it "assigns a newly created umpire as @umpire" do
        post :create, {:umpire => valid_attributes}, valid_session
        expect(assigns(:umpire)).to be_a(Umpire)
        expect(assigns(:umpire)).to be_persisted
      end

      it "redirects to the created umpire" do
        post :create, {:umpire => valid_attributes}, valid_session
        expect(response).to redirect_to(Umpire.last)
      end
    end

    describe "with invalid params" do
      it "assigns a newly created but unsaved umpire as @umpire" do
        post :create, {:umpire => invalid_attributes}, valid_session
        expect(assigns(:umpire)).to be_a_new(Umpire)
      end

      it "re-renders the 'new' template" do
        post :create, {:umpire => invalid_attributes}, valid_session
        expect(response).to render_template("new")
      end
    end
  end

  describe "PUT update" do
    describe "with valid params" do
      let(:new_attributes) {
        skip("Add a hash of attributes valid for your model")
      }

      it "updates the requested umpire" do
        umpire = Umpire.create! valid_attributes
        put :update, {:id => umpire.to_param, :umpire => new_attributes}, valid_session
        umpire.reload
        skip("Add assertions for updated state")
      end

      it "assigns the requested umpire as @umpire" do
        umpire = Umpire.create! valid_attributes
        put :update, {:id => umpire.to_param, :umpire => valid_attributes}, valid_session
        expect(assigns(:umpire)).to eq(umpire)
      end

      it "redirects to the umpire" do
        umpire = Umpire.create! valid_attributes
        put :update, {:id => umpire.to_param, :umpire => valid_attributes}, valid_session
        expect(response).to redirect_to(umpire)
      end
    end

    describe "with invalid params" do
      it "assigns the umpire as @umpire" do
        umpire = Umpire.create! valid_attributes
        put :update, {:id => umpire.to_param, :umpire => invalid_attributes}, valid_session
        expect(assigns(:umpire)).to eq(umpire)
      end

      it "re-renders the 'edit' template" do
        umpire = Umpire.create! valid_attributes
        put :update, {:id => umpire.to_param, :umpire => invalid_attributes}, valid_session
        expect(response).to render_template("edit")
      end
    end
  end

  describe "DELETE destroy" do
    it "destroys the requested umpire" do
      umpire = Umpire.create! valid_attributes
      expect {
        delete :destroy, {:id => umpire.to_param}, valid_session
      }.to change(Umpire, :count).by(-1)
    end

    it "redirects to the umpires list" do
      umpire = Umpire.create! valid_attributes
      delete :destroy, {:id => umpire.to_param}, valid_session
      expect(response).to redirect_to(umpires_url)
    end
  end

end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_81_goodG2B.cpp
Label Definition File: CWE319_Cleartext_Tx_Sensitive_Info__w32.label.xml
Template File: sources-sinks-81_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 319 Cleartext Transmission of Sensitive Information
 * BadSource: listen_socket Read the password using a listen socket (server side)
 * GoodSource: Use a hardcoded password (one that was not sent over the network)
 * Sinks:
 *    GoodSink: Decrypt the password before using it in an authentication API call to show that it was transferred as ciphertext
 *    BadSink : Use the password directly from the source in an authentication API call to show that it was transferred as plaintext
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_81.h"

#include <windows.h>
#pragma comment(lib, "advapi32.lib")

#define HASH_INPUT "ABCDEFG123456" /* INCIDENTAL: Hardcoded crypto */

namespace CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_81
{

void CWE319_Cleartext_Tx_Sensitive_Info__w32_char_listen_socket_81_goodG2B::action(char * password) const
{
    {
        HANDLE pHandle;
        char * username = "User";
        char * domain = "Domain";
        /* Use the password in LogonUser() to establish that it is "sensitive" */
        /* POTENTIAL FLAW: Using sensitive information that was possibly sent in plaintext over the network */
        if (LogonUserA(
                    username,
                    domain,
                    password,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
    }
}

}
#endif /* OMITGOOD */


text:
//--------------------------------------------------------------------------------------------------//
//--------------------------------------------- Filters --------------------------------------------//
//--------------------------------------------------------------------------------------------------//

Router._filters = {

  isReady: function () {
    if (!this.ready()) {
      // console.log('not ready')
      this.render(getTemplate('loading'));
    }else{
      this.next();
      // console.log('ready')
    }
  },

  clearSeenMessages: function () {
    clearSeenMessages();
    this.next();
  },

  resetScroll: function () {
    var scrollTo = window.currentScroll || 0;
    var $body = $('body');
    $body.scrollTop(scrollTo);
    $body.css("min-height", 0);
  },

  /*
  isLoggedIn: function () {
    if (!(Meteor.loggingIn() || Meteor.user())) {
      throwError(i18n.t('please_sign_in_first'));
      var current = getCurrentRoute();
      if (current){
        Session.set('fromWhere', current);
      }
      this.render('entrySignIn');
    } else {
      this.next();
    }
  },
  */

  isLoggedOut: function () {
    if(Meteor.user()){
      this.render('already_logged_in');
    } else {
      this.next();
    }
  },

  isAdmin: function () {
    if(!this.ready()) return;
    if(!isAdmin()){
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  canView: function () {
    if(!this.ready() || Meteor.loggingIn()){
      this.render(getTemplate('loading'));
    } else if (!can.view()) {
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  canViewPendingPosts: function () {
    var post = this.data();
    if (!!post && post.status == STATUS_PENDING && !can.viewPendingPosts()) {
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  canViewRejectedPosts: function () {
    var post = this.data();
    if (!!post && post.status == STATUS_REJECTED && !can.viewRejectedPosts()) {
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  canPost: function () {
    if(!this.ready() || Meteor.loggingIn()){
      this.render(getTemplate('loading'));
    } else if(!can.post()) {
      flashMessage(i18n.t("sorry_you_dont_have_permissions_to_add_new_items"), "error");
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  canEditPost: function () {
    if(!this.ready()) return;
    // Already subscribed to this post by route({waitOn: ...})
    var post = Posts.findOne(this.params._id);
    if(!can.currentUserEdit(post)){
      flashMessage(i18n.t("sorry_you_cannot_edit_this_post"), "error");
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  canEditComment: function () {
    if(!this.ready()) return;
    // Already subscribed to this comment by CommentPageController
    var comment = Comments.findOne(this.params._id);
    if(!can.currentUserEdit(comment)){
      flashMessage(i18n.t("sorry_you_cannot_edit_this_comment"), "error");
      this.render(getTemplate('no_rights'));
    } else {
      this.next();
    }
  },

  hasCompletedProfile: function () {
    if(!this.ready()) return;
    var user = Meteor.user();
    if (user && ! userProfileComplete(user)){
      this.render(getTemplate('user_email'));
    } else {
      this.next();
    }
  },

  setTitle: function () {
    // if getTitle is set, use it. Otherwise default to site title.
    var title = (typeof this.getTitle === 'function') ? this.getTitle() : getSetting("title", "Telescope");
    document.title = title;
  }

};

filters = Router._filters;
coreSubscriptions = new SubsManager({
  // cache recent 50 subscriptions
  cacheLimit: 50,
  // expire any subscription after 30 minutes
  expireIn: 30
});

Meteor.startup( function (){

  if(Meteor.isClient){

    // Load Hooks

    Router.onBeforeAction( function () {
      Session.set('categorySlug', null);

      // if we're not on the search page itself, clear search query and field
      if(Router.current().route.getName() !== 'search'){
        Session.set('searchQuery', '');
        $('.search-field').val('').blur();
      }

      this.next();

    });

    // onRun Hooks

    // note: this has to run in an onRun hook, because onBeforeAction hooks can get called multiple times
    // per route, which would erase the message before the user has actually seen it
    // TODO: find a way to make this work even with HCRs.
    Router.onRun(filters.clearSeenMessages);

    // Before Hooks

    Router.onBeforeAction(filters.isReady);
    Router.onBeforeAction(filters.canView, {except: ['atSignIn', 'atSignUp', 'atForgotPwd', 'atResetPwd', 'signOut', 'join']});
    Router.onBeforeAction(filters.canViewPendingPosts, {only: ['post_page']});
    Router.onBeforeAction(filters.canViewRejectedPosts, {only: ['post_page']});
    Router.onBeforeAction(filters.hasCompletedProfile);
    Router.onBeforeAction(filters.isLoggedOut, {only: []});
    Router.onBeforeAction(filters.canPost, {only: ['posts_pending', 'post_submit']});
    Router.onBeforeAction(filters.canEditPost, {only: ['post_edit']});
    Router.onBeforeAction(filters.canEditComment, {only: ['comment_edit']});
    Router.onBeforeAction(filters.isAdmin, {only: ['posts_pending', 'all-users', 'settings', 'toolbox', 'logs']});

    Router.plugin('ensureSignedIn', {only: ['post_submit', 'post_edit', 'comment_edit']});

    // After Hooks

    // Router.onAfterAction(filters.resetScroll, {except:['posts_top', 'posts_new', 'posts_best', 'posts_pending', 'posts_category', 'all-users']});
    Router.onAfterAction(analyticsInit); // will only run once thanks to _.once()
    Router.onAfterAction(analyticsRequest); // log this request with mixpanel, etc
    Router.onAfterAction(filters.setTitle);

    // Unload Hooks

    //

  }

});


text:
'use strict';

angular.module('csyywx')
	.service('orderService', function() {
		this.order = {};
	})