text:
var base_url = 'http://wangyu.scripts.mit.edu/cssa';

angular.module('starter.services', [])

/**
 * A simple example service that returns some data.
 */
.factory('Util', function($rootScope, $http){
    var service = {
      uid: '',

      signin: function(username, password){
        var self = this;
        $http.post(base_url+'/User/ajax_login', {
          'username': username,
          'password': password
        }).success(function(ret){
          if(ret.error === undefined){
            self.uid = ret.uid;
            localStorage['cssa_uid'] = ret.uid;
            $rootScope.$broadcast('login.success');
          }
          else{
            $rootScope.$broadcast('login.error.password');
          }
        }).error(function(){
          $rootScope.$broadcast('login.error.connection');
        });
      },

      is_signedin: function(){
        if(this.uid !== '')
          return true;
        else
          return false;
      },

      get_user_uid: function(){
        return this.uid;
      },

      get_image_base_url: function(){
        return base_url+'/Public/Uploaded/';
      }
    };

    if(localStorage['cssa_uid']!==undefined){
      service.uid = localStorage['cssa_uid'];
      $rootScope.$broadcast('login.success');
    }

    return service;
})

.factory('Section', function($rootScope, $http) {
    var service = {
    sections: [],

    sync: function(){
      var self = this;
      $http.get(base_url+'/Client/sections').success(function(data){
        self.sections = data;
        $rootScope.$broadcast('section.update');
      });
    },

    all: function(){
      // $rootScope.$broadcast('section.update');
      return this.sections;
    },

    get: function(id) {
        for(var i in this.sections){
          if(this.sections[i].id == id){
            return this.sections[i];
          }
        }
        return null;
      }
    };
    return service;
})

.factory('Events', function($rootScope, $http, Util) {
    var service = {
      all_events: [],
      my_events: [],

      sync: function(my_events){
        var self = this;
        if(my_events===true){
          extra_url = '/type/my/uid/'+Util.get_user_uid();
        }
        else{
          extra_url = '';
        }
        $http.get(base_url+'/Client/events'+extra_url).success(function(data){
          if(my_events===true){
            self.my_events = data;
          }
          else{
            self.all_events = data;
          }
          $rootScope.$broadcast('events.update');
        });
      },

      all: function(my_events){
        var self = this;
        if(my_events === true){
          return self.my_events;
        }
        else{
          return self.all_events;
        }
      }
    };
    return service;
})

.factory('Post', function($rootScope, $http, Util) {
  // Might use a resource here that returns a JSON array

  // Some fake testing data
  var service = {
    posts: [],

    sync: function(section_id){
      var self = this;
      $http.get(base_url+'/Client/posts/section_id/'+section_id).success(function(data){
        for(var i in data){
          data[i].from_now = moment(data[i].publish_time).fromNow();
          self.posts[data[i].id] = data[i];
        }
        $rootScope.$broadcast('post.update');
      });
    },

    load: function(post_id){
      var self = this;
      if(Util.is_signedin()){
        var url_uid_part = '/uid/'+Util.get_user_uid();
      }
      $http.get(base_url+'/Client/post/id/'+post_id+url_uid_part).success(function(data){
        if(data.event_time){
          data.event_date = data.event_time.split(' ')[0];  // this is mysql specific! get the date part of datetime
        }
        self.posts[data.id] = data;
        $rootScope.$broadcast('post.load');
      });
    },

    by_section: function(section_id){
      var self = this;
      var out = [];
      for(var i in self.posts){
        if(self.posts[i].section_id == section_id){
          out.push(self.posts[i]);
        }
      }
      return out;
    },

    get: function(id){
      return this.posts[id];
    },

    delete_post: function(id, callback){
      $http.get(base_url+'/Post/ajax_delete/id/'+id+'/uid/'+Util.get_user_uid()).success(function(result){
        callback();
        $rootScope.$broadcast('post.changed');
      });
    },

    add_post: function(post, callback){
      var self = this;
      post.id = Util.get_user_uid();
      post.is_event = post.is_event?'1':'0';
      $http.post(base_url+'/Post/ajax_add', post).success(function(data){
        if(!(data.id in self.posts)){
          self.posts.unshift(data);
        }
        callback(data);
      });
    },

    add_comment: function(comment, callback){
      var self = this;
      comment.uid = Util.get_user_uid();
      $http.post(base_url+'/Post/add_comment', comment).success(function(data){
        callback(data);
      });
    },

    close_post: function(id, closed, callback){
      var self = this;
      var url_uid_part = '/uid/'+Util.get_user_uid();
      $http.get(base_url+'/Post/close_post/id/'+id+'/closed/'+closed+url_uid_part).success(function(result){
        callback();
        // $rootScope.$broadcast('post.changed');
      });
    },

    send_rsvp: function(rsvp, callback){
      var self = this;
      rsvp.uid = Util.get_user_uid();
      $http.post(base_url+'/Post/signup', rsvp).success(function(data){
        callback(data);
      });
    },

    cancel_rsvp: function(id, callback){
      var self = this;
      rsvp = {
        cancel: 1,
        post_id: id,
        uid: Util.get_user_uid()
      };
      $http.post(base_url+'/Post/signup', rsvp).success(function(data){
        callback(data);
      });
    }
  };
  return service;
});


text:
import React, { Component } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Feedback.scss';

class Feedback extends Component {

  render() {
    return (

          Ask a question
          |
          Report an issue

    );
  }

}

export default withStyles(Feedback, s);

redpajama_set_name: RedPajamaGithub


text:
<component name="DependencyValidationManager">
  <scope name="livingdoc" pattern="(test:*..*||src:*..*)&&!src[group:livingdoc-documentation]:*..*" />
</component>


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

<!--
  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.
-->

<!--
    GridGain Spring configuration file to startup grid cache.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="fileSystemConfiguration">
            <list>
                <bean class="org.apache.ignite.configuration.FileSystemConfiguration">
                    <property name="name" value="test"/>
                    <property name="metaCacheName" value="meta"/>
                    <property name="dataCacheName" value="data"/>

                    <property name="maxSpaceSize" value="#{100L * 1024 * 1024}"/>

                    <!-- Loopback endpoint. -->
                    <property name="ipcEndpointConfiguration">
                        <bean class="org.apache.ignite.igfs.IgfsIpcEndpointConfiguration">
                            <property name="type" value="TCP" />
                        </bean>
                    </property>
                </bean>
            </list>
        </property>

        <!-- Cache configurations (all properties are optional). -->
        <property name="cacheConfiguration">
            <list>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <!-- Configure type metadata to enable queries. -->
                    <property name="typeMetadata">
                        <list>
                            <bean class="org.apache.ignite.cache.CacheTypeMetadata">
                                <property name="keyType" value="java.lang.Integer"/>
                                <property name="valueType" value="Organization"/>
                                <property name="ascendingFields">
                                    <map>
                                        <entry key="name" value="java.lang.String"/>
                                    </map>
                                </property>
                            </bean>
                            <bean class="org.apache.ignite.cache.CacheTypeMetadata2"/>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

    <bean id="grid.cfg.failed" class="org.apache.ignite.configuration.IgniteConfiguration2"/>
</beans>


text:
<?php

namespace Google\Service\RemoteBuildExecution;

class GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteInstanceRequest extends \Google\Model
{
  public $name;

  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteInstanceRequest::class, 'Google_Service_RemoteBuildExecution_GoogleDevtoolsRemotebuildexecutionAdminV1alphaDeleteInstanceRequest');


text:
namespace base {

bool StringToUint128(StringPiece input, absl::uint128* output) {
  return internal::StringToIntImpl(input, *output);
}

bool HexStringToUInt128(StringPiece input, absl::uint128* output) {
  return internal::HexStringToIntImpl(input, *output);
}

}  // namespace base


text:
module Grapi
  class PostsAPI < Grape::API
    helpers do
      def check_index
        check_params(['user_id'])
        error!('Not Found', 404) unless User.find_by_id(params[:user_id])
      end

      def get_resource
        @model =  Post.find_by_id(params[:id])
        error!('Not Found', 404) unless @model
      end

      def authorize_resource
        error!('Forbidden', 403) unless @model.authorize!(current_user)
      end

      def permited_params
        filter_data(['title', 'text'])
      end
    end

    before do
      authenticate!
    end

    resource :posts do
      get do
        check_index
        @scope = Post.find({user_id: params[:user_id]}).limit(10)
        paginate
        respond_with @scope
      end

      post do
        @model = Post.create(permited_params.merge(user_id: current_user.id))
        respond_with @model
      end

      get ':id' do
        get_resource
        respond_with @model
      end

      put ':id' do
        get_resource
        @model.update(permited_params)
        respond_with @model
      end

      delete ':id' do
        get_resource
        authorize_resource
        @model.destroy
        status 204
      end
    end
  end
end


text:
int main(int argc, char* argv[])
{
    const char *DestinationName = (argc > 1) ? argv[1] : "localhost";
    const Uint16 DestinationPort = (argc > 2) ? atoi(argv[2]) : 2000;
    const std::string Behaviour = (argc > 3) ? argv[3] : "manual";

    // Initialize SDL_net
    if (SDLNet_Init() < 0)
    {
        std::cerr << "SDLNet_Init: " << SDLNet_GetError() << "\n";
        exit(EXIT_FAILURE);
    }

    IPaddress ServerIP;
    TCPsocket ServerSocket;

    std::cout << "resolving hostname...\n";
    if (SDLNet_ResolveHost(&ServerIP, DestinationName, DestinationPort))
    {
        std::cerr << "failed to resolve " << DestinationName << "\n";
        std::cerr << SDL_GetError();
        exit(3);
    }

    Uint32 ServerIPHost = ServerIP.host;
    std::cout << "Server IP: ";
    std::cout << CNet::TranslateAddr(ServerIP.host);
    std::cout << ", port " << ServerIP.port;
    std::cout << "\n";

    std::cout << "connecting to server ";
    std::cout << CNet::TranslateAddr(ServerIP.host) << ":" << DestinationPort;
    std::cout << " (" << DestinationName << ")";
    std::cout << "...\n";
    ServerSocket = SDLNet_TCP_Open(&ServerIP);
    if (!ServerSocket)
    {
        std::cerr << "failed to connect to server\n";
        std::cerr << SDL_GetError();
        exit(4);
    }

    std::cerr << "sending player name...\n";

    //Insert your Playername here
    const char PlayerName[16] = "BOT";

    if (SDLNet_TCP_Send(ServerSocket, (void *)PlayerName, sizeof(PlayerName)) != sizeof(PlayerName))
    {
        std::cerr << "failed to notify client\n";
        std::cerr << SDL_GetError();
        exit(5);
    }

    char Buffer[BUFFER_SIZE];

    while (true)
    {
        GameState state;
        if (SDLNet_TCP_Recv(ServerSocket, (void *)Buffer, BUFFER_SIZE) != BUFFER_SIZE)
        {
            std::cerr << "failed to receive data from server\n";
            std::cerr << SDL_GetError();
            exit(5);
        }
        std::cout << "Received buffer from Server" << std::endl;

        std::istringstream iss(Buffer);
        state.Deserialize(iss);

        NetRequest* Action = new NetRequest();

        //Do magic here with Action

        std::cin.ignore();

        Action->moving = true;
        Action->shoot = true;

        //Dont touch the following

        int size = SDLNet_TCP_Send(ServerSocket, (void *)Action, sizeof(NetRequest));

        if (size != sizeof(NetRequest))
        {
            std::cerr << "failed to send data to server\n";
            std::cerr << SDL_GetError();
            exit(5);
        }
    }

    return 0;
}


text:
package com.navercorp.pinpoint.web.websocket;

import com.navercorp.pinpoint.rpc.packet.stream.StreamCode;
import com.navercorp.pinpoint.thrift.dto.command.TRouteResult;

import java.util.*;

/**
 * @Author Taejin Koo
 */
public enum ActiveThreadCountErrorType {

    UNSUPPORTED_VERSION((short) 111, "UNSUPPORTED VERSION", StreamCode.TYPE_UNSUPPORT.name()),
    CLUSTER_OPTION_NOT_SET((short) 121, "CLUSTER OPTION NOT SET", StreamCode.CONNECTION_UNSUPPORT.name()),

    TIMEOUT((short) 211, "TIMEOUT", TRouteResult.TIMEOUT.name()),

    NOT_FOUND((short) -1, "NOT FOUND", StreamCode.CONNECTION_NOT_FOUND.name()),
    CLUSTER_CHANNEL_CLOSED((short) -1, "CLUSTER CHANNEL CLOSED", StreamCode.STATE_CLOSED.name()),
    PINPOINT_INTERNAL_ERROR((short) -1, "PINPOINT INTERNAL ERROR");

    private final static Map<String, ActiveThreadCountErrorType> CODE_MAP = Collections.unmodifiableMap(initializeCodeMapping());

    private final short code;
    private final String message;
    private final List<String> errorMessageList = new ArrayList<>();
    private static final String LINE_DELEMETER = "-";

    ActiveThreadCountErrorType(short code, String message, String... candidateErrorMessages) {
        this.code = code;
        this.message = message;

        if (candidateErrorMessages != null) {
            for (String errorMessage : candidateErrorMessages) {
                errorMessageList.add(errorMessage);
            }
        }
    }

    public short getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public List<String> getErrorMessageList() {
        return errorMessageList;
    }

    private static Map<String, ActiveThreadCountErrorType> initializeCodeMapping() {
        Map<String, ActiveThreadCountErrorType> codeMap = new HashMap<>();
        for (ActiveThreadCountErrorType errorType : ActiveThreadCountErrorType.values()) {

            List<String> errorMessageList = errorType.getErrorMessageList();
            for (String errorMessage : errorMessageList) {
                codeMap.put(errorMessage, errorType);
            }

        }
        return codeMap;
    }

    public static ActiveThreadCountErrorType getType(String errorMessage) {
        ActiveThreadCountErrorType errorType = CODE_MAP.get(errorMessage);
        if (errorType == null) {
            return PINPOINT_INTERNAL_ERROR;
        }
        return errorType;
    }

}


text:
package org.apache.hadoop.fs.s3a.impl;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.google.common.util.concurrent.ListeningExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathIsNotEmptyDirectoryException;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.s3a.Invoker;
import org.apache.hadoop.fs.s3a.Retries;
import org.apache.hadoop.fs.s3a.S3AFileStatus;
import org.apache.hadoop.fs.s3a.S3ALocatedFileStatus;
import org.apache.hadoop.fs.s3a.Tristate;
import org.apache.hadoop.fs.s3a.s3guard.BulkOperationState;
import org.apache.hadoop.fs.s3a.s3guard.MetadataStore;
import org.apache.hadoop.fs.s3a.s3guard.S3Guard;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.DurationInfo;

import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.hadoop.fs.s3a.impl.CallableSupplier.maybeAwaitCompletion;
import static org.apache.hadoop.fs.s3a.impl.CallableSupplier.submit;

/**
 * Implementation of the delete() operation.
 *

 * How S3Guard/Store inconsistency is handled:
 *

 *

 *     The list operation does not ask for tombstone markers; objects
 *     under tombstones will be found and deleted.
 *     The {@code extraFilesDeleted} counter will be incremented here.
 *

 *

 *     That may result in recently deleted files being found and
 *     duplicate delete requests issued. This is mostly harmless.
 *

 *

 *     If a path is considered authoritative on the client, so only S3Guard
 *     is used for listings, we wrap up the delete with a scan of raw S3.
 *     This will find and eliminate OOB additions.
 *

 *

 *     Exception 1: simple directory markers of the form PATH + "/".
 *     These are treated as a signal that there are no children; no
 *     listing is made.
 *

 *

 *     Exception 2: delete(path, true) where path has a tombstone in S3Guard.
 *     Here the delete is downgraded to a no-op even before this operation
 *     is created. Thus: no listings of S3.
 *

 *

 * If this class is logged at debug, requests will be audited:
 * the response to a bulk delete call will be reviewed to see if there
 * were fewer files deleted than requested; that will be printed
 * at WARN level. This is independent of handling rejected delete
 * requests which raise exceptions -those are processed lower down.
 *

 * Performance tuning:
 *

 * The operation to POST a delete request (or issue many individual
 * DELETE calls) then update the S3Guard table is done in an async
 * operation so that it can overlap with the LIST calls for data.
 * However, only one single operation is queued at a time.
 *

 * Executing more than one batch delete is possible, it just
 * adds complexity in terms of error handling as well as in
 * the datastructures used to track outstanding operations.
 * If this is done, then it may be good to experiment with different
 * page sizes. The default value is
 * {@link InternalConstants#MAX_ENTRIES_TO_DELETE}, the maximum a single
 * POST permits.
 *

 * 1. Smaller pages executed in parallel may have different
 * performance characteristics when deleting very large directories,
 * because it will be the DynamoDB calls which will come to dominate.
 * Any exploration of options here MUST be done with performance
 * measurements taken from test runs in EC2 against local DDB and S3 stores,
 * so as to ensure network latencies do not skew the results.
 *

 * 2. Note that as the DDB thread/connection pools will be shared across
 * all active delete operations, speedups will be minimal unless
 * those pools are large enough to cope the extra load.
 *

 * There are also some opportunities to explore in
 * {@code DynamoDBMetadataStore} with batching delete requests
 * in the DDB APIs.
 */
public class DeleteOperation extends ExecutingStoreOperation<Boolean> {

  private static final Logger LOG = LoggerFactory.getLogger(
      DeleteOperation.class);

  /**
   * Pre-fetched source status.
   */
  private final S3AFileStatus status;

  /**
   * Recursive delete?
   */
  private final boolean recursive;

  /**
   * Callback provider.
   */
  private final OperationCallbacks callbacks;

  /**
   * Number of entries in a page.
   */
  private final int pageSize;

  /**
   * Metastore -never null but may be the NullMetadataStore.
   */
  private final MetadataStore metadataStore;

  /**
   * Executor for async operations.
   */
  private final ListeningExecutorService executor;

  /**
   * List of keys built up for the next delete batch.
   */
  private List<DeleteObjectsRequest.KeyVersion> keys;

  /**
   * List of paths built up for deletion.
   */
  private List<Path> paths;

  /**
   * The single async delete operation, or null.
   */
  private CompletableFuture<Void> deleteFuture;

  /**
   * Bulk Operation state if this is a bulk operation.
   */
  private BulkOperationState operationState;

  /**
   * Counter of deleted files.
   */
  private long filesDeleted;

  /**
   * Counter of files found in the S3 Store during a raw scan of the store
   * after the previous listing was in auth-mode.
   */
  private long extraFilesDeleted;

  /**
   * Constructor.
   * @param context store context
   * @param status  pre-fetched source status
   * @param recursive recursive delete?
   * @param callbacks callback provider
   * @param pageSize size of delete pages
   */
  public DeleteOperation(final StoreContext context,
      final S3AFileStatus status,
      final boolean recursive,
      final OperationCallbacks callbacks,
      final int pageSize) {

    super(context);
    this.status = status;
    this.recursive = recursive;
    this.callbacks = callbacks;
    checkArgument(pageSize > 0
            && pageSize <= InternalConstants.MAX_ENTRIES_TO_DELETE,
        "page size out of range: %s", pageSize);
    this.pageSize = pageSize;
    metadataStore = context.getMetadataStore();
    executor = context.createThrottledExecutor(1);
  }

  public long getFilesDeleted() {
    return filesDeleted;
  }

  public long getExtraFilesDeleted() {
    return extraFilesDeleted;
  }

  /**
   * Delete a file or directory tree.
   *

   * This call does not create any fake parent directory; that is
   * left to the caller.
   * The actual delete call is done in a separate thread.
   * Only one delete at a time is submitted, however, to reduce the
   * complexity of recovering from failures.
   *

   * The DynamoDB store deletes paths in parallel itself, so that
   * potentially slow part of the process is somewhat speeded up.
   * The extra parallelization here is to list files from the store/DDB while
   * that delete operation is in progress.
   *
   * @return true, except in the corner cases of root directory deletion
   * @throws PathIsNotEmptyDirectoryException if the path is a dir and this
   * is not a recursive delete.
   * @throws IOException list failures or an inability to delete a file.
   */
  @Retries.RetryTranslated
  public Boolean execute() throws IOException {
    executeOnlyOnce();

    StoreContext context = getStoreContext();
    Path path = status.getPath();
    LOG.debug("Delete path {} - recursive {}", path, recursive);
    LOG.debug("Type = {}",
        status.isFile() ? "File"
            : (status.isEmptyDirectory() == Tristate.TRUE
                ? "Empty Directory"
                : "Directory"));

    String key = context.pathToKey(path);
    if (status.isDirectory()) {
      LOG.debug("delete: Path is a directory: {}", path);
      checkArgument(
          status.isEmptyDirectory() != Tristate.UNKNOWN,
          "File status must have directory emptiness computed");

      if (!key.endsWith("/")) {
        key = key + "/";
      }

      if ("/".equals(key)) {
        LOG.error("S3A: Cannot delete the root directory."
                + " Path: {}. Recursive: {}",
            status.getPath(), recursive);
        return false;
      }

      if (!recursive && status.isEmptyDirectory() == Tristate.FALSE) {
        throw new PathIsNotEmptyDirectoryException(path.toString());
      }
      if (status.isEmptyDirectory() == Tristate.TRUE) {
        LOG.debug("deleting empty directory {}", path);
        deleteObjectAtPath(path, key, false);
      } else {
        deleteDirectoryTree(path, key);
      }

    } else {
      // simple file.
      LOG.debug("deleting simple file {}", path);
      deleteObjectAtPath(path, key, true);
    }
    LOG.debug("Deleted {} files", filesDeleted);
    return true;
  }

  /**
   * Delete a directory tree.
   *

   * This is done by asking the filesystem for a list of all objects under
   * the directory path, without using any S3Guard tombstone markers to hide
   * objects which may be returned in S3 listings but which are considered
   * deleted.
   *

   * Once the first {@link #pageSize} worth of objects has been listed, a batch
   * delete is queued for execution in a separate thread; subsequent batches
   * block waiting for the first call to complete or fail before again,
   * being deleted in the separate thread.
   *

   * After all listed objects are queued for deletion,
   * if the path is considered authoritative in the client, a final scan
   * of S3 without S3Guard is executed, so as to find and delete
   * any out-of-band objects in the tree.
   * @param path directory path
   * @param dirKey directory key
   * @throws IOException failure
   */
  @Retries.RetryTranslated
  protected void deleteDirectoryTree(final Path path,
      final String dirKey) throws IOException {
    // create an operation state so that the store can manage the bulk
    // operation if it needs to
    operationState = S3Guard.initiateBulkWrite(
        metadataStore,
        BulkOperationState.OperationType.Delete,
        path);
    try (DurationInfo ignored =
             new DurationInfo(LOG, false, "deleting %s", dirKey)) {

      // init the lists of keys and paths to delete
      resetDeleteList();
      deleteFuture = null;

      // list files including any under tombstones through S3Guard
      LOG.debug("Getting objects for directory prefix {} to delete", dirKey);
      final RemoteIterator<S3ALocatedFileStatus> locatedFiles =
          callbacks.listFilesAndEmptyDirectories(path, status,
              false, true);

      // iterate through and delete. The next() call will block when a new S3
      // page is required; this any active delete submitted to the executor
      // will run in parallel with this.
      while (locatedFiles.hasNext()) {
        // get the next entry in the listing.
        S3AFileStatus child = locatedFiles.next().toS3AFileStatus();
        queueForDeletion(child);
      }
      LOG.debug("Deleting final batch of listed files");
      submitNextBatch();
      maybeAwaitCompletion(deleteFuture);

      // if s3guard is authoritative we follow up with a bulk list and
      // delete process on S3 this helps recover from any situation where S3
      // and S3Guard have become inconsistent.
      // This is only needed for auth paths; by performing the previous listing
      // without tombstone filtering, any files returned by the non-auth
      // S3 list which were hidden under tombstones will have been found
      // and deleted.

      if (callbacks.allowAuthoritative(path)) {
        LOG.debug("Path is authoritatively guarded;"
            + " listing files on S3 for completeness");
        // let the ongoing delete finish to avoid duplicates
        final RemoteIterator<S3AFileStatus> objects =
            callbacks.listObjects(path, dirKey);

        // iterate through and delete. The next() call will block when a new S3
        // page is required; this any active delete submitted to the executor
        // will run in parallel with this.
        while (objects.hasNext()) {
          // get the next entry in the listing.
          extraFilesDeleted++;
          queueForDeletion(deletionKey(objects.next()), null);
        }
        if (extraFilesDeleted > 0) {
          LOG.debug("Raw S3 Scan found {} extra file(s) to delete",
              extraFilesDeleted);
          // there is no more data:
          // await any ongoing operation
          submitNextBatch();
          maybeAwaitCompletion(deleteFuture);
        }
      }

      // final cleanup of the directory tree in the metastore, including the
      // directory entry itself.
      try (DurationInfo ignored2 =
               new DurationInfo(LOG, false, "Delete metastore")) {
        metadataStore.deleteSubtree(path, operationState);
      }
    } finally {
      IOUtils.cleanupWithLogger(LOG, operationState);
    }
    LOG.debug("Delete \"{}\" completed; deleted {} objects", path,
        filesDeleted);
  }

  /**
   * Build an S3 key for a delete request,
   * possibly adding a "/" if it represents directory and it does
   * not have a trailing slash already.
   * @param stat status to build the key from
   * @return a key for a delete request
   */
  private String deletionKey(final S3AFileStatus stat) {
    return getStoreContext().fullKey(stat);
  }

  /**
   * Queue for deletion.
   * @param stat status to queue
   * @throws IOException failure of the previous batch of deletions.
   */
  private void queueForDeletion(
      final S3AFileStatus stat) throws IOException {
    queueForDeletion(deletionKey(stat), stat.getPath());
  }

  /**
   * Queue keys for deletion.
   * Once a page of keys are ready to delete this
   * call is submitted to the executor, after waiting for the previous run to
   * complete.
   *
   * @param key key to delete
   * @param deletePath nullable path of the key
   * @throws IOException failure of the previous batch of deletions.
   */
  private void queueForDeletion(final String key,
      @Nullable final Path deletePath) throws IOException {
    LOG.debug("Adding object to delete: \"{}\"", key);
    keys.add(new DeleteObjectsRequest.KeyVersion(key));
    if (deletePath != null) {
      paths.add(deletePath);
    }

    if (keys.size() == pageSize) {
      submitNextBatch();
    }
  }

  /**
   * Wait for the previous batch to finish then submit this page.
   * The lists of keys and pages are reset here.
   *
   * @throws IOException failure of the previous batch of deletions.
   */
  private void submitNextBatch()
      throws IOException {
    // delete a single page of keys and the metadata.
    // block for any previous batch.
    maybeAwaitCompletion(deleteFuture);

    // delete the current page of keys and paths
    deleteFuture = submitDelete(keys, paths);
    // reset the references so a new list can be built up.
    resetDeleteList();
  }

  /**
   * Reset the lists of keys and paths so that a new batch of
   * entries can built up.
   */
  private void resetDeleteList() {
    keys = new ArrayList<>(pageSize);
    paths = new ArrayList<>(pageSize);
  }

  /**
   * Delete a file or directory marker.
   * @param path path
   * @param key key
   * @param isFile is this a file?
   * @throws IOException failure
   */
  @Retries.RetryTranslated
  private void deleteObjectAtPath(
      final Path path,
      final String key,
      final boolean isFile)
      throws IOException {
    LOG.debug("delete: {} {}", (isFile ? "file" : "dir marker"), key);
    filesDeleted++;
    callbacks.deleteObjectAtPath(path, key, isFile, operationState);
  }

  /**
   * Delete a single page of keys and optionally the metadata.
   * For a large page, it is the metadata size which dominates.
   * Its possible to invoke this with empty lists of keys or paths.
   * If both lists are empty no work is submitted and null is returned.
   *
   * @param keyList keys to delete.
   * @param pathList paths to update the metastore with.
   * @return the submitted future or null
   */
  private CompletableFuture<Void> submitDelete(
      final List<DeleteObjectsRequest.KeyVersion> keyList,
      final List<Path> pathList) {

    if (keyList.isEmpty() && pathList.isEmpty()) {
      return null;
    }
    filesDeleted += keyList.size();
    return submit(executor, () -> {
      asyncDeleteAction(operationState,
          keyList,
          pathList,
          LOG.isDebugEnabled());
      return null;
    });
  }

  /**
   * The action called in the asynchronous thread to delete
   * the keys from S3 and paths from S3Guard.
   *
   * @param state ongoing operation state
   * @param keyList keys to delete.
   * @param pathList paths to update the metastore with.
   * @param auditDeletedKeys should the results be audited and undeleted
   * entries logged?
   * @throws IOException failure
   */
  @Retries.RetryTranslated
  private void asyncDeleteAction(
      final BulkOperationState state,
      final List<DeleteObjectsRequest.KeyVersion> keyList,
      final List<Path> pathList,
      final boolean auditDeletedKeys)
      throws IOException {
    try (DurationInfo ignored =
             new DurationInfo(LOG, false, "Delete page of keys")) {
      DeleteObjectsResult result = null;
      List<Path> undeletedObjects = new ArrayList<>();
      if (!keyList.isEmpty()) {
        result = Invoker.once("Remove S3 Keys",
            status.getPath().toString(),
            () -> callbacks.removeKeys(
                keyList,
                false,
                undeletedObjects,
                state,
                !auditDeletedKeys));
      }
      if (!pathList.isEmpty()) {
        metadataStore.deletePaths(pathList, state);
      }
      if (auditDeletedKeys && result != null) {
        // audit the deleted keys
        List<DeleteObjectsResult.DeletedObject> deletedObjects =
            result.getDeletedObjects();
        if (deletedObjects.size() != keyList.size()) {
          // size mismatch
          LOG.warn("Size mismatch in deletion operation. "
                  + "Expected count of deleted files: {}; "
                  + "actual: {}",
              keyList.size(), deletedObjects.size());
          // strip out the deleted keys
          for (DeleteObjectsResult.DeletedObject del : deletedObjects) {
            keyList.removeIf(kv -> kv.getKey().equals(del.getKey()));
          }
          for (DeleteObjectsRequest.KeyVersion kv : keyList) {
            LOG.debug("{}", kv.getKey());
          }
        }
      }
    }
  }

}


text:
module HesburghErrors
  module ApplicationHelper
  end
end


text:
package nz.co.cloudstore.serialbot;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;

import nz.co.cloudstore.serialbot.HostListActivity;

/**
 * This is a simple framework for a test of an Application. See
 * {@link android.test.ApplicationTestCase ApplicationTestCase} for more
 * information on how to write and extend Application tests.
 * <p/>
 * To run this test, you can type: adb shell am instrument -w \ -e class
 * nz.co.cloudstore.serialbot.HostListActivityTest \
 * nz.co.cloudstore.serialbot.tests/android.test.InstrumentationTestRunner
 */
public class HostListActivityTest extends ActivityInstrumentationTestCase2<HostListActivity> {
	private Activity mActivity;

	public HostListActivityTest() {
		super("nz.co.cloudstore.serialbot", HostListActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();

		setActivityInitialTouchMode(false);

		mActivity = getActivity();
	}
}


text:
from .components import ComponentMeta

hetero_kmeans_cpn_meta = ComponentMeta("HeteroKmeans")

@hetero_kmeans_cpn_meta.bind_param
def hetero_kmeans_param():
    from federatedml.param.hetero_kmeans_param import KmeansParam

    return KmeansParam

@hetero_kmeans_cpn_meta.bind_runner.on_guest
def hetero_kmeans_runner_guest():
    from federatedml.unsupervised_learning.kmeans.hetero_kmeans.hetero_kmeans_client import (
        HeteroKmeansGuest,
    )

    return HeteroKmeansGuest

@hetero_kmeans_cpn_meta.bind_runner.on_host
def hetero_kmeans_runner_host():
    from federatedml.unsupervised_learning.kmeans.hetero_kmeans.hetero_kmeans_client import (
        HeteroKmeansHost,
    )

    return HeteroKmeansHost

@hetero_kmeans_cpn_meta.bind_runner.on_arbiter
def hetero_kmeans_runner_arbiter():
    from federatedml.unsupervised_learning.kmeans.hetero_kmeans.hetero_kmeans_arbiter import (
        HeteroKmeansArbiter,
    )

    return HeteroKmeansArbiter


text:
Sección Clientes

Sección Usuarios


text:
Value | Description
----- | -----------
course.schedule.read | read scheduled courses
calendar.event.read | read events in calendar
calendar.event.write | write events to calendar
user.info.basic.read | read user basic information


text:
package com.orientechnologies.orient.graph.blueprints;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.exception.OValidationException;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class GraphValidationTest {

  public static final String URL = "memory:" + GraphValidationTest.class.getSimpleName();

  @Before
  public void beforeMethod() {
    OrientGraph g = new OrientGraph(URL, "admin", "admin");
    g.drop();
  }

  @Test
  public void testValidationOnVertices() {
    OrientGraphNoTx g1 = new OrientGraphNoTx(URL, "admin", "admin");
    try {
      final OrientVertexType validationTestType = g1.createVertexType("ValidationTest");
      validationTestType.createEdgeProperty(Direction.OUT, "Connection").setMandatory(true);
      validationTestType.createEdgeProperty(Direction.IN, "Connection").setMandatory(true);

      final OrientEdgeType connectionType = g1.createEdgeType("Connection");
      connectionType.createProperty("in", OType.LINK, validationTestType).setMandatory(true);
      connectionType.createProperty("out", OType.LINK, validationTestType).setMandatory(true);
    } finally {
      g1.shutdown();
    }

    OrientGraph g2 = new OrientGraph(URL, "admin", "admin");
    try {
      OrientVertex vertex1 = g2.addTemporaryVertex("ValidationTest");
      OrientVertex vertex2 = g2.addTemporaryVertex("ValidationTest");
      OrientVertex vertex3 = g2.addTemporaryVertex("ValidationTest");
      OrientVertex vertex4 = g2.addTemporaryVertex("ValidationTest");

      vertex1.addEdge("Connection", vertex2);
      vertex2.addEdge("Connection", vertex3);
      vertex3.addEdge("Connection", vertex4);
      vertex4.addEdge("Connection", vertex1);

      g2.commit();

    } finally {
      g2.shutdown();
    }
  }

  @Test
  public void ok() {
    setupSchema();
    final OrientGraphNoTx graphNoTx = new OrientGraphNoTx(URL, "admin", "admin");
    try {

      graphNoTx.addVertex("class:M", "name", "n0");
      try {
        graphNoTx.addVertex("class:M");
        throw new RuntimeException("Schema problem was not detected!");
      } catch (Throwable e) {
        // This is what happens => OK
        System.out.println("This is the Message I want to see: \n" + e);
      }

      graphNoTx.commit();
    } finally {
      graphNoTx.shutdown();
    }
  }

  @Test
  public void fail() {
    setupSchema();
    final OrientGraphFactory orientGraphFactory =
        new OrientGraphFactory(URL, "admin", "admin").setupPool(1, 10);
    OrientGraph graph = orientGraphFactory.getTx();
    try {

      graph.addVertex("class:M", "name", "n0");
      try {
        graph.addVertex("class:M");
        graph.commit();
        // This is what happens => not OK?
        throw new RuntimeException("Schema problem was not detected!");
      } catch (OValidationException e) {
        System.out.println("This is the Message I want to see: \n" + e);
      }

    } finally {
      graph.shutdown();
    }
  }

  @Test
  public void edgesCannotBeVertices() {
    OrientGraphNoTx gNoTx = new OrientGraphNoTx(URL, "admin", "admin");
    try {
      gNoTx.createVertexType("TestV");
      gNoTx.createEdgeType("TestE");

      OrientVertex v = gNoTx.addVertex("class:TestV");
      OrientVertex loadedV = gNoTx.getVertex(v.getIdentity());
      try {
        OrientEdge e = gNoTx.getEdge(v.getIdentity().toString());
        Assert.fail();
      } catch (IllegalArgumentException e) {
        // OK
      }
    } finally {
      gNoTx.shutdown();
    }

    OrientGraph g = new OrientGraph(URL, "admin", "admin");
    try {
      OrientVertex v = g.addVertex("class:TestV");
      OrientVertex loadedV = g.getVertex(v.getIdentity().toString());
      try {
        OrientEdge e = g.getEdge(v.getIdentity());
        Assert.fail();
      } catch (IllegalArgumentException e) {
        // OK
      }
    } finally {
      g.shutdown();
    }
  }

  private void setupSchema() {
    OrientGraphNoTx graphNoTx = new OrientGraphNoTx(URL, "admin", "admin");
    try {

      ODatabaseDocumentTx database = graphNoTx.getRawGraph();
      OSchema oScchema = database.getMetadata().getSchema();

      oScchema.getClass("V").setStrictMode(true);
      oScchema.getClass("E").setStrictMode(true);

      OrientVertexType CmVertexBaseType = graphNoTx.createVertexType("CmVertexBase", "V");
      CmVertexBaseType.setStrictMode(true);

      OrientVertexType CmEdgeBaseType = graphNoTx.createVertexType("CmEdgeBase", "V");
      CmEdgeBaseType.setStrictMode(true);

      OClass mOClass =
          database
              .getMetadata()
              .getSchema()
              .createClass("M", database.getMetadata().getSchema().getClass("V"));
      mOClass.createProperty("name", OType.STRING).setMandatory(true).setNotNull(true);
      mOClass.setStrictMode(true);

      graphNoTx.commit();
    } finally {
      graphNoTx.shutdown();
    }
  }

  @Test(expected = OValidationException.class)
  public void testPropertyReadOnly() {
    OrientGraphNoTx graphNoTx = new OrientGraphNoTx(URL);
    OrientVertexType testType = graphNoTx.createVertexType("Test");
    OProperty prop;
    prop = testType.createProperty("name", OType.STRING).setReadonly(true);
    graphNoTx.shutdown();

    Assert.assertTrue(prop.isReadonly()); // this one passes

    OrientGraph graph = new OrientGraph(URL);
    try {
      OrientVertex vert1 = graph.addVertex("class:Test", "name", "Sam");
      graph.commit();

      vert1.setProperty("name", "Ben"); // should throw an exception
      graph.commit();

      Assert.assertEquals(vert1.getProperty("name"), "Sam"); // fails
    } finally {
      graph.shutdown();
    }
  }

  @Test
  public void testNoTxGraphConstraints() {
    OrientGraphNoTx graphNoTx = new OrientGraphNoTx(URL);
    OrientVertexType testType = graphNoTx.createVertexType("Test");
    testType.createProperty("age", OType.INTEGER).setMax("3");
    OrientVertex vert1 = graphNoTx.addVertex("class:Test", "age", 2);

    try {
      vert1.setProperty("age", 4);
    } catch (OValidationException e) {
      Assert.assertEquals((int) vert1.getProperty("age"), 2); // this fails
    } finally {
      graphNoTx.shutdown();
    }
  }
}


text:
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router'
import './app.css'

const App = React.createClass({
  contextTypes: {
    router: React.PropTypes.object.isRequired
  },

  getInitialState() {
    return {
      tacos: [
        { name: 'duck confit' },
        { name: 'carne asada' },
        { name: 'shrimp' }
      ]
    }
  },

  addTaco() {
    let name = prompt('taco name?')

    this.setState({
      tacos: this.state.tacos.concat({ name })
    })
  },

  handleRemoveTaco(removedTaco) {
    this.setState({
      tacos: this.state.tacos.filter(function (taco) {
        return taco.name != removedTaco
      })
    })

    this.context.router.push('/')
  },

  render() {
    let links = this.state.tacos.map(function (taco, i) {
      return (

          <Link to={`/taco/${taco.name}`}>{taco.name}</Link>

      )
    })
    return (

        <button onClick={this.addTaco}>Add Taco</button>

          {links}

          {this.props.children && React.cloneElement(this.props.children, {
            onRemoveTaco: this.handleRemoveTaco
          })}

    )
  }
})

const Taco = React.createClass({
  remove() {
    this.props.onRemoveTaco(this.props.params.name)
  },

  render() {
    return (

{this.props.params.name}

        <button onClick={this.remove}>remove</button>

    )
  }
})

render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="taco/:name" component={Taco} />
    </Route>
  </Router>
), document.getElementById('example'))


text:
export interface Extra {
    name: string,
    price: number,
}


text:
using System;

namespace SFA.DAS.EmployerAccounts.Api.Types
{
    public class AccountDetail
    {
        public long AccountId { get; set; }
        public string HashedAccountId { get; set; }
        public string PublicHashedAccountId { get; set; }
        public string DasAccountName { get; set; }
        public DateTime DateRegistered { get; set; }
        public string OwnerEmail { get; set; }
        public ResourceList LegalEntities { get; set; }
        public ResourceList PayeSchemes { get; set; }

        [Obsolete]
        public string DasAccountId => HashedAccountId;

        public AccountAgreementType AccountAgreementType { get; set; }
        public string ApprenticeshipEmployerType { get; set; }
    }
}


text:
package se.sics.mspsim.config;

import java.util.ArrayList;
import se.sics.mspsim.core.DMA;
import se.sics.mspsim.core.IOPort;
import se.sics.mspsim.core.IOUnit;
import se.sics.mspsim.core.InterruptMultiplexer;
import se.sics.mspsim.core.MSP430Config;
import se.sics.mspsim.core.MSP430Core;
import se.sics.mspsim.core.Multiplier;
import se.sics.mspsim.core.Timer;
import se.sics.mspsim.core.USART;

public class MSP430f2132Config extends MSP430Config {
  /* offset from beginning of interrupt table, since the beginning of the
   * interrupt table is either 0xFFC0 or 0xFFE0, depending on how you
   * interpret the MSP430F2132 datasheet. */
  int ivStart = 0xFFE0; // or 0xFFC0?
  int o = 0;            // or 16?

  // Input map for Timer1_A2 (MSP430F2132)
  public static final int[] Timer1_A2InputMap = new int[] {
    Timer.SRC_PORT + 0x10, Timer.SRC_ACLK,
      Timer.SRC_SMCLK, Timer.SRC_PORT + 0x21,     // Timer
    Timer.SRC_PORT + 0x11, Timer.SRC_PORT + 0x36,
      Timer.SRC_GND, Timer.SRC_VCC,               // Cap 0
    Timer.SRC_PORT + 0x37, Timer.SRC_CAOUT,
      Timer.SRC_GND, Timer.SRC_VCC                // Cap 1
  };

  public MSP430f2132Config () {
    maxInterruptVector = (0xFFFE - ivStart) / 2; // 15 or 31

    // Use Flash for MSP430f5437
    useFlash();

    TimerConfig timer0_A3 = new TimerConfig(
        9+o,   // interrupt vector for timer CCR0
        8+o,   // interrupt vector for other CCRx's
        3,     // number of CCRs
        0x160, // address of timer control register
        Timer.TIMER_Ax149, // input map ("signal connections" table)
        "Timer0_A3", // name
        Timer.TAIV // interrupt vector (from peripheral file map)
        );
    TimerConfig timer1_A2 = new TimerConfig(
        13+o,
        12+o,
        2,
        0x180,
        Timer1_A2InputMap,
        "Timer1_A2",
        Timer.TBIV
        );
    timerConfig = new TimerConfig[] {timer0_A3, timer1_A2};

    infoMemConfig(0x1000, 128 * 2);
    mainFlashConfig(0xe000, 8 * 1024);
    ramConfig(0x200, 512);
  }

  public int setup (MSP430Core cpu, ArrayList<IOUnit> ioUnits) {
    // XXX no USARTs in this chip.  can we do USCI?

    Multiplier mp = new Multiplier(cpu, cpu.memory, 0);
    cpu.setIORange(0x130, 0x0f, mp);
    ioUnits.add(mp);

    // no DMA

    // IO ports.  Ports 1 and 2 can generate interrupts
    ioUnits.add(new IOPort(cpu, 1, 2+o, cpu.memory, 0x20)); // IO1
    ioUnits.add(new IOPort(cpu, 2, 3+o, cpu.memory, 0x28)); // IO2

    // ports 3 and 4 cannot generate interrupts
    ioUnits.add(new IOPort(cpu, 3, 0, cpu.memory, 0x18));
    ioUnits.add(new IOPort(cpu, 4, 0, cpu.memory, 0x1c));

    // XXX ADC10

    return 3 + 6; // XXX why?
  }
}


text:
import {Log} from '../kernel_names';
import {GradConfig} from '../kernel_registry';
import {cast} from '../ops/cast';
import {div} from '../ops/div';
import {Tensor} from '../tensor';

export const logGradConfig: GradConfig = {
  kernelName: Log,
  inputsToSave: ['x'],
  gradFunc: (dy: Tensor, saved: Tensor[]) => {
    const [x] = saved;
    return {x: () => div(dy, cast(x, 'float32'))};
  }
};


text:
> Javascript implementation of A* Pathfinding, developed for use with [http://jsiso.com](http://jsiso.com)

## Getting Started
This script is developed to work with Node.js and in the Browser.

### Node
```shell
npm install js-pathfind
```

```js
var Pathfind = require('js-pathfind');
```

### Browser
```html
<script type="text/javascript" src="build/pathfind.min.js"></script>
```

```js
var Pathfind = window.Pathfind;
```

## Pathfind

### Pathfind(start, end, map);
#### start
Type: `array`
Starting location x and y co-ordinate: [x, y]

#### end
Type: `array`
Ending location x and y co-ordinate: [x, y]

#### Map
Type: `array`
2d array of any size which holds all the co-ordinates on the map. 0 = open square, 1 or above = blocked square
x values  = columns
y values = rows (first row = 0)

### Return
Type: `array` or `boolean`
The returned value will be an array of co-ordinates showing the route through the map or false if not route is possible.

## Example
```js
var start = [0,0];
var end = [4,4];
var map = [
    [0, 0, 0, 1, 0],
    [1, 0, 0, 0, 1],
    [0, 0, 1, 0, 0],
    [0, 0, 1, 1, 0],
    [0, 0, 1, 1, 0]
];
var path = Pathfind(start, end, map);
console.log(path); // Output = [ [ 0, 0 ], [ 1, 1 ], [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 4 ] ]

start = [0, 4]; // Start Bottom left
path = Pathfind(start, end, map);
console.log(path); // Output = false
```

## License
MIT License 2013-2015 Edward Smyth


text:
test_cookbook_encode 'recipe 1' do
  action :url_encode
  message "encode first"
end

powershell 'echo_from_powershell_script' do
  source_text = 'write-output "message from powershell script"'
  source source_text
end

test_cookbook_encode 'recipe 2' do
  action :update_chef_node
  message "encode again"
end

test_cookbook_echo 'recipe 3' do
  action :echo_text
  message "then echo"
end

test_cookbook_echo 'recipe 4' do
  action :check_chef_node
  # must be the same message as in the last encode::action :update_chef_node
  message "encode again"
end

powershell 'echo_from_powershell_script_again' do
  source_text = 'write-output "another powershell message"'
  source source_text
end

powershell 'echo_from_powershell_script_once_more' do
  source_text = 'write-output "one more powershell message"'
  source source_text
end

test_cookbook_echo 'recipe 5' do
  action :echo_text
  message "echo again"
end


text:
<component
	id="ActivityViewer"
	title="Activity Viewer 2.0"
	tooltip="Viewer for Custom Activities"
	icon="res/ActivityViewer/ActivityViewer.png"
	handlerType="div"
	propertySheetPath="aps/PropertyPage.html"
	group="ScnCommunityVisualizations"
	databound="false"
	modes="commons"
>

	<requireJs modes="commons">res/ActivityViewer/ActivityViewer</requireJs>

	<cssInclude>res/ActivityViewer/ActivityViewer.css</cssInclude>

	<property
		id="activities"
		type="String"
		title="Activities"
		group="Display"
		bindable="true"
		visible="true">

	</property>
	<property
		id="categories"
		type="String"
		title="Categories"
		group="Display"
		bindable="true"
		visible="true">

	</property>
	<property
		id="onSelectionChanged"
		type="ScriptText"
		title="On Selection Changed"
		group="Events"
		visible="true">

	</property>
	<property
		id="selectedKey"
		type="String"
		title="Selected Key"
		group="Display"
		bindable="true"
		visible="false">

	</property>
	<property
		id="states"
		type="String"
		title="States"
		group="Display"
		bindable="true"
		visible="true">

	</property>

	<initialization>
		<defaultValue property="TOP_MARGIN">0</defaultValue>
		<defaultValue property="BOTTOM_MARGIN">auto</defaultValue>
		<defaultValue property="LEFT_MARGIN">0</defaultValue>
		<defaultValue property="RIGHT_MARGIN">auto</defaultValue>
		<defaultValue property="WIDTH">600</defaultValue>
		<defaultValue property="HEIGHT">400</defaultValue>

		<defaultValue property="activities"><![CDATA[[{"parentKey":"ROOT","key":"ELEMENT","leaf":false,"text":"Distribution","category":"CAT1","state":"FAILED","startDate":"20130101","endDate":"20130205"},{"parentKey":"ROOT","key":"ELEMENT1","leaf":false,"text":"Process","category":"CAT1","state":"RUNNING","startDate":"20140102","endDate":"20140605"},{"parentKey":"ROOT","key":"ELEMENT2","leaf":false,"text":"Buying","category":"CAT2","state":"STANDARD","startDate":"20140905","endDate":"20141216"},{"parentKey":"ROOT","key":"ELEMENT3","leaf":false,"text":"Work On","state":"KILLED","category":"CAT2","startDate":"20141228","endDate":"20150206"}]]]></defaultValue>
		<defaultValue property="categories"><![CDATA[[{"parentKey":"ROOT","key":"CAT1","leaf":false,"text":"Good Products"},{"parentKey":"ROOT","key":"CAT2","leaf":false,"text":"Better Products"}]]]></defaultValue>
		<defaultValue property="onSelectionChanged"><![CDATA[]]></defaultValue>
		<defaultValue property="selectedKey"><![CDATA[]]></defaultValue>
		<defaultValue property="states"><![CDATA[[{"parentKey":"ROOT","key":"STANDARD","leaf":false,"style":"bar"},{"parentKey":"ROOT","key":"FAILED","leaf":false,"style":"bar-failed"},{"parentKey":"ROOT","key":"RUNNING","leaf":false,"style":"bar-running"},{"parentKey":"ROOT","key":"SUCCEEDED","leaf":false,"style":"bar-succeeded"},{"parentKey":"ROOT","key":"KILLED","leaf":false,"style":"killed"}]]]></defaultValue>

	</initialization>

</component>


text:
var conf = require('../../config/config')
var nodemailer = require("nodemailer")
var smtpTransport = require('nodemailer-smtp-transport')

var transporter = nodemailer.createTransport(smtpTransport({
    host: conf.email.host,
    port: conf.email.port,
    auth: {
        user: conf.email.user,
        pass: conf.email.password
    }
}))

exports.send = function (opts) {
    return new Promise(function (resolve) {
        var mailOptions = {
            from: conf.email.from,
            to: opts.to,
            subject: opts.title,
            html: opts.content
        }

        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return resolve(false)
            }
            return resolve(true)
        })
    })
}


text:
<?php

namespace Sylius\Component\Core\StateResolver;

use SM\Factory\FactoryInterface;
use SM\StateMachine\StateMachineInterface;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Order\StateResolver\StateResolverInterface;
use Sylius\Component\Core\Model\PaymentInterface;
use Sylius\Component\Core\OrderPaymentStates;
use Sylius\Component\Core\OrderPaymentTransitions;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
class OrderPaymentStateResolver implements StateResolverInterface
{
    /**
     * @var FactoryInterface
     */
    private $stateMachineFactory;

    /**
     * @param FactoryInterface $stateMachineFactory
     */
    public function __construct(FactoryInterface $stateMachineFactory)
    {
        $this->stateMachineFactory = $stateMachineFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function resolve(OrderInterface $order)
    {
        $stateMachine = $this->stateMachineFactory->get($order, OrderPaymentTransitions::GRAPH);
        $completedPaymentTotal = 0;

        $payments = $order->getPayments()->filter(function (PaymentInterface $payment) {
            return PaymentInterface::STATE_COMPLETED === $payment->getState();
        });

        foreach ($payments as $payment) {
            $completedPaymentTotal += $payment->getAmount();
        }

        if (0 < $payments->count() && $completedPaymentTotal >= $order->getTotal()) {
            $this->applyTransition($stateMachine, OrderPaymentTransitions::TRANSITION_PAY);
            return;
        }

        if ($completedPaymentTotal < $order->getTotal() && 0 < $completedPaymentTotal) {
            $this->applyTransition($stateMachine, OrderPaymentTransitions::TRANSITION_PARTIALLY_PAY);
            return;
        }
    }

    /**
     * @param StateMachineInterface $stateMachine
     * @param string $transition
     */
    private function applyTransition(StateMachineInterface $stateMachine, $transition)
    {
        if ($stateMachine->can($transition)) {
            $stateMachine->apply($transition);
        }
    }
}


text:
Wanna Play a Game?

<button class="btn start-game">Let's Do This!</button>


text:
import logging

{% if cookiecutter.use_logstash.startswith('y') -%}
import logstash
{%- endif %}
import connexion
import yaml
import json
from prance import ResolvingParser

from {{cookiecutter.project_slug}} import options

logging.basicConfig(level=logging.INFO)

# Logging configuration
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    '%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

{% if cookiecutter.use_logstash.startswith('y') -%}
logstash_options = options()['logstash']
ls = logstash.TCPLogstashHandler(
    host=logstash_options['host'],
    port=logstash_options['port'])
ls.setLevel(logging.INFO)
logger.addHandler(ls)
{%- endif %}

app = connexion.App("{{cookiecutter.project_name}}")
parsed_definition = yaml.load(open("config/api.yml"))
swagger_definiton = ResolvingParser(
    spec_string=json.dumps(parsed_definition)).specification
app.add_api(swagger_definiton,
            strict_validation=True,
            validate_responses=True)

application = app.app

if __name__ == '__main__':
    app.run(port=8080, server='flask')


text:
package org.jf.dexlib2.iface.value;

import javax.annotation.*;

/**
 * This class represents an encoded integer value.
 */
public interface IntEncodedValue extends EncodedValue {
    /**
     * Gets the integer value.
     *
     * @return the int value
     */
    int getValue();

    /**
     * Returns a hashcode for this EncodedIntValue.
     *

     * This hashCode is defined to be the following:
     *

     *

     * {@code
     * int hashCode = getValue();
     * }

     *
     * @return The hash code value for this EncodedIntValue
     */
    @Override
    int hashCode();

    /**
     * Compares this IntEncodedValue to another IntEncodedValue for equality.
     *

     * This IntEncodedValue is equal to another IntEncodedValue if the values returned by getValue() are equal.
     *
     * @param o The object to be compared for equality with this IntEncodedValue
     * @return true if the specified object is equal to this IntEncodedValue
     */
    @Override
    boolean equals(@Nullable Object o);

    /**
     * Compare this IntEncodedValue to another EncodedValue.
     *

     * The comparison is first done on the return values of getValueType(). If the other value is another
     * IntEncodedValue, the return values of getValue() are compared.
     *
     * @param o The EncodedValue to compare with this IntEncodedValue
     * @return An integer representing the result of the comparison
     */
    @Override
    int compareTo(@Nonnull EncodedValue o);
}


text:
[![Build Status](https://travis-ci.org/mediascience/jaxrs-trailing-slash.svg?branch=master)](https://travis-ci.org/mediascience/jaxrs-trailing-slash)

## JAX-RS Trailing Slash

Enforce a trailing-slash policy in JAX-RS. This module
includes a collection of policies and an enforcing filter
for JAX-RS 2.0.

This was originally a demonstration of JAX-RS 2.0 filters
introduced [here](http://aztecrex.blogspot.com/2014/06/filters-in-jax-rs-20.html).

Per the JAX-RS specification, a request URI with a trailing
slash is treated the same as one without a trailing slash
for the purpose of selecting a handler method. While
this can be fine in some applications, it is problematic in
others. This module provides a uniform means to declaratively
reject or accept, per resource method, an incoming
request depending on whether its resource path has a
trailing slash.

The module defines three policies:

1. 'Allow' lets any request pass. This is the same as
not applying the filter at all.
2. 'Require' passes a request only if the requested
path has a trailing slash.
3. 'Prohibit' passes a request only if the requested path
does not have a trailing slash.

The default filter policy is 'Prohibit.'

## Usage

### Include Dependencies
Include the dependency in your build config.
```
<dependency>
  <groupId>com.msiops.jaxrs</groupId>
  <artifactId>jaxrs-trailing-slash</artifactId>
  <version>1.0.2</version>
</dependency>
```

### Configuring Resources

The module provides filters for enforcing trailing slash
policy and injecting policy into a request context as needed
by an application. The three methods for injecting policy
are *global configuration*, *dynamic configuration*, and
*static configuration*.

*Global configuration* is accomplished by registering the enforcement
filter and, optionally, a policy filter in your application (see
manual configurations below).

The filters, `AllowTrailingSlashFilter`, `ProhibitTrailingSlashFilter`,
and `RequireTrailingSlashFilter`, support *dynamic configuration*:
```
public class AllowTrailingSlashForDocumentRequests implements DynamicFeature {
    @Override
    public void configure(ResourceInfo resInf, FeatureContext ctx) {
        if (DocumentResource.class.equals(resInf.getResourceClass())) {
            ctx.register(AllowTrailingSlashFilter.class);
        }
    }
}
```

The annotations, `@AllowTrailingSlash`, `@ProhibitTrailingSlash`, and
`@RequireTrailingSlash` provide *static configuration* for a resource:
```
@Path("data")
public class DataResource {
    @GET
    @RequireTrailingSlash
    String getData() {
        return "data";
    }
}
```

Or:
```
@Path("data")
@RequireTrailingSlash
public class DataResource {
    @GET
    String getData() {
        return "data";
    }
}
```

### Manual Filter Registration

Depending on your JAX-RS implementation, you can register filters
manually. For example, to simply enforce the default policy for all
resources:
```
    // Jersey-specific, explicitly include enforcement filter
    final ResourceConfig config = new ResourceConfig(MyResource.class,
          TrailingSlashEnforcementFilter.class);

    JdkHttpServerFactory.createHttpServer(URI.create(BASE_URI), config);
```

Or, to enforce a specific policy for all resources:
```
    // Jersey-specific, explicitly enforce trailing slash required on all resources
    final ResourceConfig config = new ResourceConfig(MyResource.class,
          TrailingSlashEnforcementFilter.class,
          RequreTrailingSlashFilter.class);

    JdkHttpServerFactory.createHttpServer(URI.create(BASE_URI), config);
```

Note that if you need dynamic configuration, do not include the policy
filter globally.

For static (annotation) configuration, include just the enforcement filter along
with whatever static implementation filters you need in your application:
```
    // Jersey-specific, explicitly include enforcement and ability to statically
    // configure required trailing slashes on some resources.
    final ResourceConfig config = new ResourceConfig(MyResource.class,
          TrailingSlashEnforcementFilter.class,
          RequreTrailingSlashStaticFilter.class);

    JdkHttpServerFactory.createHttpServer(URI.create(BASE_URI), config);
```

### Automatic Discovery

The enforcement filter and the static override filters can be discovered
automatically by a suitable JAX-RS implementation:
```
    // Jersey-specific, automatic discovery
    final ResourceConfig config = new ResourceConfig(MyResource.class);
    config.packages("com.msiops.jaxrs.trailingslash");

    JdkHttpServerFactory.createHttpServer(URI.create(BASE_URI), config);
```

Note that this does not discover the explicit override filters so that they
do not get automatically applied. They are meant for dynamic registration
in this case.

# Build

This code requires Java 8. In development, it is built with Oracle JDK
1.8 and Gradle 2.0 release candidate. It can likely be built with Gradle
1.12.


text:
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/serviceDescription"
    android:requireDeviceUnlock="false" >

    <aid-group
        android:category="other"
        android:description="@string/helloServiceDescription" >
        	<aid-filter android:name="D2760000850102"  />
         </aid-group>

</host-apdu-service>


text:
<?php
defined('_JEXEC') or die();

JFormHelper::loadFieldClass('filelist');
class JFormFieldGetcertificate extends JFormFieldFileList {

	/**
	 * Element name
	 *
	 * @access    protected
	 * @var        string
	 */
	var $type = 'Getcertificate';

	/*
	protected function getInput() {

		$options = array();

		$folder =$this->directory;
		$safePath = VmConfig::get('forSale_path', '');

		$certificatePath = $safePath . $folder;
		$certificatePath = JPath::clean($certificatePath);

		// Is the path a folder?
		if (!is_dir($certificatePath)) {
			return '' . vmText::sprintf('VMPAYMENT_PAYPAL_CERTIFICATE_FOLDER_NOT_EXIST', $certificatePath) . '';
		}
		$path = str_replace('/', DS, $certificatePath);

		// Prepend some default options based on field attributes.
		if (!$this->hideNone)
		{
			$options[] = JHtml::_('select.option', '-1', vmText::alt('JOPTION_DO_NOT_USE', preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)));
		}

		if (!$this->hideDefault)
		{
			$options[] = JHtml::_('select.option', '', vmText::alt('JOPTION_USE_DEFAULT', preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)));
		}

		// Get a list of files in the search path with the given filter.
		$files = JFolder::files($path, $this->filter);

		// Build the options list from the list of files.
		if (is_array($files))
		{
			foreach ($files as $file)
			{
				// Check to see if the file is in the exclude mask.
				if ($this->exclude)
				{
					if (preg_match(chr(1) . $this->exclude . chr(1), $file))
					{
						continue;
					}
				}

				// If the extension is to be stripped, do it.
				if ($this->stripExt)
				{
					$file = JFile::stripExt($file);
				}

				$options[] = JHtml::_('select.option', $file, $file);
			}
		}

		// Merge any additional options in the XML definition.
		//$options = array_merge(parent::getOptions(), $options);

		return $options;

	}
	*/
	protected function getOptions() {
		$options = array();
		$folder = $this->directory;
		$safePath = VmConfig::get('forSale_path', '');

		$certificatePath = $safePath . $folder;
		$certificatePath = JPath::clean($certificatePath);

		// Is the path a folder?
		if (!is_dir($certificatePath)) {
			return '' . vmText::sprintf('VMPAYMENT_PAYPAL_CERTIFICATE_FOLDER_NOT_EXIST', $certificatePath) . '';
		}
		$path = str_replace('/', DS, $certificatePath);

		// Prepend some default options based on field attributes.
		if (!$this->hideNone) {
			$options[] = JHtml::_('select.option', '-1', JText::alt('JOPTION_DO_NOT_USE', preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)));
		}

		if (!$this->hideDefault) {
			$options[] = JHtml::_('select.option', '', JText::alt('JOPTION_USE_DEFAULT', preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)));
		}

		// Get a list of files in the search path with the given filter.
		$files = JFolder::files($path, $this->filter);

		// Build the options list from the list of files.
		if (is_array($files)) {
			foreach ($files as $file) {
				// Check to see if the file is in the exclude mask.
				if ($this->exclude) {
					if (preg_match(chr(1) . $this->exclude . chr(1), $file)) {
						continue;
					}
				}

				// If the extension is to be stripped, do it.
				if ($this->stripExt) {
					$file = JFile::stripExt($file);
				}

				$options[] = JHtml::_('select.option', $file, $file);
			}
		}

		return $options;
	}

}


text:
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {ServerRoutes} from './serverRoutes';
import {IQuestionDetails} from '../models/QuestionDetails';
import {Observable} from 'rxjs/Observable';
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";

@Injectable()
export class CustomViewsServices {
  constructor(private http: Http) { }

  getQuestionBy(id: number): Observable<IQuestionDetails> {
    return this.http
      .get(`${ServerRoutes.CUSTOM_VIEWS}/question/${id}`)
      .map(res => res.json());
  }

  upvoteAnswer(id: number): Promise<Response> {
    return this.http
      .put(`${ServerRoutes.CUSTOM_VIEWS}/answer/${id}/upvoteAnswer`, null)
      .toPromise();
  }

  downvoteAnswer(id: number): Promise<Response> {
    return this.http
      .put(`${ServerRoutes.CUSTOM_VIEWS}/answer/${id}/unvoteAnswer`, null)
      .toPromise();
  }
}


text:
const gulp 			= require( 'gulp' );
const watch 		= require( 'gulp-watch' );
const sass 			= require( 'gulp-sass' );
const del 			= require( 'del' );
const concat 		= require( 'gulp-concat' );
const rename		= require( 'gulp-rename' );
const uglify		= require( 'gulp-uglify' );
const cleanCSS		= require( 'gulp-clean-css' );
const sourcemaps 	= require( 'gulp-sourcemaps' );
const autoprefixer 	= require( 'gulp-autoprefixer' );
const imagemin		= require( 'gulp-imagemin' );
const gulpIgnore 	= require( 'gulp-ignore' );
const eslint		= require( 'gulp-eslint' );
const mocha			= require( 'gulp-mocha' );

// path variables
const paths = {
	'src':[
		'./models/**/*.js',
		'./routes/**/*.js',
		'keystone.js',
		'package.json' ],
	'css':[
		'public/modules/**/*.css',
		'public/styles/**/*.scss' ],
	'standalone-css':[
		'public/styles/font-awesome/*.css' ],
	'js':[
		'public/modules/**/*.js',
		'public/js/mare.js',
		'public/js/models/*.js',
		'public/js/collections/*.js',
		'public/js/views/*.js',
		'public/js/routers/*.js',
		'public/js/main.js' ],
	'standalone-js':[
		'public/js/lib/standalone-scripts/**/*.js' ],
	'lint-js':[
		'public/js/mare.js',
		'public/js/models/*.js',
		'public/js/collections/*.js',
		'public/js/views/*.js',
		'public/js/routers/*.js',
		'public/js/main.js' ],
	'img':[
		'public/images/**/*',
		'public/modules/**/*.gif' ],
	'fonts':[
		'public/fonts/*.eot',
		'public/fonts/*.svg',
		'public/fonts/*.ttf',
		'public/fonts/*.woff',
		'public/fonts/*.woff2' ],
	'tests':[
		'tests/*.js' ]
};

// styles task
gulp.task( 'styles', () => {
	return gulp.src( paths.css )
		.pipe( sourcemaps.init() )
		.pipe( sass() )
		.pipe( autoprefixer() )
		.pipe( concat( 'mare.css' ) )
		.pipe( gulp.dest( 'public/dist' ) )
		.pipe( cleanCSS( { compatibility: 'ie8' } ) )
		.pipe( rename( { suffix: '.min' } ) )
		.pipe( sourcemaps.write( '.' ) )
		.pipe( gulp.dest( 'public/dist' ) );
});

// TODO: need to figure out why it's not coming in with the Bootstrap styles for the minified output.
// task for styles which are meant to remain separate from the concatenated, minified styles file
gulp.task( 'standalone-styles', () => {
	return gulp.src(paths[ 'standalone-css' ])
		.pipe( gulp.dest( 'public/dist' ));
});

// task for scripts which are meant to remain separate from the concatenated, minified scripts file
gulp.task( 'standalone-scripts', () => {
	return gulp.src( paths[ 'standalone-js' ] )
		.pipe( gulp.dest( 'public/dist' ) );
});

gulp.task( 'fonts', () => {
	return gulp.src( paths.fonts )
		.pipe( gulp.dest( 'public/dist/fonts' ));
})

// scripts task
gulp.task( 'scripts', () => {
	return gulp.src( paths.js )
		// TODO: need to fix this ignore, it's not working
		.pipe( gulpIgnore.exclude( paths[ 'standalone-js' ] ) )
		.pipe( sourcemaps.init() )
		.pipe( concat( 'mare.js' ) )
		.pipe( gulp.dest( 'public/dist' ) )
		.pipe( uglify())
		.pipe( rename( { suffix: '.min' } ) )
		.pipe( sourcemaps.write( '.' ) )
		.pipe( gulp.dest( 'public/dist' ) );
});

// images task
gulp.task( 'images', () => {
	return gulp.src( paths.img )
		.pipe( imagemin() )
		.pipe( gulp.dest( 'public/dist/img' ) );
});

// gulp eslint task
gulp.task( 'eslint', () => {
	return gulp.src( paths[ 'lint-js' ] )
		.pipe( eslint() ) // eslint() attaches the lint output to the "eslint" property of the file object so it can be used by other modules.
		.pipe( eslint.format() ) // eslint.format() outputs the lint results to the console.  Alternatively use eslint.formatEach() (see Docs).
		.pipe( eslint.failAfterError() ); // To have the process exit with an error code (1) on lint error, return the stream and pipe to failAfterError last.
});

// gulp eslint task for watching
gulp.task( 'eslint-watch', () => {
	return gulp.src( paths[ 'lint-js' ] )
		.pipe( eslint() ) // eslint() attaches the lint output to the "eslint" property of the file object so it can be used by other modules.
		.pipe( eslint.format() ); // eslint.format() outputs the lint results to the console.  Alternatively use eslint.formatEach() (see Docs).
});

// Watch task
gulp.task( 'watch', () => {
	gulp.watch( paths.css, gulp.series( 'styles' ) );
	gulp.watch( paths.js, gulp.series( 'eslint-watch', 'scripts' ) );
	gulp.watch( paths.img, gulp.series( 'images' ) );
	gulp.watch( paths.tests, gulp.series( 'test' ) );
});

// Empty out the dist directory to ensure old files don't hang around
gulp.task( 'clean', () => {
	return del( [ 'public/dist/*' ] );
});

// Run all the mocha tests
gulp.task( 'test', () => {
	return gulp.src( paths.tests, { read: false } )
		// gulp-mocha needs filepaths so you can't have any plugins before it
		.pipe( mocha( { reporter: 'nyan' } ) );
});

// gulp build task
gulp.task( 'build', gulp.parallel( 'standalone-styles', 'styles', 'standalone-scripts', 'scripts', 'images', 'fonts' ) );

gulp.task( 'default', gulp.series( 'clean', 'eslint-watch', 'test', 'build', 'watch' ) );


text:
package com.mmnaseri.dragonfly.runtime.assets;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (2013/10/11, 12:26)
 */
public class AsynchronousPostProcessor<C, P> extends Thread implements ApplicationContextAware {

    private final DefaultPostProcessor<C, P> postProcessor;

    public AsynchronousPostProcessor(Class<C> contextType, Class<P> postProcessorType, PostProcessor<C, P> callback) {
        super("postProcessor:" + postProcessorType.getSimpleName() + "@" + contextType.getSimpleName());
        this.postProcessor = new DefaultPostProcessor<C, P>(contextType, postProcessorType, callback);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        postProcessor.setApplicationContext(applicationContext);
    }

    @Override
    public synchronized void start() {
        postProcessor.run();
    }
}


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Proxy
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;

namespace Twilio.Rest.Proxy.V1.Service.Session
{
    /// <summary> Delete a specific Interaction. </summary>
    public class DeleteInteractionOptions : IOptions<InteractionResource>
    {

        ///<summary> The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to delete. </summary>
        public string PathServiceSid { get; }

        ///<summary> The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to delete. </summary>
        public string PathSessionSid { get; }

        ///<summary> The Twilio-provided string that uniquely identifies the Interaction resource to delete. </summary>
        public string PathSid { get; }

        /// <summary> Construct a new DeleteInteractionOptions </summary>
        /// <param name="pathServiceSid"> The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to delete. </param>
        /// <param name="pathSessionSid"> The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to delete. </param>
        /// <param name="pathSid"> The Twilio-provided string that uniquely identifies the Interaction resource to delete. </param>
        public DeleteInteractionOptions(string pathServiceSid, string pathSessionSid, string pathSid)
        {
            PathServiceSid = pathServiceSid;
            PathSessionSid = pathSessionSid;
            PathSid = pathSid;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            return p;
        }

    }

    /// <summary> Retrieve a list of Interactions for a given [Session](https://www.twilio.com/docs/proxy/api/session). </summary>
    public class FetchInteractionOptions : IOptions<InteractionResource>
    {

        ///<summary> The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. </summary>
        public string PathServiceSid { get; }

        ///<summary> The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. </summary>
        public string PathSessionSid { get; }

        ///<summary> The Twilio-provided string that uniquely identifies the Interaction resource to fetch. </summary>
        public string PathSid { get; }

        /// <summary> Construct a new FetchInteractionOptions </summary>
        /// <param name="pathServiceSid"> The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. </param>
        /// <param name="pathSessionSid"> The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. </param>
        /// <param name="pathSid"> The Twilio-provided string that uniquely identifies the Interaction resource to fetch. </param>
        public FetchInteractionOptions(string pathServiceSid, string pathSessionSid, string pathSid)
        {
            PathServiceSid = pathServiceSid;
            PathSessionSid = pathSessionSid;
            PathSid = pathSid;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            return p;
        }

    }

    /// <summary> Retrieve a list of all Interactions for a Session. A maximum of 100 records will be returned per page. </summary>
    public class ReadInteractionOptions : ReadOptions<InteractionResource>
    {

        ///<summary> The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. </summary>
        public string PathServiceSid { get; }

        ///<summary> The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. </summary>
        public string PathSessionSid { get; }

        /// <summary> Construct a new ListInteractionOptions </summary>
        /// <param name="pathServiceSid"> The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. </param>
        /// <param name="pathSessionSid"> The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. </param>
        public ReadInteractionOptions(string pathServiceSid, string pathSessionSid)
        {
            PathServiceSid = pathServiceSid;
            PathSessionSid = pathSessionSid;
        }

        /// <summary> Generate the necessary parameters </summary>
        public  override List<KeyValuePair<string, string>> GetParams()
        {
            var p = new List<KeyValuePair<string, string>>();

            if (PageSize != null)
            {
                p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
            }
            return p;
        }

    }

}


text:
      {{ range first 1 (where .Data.Pages "Section" "projectsFeatured") }}

{{ .Params.tag }}

              {{ .Params.client }}
              <link itemprop="sameAs" href="{{ .Params.clientsame }}" />
              <meta itemprop="address" content="{{ .Params.clientlocation }}" />
              <meta itemprop="contributor" content="{{ .Params.workfor }}" />

{{ .Params.category }}

            {{ .Title }}

            <meta itemprop="name" content="William Pansky"/>
            <link itemprop="sameAs" href="https://williampansky.com"/>

Published on <time itemprop="datePublished">{{ .PublishDate.Format "January 2, 2006" }}</time>. {{ .ReadingTime }} minute read.

{{ .Params.summary }} view project

              {{ .Params.name }}
              <link itemprop="sameAs" href="{{ .Params.projecturl }}" />
             / {{ .Keywords }}

      {{ end }}

      {{ range first 2 (where .Data.Pages.ByDate.Reverse "Section" "projects") }}

{{ .Params.tag }}

              {{ .Params.client }}
              <link itemprop="sameAs" href="{{ .Params.clientsame }}" />
              <meta itemprop="address" content="{{ .Params.clientlocation }}" />
              <meta itemprop="contributor" content="{{ .Params.workfor }}" />

{{ .Params.category }}

            {{ .Title }}

            <meta itemprop="name" content="William Pansky"/>
            <link itemprop="sameAs" href="https://williampansky.com"/>

Published on <time itemprop="datePublished">{{ .PublishDate.Format "January 2, 2006" }}</time>. {{ .ReadingTime }} minute read.

{{ .Params.summary }} read on

              {{ .Params.name }}
              <link itemprop="sameAs" href="{{ .Params.projecturl }}" />
             / {{ .Keywords }}

      {{ end }}

      {{ range first 1 (after 2 (where .Data.Pages.ByDate.Reverse "Section" "projects")) }}

          {{ if isset .Params "hero" }}

          {{ else if isset .Params "image" }}

          {{ end }}

{{ .Params.tag }}

                {{ .Params.client }}
                <link itemprop="sameAs" href="{{ .Params.clientsame }}" />
                <meta itemprop="address" content="{{ .Params.clientlocation }}" />
                <meta itemprop="contributor" content="{{ .Params.workfor }}" />

{{ .Params.category }}

              {{ .Title }}

              <meta itemprop="name" content="William Pansky"/>
              <link itemprop="sameAs" href="https://williampansky.com"/>

Published on <time itemprop="datePublished">{{ .PublishDate.Format "January 2, 2006" }}</time>. {{ .ReadingTime }} minute read.

{{ .Params.summary }} read on

                {{ .Params.name }}
                <link itemprop="sameAs" href="{{ .Params.projecturl }}" />
               / {{ .Keywords }}

      {{ end }}

      {{ range first 1 (after 2 (where .Data.Pages.ByDate.Reverse "Section" "projects")) }}

{{ .Params.tag }}

                {{ .Params.client }}
                <link itemprop="sameAs" href="{{ .Params.clientsame }}" />
                <meta itemprop="address" content="{{ .Params.clientlocation }}" />
                <meta itemprop="contributor" content="{{ .Params.workfor }}" />

              {{ if isset .Params "hero" }}

              {{ else if isset .Params "image" }}

              {{ end }}

{{ .Params.category }}

              {{ .Title }}

              <meta itemprop="name" content="William Pansky"/>
              <link itemprop="sameAs" href="https://williampansky.com"/>

Published on <time itemprop="datePublished">{{ .PublishDate.Format "January 2, 2006" }}</time>. {{ .ReadingTime }} minute read.

{{ .Params.summary }} view project

                {{ .Params.name }}
                <link itemprop="sameAs" href="{{ .Params.projecturl }}" />
               / {{ .Keywords }}

      {{ end }}

      {{ range first 2 (after 3 (where .Data.Pages.ByDate.Reverse "Section" "projects")) }}

{{ .Params.tag }}

              {{ .Params.client }}
              <link itemprop="sameAs" href="{{ .Params.clientsame }}" />
              <meta itemprop="address" content="{{ .Params.clientlocation }}" />
              <meta itemprop="contributor" content="{{ .Params.workfor }}" />

{{ .Params.category }}

            {{ .Title }}

            <meta itemprop="name" content="William Pansky"/>
            <link itemprop="sameAs" href="https://williampansky.com"/>

Published on <time itemprop="datePublished">{{ .PublishDate.Format "January 2, 2006" }}</time>. {{ .ReadingTime }} minute read.

{{ .Params.summary }} read on

              {{ .Params.name }}
              <link itemprop="sameAs" href="{{ .Params.projecturl }}" />
             / {{ .Keywords }}

      {{ end }}


text:
//
//  JLRecomendViewController.m
//  百思不得姐
//
//  Created by kfz on 16/6/10.
//  Copyright © 2016年 kongfz. All rights reserved.
//  推荐关注";

#import "JLRecomendViewController.h"
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import "JLRecomendList.h"
#import "JLRecomendCell.h"
#import "JLUser.h"
#import "JLUserCell.h"
#import <MJRefresh.h>

@interface JLRecomendViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray <JLRecomendList *>*categoryList;
@property (strong, nonatomic) NSArray <JLUser *>*userList;

@property (weak, nonatomic) IBOutlet UITableView *categoryView;
@property (weak, nonatomic) IBOutlet UITableView *userView;

@property (assign, nonatomic) NSUInteger categoryIndex;

@end

static NSString *recomendID = @"recomend_cell";
static NSString *userID = @"user_cell";

@implementation JLRecomendViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUp];
    [self addRefresh];
}

- (void)addRefresh {
    self.userView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(userRefresh)];
    [self.userView.header beginRefreshing];

    self.userView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(userLoadMore)];
}

- (void)setUp {
    self.title = @"推荐关注";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.userView.rowHeight = 60;

    // 注册"cell"
    [self.categoryView registerNib:[UINib nibWithNibName:@"JLRecomendCell" bundle:nil] forCellReuseIdentifier:recomendID];
    [self.userView registerNib:[UINib nibWithNibName:@"JLUserCell" bundle:nil] forCellReuseIdentifier:userID];

    [SVProgressHUD showWithStatus:@"loading"];

    [JLNetTool getRecomendCategorySuccess:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        self.categoryList = [JLRecomendList mj_objectArrayWithKeyValuesArray:responseObject[@"list"] context:nil];
        [self.categoryView reloadData];
        [self.categoryView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败"];

    }];

}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma -mark TableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.categoryView) {
        return self.categoryList.count;
    }else if (tableView == self.userView) {
        return self.categoryList[self.categoryIndex].users.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell  = nil;
    if (tableView == self.categoryView) {
        cell = [tableView dequeueReusableCellWithIdentifier:recomendID];
        ((JLRecomendCell *)cell).model = self.categoryList[indexPath.row];
    } if (tableView == self.userView) {
//        NSLog(@"------categoryIndex:%ld  indexPath.row:%ld",self.categoryIndex, indexPath.row);
        cell = [tableView dequeueReusableCellWithIdentifier:userID];
        NSLog(@"indexPath.row:%ld--users.count:%ld",indexPath.row,self.categoryList[self.categoryIndex].users.count);
        ((JLUserCell *)cell).model = self.categoryList[self.categoryIndex].users[indexPath.row];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.categoryView) {
        self.categoryIndex = indexPath.row;
        if ( self.categoryList[indexPath.row].users.count ) {
            [self.userView reloadData];
            return;
        }
        // 赶紧刷新表格,目的是: 马上显示当前category的用户数据, 不让用户看见上一个category的残留数据
        [self.userView reloadData];
        [self .userView.header beginRefreshing];
    } if (tableView == self.userView) {

    }
}

#pragma -mark 刷新控件-方法
/**
 * 下拉刷新
 */
- (void)userRefresh {
    JLRecomendList *list = self.categoryList[self.categoryIndex];
    [JLNetTool getRecomendUserListId:list.ID page:1  Success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        list.users = [JLUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"] context:nil];
        list.totalPage = [responseObject[@"total_page"] integerValue];
        list.nextPage = [responseObject[@"next_page"] integerValue];

        [self.userView.header endRefreshing];
        [self.userView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.userView.header endRefreshing];
    }];
}

/**
 * 上拉加载更多
 */
- (void)userLoadMore {
    JLRecomendList *list = self.categoryList[self.categoryIndex];
    if (list.nextPage > list.totalPage) {
        [self.userView.footer endRefreshing];
        return;
    }

    [JLNetTool getRecomendUserListId:list.ID page:list.nextPage++  Success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray *users = [JLUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"] context:nil];
        list.totalPage = [responseObject[@"total_page"] integerValue];

        [list.users addObjectsFromArray:users];
        [self.userView reloadData];
        [self.userView.footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.userView.footer endRefreshing];
    }];
}

@end


text:
package org.recap.model.export;

import org.junit.Test;
import org.recap.BaseTestCase;
import org.recap.model.jpa.BibliographicEntity;
import org.recap.model.jpa.HoldingsEntity;
import org.recap.model.jpa.ItemEntity;
import org.recap.repository.BibliographicDetailsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Created by premkb on 2/10/16.
 */
public class DeletedDataDumpCallableUT extends BaseTestCase {
    @Autowired
    ApplicationContext appContext;

    @Autowired
    BibliographicDetailsRepository bibliographicDetailsRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Test
    public void call() throws Exception {
        int pageNum = 0;
        int batchSize = 1000;
        DataDumpRequest dataDumpRequest = new DataDumpRequest();
        List<String> institutionCodes = new ArrayList<>();
        institutionCodes.add("PUL");
        dataDumpRequest.setInstitutionCodes(institutionCodes);
        dataDumpRequest.setBatchSize(batchSize);
        dataDumpRequest.setFetchType("1");
        List<Integer> cgIds = new ArrayList<>();
        cgIds.add(1);
        cgIds.add(2);
        dataDumpRequest.setCollectionGroupIds(cgIds);
        try {
            saveAndGetBibliographicEntities();
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
        DeletedDataDumpCallable deletedDataDumpCallable = appContext.getBean(DeletedDataDumpCallable.class,pageNum,batchSize,dataDumpRequest,bibliographicDetailsRepository);
        List<BibliographicEntity> bibliographicEntityList = (List<BibliographicEntity>)deletedDataDumpCallable.call();
        BibliographicEntity bibliographicEntity = bibliographicEntityList.get(0);
        assertNotNull(bibliographicEntityList);
        assertEquals(1,bibliographicEntityList.size());
        assertEquals(new Integer(1),bibliographicEntity.getOwningInstitutionId());
        assertEquals("2",bibliographicEntity.getOwningInstitutionBibId());
    }

    private List<BibliographicEntity> saveAndGetBibliographicEntities() throws URISyntaxException, IOException {
        List<BibliographicEntity> bibliographicEntities = new ArrayList<>();
        BibliographicEntity bibliographicEntity = new BibliographicEntity();
        bibliographicEntity.setContent("bib content".getBytes());
        bibliographicEntity.setOwningInstitutionId(1);
        bibliographicEntity.setOwningInstitutionBibId("2");
        bibliographicEntity.setCreatedDate(new Date());
        bibliographicEntity.setCreatedBy("tst");
        bibliographicEntity.setLastUpdatedDate(new Date());
        bibliographicEntity.setLastUpdatedBy("tst");

        HoldingsEntity holdingsEntity = new HoldingsEntity();
        holdingsEntity.setContent("holding content".getBytes());
        holdingsEntity.setCreatedDate(new Date());
        holdingsEntity.setCreatedBy("etl");
        holdingsEntity.setLastUpdatedDate(new Date());
        holdingsEntity.setLastUpdatedBy("etl");
        holdingsEntity.setOwningInstitutionId(1);
        holdingsEntity.setOwningInstitutionHoldingsId("3");

        ItemEntity itemEntity = new ItemEntity();
        itemEntity.setLastUpdatedDate(new Date());
        itemEntity.setOwningInstitutionItemId("4");
        itemEntity.setOwningInstitutionId(1);
        itemEntity.setCreatedDate(new Date());
        itemEntity.setCreatedBy("tst");
        itemEntity.setLastUpdatedDate(new Date());
        itemEntity.setLastUpdatedBy("tst");
        String barcode = "1234";
        itemEntity.setBarcode(barcode);
        itemEntity.setCallNumber("x.12321");
        itemEntity.setCollectionGroupId(1);
        itemEntity.setCallNumberType("1");
        itemEntity.setCustomerCode("1");
        itemEntity.setItemAvailabilityStatusId(1);
        itemEntity.setCopyNumber(123);
        itemEntity.setDeleted(true);
        itemEntity.setHoldingsEntities(Arrays.asList(holdingsEntity));

        bibliographicEntity.setHoldingsEntities(Arrays.asList(holdingsEntity));
        bibliographicEntity.setItemEntities(Arrays.asList(itemEntity));
        itemEntity.setBibliographicEntities(bibliographicEntities);
        BibliographicEntity savedBibliographicEntity = bibliographicDetailsRepository.saveAndFlush(bibliographicEntity);
        entityManager.refresh(savedBibliographicEntity);
        bibliographicEntities.add(savedBibliographicEntity);
        return bibliographicEntities;
    }
}


text:
void serial_init(void);

void serial_write(unsigned char c);

void print(const char *s);

void bigint_print(const unsigned char *x, unsigned char xlen);

void printllu(unsigned long long x);

void bigint_print_hex(const unsigned char *x, unsigned char xlen);

#endif


text:
require 'fileutils'

module NETBuildpack::Util

  # A very simple and naive logger.  This is only intended to tide us over until a more robust logging solution is
  # exposed to buildpacks
  class Logger

    # The directory that diagnostics are written into
    DIAGNOSTICS_DIRECTORY = '.buildpack-diagnostics'.freeze

    # Creates a new logger
    #
    # @param [String] app_dir the root directory to write diagnostics to
    def initialize(app_dir)
      @diagnostics_directory = File.join app_dir, DIAGNOSTICS_DIRECTORY
      @log_file = File.join @diagnostics_directory, LOG_FILE_NAME

      FileUtils.mkdir_p @diagnostics_directory
      Logger.log(@log_file, @log_file)
    end

    def log(title, data = nil)
      Logger.log @log_file, title, data
    end

    private

    LOG_FILE_NAME = 'buildpack.log'.freeze

    def self.log(file, title, data = nil)
      File.open(file, 'a') do |log|
        log.sync = true

        log.write "#{time_in_millis}: #{title}\n"

        if data
          data_string = data.is_a?(Hash) || data.is_a?(Array) ? data.to_yaml: data.to_s
          data_string.each_line { |line| log.write "\t#{line}" }
        end

        log.write "\n"
      end
    end

    def self.time_in_millis
      Time.now.xmlschema(3).sub(/T/, ' ')
    end

  end

end