text:
<?php
namespace XeroPHP\Models\PayrollAU;

use XeroPHP\Remote;

class PayRun extends Remote\Object
{

    /**
     * See PayrollCalendars
     *
     * @property string PayrollCalendarID
     */

    /**
     * Xero identifier for pay run
     *
     * @property string PayRunID
     */

    /**
     * Period Start Date for the PayRun (YYYY-MM-DD)
     *
     * @property \DateTimeInterface PayRunPeriodStartDate
     */

    /**
     * Period End Date for the PayRun (YYYY-MM-DD)
     *
     * @property \DateTimeInterface PayRunPeriodEndDate
     */

    /**
     * See PayRun Status types
     *
     * @property string PayRunStatus
     */

    /**
     * Payment Date for the PayRun (YYYY-MM-DD)
     *
     * @property \DateTimeInterface PaymentDate
     */

    /**
     * Payslip message for the PayRun
     *
     * @property string PayslipMessage
     */

    /**
     * See Payslip
     *
     * @property Payslip[] Payslips
     */

    /**
     * Total Wages for the PayRun
     *
     * @property string Wages
     */

    /**
     * Total Deduction for the PayRun
     *
     * @property string Deductions
     */

    /**
     * Total Tax for the PayRun
     *
     * @property float Tax
     */

    /**
     * Total Super for the PayRun
     *
     * @property string Super
     */

    /**
     * Total Reimbursement for the PayRun
     *
     * @property string Reimbursement
     */

    /**
     * Total NetPay for the PayRun
     *
     * @property string NetPay
     */

    /**
     * Get the resource uri of the class (Contacts) etc
     *
     * @return string
     */
    public static function getResourceURI()
    {
        return 'PayRuns';
    }

    /**
     * Get the root node name.  Just the unqualified classname
     *
     * @return string
     */
    public static function getRootNodeName()
    {
        return 'PayRun';
    }

    /**
     * Get the guid property
     *
     * @return string
     */
    public static function getGUIDProperty()
    {
        return 'PayRunID';
    }

    /**
     * Get the stem of the API (core.xro) etc
     *
     * @return string|null
     */
    public static function getAPIStem()
    {
        return Remote\URL::API_PAYROLL;
    }

    /**
     * Get the supported methods
     */
    public static function getSupportedMethods()
    {
        return [
            Remote\Request::METHOD_POST,
            Remote\Request::METHOD_GET
        ];
    }

    /**
     *
     * Get the properties of the object.  Indexed by constants
     *  [0] - Mandatory
     *  [1] - Type
     *  [2] - PHP type
     *  [3] - Is an Array
     *  [4] - Saves directly
     *
     * @return array
     */
    public static function getProperties()
    {
        return [
            'PayrollCalendarID' => [true, self::PROPERTY_TYPE_STRING, null, false, false],
            'PayRunID' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'PayRunPeriodStartDate' => [false, self::PROPERTY_TYPE_DATE, '\\DateTimeInterface', false, false],
            'PayRunPeriodEndDate' => [false, self::PROPERTY_TYPE_DATE, '\\DateTimeInterface', false, false],
            'PayRunStatus' => [false, self::PROPERTY_TYPE_ENUM, null, false, false],
            'PaymentDate' => [false, self::PROPERTY_TYPE_DATE, '\\DateTimeInterface', false, false],
            'PayslipMessage' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'Payslips' => [false, self::PROPERTY_TYPE_OBJECT, 'PayrollAU\\Payslip', true, false],
            'Wages' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'Deductions' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'Tax' => [false, self::PROPERTY_TYPE_FLOAT, null, false, false],
            'Super' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'Reimbursement' => [false, self::PROPERTY_TYPE_STRING, null, false, false],
            'NetPay' => [false, self::PROPERTY_TYPE_STRING, null, false, false]
        ];
    }

    public static function isPageable()
    {
        return true;
    }

    /**
     * @return string
     */
    public function getPayrollCalendarID()
    {
        return $this->_data['PayrollCalendarID'];
    }

    /**
     * @param string $value
     * @return PayRun
     */
    public function setPayrollCalendarID($value)
    {
        $this->propertyUpdated('PayrollCalendarID', $value);
        $this->_data['PayrollCalendarID'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getPayRunID()
    {
        return $this->_data['PayRunID'];
    }

    /**
     * @param string $value
     * @return PayRun
     */
    public function setPayRunID($value)
    {
        $this->propertyUpdated('PayRunID', $value);
        $this->_data['PayRunID'] = $value;
        return $this;
    }

    /**
     * @return \DateTimeInterface
     */
    public function getPayRunPeriodStartDate()
    {
        return $this->_data['PayRunPeriodStartDate'];
    }

    /**
     * @param \DateTimeInterface $value
     * @return PayRun
     */
    public function setPayRunPeriodStartDate(\DateTimeInterface $value)
    {
        $this->propertyUpdated('PayRunPeriodStartDate', $value);
        $this->_data['PayRunPeriodStartDate'] = $value;
        return $this;
    }

    /**
     * @return \DateTimeInterface
     */
    public function getPayRunPeriodEndDate()
    {
        return $this->_data['PayRunPeriodEndDate'];
    }

    /**
     * @param \DateTimeInterface $value
     * @return PayRun
     */
    public function setPayRunPeriodEndDate(\DateTimeInterface $value)
    {
        $this->propertyUpdated('PayRunPeriodEndDate', $value);
        $this->_data['PayRunPeriodEndDate'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getPayRunStatus()
    {
        return $this->_data['PayRunStatus'];
    }

    /**
     * @param string $value
     * @return PayRun
     */
    public function setPayRunStatus($value)
    {
        $this->propertyUpdated('PayRunStatus', $value);
        $this->_data['PayRunStatus'] = $value;
        return $this;
    }

    /**
     * @return \DateTimeInterface
     */
    public function getPaymentDate()
    {
        return $this->_data['PaymentDate'];
    }

    /**
     * @param \DateTimeInterface $value
     * @return PayRun
     */
    public function setPaymentDate(\DateTimeInterface $value)
    {
        $this->propertyUpdated('PaymentDate', $value);
        $this->_data['PaymentDate'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getPayslipMessage()
    {
        return $this->_data['PayslipMessage'];
    }

    /**
     * @return Payslip[]|Remote\Collection
     * Always returns a collection, switch is for type hinting
     */
    public function getPayslips()
    {
        return $this->_data['Payslips'];
    }

    /**
     * @return string
     */
    public function getWages()
    {
        return $this->_data['Wages'];
    }

    /**
     * @return string
     */
    public function getDeductions()
    {
        return $this->_data['Deductions'];
    }

    /**
     * @return float
     */
    public function getTax()
    {
        return $this->_data['Tax'];
    }

    /**
     * @return string
     */
    public function getSuper()
    {
        return $this->_data['Super'];
    }

    /**
     * @return string
     */
    public function getReimbursement()
    {
        return $this->_data['Reimbursement'];
    }

    /**
     * @return string
     */
    public function getNetPay()
    {
        return $this->_data['NetPay'];
    }

}


text:
package com.flying.promotion.javatuning.future.pattern;

/**
 * Created by Joseph on 7/25/2016.
 */
public class RealData implements Data{
    protected final String result;
    public RealData(String para) {
        //RealData构造很曼,使用sleep
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i < 10; i++) {
            sb.append(para);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        result=sb.toString();
    }
    public String getResult() {
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var app = angular.module('core', ['ui.bootstrap']);

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, customer,$rootScope)
{

  $rootScope.example = "Hi, i'm $RootScope";

});

app.controller('CustomerController', function($scope, $timeout, $modal, $log) {

    // MODAL WINDOW

$scope.someModalWindow = function(index, x) {
  console.log('open modal ', index)
  var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalController,
      //size: 'lg',
      resolve: {
          x: function () {
            return x;
          },
          index: function () {
            return index;
          }
      }
  });

  modalInstance.result.then(function (x) {
    console.log(x)
    // this is returned from the `$scope.ok` function in ModalController
  }, function () {
    console.log('dismissed');
  });
}

var ModalController = function ($scope, $modalInstance, $rootScope, x, index, $http, $timeout) {
  $scope.x = x;
  $scope.sendEmail = {};
  $scope.isSendingMail = false;

  $scope.send = function (isValid) {
    if(isValid) {
     //$modalInstance.close($scope.x); // If you want to return something back to the caller
    }
    var data = {
      sendEmail: $scope.sendEmail,
      collection1: $scope.x.collection1[index]
    }
    $scope.isSendingMail = true;
    $scope.success = false;
    $scope.error = false;
    $http.post('/bruktebilers/email', data).then(function(result) {
      console.log("result", result)
      $scope.isSendingMail = false;
      $scope.success = true;
      $scope.sendEmail = {};
      $timeout(function(){
        $modalInstance.close($scope.x);
      }, 3000);
    }, function(result){
      console.error(result)
      $scope.error = true;
      $scope.isSendingMail = false;
    });
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

});


text:
let actionHistory;
let activeStore;

function concatMiddleware(...middlewares) {
  return options => {
    const setup = middlewares.reduce((setup, middleware) => (middleware ? [...setup, middleware(options)] : setup), []);

    return last => {
      const stack = setup.slice();
      const work = index => (...args) => {
        const next = stack[index];

        return (next ? next(work(index + 1)) : last)(...args);
      };

      return work(0);
    };
  };
}

export default function(initialState = {}, ...middleware) {
  return window.WebChat.createStore(
    initialState,
    concatMiddleware(store => {
      actionHistory = [];
      activeStore = store;

      return next => action => {
        actionHistory.push(action);

        return next(action);
      };
    }, ...middleware)
  );
}

function dispatch(...args) {
  if (!activeStore) {
    throw new Error('WebChatTest: Please use "window.WebChatTest.createStore" when initializing Web Chat.');
  }

  return activeStore.dispatch(...args);
}

function getActionHistory() {
  if (!actionHistory) {
    throw new Error('WebChatTest: Please use "window.WebChatTest.createStore" when initializing Web Chat.');
  }

  return actionHistory;
}

function getState() {
  if (!activeStore) {
    throw new Error('WebChatTest: Please use "window.WebChatTest.createStore" when initializing Web Chat.');
  }

  return activeStore.getState();
}

export { dispatch, getActionHistory, getState };


text:
@interface SaveableTableView : UITableViewController {
	//BOOL hasNewData;
	id dataObject;
	NSString* serverCall;
	PListModel* model;

	//BOOL hasOutstandingCall;
	//BOOL callWasCanceled;

	id <LotViewDelegate> delegate;
}
//@property (nonatomic) BOOL hasNewData;
@property (nonatomic,retain) id dataObject;
@property (nonatomic,retain) NSString* serverCall;
@property (nonatomic,retain) id <LotViewDelegate> delegate;

- (IBAction) saveAndClose;
- (IBAction) close;

//protected ==========
- (void) rewriteData;
- (void) save;
- (void) serverDidRespond:(NSNotification*)notification;
- (void) saveDidSucceed;
- (void) saveDidFail:(ServerResponse*)response;

@end


text:
package org.keycloak.testsuite.forms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.ClientAuthenticationFlowContext;
import org.keycloak.authentication.authenticators.client.AbstractClientAuthenticator;
import org.keycloak.events.Details;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.ProviderConfigProperty;

/**
 * @author Marek Posolda
 */
public class PassThroughClientAuthenticator extends AbstractClientAuthenticator {

    public static final String PROVIDER_ID = "testsuite-client-passthrough";
    public static String clientId = "test-app";

    public static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
            AuthenticationExecutionModel.Requirement.REQUIRED
    };

    private static final List<ProviderConfigProperty> clientConfigProperties = new ArrayList<ProviderConfigProperty>();

    static {
        ProviderConfigProperty property;
        property = new ProviderConfigProperty();
        property.setName("passthroughauth.foo");
        property.setLabel("Foo Property");
        property.setType(ProviderConfigProperty.STRING_TYPE);
        property.setHelpText("Foo Property of this authenticator, which does nothing");
        clientConfigProperties.add(property);
        property = new ProviderConfigProperty();
        property.setName("passthroughauth.bar");
        property.setLabel("Bar Property");
        property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
        property.setHelpText("Bar Property of this authenticator, which does nothing");
        clientConfigProperties.add(property);

    }

    @Override
    public void authenticateClient(ClientAuthenticationFlowContext context) {
        ClientModel client = context.getRealm().getClientByClientId(clientId);
        if (client == null) {
            context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
            return;
        }

        context.getEvent().client(client);
        context.setClient(client);
        context.success();
    }

    @Override
    public String getDisplayType() {
        return "Testsuite Dummy Client Validation";
    }

    @Override
    public boolean isConfigurable() {
        return false;
    }

    @Override
    public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
        return REQUIREMENT_CHOICES;
    }

    @Override
    public String getHelpText() {
        return "Testsuite dummy authenticator, which automatically authenticates hardcoded client (like 'test-app' )";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return new LinkedList<>();
    }

    @Override
    public List<ProviderConfigProperty> getConfigPropertiesPerClient() {
        return clientConfigProperties;
    }

    @Override
    public Map<String, Object> getAdapterConfiguration(ClientModel client) {
        Map<String, Object> props = new HashMap<>();
        props.put("foo", "some foo value");
        props.put("bar", true);

        Map<String, Object> config = new HashMap<>();
        config.put("dummy", props);
        return config;
    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }
}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// delete_executor.cpp
//
// Identification: src/executor/delete_executor.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cinttypes>
#include "storage/storage_manager.h"
#include "executor/delete_executor.h"
#include "executor/executor_context.h"

#include "type/value.h"
#include "planner/delete_plan.h"
#include "catalog/manager.h"
#include "common/container_tuple.h"
#include "common/logger.h"
#include "executor/logical_tile.h"
#include "storage/data_table.h"
#include "storage/tile.h"
#include "storage/tile_group.h"
#include "storage/tile_group_header.h"
#include "storage/tuple.h"
#include "concurrency/transaction_manager_factory.h"
#include "catalog/trigger_catalog.h"
#include "trigger/trigger.h"
#include "catalog/table_catalog.h"
#include "parser/pg_trigger.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for delete executor.
 * @param node Delete node corresponding to this executor.
 */
DeleteExecutor::DeleteExecutor(const planner::AbstractPlan *node,
                               ExecutorContext *executor_context)
    : AbstractExecutor(node, executor_context) {}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool DeleteExecutor::DInit() {
  PELOTON_ASSERT(children_.size() == 1);
  PELOTON_ASSERT(executor_context_);

  PELOTON_ASSERT(target_table_ == nullptr);

  // Delete tuples in logical tile
  LOG_TRACE("Delete executor :: 1 child ");

  // Grab data from plan node.
  const planner::DeletePlan &node = GetPlanNode<planner::DeletePlan>();
  target_table_ = node.GetTable();
  PELOTON_ASSERT(target_table_);

  return true;
}

/**
 * @brief Delete the table tuples using the position list in the logical tile.
 *
 * If truncate is on, then it will truncate the table itself.
 * @return true on success, false otherwise.
 */
bool DeleteExecutor::DExecute() {
  PELOTON_ASSERT(target_table_);
  // Retrieve next tile.
  if (!children_[0]->Execute()) {
    return false;
  }

  std::unique_ptr<LogicalTile> source_tile(children_[0]->GetOutput());

  auto &pos_lists = source_tile.get()->GetPositionLists();

  auto &transaction_manager =
      concurrency::TransactionManagerFactory::GetInstance();

  auto current_txn = executor_context_->GetTransaction();

  LOG_TRACE("Source tile : %p Tuples : %lu ", source_tile.get(),
            source_tile->GetTupleCount());

  LOG_TRACE("Source tile info: %s", source_tile->GetInfo().c_str());

  LOG_TRACE("Transaction ID: %" PRId64,
            executor_context_->GetTransaction()->GetTransactionId());

  auto executor_pool = executor_context_->GetPool();
  auto target_table_schema = target_table_->GetSchema();
  auto column_count = target_table_schema->GetColumnCount();

  trigger::TriggerList *trigger_list = target_table_->GetTriggerList();
  if (trigger_list != nullptr) {
    LOG_TRACE("size of trigger list in target table: %d",
              trigger_list->GetTriggerListSize());
    if (trigger_list->HasTriggerType(TriggerType::BEFORE_DELETE_STATEMENT)) {
      LOG_TRACE("target table has per-statement-before-delete triggers!");
      trigger_list->ExecTriggers(TriggerType::BEFORE_DELETE_STATEMENT,
                                 current_txn);
    }
  }

  // Delete each tuple
  for (oid_t visible_tuple_id : *source_tile) {
    storage::TileGroup *tile_group =
        source_tile->GetBaseTile(0)->GetTileGroup();
    storage::TileGroupHeader *tile_group_header = tile_group->GetHeader();

    oid_t physical_tuple_id = pos_lists[0][visible_tuple_id];

    ItemPointer old_location(tile_group->GetTileGroupId(), physical_tuple_id);

    LOG_TRACE("Visible Tuple id : %u, Physical Tuple id : %u ",
              visible_tuple_id, physical_tuple_id);

    // if running at snapshot isolation,
    // then we need to retrieve the latest version of this tuple.
    if (current_txn->GetIsolationLevel() == IsolationLevelType::SNAPSHOT) {
      old_location = *(tile_group_header->GetIndirection(physical_tuple_id));

      auto storage_manager = storage::StorageManager::GetInstance();
      tile_group = storage_manager->GetTileGroup(old_location.block).get();
      tile_group_header = tile_group->GetHeader();

      physical_tuple_id = old_location.offset;
    }

    ContainerTuple<storage::TileGroup> old_tuple(tile_group, physical_tuple_id);
    storage::Tuple prev_tuple(target_table_->GetSchema(), true);

    // Get a copy of the old tuple
    for (oid_t column_itr = 0; column_itr < target_table_schema->GetColumnCount(); column_itr++) {
      type::Value val = (old_tuple.GetValue(column_itr));
      prev_tuple.SetValue(column_itr, val, executor_context_->GetPool());
    }

    // Check the foreign key source table
    if (target_table_->CheckForeignKeySrcAndCascade(&prev_tuple,
                                                    nullptr,
                                                    current_txn,
                                                    executor_context_,
                                                    false) == false)
    {
      transaction_manager.SetTransactionResult(current_txn,
                                              peloton::ResultType::FAILURE);
      return false;
    }

    bool is_owner = transaction_manager.IsOwner(current_txn, tile_group_header,
                                                physical_tuple_id);

    bool is_written = transaction_manager.IsWritten(
        current_txn, tile_group_header, physical_tuple_id);

    // if the current transaction is the creator of this version.
    // which means the current transaction has already updated the version.

    std::unique_ptr<storage::Tuple> real_tuple(
        new storage::Tuple(target_table_schema, true));
    bool tuple_is_materialzed = false;

    // check whether there are per-row-before-delete triggers on this table
    // using trigger catalog
    if (trigger_list != nullptr) {
      LOG_TRACE("size of trigger list in target table: %d",
                trigger_list->GetTriggerListSize());
      if (trigger_list->HasTriggerType(TriggerType::BEFORE_DELETE_ROW)) {
        ContainerTuple<LogicalTile> logical_tile_tuple(source_tile.get(),
                                                       visible_tuple_id);
        // Materialize the logical tile tuple
        for (oid_t column_itr = 0; column_itr < column_count; column_itr++) {
          type::Value val = (logical_tile_tuple.GetValue(column_itr));
          real_tuple->SetValue(column_itr, val, executor_pool);
        }
        tuple_is_materialzed = true;
        LOG_TRACE("target table has per-row-before-delete triggers!");
        trigger_list->ExecTriggers(TriggerType::BEFORE_DELETE_ROW, current_txn,
                                   real_tuple.get(), executor_context_);
      }
    }

    if (is_owner == true && is_written == true) {
      // if the transaction is the owner of the tuple, then directly update in
      // place.
      LOG_TRACE("The current transaction is the owner of the tuple");
      transaction_manager.PerformDelete(current_txn, old_location);
    } else {
      bool is_ownable = is_owner ||
                        transaction_manager.IsOwnable(
                            current_txn, tile_group_header, physical_tuple_id);

      if (is_ownable == true) {
        // if the tuple is not owned by any transaction and is visible to
        // current transaction.
        LOG_TRACE("Thread is not the owner of the tuple, but still visible");

        bool acquire_ownership_success =
            is_owner ||
            transaction_manager.AcquireOwnership(current_txn, tile_group_header,
                                                 physical_tuple_id);

        if (acquire_ownership_success == false) {
          transaction_manager.SetTransactionResult(current_txn,
                                                   ResultType::FAILURE);
          return false;
        }
        // if it is the latest version and not locked by other threads, then
        // insert an empty version.
        ItemPointer new_location = target_table_->InsertEmptyVersion();

        // PerformDelete() will not be executed if the insertion failed.
        // There is a write lock acquired, but since it is not in the write set,
        // because we haven't yet put them into the write set.
        // the acquired lock can't be released when the txn is aborted.
        // the YieldOwnership() function helps us release the acquired write
        // lock.
        if (new_location.IsNull() == true) {
          LOG_TRACE("Fail to insert new tuple. Set txn failure.");
          if (is_owner == false) {
            // If the ownership is acquire inside this update executor, we
            // release it here
            transaction_manager.YieldOwnership(current_txn, tile_group_header,
                                               physical_tuple_id);
          }
          transaction_manager.SetTransactionResult(current_txn,
                                                   ResultType::FAILURE);
          return false;
        }
        transaction_manager.PerformDelete(current_txn, old_location,
                                          new_location);

        executor_context_->num_processed += 1;  // deleted one
      } else {
        // transaction should be aborted as we cannot update the latest version.
        LOG_TRACE("Fail to update tuple. Set txn failure.");
        transaction_manager.SetTransactionResult(current_txn,
                                                 ResultType::FAILURE);
        return false;
      }
    }
    // execute after-delete-row triggers and
    // record on-commit-delete-row triggers into current transaction
    if (trigger_list != nullptr) {
      LOG_TRACE("size of trigger list in target table: %d",
                trigger_list->GetTriggerListSize());
      if (trigger_list->HasTriggerType(TriggerType::AFTER_DELETE_ROW) ||
          trigger_list->HasTriggerType(TriggerType::ON_COMMIT_DELETE_ROW)) {
        if (!tuple_is_materialzed) {
          ContainerTuple<LogicalTile> logical_tile_tuple(source_tile.get(),
                                                         visible_tuple_id);
          // Materialize the logical tile tuple
          for (oid_t column_itr = 0; column_itr < column_count; column_itr++) {
            type::Value val = (logical_tile_tuple.GetValue(column_itr));
            real_tuple->SetValue(column_itr, val, executor_pool);
          }
        }
        if (trigger_list->HasTriggerType(TriggerType::AFTER_DELETE_ROW)) {
          LOG_TRACE("target table has per-row-after-delete triggers!");
          trigger_list->ExecTriggers(TriggerType::AFTER_DELETE_ROW, current_txn,
                                     real_tuple.get(), executor_context_);
        }
        if (trigger_list->HasTriggerType(TriggerType::ON_COMMIT_DELETE_ROW)) {
          LOG_TRACE("target table has per-row-on-commit-delete triggers!");
          trigger_list->ExecTriggers(TriggerType::ON_COMMIT_DELETE_ROW,
                                     current_txn, real_tuple.get(),
                                     executor_context_);
        }
      }
    }
  }
  // execute after-delete-statement triggers and
  // record on-commit-delete-statement triggers into current transaction
  if (trigger_list != nullptr) {
    LOG_TRACE("size of trigger list in target table: %d",
              trigger_list->GetTriggerListSize());
    if (trigger_list->HasTriggerType(TriggerType::AFTER_DELETE_STATEMENT)) {
      LOG_TRACE("target table has per-statement-after-delete triggers!");
      trigger_list->ExecTriggers(TriggerType::AFTER_DELETE_STATEMENT,
                                 current_txn);
    }
    if (trigger_list->HasTriggerType(TriggerType::ON_COMMIT_DELETE_STATEMENT)) {
      LOG_TRACE("target table has per-statement-on-commit-delete triggers!");
      trigger_list->ExecTriggers(TriggerType::ON_COMMIT_DELETE_STATEMENT,
                                 current_txn);
    }
  }
  return true;
}

}  // namespace executor
}  // namespace peloton


text:
require "api_versioning/engine"

module ApiVersioning
end


text:
define([
	"dojo/_base/declare", // declare
	"./a11y"	// _getTabNavigable
], function(declare, a11y){

	// module:
	//		dijit/_DialogMixin

	return declare("dijit._DialogMixin", null, {
		// summary:
		//		This provides functions useful to Dialog and TooltipDialog

		// actionBarTemplate: String
		//		HTML snippet to show the action bar (gray bar with OK/cancel buttons).
		//		Blank by default, but used by ConfirmDialog/ConfirmTooltipDialog subclasses.
		actionBarTemplate: "",

		execute: function(/*Object*/ /*===== formContents =====*/){
			// summary:
			//		Callback when the user hits the submit button.
			//		Override this method to handle Dialog execution.
			// description:
			//		After the user has pressed the submit button, the Dialog
			//		first calls onExecute() to notify the container to hide the
			//		dialog and restore focus to wherever it used to be.
			//
			//		*Then* this method is called.
			// type:
			//		callback
		},

		onCancel: function(){
			// summary:
			//		Called when user has pressed the Dialog's cancel button, to notify container.
			// description:
			//		Developer shouldn't override or connect to this method;
			//		it's a private communication device between the TooltipDialog
			//		and the thing that opened it (ex: `dijit/form/DropDownButton`)
			// type:
			//		protected
		},

		onExecute: function(){
			// summary:
			//		Called when user has pressed the dialog's OK button, to notify container.
			// description:
			//		Developer shouldn't override or connect to this method;
			//		it's a private communication device between the TooltipDialog
			//		and the thing that opened it (ex: `dijit/form/DropDownButton`)
			// type:
			//		protected
		},

		_onSubmit: function(){
			// summary:
			//		Callback when user hits submit button
			// type:
			//		protected
			this.onExecute();	// notify container that we are about to execute
			this.execute(this.get('value'));
		},

		_getFocusItems: function(){
			// summary:
			//		Finds focusable items in dialog,
			//		and sets this._firstFocusItem and this._lastFocusItem
			// tags:
			//		protected

			var elems = a11y._getTabNavigable(this.domNode);
			this._firstFocusItem = elems.lowest || elems.first || this.closeButtonNode || this.domNode;
			this._lastFocusItem = elems.last || elems.highest || this._firstFocusItem;
		}
	});
});


text:
RSpec.describe Scale::Api::Tasks, 'audio transcription' do
  let(:scale) { Scale.new(api_key: SCALE_TEST_API_KEY) }

  it 'returns transcription for audio transcription task' do
    response = VCR.use_cassette('audio_transcription') do
      scale.create_audiotranscription_task(
        callback_url: 'http://www.example.com/callback',
        attachment_type: 'audio',
        attachment: 'https://storage.googleapis.com/deepmind-media/pixie/knowing-what-to-say/second-list/speaker-3.wav',
        verbatim: false)
    end

    expect(response.type).to eq 'audiotranscription'
    expect(response.response.keys).to contain_exactly('transcript', 'duration', 'alignment')
  end
end


text:
// ChatMessage.cpp : Implementation of ChatMessage

#include "stdafx.h"
#include ".\skypemessagequeue.h"
#include ".\conversion.h"
#include ".\usercollection.h"
#include ".\user.h"
#include ".\chatmessagecollection.h"
#include ".\chatmessage.h"
#include ".\chat.h"
#include ".\datetime.h"

#define CHAT_MESSAGE_ID_CHECK \
	if(m_lID == -1) \
		return AtlReportError(GetObjectCLSID(), _T("Chat Message's ID Not Set"), GUID_NULL, E_FAIL);

namespace SkypeAPILib
{

// ChatMessage

void ChatMessage::SetID(long ID)
{
	m_lID = ID;
}

STDMETHODIMP ChatMessage::get_ID(long *pVal)
{
	CHAT_MESSAGE_ID_CHECK

	*pVal = m_lID;
	return S_OK;
}

STDMETHODIMP ChatMessage::get_Chat(IChat **pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"CHATNAME");
		CComObject<Chat> * ptrChat;
		CComObject<Chat>::CreateInstance(& ptrChat);
		ptrChat->SetName(pResult);
		free(pResult);
		return ptrChat->QueryInterface(pVal);
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_Timestamp(DATE *pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pStrTimestamp = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"TIMESTAMP");
		*pVal = UnixTimestampToDATE(_wtol(pStrTimestamp));
		free(pStrTimestamp);
		return S_OK;
	} catch(WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_MessageFrom(IUser **pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"FROM_HANDLE");
		CComObject<User> * ptrUser;
		CComObject<User>::CreateInstance(& ptrUser);
		ptrUser->SetUserName(pResult);
		free(pResult);
		ptrUser->AddRef();
		return ptrUser->QueryInterface(pVal);
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_MessageType(SkypeChatMessageType *pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"TYPE");
		*pVal = TextToSkypeChatMessageType(pResult);
		free(pResult);
		return S_OK;
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_Users(IUserCollection **pVal)
{
	CComObject<UserCollection> * ptrUsers;

	HRESULT hr = CComObject<UserCollection>::CreateInstance(& ptrUsers);
	if(FAILED(hr)) {
		return AtlReportError(GetObjectCLSID(), L"Unable to create user list", GUID_NULL, hr);
	}

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"USERS");
		ptrUsers->SetItemList(pResult);
		free(pResult);
		return ptrUsers->QueryInterface(pVal);
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_LeftReason(SkypeChatMessageLeftReason *pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"LEAVEREASON");
		*pVal = TextToSkypeChatMessageLeftReason(pResult);
		free(pResult);
		return S_OK;
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_Body(BSTR *pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"BODY");
		*pVal = SysAllocString(pResult);
		free(pResult);
		return S_OK;
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::get_Status(SkypeChatMessageStatus *pVal)
{
	CHAT_MESSAGE_ID_CHECK

	try {
		WCHAR * pResult = gSkypeQueue.RetrieveProperty(L"CHATMESSAGE", m_lID, L"STATUS");
		*pVal = TextToSkypeChatMessageStatus(pResult);
		free(pResult);
		return S_OK;
	} catch (const WCHAR * err) {
		return AtlReportError(GetObjectCLSID(), err, GUID_NULL, E_FAIL);
	}
}

STDMETHODIMP ChatMessage::put_Status(SkypeChatMessageStatus /*newVal*/)
{
	// TODO: Add your implementation code here

	return S_OK;
}

}


text:
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;

namespace Umbraco.Cms.Infrastructure.Persistence.Dtos;

[TableName(TableName)]
[PrimaryKey("id", AutoIncrement = false)]
[ExplicitColumns]
public class DocumentVersionDto
{
    private const string TableName = Constants.DatabaseSchema.Tables.DocumentVersion;

    [Column("id")]
    [PrimaryKeyColumn(AutoIncrement = false)]
    [ForeignKey(typeof(ContentVersionDto))]
    public int Id { get; set; }

    [Column("templateId")]
    [NullSetting(NullSetting = NullSettings.Null)]
    [ForeignKey(typeof(TemplateDto), Column = "nodeId")]
    public int? TemplateId { get; set; }

    [Column("published")]
    public bool Published { get; set; }

    [ResultColumn]
    [Reference(ReferenceType.OneToOne)]
    public ContentVersionDto ContentVersionDto { get; set; } = null!;
}


text:
/**
 * @fileoverview Main app file
 * @author Gyandeep Singh
 */

"use strict";

import m, { route } from "mithril/index";
import Header from "./components/Header";
import Body from "./components/Body";
import "../less/app.less";

/**
 * Parses the route to return the just the main route name
 * Default it returns new as its the default route
 * @returns {string} route name
 * @private
 */
const getParsedRouteName = () => route.get().split("/")[1] || "new";

class App {
    /**
     * Mithril view
     * @param {object} vnode - standrd mithril view method
     * @returns {object} mithril vdom
     */
    view(vnode) {
        const routeName = getParsedRouteName();

        return m(
            "div",
            {
                className: "mithril-hn"
            },
            [
                m(Header, {
                    currentPage: vnode.attrs.id ? parseInt(vnode.attrs.id) : 1,
                    routeName
                }),
                m(Body, {
                    currentPage: vnode.attrs.id ? parseInt(vnode.attrs.id) : 1,
                    routeName
                })
            ]
        );
    }
}

route.prefix("");
route(document.getElementById("app"), "/new", {
    "/new": App,
    "/new/:id": App,
    "/show": App,
    "/show/:id": App,
    "/ask": App,
    "/ask/:id": App,
    "/jobs": App,
    "/jobs/:id": App,
});


text:
package cmd

import (
	"errors"

	davclient "github.com/cloudfoundry/bosh-davcli/client"
)

type ExistsCmd struct {
	client davclient.Client
}

func newExistsCmd(client davclient.Client) (cmd ExistsCmd) {
	cmd.client = client
	return
}

func (cmd ExistsCmd) Run(args []string) (err error) {
	if len(args) != 1 {
		err = errors.New("Incorrect usage, exists needs remote blob path")
		return
	}
	err = cmd.client.Exists(args[0])
	return
}


text:
"""TensorFlow NMT model implementation."""
from __future__ import print_function

import argparse
import os
import random
import sys

# import matplotlib.image as mpimg
import numpy as np
import tensorflow as tf

from . import inference
from . import train
from .utils import evaluation_utils
from .utils import misc_utils as utils
from .utils import vocab_utils

utils.check_tensorflow_version()

FLAGS = None

INFERENCE_KEYS = ["src_max_len_infer", "tgt_max_len_infer", "subword_option",
                  "infer_batch_size", "beam_width",
                  "length_penalty_weight", "sampling_temperature",
                  "num_translations_per_input", "infer_mode"]

def add_arguments(parser):
  """Build ArgumentParser."""
  parser.register("type", "bool", lambda v: v.lower() == "true")

  # network
  parser.add_argument("--num_units", type=int, default=32, help="Network size.")
  parser.add_argument("--num_layers", type=int, default=2,
                      help="Network depth.")
  parser.add_argument("--num_encoder_layers", type=int, default=None,
                      help="Encoder depth, equal to num_layers if None.")
  parser.add_argument("--num_decoder_layers", type=int, default=None,
                      help="Decoder depth, equal to num_layers if None.")
  parser.add_argument("--encoder_type", type=str, default="uni", help="""\
      uni | bi | gnmt.
      For bi, we build num_encoder_layers/2 bi-directional layers.
      For gnmt, we build 1 bi-directional layer, and (num_encoder_layers - 1)
        uni-directional layers.\
      """)
  parser.add_argument("--residual", type="bool", nargs="?", const=True,
                      default=False,
                      help="Whether to add residual connections.")
  parser.add_argument("--time_major", type="bool", nargs="?", const=True,
                      default=True,
                      help="Whether to use time-major mode for dynamic RNN.")
  parser.add_argument("--num_embeddings_partitions", type=int, default=0,
                      help="Number of partitions for embedding vars.")

  # attention mechanisms
  parser.add_argument("--attention", type=str, default="", help="""\
      luong | scaled_luong | bahdanau | normed_bahdanau or set to "" for no
      attention\
      """)
  parser.add_argument(
      "--attention_architecture",
      type=str,
      default="standard",
      help="""\
      standard | gnmt | gnmt_v2.
      standard: use top layer to compute attention.
      gnmt: GNMT style of computing attention, use previous bottom layer to
          compute attention.
      gnmt_v2: similar to gnmt, but use current bottom layer to compute
          attention.\
      """)
  parser.add_argument(
      "--output_attention", type="bool", nargs="?", const=True,
      default=True,
      help="""\
      Only used in standard attention_architecture. Whether use attention as
      the cell output at each timestep.
      .\
      """)
  parser.add_argument(
      "--pass_hidden_state", type="bool", nargs="?", const=True,
      default=True,
      help="""\
      Whether to pass encoder's hidden state to decoder when using an attention
      based model.\
      """)

  # optimizer
  parser.add_argument("--optimizer", type=str, default="sgd", help="sgd | adam")
  parser.add_argument("--learning_rate", type=float, default=1.0,
                      help="Learning rate. Adam: 0.001 | 0.0001")
  parser.add_argument("--warmup_steps", type=int, default=0,
                      help="How many steps we inverse-decay learning.")
  parser.add_argument("--warmup_scheme", type=str, default="t2t", help="""\
      How to warmup learning rates. Options include:
        t2t: Tensor2Tensor's way, start with lr 100 times smaller, then
             exponentiate until the specified lr.\
      """)
  parser.add_argument(
      "--decay_scheme", type=str, default="", help="""\
      How we decay learning rate. Options include:
        luong234: after 2/3 num train steps, we start halving the learning rate
          for 4 times before finishing.
        luong5: after 1/2 num train steps, we start halving the learning rate
          for 5 times before finishing.\
        luong10: after 1/2 num train steps, we start halving the learning rate
          for 10 times before finishing.\
      """)

  parser.add_argument(
      "--num_train_steps", type=int, default=12000, help="Num steps to train.")
  parser.add_argument("--colocate_gradients_with_ops", type="bool", nargs="?",
                      const=True,
                      default=True,
                      help=("Whether try colocating gradients with "
                            "corresponding op"))

  # initializer
  parser.add_argument("--init_op", type=str, default="uniform",
                      help="uniform | glorot_normal | glorot_uniform")
  parser.add_argument("--init_weight", type=float, default=0.1,
                      help=("for uniform init_op, initialize weights "
                            "between [-this, this]."))

  # data
  parser.add_argument("--src", type=str, default=None,
                      help="Source suffix, e.g., en.")
  parser.add_argument("--tgt", type=str, default=None,
                      help="Target suffix, e.g., de.")
  parser.add_argument("--train_prefix", type=str, default=None,
                      help="Train prefix, expect files with src/tgt suffixes.")
  parser.add_argument("--dev_prefix", type=str, default=None,
                      help="Dev prefix, expect files with src/tgt suffixes.")
  parser.add_argument("--test_prefix", type=str, default=None,
                      help="Test prefix, expect files with src/tgt suffixes.")
  parser.add_argument("--out_dir", type=str, default=None,
                      help="Store log/model files.")

  # Vocab
  parser.add_argument("--vocab_prefix", type=str, default=None, help="""\
      Vocab prefix, expect files with src/tgt suffixes.\
      """)
  parser.add_argument("--embed_prefix", type=str, default=None, help="""\
      Pretrained embedding prefix, expect files with src/tgt suffixes.
      The embedding files should be Glove formated txt files.\
      """)
  parser.add_argument("--sos", type=str, default="<s>",
                      help="Start-of-sentence symbol.")
  parser.add_argument("--eos", type=str, default="</s>",
                      help="End-of-sentence symbol.")
  parser.add_argument("--share_vocab", type="bool", nargs="?", const=True,
                      default=False,
                      help="""\
      Whether to use the source vocab and embeddings for both source and
      target.\
      """)
  parser.add_argument("--check_special_token", type="bool", default=True,
                      help="""\
                      Whether check special sos, eos, unk tokens exist in the
                      vocab files.\
                      """)

  # Sequence lengths
  parser.add_argument("--src_max_len", type=int, default=50,
                      help="Max length of src sequences during training.")
  parser.add_argument("--tgt_max_len", type=int, default=50,
                      help="Max length of tgt sequences during training.")
  parser.add_argument("--src_max_len_infer", type=int, default=None,
                      help="Max length of src sequences during inference.")
  parser.add_argument("--tgt_max_len_infer", type=int, default=None,
                      help="""\
      Max length of tgt sequences during inference.  Also use to restrict the
      maximum decoding length.\
      """)

  # Default settings works well (rarely need to change)
  parser.add_argument("--unit_type", type=str, default="lstm",
                      help="lstm | gru | layer_norm_lstm | nas")
  parser.add_argument("--forget_bias", type=float, default=1.0,
                      help="Forget bias for BasicLSTMCell.")
  parser.add_argument("--dropout", type=float, default=0.2,
                      help="Dropout rate (not keep_prob)")
  parser.add_argument("--max_gradient_norm", type=float, default=5.0,
                      help="Clip gradients to this norm.")
  parser.add_argument("--batch_size", type=int, default=128, help="Batch size.")

  parser.add_argument("--steps_per_stats", type=int, default=100,
                      help=("How many training steps to do per stats logging."
                            "Save checkpoint every 10x steps_per_stats"))
  parser.add_argument("--max_train", type=int, default=0,
                      help="Limit on the size of training data (0: no limit).")
  parser.add_argument("--num_buckets", type=int, default=5,
                      help="Put data into similar-length buckets.")
  parser.add_argument("--num_sampled_softmax", type=int, default=0,
                      help=("Use sampled_softmax_loss if > 0."
                            "Otherwise, use full softmax loss."))

  # SPM
  parser.add_argument("--subword_option", type=str, default="",
                      choices=["", "bpe", "spm"],
                      help="""\
                      Set to bpe or spm to activate subword desegmentation.\
                      """)

  # Experimental encoding feature.
  parser.add_argument("--use_char_encode", type="bool", default=False,
                      help="""\
                      Whether to split each word or bpe into character, and then
                      generate the word-level representation from the character
                      reprentation.
                      """)

  # Misc
  parser.add_argument("--num_gpus", type=int, default=1,
                      help="Number of gpus in each worker.")
  parser.add_argument("--log_device_placement", type="bool", nargs="?",
                      const=True, default=False, help="Debug GPU allocation.")
  parser.add_argument("--metrics", type=str, default="bleu",
                      help=("Comma-separated list of evaluations "
                            "metrics (bleu,rouge,accuracy)"))
  parser.add_argument("--steps_per_external_eval", type=int, default=None,
                      help="""\
      How many training steps to do per external evaluation.  Automatically set
      based on data if None.\
      """)
  parser.add_argument("--scope", type=str, default=None,
                      help="scope to put variables under")
  parser.add_argument("--hparams_path", type=str, default=None,
                      help=("Path to standard hparams json file that overrides"
                            "hparams values from FLAGS."))
  parser.add_argument("--random_seed", type=int, default=None,
                      help="Random seed (>0, set a specific seed).")
  parser.add_argument("--override_loaded_hparams", type="bool", nargs="?",
                      const=True, default=False,
                      help="Override loaded hparams with values specified")
  parser.add_argument("--num_keep_ckpts", type=int, default=5,
                      help="Max number of checkpoints to keep.")
  parser.add_argument("--avg_ckpts", type="bool", nargs="?",
                      const=True, default=False, help=("""\
                      Average the last N checkpoints for external evaluation.
                      N can be controlled by setting --num_keep_ckpts.\
                      """))
  parser.add_argument("--language_model", type="bool", nargs="?",
                      const=True, default=False,
                      help="True to train a language model, ignoring encoder")

  # Inference
  parser.add_argument("--ckpt", type=str, default="",
                      help="Checkpoint file to load a model for inference.")
  parser.add_argument("--inference_input_file", type=str, default=None,
                      help="Set to the text to decode.")
  parser.add_argument("--inference_list", type=str, default=None,
                      help=("A comma-separated list of sentence indices "
                            "(0-based) to decode."))
  parser.add_argument("--infer_batch_size", type=int, default=32,
                      help="Batch size for inference mode.")
  parser.add_argument("--inference_output_file", type=str, default=None,
                      help="Output file to store decoding results.")
  parser.add_argument("--inference_ref_file", type=str, default=None,
                      help=("""\
      Reference file to compute evaluation scores (if provided).\
      """))

  # Advanced inference arguments
  parser.add_argument("--infer_mode", type=str, default="greedy",
                      choices=["greedy", "sample", "beam_search"],
                      help="Which type of decoder to use during inference.")
  parser.add_argument("--beam_width", type=int, default=0,
                      help=("""\
      beam width when using beam search decoder. If 0 (default), use standard
      decoder with greedy helper.\
      """))
  parser.add_argument("--length_penalty_weight", type=float, default=0.0,
                      help="Length penalty for beam search.")
  parser.add_argument("--sampling_temperature", type=float,
                      default=0.0,
                      help=("""\
      Softmax sampling temperature for inference decoding, 0.0 means greedy
      decoding. This option is ignored when using beam search.\
      """))
  parser.add_argument("--num_translations_per_input", type=int, default=1,
                      help=("""\
      Number of translations generated for each sentence. This is only used for
      inference.\
      """))

  # Job info
  parser.add_argument("--jobid", type=int, default=0,
                      help="Task id of the worker.")
  parser.add_argument("--num_workers", type=int, default=1,
                      help="Number of workers (inference only).")
  parser.add_argument("--num_inter_threads", type=int, default=0,
                      help="number of inter_op_parallelism_threads")
  parser.add_argument("--num_intra_threads", type=int, default=0,
                      help="number of intra_op_parallelism_threads")

def create_hparams(flags):
  """Create training hparams."""
  return tf.contrib.training.HParams(
      # Data
      src=flags.src,
      tgt=flags.tgt,
      train_prefix=flags.train_prefix,
      dev_prefix=flags.dev_prefix,
      test_prefix=flags.test_prefix,
      vocab_prefix=flags.vocab_prefix,
      embed_prefix=flags.embed_prefix,
      out_dir=flags.out_dir,

      # Networks
      num_units=flags.num_units,
      num_encoder_layers=(flags.num_encoder_layers or flags.num_layers),
      num_decoder_layers=(flags.num_decoder_layers or flags.num_layers),
      dropout=flags.dropout,
      unit_type=flags.unit_type,
      encoder_type=flags.encoder_type,
      residual=flags.residual,
      time_major=flags.time_major,
      num_embeddings_partitions=flags.num_embeddings_partitions,

      # Attention mechanisms
      attention=flags.attention,
      attention_architecture=flags.attention_architecture,
      output_attention=flags.output_attention,
      pass_hidden_state=flags.pass_hidden_state,

      # Train
      optimizer=flags.optimizer,
      num_train_steps=flags.num_train_steps,
      batch_size=flags.batch_size,
      init_op=flags.init_op,
      init_weight=flags.init_weight,
      max_gradient_norm=flags.max_gradient_norm,
      learning_rate=flags.learning_rate,
      warmup_steps=flags.warmup_steps,
      warmup_scheme=flags.warmup_scheme,
      decay_scheme=flags.decay_scheme,
      colocate_gradients_with_ops=flags.colocate_gradients_with_ops,
      num_sampled_softmax=flags.num_sampled_softmax,

      # Data constraints
      num_buckets=flags.num_buckets,
      max_train=flags.max_train,
      src_max_len=flags.src_max_len,
      tgt_max_len=flags.tgt_max_len,

      # Inference
      src_max_len_infer=flags.src_max_len_infer,
      tgt_max_len_infer=flags.tgt_max_len_infer,
      infer_batch_size=flags.infer_batch_size,

      # Advanced inference arguments
      infer_mode=flags.infer_mode,
      beam_width=flags.beam_width,
      length_penalty_weight=flags.length_penalty_weight,
      sampling_temperature=flags.sampling_temperature,
      num_translations_per_input=flags.num_translations_per_input,

      # Vocab
      sos=flags.sos if flags.sos else vocab_utils.SOS,
      eos=flags.eos if flags.eos else vocab_utils.EOS,
      subword_option=flags.subword_option,
      check_special_token=flags.check_special_token,
      use_char_encode=flags.use_char_encode,

      # Misc
      forget_bias=flags.forget_bias,
      num_gpus=flags.num_gpus,
      epoch_step=0,  # record where we were within an epoch.
      steps_per_stats=flags.steps_per_stats,
      steps_per_external_eval=flags.steps_per_external_eval,
      share_vocab=flags.share_vocab,
      metrics=flags.metrics.split(","),
      log_device_placement=flags.log_device_placement,
      random_seed=flags.random_seed,
      override_loaded_hparams=flags.override_loaded_hparams,
      num_keep_ckpts=flags.num_keep_ckpts,
      avg_ckpts=flags.avg_ckpts,
      language_model=flags.language_model,
      num_intra_threads=flags.num_intra_threads,
      num_inter_threads=flags.num_inter_threads,
  )

def _add_argument(hparams, key, value, update=True):
  """Add an argument to hparams; if exists, change the value if update==True."""
  if hasattr(hparams, key):
    if update:
      setattr(hparams, key, value)
  else:
    hparams.add_hparam(key, value)

def extend_hparams(hparams):
  """Add new arguments to hparams."""
  # Sanity checks
  if hparams.encoder_type == "bi" and hparams.num_encoder_layers % 2 != 0:
    raise ValueError("For bi, num_encoder_layers %d should be even" %
                     hparams.num_encoder_layers)
  if (hparams.attention_architecture in ["gnmt"] and
      hparams.num_encoder_layers < 2):
    raise ValueError("For gnmt attention architecture, "
                     "num_encoder_layers %d should be >= 2" %
                     hparams.num_encoder_layers)
  if hparams.subword_option and hparams.subword_option not in ["spm", "bpe"]:
    raise ValueError("subword option must be either spm, or bpe")
  if hparams.infer_mode == "beam_search" and hparams.beam_width <= 0:
    raise ValueError("beam_width must greater than 0 when using beam_search"
                     "decoder.")
  if hparams.infer_mode == "sample" and hparams.sampling_temperature <= 0.0:
    raise ValueError("sampling_temperature must greater than 0.0 when using"
                     "sample decoder.")

  # Different number of encoder / decoder layers
  assert hparams.num_encoder_layers and hparams.num_decoder_layers
  if hparams.num_encoder_layers != hparams.num_decoder_layers:
    hparams.pass_hidden_state = False
    utils.print_out("Num encoder layer %d is different from num decoder layer"
                    " %d, so set pass_hidden_state to False" % (
                        hparams.num_encoder_layers,
                        hparams.num_decoder_layers))

  # Set residual layers
  num_encoder_residual_layers = 0
  num_decoder_residual_layers = 0
  if hparams.residual:
    if hparams.num_encoder_layers > 1:
      num_encoder_residual_layers = hparams.num_encoder_layers - 1
    if hparams.num_decoder_layers > 1:
      num_decoder_residual_layers = hparams.num_decoder_layers - 1

    if hparams.encoder_type == "gnmt":
      # The first unidirectional layer (after the bi-directional layer) in
      # the GNMT encoder can't have residual connection due to the input is
      # the concatenation of fw_cell and bw_cell's outputs.
      num_encoder_residual_layers = hparams.num_encoder_layers - 2

      # Compatible for GNMT models
      if hparams.num_encoder_layers == hparams.num_decoder_layers:
        num_decoder_residual_layers = num_encoder_residual_layers
  _add_argument(hparams, "num_encoder_residual_layers",
                num_encoder_residual_layers)
  _add_argument(hparams, "num_decoder_residual_layers",
                num_decoder_residual_layers)

  # Language modeling
  if getattr(hparams, "language_model", None):
    hparams.attention = ""
    hparams.attention_architecture = ""
    hparams.pass_hidden_state = False
    hparams.share_vocab = True
    hparams.src = hparams.tgt
    utils.print_out("For language modeling, we turn off attention and "
                    "pass_hidden_state; turn on share_vocab; set src to tgt.")

  ## Vocab
  # Get vocab file names first
  if hparams.vocab_prefix:
    src_vocab_file = hparams.vocab_prefix + "." + hparams.src
    tgt_vocab_file = hparams.vocab_prefix + "." + hparams.tgt
  else:
    raise ValueError("hparams.vocab_prefix must be provided.")

  # Source vocab
  check_special_token = getattr(hparams, "check_special_token", True)
  src_vocab_size, src_vocab_file = vocab_utils.check_vocab(
      src_vocab_file,
      hparams.out_dir,
      check_special_token=check_special_token,
      sos=hparams.sos,
      eos=hparams.eos,
      unk=vocab_utils.UNK)

  # Target vocab
  if hparams.share_vocab:
    utils.print_out("  using source vocab for target")
    tgt_vocab_file = src_vocab_file
    tgt_vocab_size = src_vocab_size
  else:
    tgt_vocab_size, tgt_vocab_file = vocab_utils.check_vocab(
        tgt_vocab_file,
        hparams.out_dir,
        check_special_token=check_special_token,
        sos=hparams.sos,
        eos=hparams.eos,
        unk=vocab_utils.UNK)
  _add_argument(hparams, "src_vocab_size", src_vocab_size)
  _add_argument(hparams, "tgt_vocab_size", tgt_vocab_size)
  _add_argument(hparams, "src_vocab_file", src_vocab_file)
  _add_argument(hparams, "tgt_vocab_file", tgt_vocab_file)

  # Num embedding partitions
  num_embeddings_partitions = getattr(hparams, "num_embeddings_partitions", 0)
  _add_argument(hparams, "num_enc_emb_partitions", num_embeddings_partitions)
  _add_argument(hparams, "num_dec_emb_partitions", num_embeddings_partitions)

  # Pretrained Embeddings
  _add_argument(hparams, "src_embed_file", "")
  _add_argument(hparams, "tgt_embed_file", "")
  if getattr(hparams, "embed_prefix", None):
    src_embed_file = hparams.embed_prefix + "." + hparams.src
    tgt_embed_file = hparams.embed_prefix + "." + hparams.tgt

    if tf.gfile.Exists(src_embed_file):
      utils.print_out("  src_embed_file %s exist" % src_embed_file)
      hparams.src_embed_file = src_embed_file

      utils.print_out(
          "For pretrained embeddings, set num_enc_emb_partitions to 1")
      hparams.num_enc_emb_partitions = 1
    else:
      utils.print_out("  src_embed_file %s doesn't exist" % src_embed_file)

    if tf.gfile.Exists(tgt_embed_file):
      utils.print_out("  tgt_embed_file %s exist" % tgt_embed_file)
      hparams.tgt_embed_file = tgt_embed_file

      utils.print_out(
          "For pretrained embeddings, set num_dec_emb_partitions to 1")
      hparams.num_dec_emb_partitions = 1
    else:
      utils.print_out("  tgt_embed_file %s doesn't exist" % tgt_embed_file)

  # Evaluation
  for metric in hparams.metrics:
    best_metric_dir = os.path.join(hparams.out_dir, "best_" + metric)
    tf.gfile.MakeDirs(best_metric_dir)
    _add_argument(hparams, "best_" + metric, 0, update=False)
    _add_argument(hparams, "best_" + metric + "_dir", best_metric_dir)

    if getattr(hparams, "avg_ckpts", None):
      best_metric_dir = os.path.join(hparams.out_dir, "avg_best_" + metric)
      tf.gfile.MakeDirs(best_metric_dir)
      _add_argument(hparams, "avg_best_" + metric, 0, update=False)
      _add_argument(hparams, "avg_best_" + metric + "_dir", best_metric_dir)

  return hparams

def ensure_compatible_hparams(hparams, default_hparams, hparams_path=""):
  """Make sure the loaded hparams is compatible with new changes."""
  default_hparams = utils.maybe_parse_standard_hparams(
      default_hparams, hparams_path)

  # Set num encoder/decoder layers (for old checkpoints)
  if hasattr(hparams, "num_layers"):
    if not hasattr(hparams, "num_encoder_layers"):
      hparams.add_hparam("num_encoder_layers", hparams.num_layers)
    if not hasattr(hparams, "num_decoder_layers"):
      hparams.add_hparam("num_decoder_layers", hparams.num_layers)

  # For compatible reason, if there are new fields in default_hparams,
  #   we add them to the current hparams
  default_config = default_hparams.values()
  config = hparams.values()
  for key in default_config:
    if key not in config:
      hparams.add_hparam(key, default_config[key])

  # Update all hparams' keys if override_loaded_hparams=True
  if getattr(default_hparams, "override_loaded_hparams", None):
    overwritten_keys = default_config.keys()
  else:
    # For inference
    overwritten_keys = INFERENCE_KEYS

  for key in overwritten_keys:
    if getattr(hparams, key) != default_config[key]:
      utils.print_out("# Updating hparams.%s: %s -> %s" %
                      (key, str(getattr(hparams, key)),
                       str(default_config[key])))
      setattr(hparams, key, default_config[key])
  return hparams

def create_or_load_hparams(
    out_dir, default_hparams, hparams_path, save_hparams=True):
  """Create hparams or load hparams from out_dir."""
  hparams = utils.load_hparams(out_dir)
  if not hparams:
    hparams = default_hparams
    hparams = utils.maybe_parse_standard_hparams(
        hparams, hparams_path)
  else:
    hparams = ensure_compatible_hparams(hparams, default_hparams, hparams_path)
  hparams = extend_hparams(hparams)

  # Save HParams
  if save_hparams:
    utils.save_hparams(out_dir, hparams)
    for metric in hparams.metrics:
      utils.save_hparams(getattr(hparams, "best_" + metric + "_dir"), hparams)

  # Print HParams
  utils.print_hparams(hparams)
  return hparams

def run_main(flags, default_hparams, train_fn, inference_fn, target_session=""):
  """Run main."""
  # Job
  jobid = flags.jobid
  num_workers = flags.num_workers
  utils.print_out("# Job id %d" % jobid)

  # GPU device
  utils.print_out(
      "# Devices visible to TensorFlow: %s" % repr(tf.Session().list_devices()))

  # Random
  random_seed = flags.random_seed
  if random_seed is not None and random_seed > 0:
    utils.print_out("# Set random seed to %d" % random_seed)
    random.seed(random_seed + jobid)
    np.random.seed(random_seed + jobid)

  # Model output directory
  out_dir = flags.out_dir
  if out_dir and not tf.gfile.Exists(out_dir):
    utils.print_out("# Creating output directory %s ..." % out_dir)
    tf.gfile.MakeDirs(out_dir)

  # Load hparams.
  loaded_hparams = False
  if flags.ckpt:  # Try to load hparams from the same directory as ckpt
    ckpt_dir = os.path.dirname(flags.ckpt)
    ckpt_hparams_file = os.path.join(ckpt_dir, "hparams")
    if tf.gfile.Exists(ckpt_hparams_file) or flags.hparams_path:
      hparams = create_or_load_hparams(
          ckpt_dir, default_hparams, flags.hparams_path,
          save_hparams=False)
      loaded_hparams = True
  if not loaded_hparams:  # Try to load from out_dir
    assert out_dir
    hparams = create_or_load_hparams(
        out_dir, default_hparams, flags.hparams_path,
        save_hparams=(jobid == 0))

  ## Train / Decode
  if flags.inference_input_file:
    # Inference output directory
    trans_file = flags.inference_output_file
    assert trans_file
    trans_dir = os.path.dirname(trans_file)
    if not tf.gfile.Exists(trans_dir): tf.gfile.MakeDirs(trans_dir)

    # Inference indices
    hparams.inference_indices = None
    if flags.inference_list:
      (hparams.inference_indices) = (
          [int(token)  for token in flags.inference_list.split(",")])

    # Inference
    ckpt = flags.ckpt
    if not ckpt:
      ckpt = tf.train.latest_checkpoint(out_dir)
    inference_fn(ckpt, flags.inference_input_file,
                 trans_file, hparams, num_workers, jobid)

    # Evaluation
    ref_file = flags.inference_ref_file
    if ref_file and tf.gfile.Exists(trans_file):
      for metric in hparams.metrics:
        score = evaluation_utils.evaluate(
            ref_file,
            trans_file,
            metric,
            hparams.subword_option)
        utils.print_out("  %s: %.1f" % (metric, score))
  else:
    # Train
    train_fn(hparams, target_session=target_session)

def main(unused_argv):
  default_hparams = create_hparams(FLAGS)
  train_fn = train.train
  inference_fn = inference.inference
  run_main(FLAGS, default_hparams, train_fn, inference_fn)

if __name__ == "__main__":
  nmt_parser = argparse.ArgumentParser()
  add_arguments(nmt_parser)
  FLAGS, unparsed = nmt_parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)


text:
'use strict';

var path = require('path');
var gutil = require('gulp-util');
var babylon = require('babylon');
var through2 = require('through2');

function justdoc (opts) {
	opts = opts || {};
	var babylonOpts = opts.babylon || {
		sourceType: 'module'
	};
	var docExtension = opts.extension || 'md';
	var matchRegex = opts.regexp || /^=(.*)\n/;

	var files = [];
	return through2.obj(function transform (file, enc, callback) {
		if (file && file.isBuffer()) {
			files.push(file);
		}
		callback();
	}, function flush (done) {
		var self = this;
		files.forEach(function (file) {
			var base = file.path.replace(file.relative, '');
			var relativeParsed = path.parse(file.relative);
			var relative = path.join(relativeParsed.dir, relativeParsed.name + '.' + docExtension);
			var parsedFile = babylon.parse(file.contents.toString('utf8'), babylonOpts);

			var contents = parsedFile.comments.reduce(function (markdownDoc, comment) {
				var match = matchRegex.exec(comment.value);
				if (match) {
					var docmarkComment = comment.value.replace(matchRegex, '');
					var leading = match[1];
					if (leading !== undefined && leading.length > 0) {
						return markdownDoc.concat(docmarkComment.split(/\n/).map(function (docmarkLine) {
							return docmarkLine.replace(leading, '');
						}).join('\n') + '\n');
					}
					return markdownDoc.concat(docmarkComment + '\n');
				}
				return markdownDoc;
			}, '');

			if (contents.length) {
				self.push(new gutil.File({
					base: base,
					path: path.join(base, relative),
					contents: new Buffer(contents, 'utf8')
				}));
			}
		});
		done();
	});
}

module.exports = justdoc;


text:
package org.apache.maven.settings;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import org.apache.maven.settings.v4.SettingsXpp3Reader;
import org.junit.jupiter.api.Test;

/**
 * Tests that the global settings.xml shipped with the distribution is in good state.
 *
 * @author Benjamin Bentmann
 */
public class GlobalSettingsTest {

    @Test
    public void testValidGlobalSettings() throws Exception {
        String basedir = System.getProperty("basedir", System.getProperty("user.dir"));

        File globalSettingsFile = new File(basedir, "src/assembly/maven/conf/settings.xml");
        assertTrue(globalSettingsFile.isFile(), globalSettingsFile.getAbsolutePath());

        try (Reader reader = new InputStreamReader(new FileInputStream(globalSettingsFile), StandardCharsets.UTF_8)) {
            new SettingsXpp3Reader().read(reader);
        }
    }
}


text:
package alluxio.underfs.cos;

import alluxio.AlluxioURI;
import alluxio.Constants;
import alluxio.conf.PropertyKey;
import alluxio.underfs.UnderFileSystem;
import alluxio.underfs.UnderFileSystemConfiguration;
import alluxio.underfs.UnderFileSystemFactory;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;

import java.io.IOException;
import javax.annotation.concurrent.ThreadSafe;

/**
 * Factory for creating {@link COSUnderFileSystem}.
 */
@ThreadSafe
public class COSUnderFileSystemFactory implements UnderFileSystemFactory {

  /**
   * Constructs a new {@link COSUnderFileSystemFactory}.
   */
  public COSUnderFileSystemFactory() {}

  @Override
  public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) {
    Preconditions.checkNotNull(path, "path");

    if (checkCOSCredentials(conf)) {
      try {
        return COSUnderFileSystem.createInstance(new AlluxioURI(path), conf);
      } catch (Exception e) {
        throw Throwables.propagate(e);
      }
    }

    String err = "COS Credentials not available, cannot create COS Under File System.";
    throw Throwables.propagate(new IOException(err));
  }

  @Override
  public boolean supportsPath(String path) {
    return path != null && path.startsWith(Constants.HEADER_COS);
  }

  /**
   * @param conf optional configuration object for the UFS
   *
   * @return true if both access, secret and endpoint keys are present, false otherwise
   */
  private boolean checkCOSCredentials(UnderFileSystemConfiguration conf) {
    return conf.isSet(PropertyKey.COS_ACCESS_KEY)
        && conf.isSet(PropertyKey.COS_SECRET_KEY)
        && conf.isSet(PropertyKey.COS_REGION);
  }
}


text:
/**
 * InvalidPreparation Exception class
 */
(function()
{
  var global = this,
      nspace = global.Exception,
      Exception = nspace.Exception;

  /**
   * @type InvalidPreparation
   */
  var InvalidPreparation = nspace.InvalidPreparation = function(message)
  {
    this.__construct(message);
  };

  InvalidPreparation.prototype = new Exception('InvalidPrepartion');

})();


text: google-site-verification: google7459a23780451026.html


text:
var url = "";
(function ($, root, undefined) {
	$(function () {
		url = $("#urlsrc").val();
		if ($(window).width() < 900){
			loadJS('mytheme-jquery-plugin', '/js/plugins.min.js');
			loadJS('mytheme-jquery-main', '/js/main.min.js');
			loadJS('mytheme-jquery-house', '/js/cn_interactive_house.min.js');
			loadJS('mytheme-jquery-track', '/js/SitecoreClientTracking.js');
			loadJS('mytheme-jquery-perso', '/js/SitecorePersonalizationv.js');
		}
	});

})(jQuery, this);

function loadJS(id, src) {
    if (document.getElementById(id) != null) return;
    var js = document.createElement('script');
    js.id = id; js.async = false; js.src = url+src;
    document.getElementsByTagName('head')[0].appendChild(js);
}


text:
/**
 * @fileoverview Rule to flag when initializing to undefined
 * @author Ilya Volodin
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    return {

        "VariableDeclarator": function(node) {
            var name = node.id.name;
            var init = node.init && node.init.name;

            if (init === "undefined") {
                context.report(node, "It's not necessary to initialize '{{name}}' to undefined.", { name: name });
            }
        }
    };

};


text:
package org.metaborg.spoofax.core.transform;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.action.ITransformAction;
import org.metaborg.core.action.TransformActionContrib;
import org.metaborg.core.context.IContext;
import org.metaborg.core.editor.IEditorRegistry;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.messages.IMessage;
import org.metaborg.core.resource.IResourceService;
import org.metaborg.core.source.ISourceRegion;
import org.metaborg.core.transform.ITransformConfig;
import org.metaborg.core.transform.TransformException;
import org.metaborg.core.unit.IUnit;
import org.metaborg.spoofax.core.action.TransformAction;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService;
import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService;
import org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxTransformUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxUnitService;
import org.metaborg.spoofax.core.unit.TransformContrib;
import org.metaborg.spoofax.core.unit.TransformOutput;
import org.metaborg.util.iterators.Iterables2;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.metaborg.util.time.Timer;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.terms.util.TermUtils;
import org.strategoxt.HybridInterpreter;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;

public class StrategoTransformer implements IStrategoTransformer {
    private static final ILogger logger = LoggerUtils.logger(StrategoTransformer.class);

    private final IResourceService resourceService;
    private final ISpoofaxUnitService unitService;
    private final IEditorRegistry editorRegistry;
    private final ISpoofaxTracingService tracingService;
    private final IStrategoRuntimeService strategoRuntimeService;
    private final IStrategoCommon common;

    @Inject public StrategoTransformer(IResourceService resourceService, ISpoofaxUnitService unitService,
        IEditorRegistry editorRegistry, ISpoofaxTracingService tracingService,
        IStrategoRuntimeService strategoRuntimeService, IStrategoCommon common) {
        this.resourceService = resourceService;
        this.unitService = unitService;
        this.editorRegistry = editorRegistry;
        this.tracingService = tracingService;
        this.strategoRuntimeService = strategoRuntimeService;
        this.common = common;
    }

    @Override public ISpoofaxTransformUnit<ISpoofaxParseUnit> transform(ISpoofaxParseUnit input, IContext context,
        TransformActionContrib action, ITransformConfig config) throws TransformException {
        if(!input.valid()) {
            throw new TransformException("Cannot transform parse unit " + input + ", it is not valid");
        }
        return transform(input, context, action, input.source(), input.ast(), config);
    }

    @Override public ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit> transform(ISpoofaxAnalyzeUnit input, IContext context,
        TransformActionContrib action, ITransformConfig config) throws TransformException {
        if(!input.valid()) {
            throw new TransformException("Cannot transform analyze unit " + input + ", it is not valid");
        }
        if(!input.hasAst()) {
            throw new TransformException("Cannot transform analyze unit " + input + ", it has no AST");
        }
        return transform(input, context, action, input.source(), input.ast(), config);
    }

    @Override public Collection<ISpoofaxTransformUnit<ISpoofaxParseUnit>> transformAllParsed(
        Iterable<ISpoofaxParseUnit> inputs, IContext context, TransformActionContrib action, ITransformConfig config)
        throws TransformException {
        final int size = Iterables.size(inputs);
        final Collection<ISpoofaxTransformUnit<ISpoofaxParseUnit>> transformUnits =
            Lists.newArrayListWithCapacity(size);
        for(ISpoofaxParseUnit input : inputs) {
            if(!input.valid()) {
                throw new TransformException("Cannot transform parse unit " + input + ", it is not valid");
            }
            transformUnits.add(transform(input, context, action, input.source(), input.ast(), config));
        }
        return transformUnits;
    }

    @Override public Collection<ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit>> transformAllAnalyzed(
        Iterable<ISpoofaxAnalyzeUnit> inputs, IContext context, TransformActionContrib action, ITransformConfig config)
        throws TransformException {
        final int size = Iterables.size(inputs);
        final Collection<ISpoofaxTransformUnit<ISpoofaxAnalyzeUnit>> transformUnits =
            Lists.newArrayListWithCapacity(size);
        for(ISpoofaxAnalyzeUnit input : inputs) {
            if(!input.valid()) {
                throw new TransformException("Cannot transform analyze unit " + input + ", it is not valid");
            }
            if(!input.hasAst()) {
                throw new TransformException("Cannot transform analyze unit " + input + ", it has no AST");
            }
            transformUnits.add(transform(input, context, action, input.source(), input.ast(), config));
        }
        return transformUnits;
    }

    private <I extends IUnit> ISpoofaxTransformUnit<I> transform(I input, IContext context,
        TransformActionContrib actionContribution, FileObject source, IStrategoTerm term, ITransformConfig config)
        throws TransformException {
        final FileObject location = context.location();
        final ILanguageComponent component = actionContribution.contributor;
        final TransformAction action = action(actionContribution.action);

        // Get selected term, if any.
        final IStrategoTerm selectedTerm;
        final ISourceRegion selection = config.selection();
        if(selection != null) {
            final Iterable<IStrategoTerm> terms = tracingService.toTermsWithin(term, selection);
            final Iterator<IStrategoTerm> termsIterator = terms.iterator();
            if(termsIterator.hasNext()) {
                selectedTerm = termsIterator.next();
            } else {
                selectedTerm = null;
            }
        } else {
            selectedTerm = null;
        }

        // Get input term
        final IStrategoTerm inputTerm = common.builderInputTerm(term, selectedTerm, source, location);

        // Get Stratego runtime
        final HybridInterpreter runtime;
        try {
            runtime = strategoRuntimeService.runtime(component, context);
        } catch(MetaborgException e) {
            throw new TransformException("Transformation failed unexpectedly; cannot get Stratego interpreter", e);
        }

        // Transform
        logger.debug("Transforming {} with '{}'", source, action.name);
        final Timer timer = new Timer(true);
        final IStrategoTerm outputTerm;
        try {
            outputTerm = common.invoke(runtime, inputTerm, action.strategy);
        } catch(MetaborgException e) {
            throw new TransformException(e.getMessage(), e.getCause());
        }
        final long duration = timer.stop();
        if(outputTerm == null) {
            final String message = logger.format("Invoking Stratego strategy {} failed", action.strategy);
            throw new TransformException(message);
        }

        // Get the result and, if allowed and required, write to file
        List<TransformOutput> outputs;
        IStrategoTerm resultTerm;
        if(outputTerm.getSubtermCount() == 2 && TermUtils.isTuple(outputTerm)) {
            final IStrategoTerm resourceTerm = outputTerm.getSubterm(0);
            final IStrategoTerm contentTerm = outputTerm.getSubterm(1);
            try {
                if(TermUtils.isString(resourceTerm)) {
                    resultTerm = contentTerm;
                    outputs = Lists.newArrayList(output(resourceTerm, contentTerm, location, config));
                } else if(TermUtils.isList(resourceTerm)) {
                    if(!TermUtils.isList(contentTerm)
                        || resourceTerm.getSubtermCount() != contentTerm.getSubtermCount()) {
                        logger.error("List of terms does not match list of file names, cannot write to file.");
                        resultTerm = null;
                        outputs = Collections.emptyList();
                    } else {
                        outputs = Lists.newArrayListWithExpectedSize(resourceTerm.getSubtermCount());
                        for(int i = 0; i < resourceTerm.getSubtermCount(); i++) {
                            outputs
                                .add(output(resourceTerm.getSubterm(i), contentTerm.getSubterm(i), location, config));
                        }
                        resultTerm = resourceTerm.getSubtermCount() == 1 ? resourceTerm.getSubterm(0) : null;
                    }
                } else {
                    logger.error(
                        "First term of result tuple {} is neither a string, nor a list, cannot write output file",
                        resourceTerm);
                    resultTerm = null;
                    outputs = Collections.emptyList();
                }
            } catch(MetaborgException ex) {
                logger.error("Failed to output result", ex);
                resultTerm = null;
                outputs = Collections.emptyList();
            }
        } else {
            resultTerm = outputTerm;
            outputs = Collections.emptyList();
        }

        // Open editor
        if(action.flags.openEditor) {
            List<FileObject> resources = Lists.newArrayListWithExpectedSize(outputs.size());
            for(TransformOutput output : outputs) {
                if(output.resource != null) {
                    resources.add(output.resource);
                }
            }
            editorRegistry.open(resources, context.project());
        }

        // Return result
        final TransformContrib contrib = new TransformContrib(resultTerm != null || !Iterables.isEmpty(outputs), true,
            resultTerm, outputs, Iterables2.<IMessage>empty(), duration);
        return unitService.transformUnit(input, contrib, context, actionContribution);
    }

    private TransformAction action(ITransformAction action) throws TransformException {
        if(!(action instanceof TransformAction)) {
            final String message = logger.format("Action {} is not a Stratego transformation action", action);
            throw new TransformException(message);
        }
        return (TransformAction) action;
    }

    private TransformOutput output(IStrategoTerm resourceTerm, IStrategoTerm contentTerm, FileObject location,
        ITransformConfig config) throws MetaborgException {
        if(!(TermUtils.isString(resourceTerm))) {
            throw new MetaborgException("First term of result tuple {} is not a string, cannot write output file");
        } else {
            final String resourceString = TermUtils.toJavaString(resourceTerm);
            // writing to output file is allowed
            FileObject output;
            if(!config.dryRun()) {
                final String resultContents = common.toString(contentTerm);
                output = resourceService.resolve(location, resourceString);
                try(OutputStream stream = output.getContent().getOutputStream()) {
                    IOUtils.write(resultContents, stream, Charset.defaultCharset());
                } catch(IOException e) {
                    logger.error("Error occurred while writing output file", e);
                }
            } else {
                output = null;
            }
            return new TransformOutput(resourceString, output, contentTerm);
        }
    }

}


text:
'''
    Process sensor plugin

    Generates the running processes information
'''
import psutil, getpass
import datetime, time, logging
from ptop.core import Plugin
from ptop.constants import (PRIVELAGED_USERS,
                            INVALID_PROCESSES,
                            SYSTEM_USERS
                            )

class ProcessSensor(Plugin):
    def __init__(self,**kwargs):
        super(ProcessSensor,self).__init__(**kwargs)
        # there will be two parts of the returned value, one will be text and other graph
        # there can be many text (key,value) pairs to display corresponding to each key
        self.currentValue['text'] = { 'running_processes' : 0,'running_threads' : 0}
        # nested structure is used for keeping the info of processes
        self.currentValue['table'] = []
        self._currentSystemUser = getpass.getuser()
        self._logger = logging.getLogger(__name__)

    def format_time(self, d):
        ret = '{0} day{1} '.format(d.days, ' s'[d.days > 1]) if d.days else ''
        h = d.seconds // 3600
        s = d.seconds - 3600 * h
        m = s // 60
        s -= m * 60
        return ret + '{0:2d}:{1:02d}:{2:02d}'.format(h, m, s)

    # overriding the upate method
    def update(self):
        # flood the data
        thread_count = 0 #keep track number of threads
        proc_count = 0 #keep track of number of processes
        proc_info_list = []
        for proc in psutil.process_iter():
            # info of a single process
            proc_info = {}
            proc_info['id'] = proc.pid
            proc_info['name'] = proc.name()
            '''
             Getting more info about the processes
             In case of MacOSx all of the processes that are returned by psutil.process_iter()
             for all the users(root, adminstrator, normal user)
             There should be a check for the current user is root or not
             because getting further process info for root processes as a normal
             user will give Permission Denied #10
            '''
            p = psutil.Process(proc.pid)
            proc_info['user'] = p.username()
            try:
                if ((proc_info['user'] == self._currentSystemUser) or (self._currentSystemUser in PRIVELAGED_USERS)) \
                        and p.status() not in INVALID_PROCESSES:
                    delta = datetime.timedelta(seconds=(time.time() - p.create_time()))
                    proc_info['rawtime'] = time.time() - p.create_time()
                    proc_info['time'] =  self.format_time(delta)
                    proc_info['command'] = ' '.join(p.cmdline())
                    # incrementing the thread_count and proc_count
                    thread_count += p.num_threads()
                    proc_info['cpu'] = p.cpu_percent()
                    proc_info['memory'] = round(p.memory_percent(),2)
                    # Add information of the local ports used by the process
                    proc_info['local_ports'] = [x.laddr[1] for x in p.connections()]
                    # Add information of the open files by the process
                    proc_info['open_files'] = p.open_files()
                    proc_count += 1
                    # recording the info
                    proc_info_list.append(proc_info)
                    # Aggregate all the system users
                    if proc_info['user'] not in SYSTEM_USERS:
                        SYSTEM_USERS.append(proc_info['user'])
            except:
                '''
                    In case ptop does not have privelages to access info for some of the processes
                    just log them and don't show them in the processes table
                '''
                self._logger.info('''Not able to get info for process {0} with status {1} invoked by user {2}, ptop
                                   is invoked by the user {3}'''.format(str(p.pid),
                                                                        p.status(),
                                                                        p.username(),
                                                                        self._currentSystemUser
                                                                        ),
                                                                        exc_info=True)

        # padding time
        time_len = max((len(proc['time']) for proc in proc_info_list))
        for proc in proc_info_list:
            proc['time'] = '{0: >{1}}'.format(proc['time'], time_len)

        self.currentValue['table'] = []
        self.currentValue['table'].extend(proc_info_list)
        self.currentValue['text']['running_processes'] = str(proc_count)
        self.currentValue['text']['running_threads'] = str(thread_count)

# make the process sensor less frequent as it takes more time to fetch info
process_sensor = ProcessSensor(name='Process',sensorType='table',interval=1)


text:
static const TCHAR testTargetName[] = _T("TARGET");

int TestCredUICmdLinePromptForCredentials(int argc, char* argv[])
{
	BOOL fSave;
	DWORD status;
	DWORD dwFlags;
	TCHAR UserName[CREDUI_MAX_USERNAME_LENGTH];
	TCHAR Password[CREDUI_MAX_PASSWORD_LENGTH];

	fSave = FALSE;
	ZeroMemory(UserName, sizeof(UserName));
	ZeroMemory(Password, sizeof(Password));
	dwFlags = CREDUI_FLAGS_DO_NOT_PERSIST | CREDUI_FLAGS_EXCLUDE_CERTIFICATES;

	status = CredUICmdLinePromptForCredentials(testTargetName, NULL, 0,
		UserName, CREDUI_MAX_USERNAME_LENGTH,
		Password, CREDUI_MAX_PASSWORD_LENGTH, &fSave, dwFlags);

	if (status != NO_ERROR)
	{
		printf("CredUIPromptForCredentials unexpected status: 0x%08"PRIX32"\n", status);
		return -1;
	}

	_tprintf(_T("UserName: %s Password: %s\n"), UserName, Password);

	return 0;
}


text:
IMAGE?=sapcc/hyperkube

ARCH=amd64
CNI_PLUGINS_RELEASE=v0.8.5
CNI_DEDUP_BRIDGE_RELEASE=v0.1.0
MULTUS_RELEASE=3.2
BASEIMAGE?=k8s.gcr.io/hyperkube-$(ARCH):$(VERSION)

TEMP_DIR:=$(shell mktemp -d -t hyperkubeXXXXXX)

build: cni
ifndef VERSION
    $(error VERSION is undefined)
endif
	cp -r ./* ${TEMP_DIR}
	cd ${TEMP_DIR} && sed -i.back "s|BASEIMAGE|${BASEIMAGE}|g" Dockerfile
	docker build --pull -t ${IMAGE}:${VERSION} ${TEMP_DIR}
	rm -rf "${TEMP_DIR}"

push: build
	docker push ${IMAGE}:${VERSION}

cni:
	mkdir -p ${TEMP_DIR}/cni-bin/bin
	curl -sSL --retry 5 https://github.com/containernetworking/plugins/releases/download/${CNI_PLUGINS_RELEASE}/cni-plugins-linux-${ARCH}-${CNI_PLUGINS_RELEASE}.tgz | tar -xz -C ${TEMP_DIR}/cni-bin/bin
	curl -sSL --retry 5 https://github.com/intel/multus-cni/releases/download/v${MULTUS_RELEASE}/multus-cni_${MULTUS_RELEASE}_linux_amd64.tar.gz | tar --strip 1 -xz -C ${TEMP_DIR}/cni-bin/bin
	curl -o ${TEMP_DIR}/cni-bin/bin/dedup-bridge -sSL --retry 5 https://github.com/sapcc/cni-dedup-bridge/releases/download/${CNI_DEDUP_BRIDGE_RELEASE}/dedup-bridge
	chmod +x ${TEMP_DIR}/cni-bin/bin/dedup-bridge

.PHONY: build push all cni