text:
package org.apache.drill.exec.store.parquet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.expression.ValueExpressions;
import org.apache.drill.common.logical.FormatPluginConfig;
import org.apache.drill.common.logical.StoragePluginConfig;
import org.apache.drill.exec.physical.base.GroupScan;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.store.ColumnExplorer;
import org.apache.drill.exec.store.StoragePluginRegistry;
import org.apache.drill.exec.store.dfs.DrillFileSystem;
import org.apache.drill.exec.store.dfs.FileSelection;
import org.apache.drill.exec.store.parquet.metadata.Metadata;
import org.apache.drill.exec.util.DrillFileSystemUtil;
import org.apache.drill.exec.store.dfs.MetadataContext;
import org.apache.drill.exec.store.dfs.MetadataContext.PruneStatus;
import org.apache.drill.exec.store.dfs.ReadEntryWithPath;
import org.apache.drill.exec.store.parquet.metadata.MetadataBase.ParquetFileMetadata;
import org.apache.drill.exec.store.parquet.metadata.MetadataBase.ParquetTableMetadataBase;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;

@JsonTypeName("parquet-scan")
public class ParquetGroupScan extends AbstractParquetGroupScan {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParquetGroupScan.class);

  private final ParquetFormatPlugin formatPlugin;
  private final ParquetFormatConfig formatConfig;
  private final DrillFileSystem fs;
  private final MetadataContext metaContext;
  private boolean usedMetadataCache; // false by default
  // may change when filter push down / partition pruning is applied
  private String selectionRoot;
  private String cacheFileRoot;

  @JsonCreator
  public ParquetGroupScan(@JacksonInject StoragePluginRegistry engineRegistry,
                          @JsonProperty("userName") String userName,
                          @JsonProperty("entries") List<ReadEntryWithPath> entries,
                          @JsonProperty("storage") StoragePluginConfig storageConfig,
                          @JsonProperty("format") FormatPluginConfig formatConfig,
                          @JsonProperty("columns") List<SchemaPath> columns,
                          @JsonProperty("selectionRoot") String selectionRoot,
                          @JsonProperty("cacheFileRoot") String cacheFileRoot,
                          @JsonProperty("filter") LogicalExpression filter) throws IOException, ExecutionSetupException {
    super(ImpersonationUtil.resolveUserName(userName), columns, entries, filter);
    Preconditions.checkNotNull(storageConfig);
    Preconditions.checkNotNull(formatConfig);
    this.formatPlugin = (ParquetFormatPlugin) engineRegistry.getFormatPlugin(storageConfig, formatConfig);
    Preconditions.checkNotNull(formatPlugin);
    this.fs = ImpersonationUtil.createFileSystem(getUserName(), formatPlugin.getFsConf());
    this.formatConfig = formatPlugin.getConfig();
    this.selectionRoot = selectionRoot;
    this.cacheFileRoot = cacheFileRoot;
    this.metaContext = new MetadataContext();

    init();
  }

  public ParquetGroupScan(String userName,
                          FileSelection selection,
                          ParquetFormatPlugin formatPlugin,
                          List<SchemaPath> columns) throws IOException {
    this(userName, selection, formatPlugin, columns, ValueExpressions.BooleanExpression.TRUE);
  }

  public ParquetGroupScan(String userName,
                          FileSelection selection,
                          ParquetFormatPlugin formatPlugin,
                          List<SchemaPath> columns,
                          LogicalExpression filter) throws IOException {
    super(userName, columns, new ArrayList<>(), filter);

    this.formatPlugin = formatPlugin;
    this.formatConfig = formatPlugin.getConfig();
    this.fs = ImpersonationUtil.createFileSystem(userName, formatPlugin.getFsConf());
    this.selectionRoot = selection.getSelectionRoot();
    this.cacheFileRoot = selection.getCacheFileRoot();

    MetadataContext metadataContext = selection.getMetaContext();
    this.metaContext = metadataContext != null ? metadataContext : new MetadataContext();

    FileSelection fileSelection = expandIfNecessary(selection);
    if (fileSelection != null) {
      if (checkForInitializingEntriesWithSelectionRoot()) {
        // The fully expanded list is already stored as part of the fileSet
        entries.add(new ReadEntryWithPath(fileSelection.getSelectionRoot()));
      } else {
        for (String fileName : fileSelection.getFiles()) {
          entries.add(new ReadEntryWithPath(fileName));
        }
      }

      init();
    }
  }

  private ParquetGroupScan(ParquetGroupScan that) {
    this(that, null);
  }

  private ParquetGroupScan(ParquetGroupScan that, FileSelection selection) {
    super(that);
    this.formatConfig = that.formatConfig;
    this.formatPlugin = that.formatPlugin;
    this.fs = that.fs;
    this.selectionRoot = that.selectionRoot;
    if (selection != null) {
      this.cacheFileRoot = selection.getCacheFileRoot();
      MetadataContext metaContext = selection.getMetaContext();
      this.metaContext = metaContext != null ? metaContext : that.metaContext;
    } else {
      this.cacheFileRoot = that.cacheFileRoot;
      this.metaContext = that.metaContext;
    }
    this.usedMetadataCache = that.usedMetadataCache;
  }

  // getters for serialization / deserialization start
  @JsonProperty("format")
  public ParquetFormatConfig getFormatConfig() {
    return formatConfig;
  }

  @JsonProperty("storage")
  public StoragePluginConfig getEngineConfig() {
    return formatPlugin.getStorageConfig();
  }

  @JsonProperty
  public String getSelectionRoot() {
    return selectionRoot;
  }

  @JsonProperty
  public String getCacheFileRoot() {
    return cacheFileRoot;
  }
  // getters for serialization / deserialization end

  @Override
  public ParquetRowGroupScan getSpecificScan(int minorFragmentId) {
    return new ParquetRowGroupScan(getUserName(), formatPlugin, getReadEntries(minorFragmentId), columns, selectionRoot, filter);
  }

  @Override
  public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
    Preconditions.checkArgument(children.isEmpty());
    return new ParquetGroupScan(this);
  }

  @Override
  public GroupScan clone(List<SchemaPath> columns) {
    ParquetGroupScan newScan = new ParquetGroupScan(this);
    newScan.columns = columns;
    return newScan;
  }

  @Override
  public ParquetGroupScan clone(FileSelection selection) throws IOException {
    ParquetGroupScan newScan = new ParquetGroupScan(this, selection);
    newScan.modifyFileSelection(selection);
    newScan.init();
    return newScan;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("ParquetGroupScan [");
    builder.append("entries=").append(entries);
    builder.append(", selectionRoot=").append(selectionRoot);
    builder.append(", numFiles=").append(getEntries().size());
    builder.append(", numRowGroups=").append(rowGroupInfos.size());
    builder.append(", usedMetadataFile=").append(usedMetadataCache);

    String filterString = getFilterString();
    if (!filterString.isEmpty()) {
      builder.append(", filter=").append(filterString);
    }

    if (usedMetadataCache) {
      // For EXPLAIN, remove the URI prefix from cacheFileRoot.  If cacheFileRoot is null, we
      // would have read the cache file from selectionRoot
      String cacheFileRootString = (cacheFileRoot == null) ?
          Path.getPathWithoutSchemeAndAuthority(new Path(selectionRoot)).toString() :
          Path.getPathWithoutSchemeAndAuthority(new Path(cacheFileRoot)).toString();
      builder.append(", cacheFileRoot=").append(cacheFileRootString);
    }

    builder.append(", columns=").append(columns);
    builder.append("]");

    return builder.toString();
  }

  // overridden protected methods block start
  @Override
  protected void initInternal() throws IOException {
    FileSystem processUserFileSystem = ImpersonationUtil.createFileSystem(ImpersonationUtil.getProcessUserName(), fs.getConf());
    Path metaPath = null;
    if (entries.size() == 1 && parquetTableMetadata == null) {
      Path p = Path.getPathWithoutSchemeAndAuthority(new Path(entries.get(0).getPath()));
      if (fs.isDirectory(p)) {
        // Using the metadata file makes sense when querying a directory; otherwise
        // if querying a single file we can look up the metadata directly from the file
        metaPath = new Path(p, Metadata.METADATA_FILENAME);
      }
      if (!metaContext.isMetadataCacheCorrupted() && metaPath != null && fs.exists(metaPath)) {
        parquetTableMetadata = Metadata.readBlockMeta(processUserFileSystem, metaPath, metaContext, formatConfig);
        if (parquetTableMetadata != null) {
          usedMetadataCache = true;
        }
      }
      if (!usedMetadataCache) {
        parquetTableMetadata = Metadata.getParquetTableMetadata(processUserFileSystem, p.toString(), formatConfig);
      }
    } else {
      Path p = Path.getPathWithoutSchemeAndAuthority(new Path(selectionRoot));
      metaPath = new Path(p, Metadata.METADATA_FILENAME);
      if (!metaContext.isMetadataCacheCorrupted() && fs.isDirectory(new Path(selectionRoot))
          && fs.exists(metaPath)) {
        if (parquetTableMetadata == null) {
          parquetTableMetadata = Metadata.readBlockMeta(processUserFileSystem, metaPath, metaContext, formatConfig);
        }
        if (parquetTableMetadata != null) {
          usedMetadataCache = true;
          if (fileSet != null) {
            parquetTableMetadata = removeUnneededRowGroups(parquetTableMetadata);
          }
        }
      }
      if (!usedMetadataCache) {
        final List<FileStatus> fileStatuses = new ArrayList<>();
        for (ReadEntryWithPath entry : entries) {
          fileStatuses.addAll(
              DrillFileSystemUtil.listFiles(fs, Path.getPathWithoutSchemeAndAuthority(new Path(entry.getPath())), true));
        }

        Map<FileStatus, FileSystem> statusMap = fileStatuses.stream()
            .collect(
                Collectors.toMap(
                    Function.identity(),
                    s -> processUserFileSystem,
                    (oldFs, newFs) -> newFs,
                    LinkedHashMap::new));

        parquetTableMetadata = Metadata.getParquetTableMetadata(statusMap, formatConfig);
      }
    }
  }

  @Override
  protected AbstractParquetGroupScan cloneWithFileSelection(Collection<String> filePaths) throws IOException {
    FileSelection newSelection = new FileSelection(null, new ArrayList<>(filePaths), getSelectionRoot(), cacheFileRoot, false);
    return clone(newSelection);
  }

  @Override
  protected Collection<DrillbitEndpoint> getDrillbits() {
    return formatPlugin.getContext().getBits();
  }

  @Override
  protected boolean supportsFileImplicitColumns() {
    return selectionRoot != null;
  }

  @Override
  protected List<String> getPartitionValues(RowGroupInfo rowGroupInfo) {
    return ColumnExplorer.listPartitionValues(rowGroupInfo.getPath(), selectionRoot);
  }
  // overridden protected methods block end

  // private methods block start
  /**
   * Expands the selection's folders if metadata cache is found for the selection root.

   * If the selection has already been expanded or no metadata cache was found, does nothing
   *
   * @param selection actual selection before expansion
   * @return new selection after expansion, if no expansion was done returns the input selection
   */
  private FileSelection expandIfNecessary(FileSelection selection) throws IOException {
    if (selection.isExpandedFully()) {
      return selection;
    }

    // use the cacheFileRoot if provided (e.g after partition pruning)
    Path metaFilePath = new Path(cacheFileRoot != null ? cacheFileRoot : selectionRoot, Metadata.METADATA_FILENAME);
    if (!fs.exists(metaFilePath)) { // no metadata cache
      if (selection.isExpandedPartial()) {
        logger.error("'{}' metadata file does not exist, but metadata directories cache file is present", metaFilePath);
        metaContext.setMetadataCacheCorrupted(true);
      }

      return selection;
    }

    return expandSelectionFromMetadataCache(selection, metaFilePath);
  }

  /**
   * For two cases the entries should be initialized with just the selection root instead of the fully expanded list:
   *

   *
 When metadata caching is corrupted (to use correct file selection)
   *
 Metadata caching is correct and used, but pruning was not applicable or was attempted and nothing was pruned
   *        (to reduce overhead in parquet group scan).
   *

   *
   * @return true if entries should be initialized with selection root, false otherwise
   */
  private boolean checkForInitializingEntriesWithSelectionRoot() {
    // TODO: at some point we should examine whether the list of entries is absolutely needed.
    return metaContext.isMetadataCacheCorrupted() || (parquetTableMetadata != null &&
        (metaContext.getPruneStatus() == PruneStatus.NOT_STARTED || metaContext.getPruneStatus() == PruneStatus.NOT_PRUNED));
  }

  /**
   * Create and return a new file selection based on reading the metadata cache file.
   *
   * This function also initializes a few of ParquetGroupScan's fields as appropriate.
   *
   * @param selection initial file selection
   * @param metaFilePath metadata cache file path
   * @return file selection read from cache
   *
   * @throws UserException when the updated selection is empty, this happens if the user selects an empty folder.
   */
  private FileSelection expandSelectionFromMetadataCache(FileSelection selection, Path metaFilePath) throws IOException {
    // get the metadata for the root directory by reading the metadata file
    // parquetTableMetadata contains the metadata for all files in the selection root folder, but we need to make sure
    // we only select the files that are part of selection (by setting fileSet appropriately)

    // get (and set internal field) the metadata for the directory by reading the metadata file
    FileSystem processUserFileSystem = ImpersonationUtil.createFileSystem(ImpersonationUtil.getProcessUserName(), fs.getConf());
    parquetTableMetadata = Metadata.readBlockMeta(processUserFileSystem, metaFilePath, metaContext, formatConfig);
    if (ignoreExpandingSelection(parquetTableMetadata)) {
      return selection;
    }
    if (formatConfig.areCorruptDatesAutoCorrected()) {
      ParquetReaderUtility.correctDatesInMetadataCache(this.parquetTableMetadata);
    }
    ParquetReaderUtility.correctBinaryInMetadataCache(parquetTableMetadata);
    List<FileStatus> fileStatuses = selection.getStatuses(fs);

    if (fileSet == null) {
      fileSet = Sets.newHashSet();
    }

    final Path first = fileStatuses.get(0).getPath();
    if (fileStatuses.size() == 1 && selection.getSelectionRoot().equals(first.toString())) {
      // we are selecting all files from selection root. Expand the file list from the cache
      for (ParquetFileMetadata file : parquetTableMetadata.getFiles()) {
        fileSet.add(file.getPath());
      }

    } else if (selection.isExpandedPartial() && !selection.hadWildcard() && cacheFileRoot != null) {
      if (selection.wasAllPartitionsPruned()) {
        // if all partitions were previously pruned, we only need to read 1 file (for the schema)
        fileSet.add(this.parquetTableMetadata.getFiles().get(0).getPath());
      } else {
        // we are here if the selection is in the expanded_partial state (i.e it has directories).  We get the
        // list of files from the metadata cache file that is present in the cacheFileRoot directory and populate
        // the fileSet. However, this is *not* the final list of files that will be scanned in execution since the
        // second phase of partition pruning will apply on the files and modify the file selection appropriately.
        for (ParquetFileMetadata file : this.parquetTableMetadata.getFiles()) {
          fileSet.add(file.getPath());
        }
      }
    } else {
      // we need to expand the files from fileStatuses
      for (FileStatus status : fileStatuses) {
        Path cacheFileRoot = status.getPath();
        if (status.isDirectory()) {
          //TODO [DRILL-4496] read the metadata cache files in parallel
          final Path metaPath = new Path(cacheFileRoot, Metadata.METADATA_FILENAME);
          final ParquetTableMetadataBase metadata = Metadata.readBlockMeta(processUserFileSystem, metaPath, metaContext, formatConfig);
          if (ignoreExpandingSelection(metadata)) {
            return selection;
          }
          for (ParquetFileMetadata file : metadata.getFiles()) {
            fileSet.add(file.getPath());
          }
        } else {
          final Path path = Path.getPathWithoutSchemeAndAuthority(cacheFileRoot);
          fileSet.add(path.toString());
        }
      }
    }

    if (fileSet.isEmpty()) {
      // no files were found, most likely we tried to query some empty sub folders
      logger.warn("The table is empty but with outdated invalid metadata cache files. Please, delete them.");
      return null;
    }

    List<String> fileNames = new ArrayList<>(fileSet);

    // when creating the file selection, set the selection root without the URI prefix
    // The reason is that the file names above have been created in the form
    // /a/b/c.parquet and the format of the selection root must match that of the file names
    // otherwise downstream operations such as partition pruning can break.
    final Path metaRootPath = Path.getPathWithoutSchemeAndAuthority(new Path(selection.getSelectionRoot()));
    this.selectionRoot = metaRootPath.toString();

    // Use the FileSelection constructor directly here instead of the FileSelection.create() method
    // because create() changes the root to include the scheme and authority; In future, if create()
    // is the preferred way to instantiate a file selection, we may need to do something different...
    // WARNING: file statuses and file names are inconsistent
    FileSelection newSelection = new FileSelection(selection.getStatuses(fs), fileNames, metaRootPath.toString(),
        cacheFileRoot, selection.wasAllPartitionsPruned());

    newSelection.setExpandedFully();
    newSelection.setMetaContext(metaContext);
    return newSelection;
  }

  private ParquetTableMetadataBase removeUnneededRowGroups(ParquetTableMetadataBase parquetTableMetadata) {
    List<ParquetFileMetadata> newFileMetadataList = new ArrayList<>();
    for (ParquetFileMetadata file : parquetTableMetadata.getFiles()) {
      if (fileSet.contains(file.getPath())) {
        newFileMetadataList.add(file);
      }
    }

    ParquetTableMetadataBase metadata = parquetTableMetadata.clone();
    metadata.assignFiles(newFileMetadataList);
    return metadata;
  }

  /**
   * If metadata is corrupted, ignore expanding selection and reset parquetTableMetadata and fileSet fields
   *
   * @param metadata parquet table metadata
   * @return true if parquet metadata is corrupted, false otherwise
   */
  private boolean ignoreExpandingSelection(ParquetTableMetadataBase metadata) {
    if (metadata == null || metaContext.isMetadataCacheCorrupted()) {
      logger.debug("Selection can't be expanded since metadata file is corrupted or metadata version is not supported");
      this.parquetTableMetadata = null;
      this.fileSet = null;
      return true;
    }
    return false;
  }
  // private methods block end

}


text:
require_relative "test_helper"
require 'timecop'

class TestTimecop < Minitest::Unit::TestCase
  def setup
    t = Time.local(2008, 9, 1, 10, 5, 0) # monday
    Timecop.travel(t)
  end

  def teardown
    Timecop.return
  end

  # Test for Date
  def test_date_parse_sunday_after_travel
    assert_equal Date.parse("2008-08-31"), Date.parse('Sunday')
  end

  def test_date_parse_monday_after_travel
    assert_equal Date.parse("2008-09-01"), Date.parse('Monday')
  end

  def test_date_parse_tuesday_after_travel
    assert_equal Date.parse("2008-09-02"), Date.parse('Tuesday')
  end

  def test_date_parse_wednesday_after_travel
    assert_equal Date.parse("2008-09-03"), Date.parse('Wednesday')
  end

  def test_date_parse_thursday_after_travel
    assert_equal Date.parse("2008-09-04"), Date.parse('Thursday')
  end

  def test_date_parse_friday_after_travel
    assert_equal Date.parse("2008-09-05"), Date.parse('Friday')
  end

  def test_date_parse_saturday_after_travel
    assert_equal Date.parse("2008-09-06"), Date.parse('Saturday')
  end

  def test_date_parse_with_additional_args
    assert_equal Date.parse("2008-09-06", false), Date.parse('Saturday')
  end

  def test_date_parse_nil_raises_type_error
    assert_raises(TypeError) { Date.parse(nil) }
  end

  # Tests for DateTime
  def test_date_time_parse_sunday_after_travel
    assert_equal DateTime.parse("2008-08-31"), DateTime.parse('Sunday')
  end

  def test_date_time_parse_monday_after_travel
    assert_equal DateTime.parse("2008-09-01"), DateTime.parse('Monday')
  end

  def test_date_time_parse_tuesday_after_travel
    assert_equal DateTime.parse("2008-09-02"), DateTime.parse('Tuesday')
  end

  def test_date_time_parse_wednesday_after_travel
    assert_equal DateTime.parse("2008-09-03"), DateTime.parse('Wednesday')
  end

  def test_date_time_parse_thursday_after_travel
    assert_equal DateTime.parse("2008-09-04"), DateTime.parse('Thursday')
  end

  def test_date_time_parse_friday_after_travel
    assert_equal DateTime.parse("2008-09-05"), DateTime.parse('Friday')
  end

  def test_date_time_parse_saturday_after_travel
    assert_equal DateTime.parse("2008-09-06"), DateTime.parse('Saturday')
  end

  def test_date_time_parse_with_additional_args
    assert_equal DateTime.parse("2008-09-06", false), DateTime.parse('Saturday')
  end

  def test_datetime_parse_nil_raises_type_error
    assert_raises(TypeError) { DateTime.parse(nil) }
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.openhds.domain.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation used to mark methods that require certain privileges to access
 *
 * @author Dave Roberge
 *
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Authorized {

	public String[] value() default {};

	public boolean requireAll() default false;
}


text:
        (function() {
          Polymer('x-test', {
            bar: '',
            observe: {
              bar: 'validate',
              pie: 'validate',
              'a.b.c': 'validateSubPath'
            },
            ready: function() {
              this.bar = 'bar';
              this.pie = 'pie';
              this.a = {b: {c: 'exists'}};
            },
            barChanged: function() {
              //console.log('I should not be called')
            },
            validate: function() {
              //console.log('validate');
              chai.assert.equal(this.bar, 'bar', 'custom change observer called');
              chai.assert.equal(this.pie, 'pie', 'custom change observer called');
              checkDone();
            },
            validateSubPath: function(oldValue, newValue) {
              //console.log('validateSubPath', oldValue, newValue);
              chai.assert.equal(newValue, 'exists', 'subpath change observer called');
              checkDone();
            }
          });
        })();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using openCaseMaster.ViewModels;
using Newtonsoft.Json;
using openCaseMaster.Models;

namespace openCaseMaster.Controllers
{
    [Authorize(Roles = "admin")]
    public class ProjectController : Controller
    {

        // GET: Project
        public ActionResult ProjectManage()
        {
            return View();
        }

        public string projectList(int page, int rows)
        {
            ProjectListModel pl = new ProjectListModel(page, rows);

            string json = JsonConvert.SerializeObject(pl);

            return json;

        }

        [HttpGet]
        public ActionResult editProject(int id)
        {
            QCTESTEntities QC_DB = new QCTESTEntities();
            var p = QC_DB.project.First(t => t.ID == id);

            var deviceList = from t1 in QC_DB.M_deviceConfig
                             join t2 in QC_DB.M_DevProMapping.Where(t => t.PID == id)
                            on t1.ID equals t2.DeviceID into Joined
                             from t2 in Joined.DefaultIfEmpty()
                             select new checkListModel
                             {
                                 Value = t1.ID.ToString(),
                                 Text = t1.mark,
                                 isCheck = t2 != null ? t2.usable : false
                             };

            var appList = from t1 in QC_DB.M_application
                             join t2 in QC_DB.project_app.Where(t => t.PID == id)
                            on t1.ID equals t2.appID into Joined
                             from t2 in Joined.DefaultIfEmpty()
                             select new checkListModel
                             {
                                 Value = t1.ID.ToString(),
                                 Text = t1.name,
                                 isCheck = t2 != null ? t2.usable : false
                             };

            ViewData["deviceList"] = deviceList.ToList();
            ViewData["appList"] = appList.ToList();

            return PartialView("_editProject", p);
        }

        [HttpPost]
        public string editProject(int ID, string Pname, string deviceList, string appList)
        {
            QCTESTEntities QC_DB = new QCTESTEntities();
            var u = QC_DB.project.First(t => t.ID == ID);
            u.Pname = Pname;

            //设备

            var dpm = QC_DB.M_DevProMapping.Where(t => t.PID == ID);

            List<string> deviceID;
            if (string.IsNullOrEmpty(deviceList.TrimEnd(',')))
                deviceID = new List<string>();
            else
                deviceID = deviceList.TrimEnd(',').Split(',').ToList();

            foreach(var d in dpm)
            {
                if(deviceID.Contains(d.DeviceID.ToString()))
                {
                    d.usable = true;
                    deviceID.Remove(d.DeviceID.ToString());
                }else
                    d.usable = false;
            }

            foreach (var d in deviceID)
            {
                M_DevProMapping temp = new M_DevProMapping();
                temp.PID = ID;
                temp.DeviceID = Convert.ToInt32(d);
                temp.usable = true;
                QC_DB.M_DevProMapping.Add(temp);
            }

            //app

            var papp = QC_DB.project_app.Where(t => t.PID == ID);

            List<string> appID;
            if (string.IsNullOrEmpty(appList.TrimEnd(',')))
                appID = new List<string>();
            else
                appID = appList.TrimEnd(',').Split(',').ToList();

            foreach (var p in papp)
            {
                if (appID.Contains(p.appID.ToString()))
                {
                    p.usable = true;
                    appID.Remove(p.appID.ToString());
                }
                else
                    p.usable = false;
            }

            foreach (var p in appID)
            {
                project_app temp = new project_app();
                temp.PID = ID;
                temp.appID = Convert.ToInt32(p);
                temp.usable = true;
                QC_DB.project_app.Add(temp);
            }

            QC_DB.SaveChanges();

            return "";
        }

        [HttpGet]
        public ActionResult addProject()
        {
            QCTESTEntities QC_DB = new QCTESTEntities();

            var deviceList = from t1 in QC_DB.M_deviceConfig
                             select new checkListModel
                             {
                                 Value = t1.ID.ToString(),
                                 Text = t1.mark
                             };

            var appList = from t1 in QC_DB.M_application
                          select new checkListModel
                          {
                              Value = t1.ID.ToString(),
                              Text = t1.name
                          };

            ViewData["deviceList"] = deviceList.ToList();
            ViewData["appList"] = appList.ToList();

            return PartialView("_editProject", new project());
        }

        [HttpPost]
        public string addProject(string Pname, string deviceList, string appList)
        {
            QCTESTEntities QC_DB = new QCTESTEntities();
            project pro = new project();
            pro.Pname = Pname;
            pro.zidonghua = true;

            QC_DB.project.Add(pro);
            //设备

            List<string> deviceID;
            if (string.IsNullOrEmpty(deviceList.TrimEnd(',')))
                deviceID = new List<string>();
            else
                deviceID = deviceList.TrimEnd(',').Split(',').ToList();

            foreach (var d in deviceID)
            {
                M_DevProMapping temp = new M_DevProMapping();
                temp.PID = pro.ID;
                temp.DeviceID = Convert.ToInt32(d);
                temp.usable = true;
                QC_DB.M_DevProMapping.Add(temp);
            }

            //app

            List<string> appID;
            if (string.IsNullOrEmpty(appList.TrimEnd(',')))
                appID = new List<string>();
            else
                appID = appList.TrimEnd(',').Split(',').ToList();

            foreach (var p in appID)
            {
                project_app temp = new project_app();
                temp.PID = pro.ID;
                temp.appID = Convert.ToInt32(p);
                temp.usable = true;
                QC_DB.project_app.Add(temp);
            }

            QC_DB.SaveChanges();

            return "";
        }

    }
}


text:
package de.roamingthings.expenses.ui.expense.controller;

import de.roamingthings.SystemPropertyActiveProfileResolver;
import de.roamingthings.expenses.expense.domain.ExpenseType;
import de.roamingthings.expenses.expense.domain.RecurrencePeriod;
import de.roamingthings.expenses.expense.domain.RecurringExpense;
import de.roamingthings.expenses.expense.repository.RecurringExpenseRepository;
import de.roamingthings.expenses.main.ExpensesTrackerApplication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.math.BigDecimal;
import java.time.LocalDate;

import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Alexander Sparkowsky [info@roamingthings.de]
 * @version 2017/04/23
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ExpensesTrackerApplication.class)
@WebAppConfiguration
@ActiveProfiles(resolver = SystemPropertyActiveProfileResolver.class)
public class RecurringExpenseControllerIT {
    @Autowired
    private WebApplicationContext wac;

    @MockBean
    private RecurringExpenseRepository recurringExpenseRepository;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void should_contain_reference_number() throws Exception {
        RecurringExpense recurringExpense = new RecurringExpense(
                "Description",
                "Label",
                LocalDate.now(),
                RecurrencePeriod.MONTHLY,
                ExpenseType.SUBSCRIPTION,
                BigDecimal.valueOf(1.0),
                "EUR",
                "creditor",
                "abc123",
                "note"
        );
        recurringExpense.setId(1L);

        when(recurringExpenseRepository.findOne(1L)).thenReturn(recurringExpense);

        this.mockMvc.perform(get("/recurring_expenses/details/1"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("id=\"referenceNumber\"")));
    }

    @Test
    public void should_delete_recurring_expense() throws Exception {
        this.mockMvc.perform(delete("/recurring_expenses/delete/1"))
                .andDo(print())
                .andExpect(status().isOk());
//                .andExpect(forwardedUrl("redirect:recurring_expenses"));

        verify(recurringExpenseRepository, times(1)).delete(1L);
    }
}


text:
require "spec_helper"

describe Cobrato::Entities::ChargeTemplate do

  let(:attributes) do
    {
      id: "1",
      name: "Template novo",
      charged_amount: 456.0,
      document_kind: "DM",
      charge_config_id: "1",
      instructions: "",
      demonstrative: "",
      registrable: false,
      auto_send_billet: false,
      interest_amount_per_month: "",
      mulct_type: "",
      mulct_value: "",
      email_sender_name: "",
      email_subject: "",
      email_text: "",
      email_reply_to: "email@company.com"
    }
  end

  subject { described_class.new(attributes) }

  it_behaves_like "entity_attributes", [:id, :name, :charged_amount, :document_kind, :charge_config_id, :instructions,
    :demonstrative, :registrable, :auto_send_billet, :interest_amount_per_month, :mulct_type, :mulct_value,
    :email_sender_name, :email_subject, :email_text, :email_reply_to]
end


text:
package com.google.copybara;

import static com.google.copybara.exception.ValidationException.checkCondition;

import com.beust.jcommander.Parameters;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.copybara.config.Config;
import com.google.copybara.config.ConfigValidator;
import com.google.copybara.config.LabelsAwareModule;
import com.google.copybara.config.Migration;
import com.google.copybara.config.ValidationResult;
import com.google.copybara.exception.RepoException;
import com.google.copybara.exception.ValidationException;
import com.google.copybara.revision.Revision;
import com.google.copybara.util.ExitCode;
import com.google.copybara.util.console.Console;
import java.io.IOException;
import java.nio.file.Path;
import java.util.function.Consumer;

/**
 * Executes the migration for the given config.
 */
@Parameters(separators = "=", commandDescription = "Executes the migration for the given config.")
public class MigrateCmd implements CopybaraCmd {

  private final ConfigValidator configValidator;
  private final Consumer<Migration> migrationRanConsumer;
  private final ConfigLoaderProvider configLoaderProvider;
  private final ModuleSet moduleSet;

  MigrateCmd(ConfigValidator configValidator, Consumer<Migration> migrationRanConsumer,
      ConfigLoaderProvider configLoaderProvider, ModuleSet moduleSet) {
    this.configValidator = Preconditions.checkNotNull(configValidator);
    this.migrationRanConsumer = Preconditions.checkNotNull(migrationRanConsumer);
    this.configLoaderProvider = Preconditions.checkNotNull(configLoaderProvider);
    this.moduleSet = moduleSet;
  }

  @Override
  public ExitCode run(CommandEnv commandEnv)
      throws RepoException, ValidationException, IOException {
    ConfigFileArgs configFileArgs = commandEnv.parseConfigFileArgs(this,
        /*useSourceRef*/true);
    ImmutableList<String> sourceRefs = configFileArgs.getSourceRefs();
    String workflowName = configFileArgs.getWorkflowName();
    updateEnvironment(workflowName);
    GeneralOptions generalOptions = commandEnv.getOptions().get(GeneralOptions.class);
    Console console = generalOptions.console();
    console.verboseFmt("Executing workflow '%s'", workflowName);
    run(
        commandEnv.getOptions(),
        configLoaderProvider.newLoader(
            configFileArgs.getConfigPath(),
            sourceRefs.size() == 1 ? Iterables.getOnlyElement(sourceRefs) : null),
        workflowName,
        commandEnv.getWorkdir(),
        sourceRefs);
    return ExitCode.SUCCESS;
  }

  /**
   * Runs the migration specified by {@code migrationName}.
   */
  private void run(Options options, ConfigLoader configLoader, String migrationName,
      Path workdir, ImmutableList<String> sourceRefs)
      throws RepoException, ValidationException, IOException {
    Config config = loadConfig(options, configLoader, migrationName);

    Migration migration = config.getMigration(migrationName);

    if (!options.get(WorkflowOptions.class).isReadConfigFromChange()) {
      this.migrationRanConsumer.accept(migration);
      migration.run(workdir, sourceRefs);
      return;
    }

    checkCondition(configLoader.supportsLoadForRevision(),
        "%s flag is not supported for the origin/config file path",
        WorkflowOptions.READ_CONFIG_FROM_CHANGE);

    // A safeguard, mirror workflows are not supported in the service anyway
    checkCondition(migration instanceof Workflow,
        "Flag --read-config-from-change is not supported for non-workflow migrations: %s",
        migrationName);
    migrationRanConsumer.accept(migration);

    Workflow<? extends Revision, ? extends Revision> workflow =
        (Workflow<? extends Revision, ? extends Revision>) migration;
    new ReadConfigFromChangeWorkflow<>(workflow, options, configLoader, configValidator)
        .run(workdir, sourceRefs);
  }

  private Config loadConfig(Options options, ConfigLoader configLoader, String migrationName)
      throws IOException, ValidationException {
    GeneralOptions generalOptions = options.get(GeneralOptions.class);
    Console console = generalOptions.console();
    Config config = configLoader.load(console);
    console.progress("Validating configuration");
    ValidationResult result = configValidator.validate(config, migrationName);
    if (!result.hasErrors()) {
      return config;
    }
    result.getErrors().forEach(console::error);
    console.error("Configuration is invalid.");
    throw new ValidationException("Error validating configuration: Configuration is invalid.");
  }

  private void updateEnvironment(String migrationName) {
    for (Object module : moduleSet.getModules().values()) {
      // We mutate the module per file loaded. Not ideal but it is the best we can do.
      if (module instanceof LabelsAwareModule) {
        LabelsAwareModule m = (LabelsAwareModule) module;
        m.setWorkflowName(migrationName);
      }
    }
  }

  @Override
  public String name() {
    return "migrate";
  }
}


text:
package org.apache.rya.rdftriplestore.utils;

import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.rdf4j.common.lang.FileFormat;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParserRegistry;

import com.google.common.collect.ImmutableSet;

/**
 * Utility methods for {@link RDFFormat}.
 */
public final class RdfFormatUtils {
    /**
     * Holds all supported {@link RDFFormat} types.
     */
    public static final Set<RDFFormat> RDF_FORMATS = RDFParserRegistry.getInstance().getKeys();

    /**
     * The set of all supported file extensions from {@link #RDF_FORMATS}.
     */
    public static final Set<String> SUPPORTED_FILE_EXTENSIONS = buildSupportedFileExtensions();

    /**
     * Private constructor to prevent instantiation.
     */
    private RdfFormatUtils() {
    }

    /**
     * Gets the RDF format whose name matches the specified name.
     * @param formatName The format name.
     * @return The {@link RDFFormat} whose name matches the specified name, or
     * {@code null} if there is no such format.
     */
    public static RDFFormat getRdfFormatFromName(final String formatName) {
        for (final RDFFormat rdfFormat : RDF_FORMATS) {
            if (rdfFormat.getName().equalsIgnoreCase(formatName)) {
                return rdfFormat;
            }
        }
        return null;
    }

    /**
     * Tries to determine the appropriate RDF file format based on the extension
     * of a file name.
     * @param fileName A file name.
     * @return An {@link RDFFormat} object if the file extension was recognized,
     * or {@code null} otherwise.
     */
    public static RDFFormat forFileName(final String fileName) {
        return forFileName(fileName, null);
    }

    /**
     * Tries to determine the appropriate RDF file format based on the extension
     * of a file name. The supplied fallback format will be returned when the
     * file name extension was not recognized.
     * @param fileName A file name.
     * @return An {@link RDFFormat} that matches the file name extension, or the
     * fallback format if the extension was not recognized.
     */
    public static RDFFormat forFileName(final String fileName, final RDFFormat fallback) {
        final Optional<RDFFormat> match = FileFormat.matchFileName(fileName, RDF_FORMATS);
        if (match.isPresent()) {
            return match.get();
        } else {
            return fallback;
        }
    }

    /**
     * @return the set of all supported file extensions from
     * {@link #RDF_FORMATS}.
     */
    private static Set<String> buildSupportedFileExtensions() {
        return ImmutableSet.copyOf(RDF_FORMATS.stream().flatMap(rdfFormat -> rdfFormat.getFileExtensions().stream()).collect(Collectors.toList()));
    }
}


text:
'use strict';

var net = require('net');
var setTimeout = require('timers').setTimeout;

var allocCluster = require('./lib/alloc-cluster');
var RelayHandler = require('../relay_handler');

allocCluster.test('relaying to init timeout server', {
    numPeers: 2
}, function t(cluster, assert) {
    var deadServer = net.createServer();

    deadServer.listen(0, '127.0.0.1', onListen);

    function onListen() {
        var deadPort = deadServer.address().port;
        var deadHostPort = '127.0.0.1:' + deadPort;

        var client = cluster.channels[0];
        var relay = cluster.channels[1];
        relay.initTimeout = 250;

        var relayChan = relay.makeSubChannel({
            serviceName: 'dead-service',
            peers: [deadHostPort]
        });
        relayChan.handler = new RelayHandler(relayChan);

        var clientChan = client.makeSubChannel({
            serviceName: 'dead-service',
            peers: [relay.hostPort],
            requestDefaults: {
                serviceName: 'dead-service',
                headers: {
                    as: 'raw',
                    cn: 'client'
                }
            }
        });

        clientChan.request({
            hasNoParent: true,
            timeout: 50
        }).send('echo', '', '', onResponse);

        function onResponse(err) {
            // should expect in timeout
            assert.ok(err);
            // console.log('err', err);
            assert.ok(err.type === 'tchannel.request.timeout' ||
                err.type === 'tchannel.timeout'
            );

            assert.equal(cluster.logger.items().length, 0);
            cluster.logger.whitelist('warn', 'destroying socket from timeouts');
            cluster.logger.whitelist('warn', 'resetting connection');
            cluster.logger.whitelist('warn', 'Got a connection error');

            setTimeout(function onTimeout() {
                var logs = cluster.logger.items();
                assert.equal(
                    logs[0].msg, 'destroying socket from timeouts'
                );
                assert.equal(logs[1].msg, 'resetting connection');
                assert.equal(logs[2].msg, 'Got a connection error');

                deadServer.close();
                assert.end();
            }, 350);
        }
    }
});


text:
import scala.util.Properties

import sbt._

object Dependencies {
  def either(environmentVariable: String, default: String): String =
    Properties.envOrElse(environmentVariable, default)

  private val sprayVersion = Properties.envOrElse("SPRAY_VERSION", "1.3.3")

  // Cloudera's distribution of Spark 1.5 is built with Akka 2.2.x,
  // as opposed to the official release, which is built with Akka 2.3.x.
  // We need to have the spray version match the Akka version of Spark
  // or else MethodNotFound pain will ensue.
  val sprayRouting =
    if(sprayVersion == "1.2.3") {
      "io.spray"        % "spray-routing" % sprayVersion
    } else {
      "io.spray"        %% "spray-routing" % sprayVersion
    }

  val sprayCan =
    if(sprayVersion == "1.2.3") {
      "io.spray"        % "spray-can" % sprayVersion
    } else {
      "io.spray"        %% "spray-can" % sprayVersion
    }
}


text:
package org.adrenalinee.stomp.listener;

import org.adrenalinee.stomp.StompHeaders;

/**
 *
 * @author 신동성
 * @since 2015. 11. 6.
 */
public interface SubscribeHandler {

	void onReceived(final Object payload, StompHeaders stompHeaders);
}


text:
nscrapy is a node crawler framework inspired by scrapy,
it providers a webui for specific configuration when introduce new data source.


text:
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <title>test</title>
        <link rel="icon" type="image/png" sizes="96x96" href="favicon2.jpg">
        <link rel="stylesheet" type="text/css" href="test.css">

<input id="idInput" class="text-center" type="text">

Product by ID

All Products

Category by ID

All Categories


text:
package com.vladkel.eFindMe.bing.results;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Results {

	private Result[] results;

	public List<Result> getResultsAsList() {
		return new ArrayList<Result>(Arrays.asList(results));
	}

	public Result[] getResults() {
		return results;
	}

	public void setResults(Result[] results) {
		this.results = results;
	}
}


text:
package com.geccocrawler.gecco.redis;

import com.geccocrawler.gecco.GeccoEngine;
import com.geccocrawler.gecco.annotation.Gecco;
import com.geccocrawler.gecco.annotation.Href;
import com.geccocrawler.gecco.annotation.HtmlField;
import com.geccocrawler.gecco.annotation.Request;
import com.geccocrawler.gecco.annotation.RequestParameter;
import com.geccocrawler.gecco.annotation.Text;
import com.geccocrawler.gecco.request.HttpRequest;
import com.geccocrawler.gecco.spider.HtmlBean;

@Gecco(matchUrl="https://github.com/{user}/{project}", pipelines="consolePipeline")
public class MyGithub implements HtmlBean {

	private static final long serialVersionUID = -7127412585200687225L;

	@Request
	private HttpRequest request;

	@RequestParameter("user")
	private String user;

	@RequestParameter("project")
	private String project;

	@Text
	@HtmlField(cssPath=".repository-meta-content")
	private String title;

	@Text
	@HtmlField(cssPath=".pagehead-actions li:nth-child(2) .social-count")
	private int star;

	@Text
	@HtmlField(cssPath=".pagehead-actions li:nth-child(3) .social-count")
	private int fork;

	@Href(click=false)
	@HtmlField(cssPath="ul.numbers-summary > li:nth-child(4) > a")
	private String contributors;

	@HtmlField(cssPath=".entry-content")
	private String readme;

	public HttpRequest getRequest() {
		return request;
	}

	public void setRequest(HttpRequest request) {
		this.request = request;
	}

	public String getReadme() {
		return readme;
	}

	public void setReadme(String readme) {
		this.readme = readme;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getProject() {
		return project;
	}

	public void setProject(String project) {
		this.project = project;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getStar() {
		return star;
	}

	public void setStar(int star) {
		this.star = star;
	}

	public int getFork() {
		return fork;
	}

	public void setFork(int fork) {
		this.fork = fork;
	}

	public String getContributors() {
		return contributors;
	}

	public void setContributors(String contributors) {
		this.contributors = contributors;
	}

	public static void main(String[] args) {
		GeccoEngine.create()
		.scheduler(new RedisStartScheduler("127.0.0.1:6379"))
		.classpath("com.geccocrawler.gecco.demo")
		.start("https://github.com/xtuhcy/gecco")
		.interval(3000)
		.run();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="ArticleScrap">

	<resultMap id="scrapList" type="egovframework.com.cop.scp.service.ScrapVO">
		<result property="scrapId" column="SCRAP_ID"/>
		<result property="nttId" column="NTT_ID"/>
		<result property="bbsId" column="BBS_ID"/>
		<result property="scrapNm" column="SCRAP_NM"/>
		<result property="useAt" column="USE_AT"/>
		<result property="frstRegisterPnttm" column="FRST_REGIST_PNTTM"/>
		<result property="frstRegisterNm" column="FRST_REGISTER_NM"/>
	</resultMap>

	<resultMap id="scrapDetail" type="egovframework.com.cop.scp.service.ScrapVO">
		<result property="scrapId" column="SCRAP_ID"/>
		<result property="nttId" column="NTT_ID"/>
		<result property="bbsId" column="BBS_ID"/>
		<result property="scrapNm" column="SCRAP_Nm"/>
		<result property="useAt" column="USE_AT"/>
		<result property="frstRegisterPnttm" column="FRST_REGIST_PNTTM"/>
		<result property="frstRegisterNm" column="FRST_REGISTER_NM"/>
		<result property="frstRegisterId" column="FRST_REGISTER_ID"/>
	</resultMap>

	<select id="selectArticleScrapList" parameterType="egovframework.com.cop.scp.service.ScrapVO" resultMap="scrapList">

			SELECT
				a.SCRAP_ID, a.NTT_ID, a.BBS_ID,
				a.SCRAP_NM, a.USE_AT,
				TO_CHAR(a.FRST_REGIST_PNTTM, 'YYYYmmdd')
				as FRST_REGIST_PNTTM,
				b.USER_NM as FRST_REGISTER_NM
			FROM
				COMTNSCRAP a
			LEFT OUTER JOIN COMVNUSERMASTER b
				ON a.FRST_REGISTER_ID = b.ESNTL_ID
			WHERE
				a.USE_AT = 'Y'
			AND
				a.FRST_REGISTER_ID = #{uniqId}

			<if test="searchCnd == 0">AND
					a.SCRAP_NM LIKE CONCAT ('%', #{searchWrd},'%')
			</if>

			ORDER BY a.FRST_REGIST_PNTTM ASC
			LIMIT #{recordCountPerPage} OFFSET #{firstIndex}

	</select>

	<select id="selectArticleScrapListCnt" parameterType="egovframework.com.cop.scp.service.ScrapVO" resultType="java.lang.Integer">

			SELECT
				COUNT(SCRAP_ID)
			FROM
				COMTNSCRAP
			WHERE
				USE_AT = 'Y'
			AND
				FRST_REGISTER_ID = #{uniqId}

			<if test="searchCnd == 0">AND
					SCRAP_NM LIKE CONCAT ('%', #{searchWrd},'%')
			</if>
	</select>

	<insert id="insertArticleScrap" parameterType="egovframework.com.cop.scp.service.ScrapVO">

			INSERT INTO COMTNSCRAP
			(SCRAP_ID, NTT_ID, BBS_ID, SCRAP_NM, USE_AT,
			 FRST_REGISTER_ID, FRST_REGIST_PNTTM
			 )
			VALUES
			( #{scrapId}, #{nttId}, #{bbsId}, #{scrapNm}, 'Y',
			  #{frstRegisterId}, NOW()
			 )

	</insert>

	<update id="deleteArticleScrap" parameterType="egovframework.com.cop.scp.service.ScrapVO">

			UPDATE COMTNSCRAP
			SET USE_AT = 'N'
			WHERE SCRAP_ID = #{scrapId}

	</update>

	<select id="selectArticleScrapDetail" parameterType="egovframework.com.cop.scp.service.ScrapVO" resultMap="scrapDetail">

			SELECT
				a.SCRAP_ID, a.NTT_ID, a.BBS_ID,
				a.SCRAP_NM, a.USE_AT,
				TO_CHAR(a.FRST_REGIST_PNTTM, 'YYYYmmdd')
				as FRST_REGIST_PNTTM,
				b.USER_NM as FRST_REGISTER_NM,
				a.FRST_REGISTER_ID
			FROM
				COMTNSCRAP a
			LEFT OUTER JOIN COMVNUSERMASTER b
				ON a.FRST_REGISTER_ID = b.ESNTL_ID
			WHERE
				a.SCRAP_ID = #{scrapId}

	</select>

 	 <update id="updateArticleScrap" parameterType="egovframework.com.cop.scp.service.ScrapVO">

			UPDATE COMTNSCRAP SET
				SCRAP_NM = #{scrapNm},
				LAST_UPDUSR_ID = #{lastUpdusrId},
				LAST_UPDT_PNTTM = NOW()
			WHERE SCRAP_ID = #{scrapId}

 	</update>
</mapper>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>this is progressive jpeg by jptran</title>
</head>
<body style="background: url(../images/mountain-progressive-jptran.jpg) no-repeat;background-size: auto">

</body>
</html>


text:
/**
 * Created by duo on 2016/9/1.
 */
CMD.register("event.EventManager", function (require) {
    var StorageType = require("storage.StorageType");

    function EventManager(nativeBridge, request) {
        this._nativeBridge = nativeBridge;
        this._request = request;
    }
    EventManager.getSessionKey = function (sessionId) {
        return "session." + sessionId;
    };
    EventManager.getSessionTimestampKey = function (sessionId) {
        return EventManager.getSessionKey(sessionId) + ".ts";
    };
    EventManager.getEventKey = function (sessionId, eventId) {
        return EventManager.getSessionKey(sessionId) + ".operative." + eventId;
    };
    EventManager.getUrlKey = function (sessionId, eventId) {
        return EventManager.getEventKey(sessionId, eventId) + ".url";
    };
    EventManager.getDataKey = function (sessionId, eventId) {
        return EventManager.getEventKey(sessionId, eventId) + ".data";
    };
    EventManager.prototype.operativeEvent = function (eventName, eventId, sessionId, eventUrl, metaDataStr) {
        var me = this;
        this._nativeBridge.Sdk.logInfo("OneWay SDK event: sending " + eventName + " event to " + eventUrl);
        this._nativeBridge.Storage.set(StorageType.PRIVATE, EventManager.getUrlKey(sessionId, eventId), eventUrl);
        this._nativeBridge.Storage.set(StorageType.PRIVATE, EventManager.getDataKey(sessionId, eventId), metaDataStr);
        this._nativeBridge.Storage.write(StorageType.PRIVATE);
        return this._request.post(eventUrl, metaDataStr, [], {
            retries: 5,
            retryDelay: 5e3,
            followRedirects: false,
            retryWithConnectionEvents: false
        }).then(function () {
            return Promise.all([
                me._nativeBridge.Storage["delete"](StorageType.PRIVATE, EventManager.getEventKey(sessionId, eventId)),
                me._nativeBridge.Storage.write(StorageType.PRIVATE)
            ]);
        });
    };
    EventManager.prototype.clickAttributionEvent = function (sessionId, clickAttributionUrl, clickAttributionUrlFollowsRedirects) {
        if(clickAttributionUrlFollowsRedirects){
            return this._request.get(clickAttributionUrl, [], {
                retries: 0,
                retryDelay: 0,
                followRedirects: true,
                retryWithConnectionEvents: false
            })
        }else{
            return this._request.get(clickAttributionUrl);
        }
    };
    EventManager.prototype.thirdPartyEvent = function (eventName, sessionId, eventUrl) {
        this._nativeBridge.Sdk.logInfo("OneWay SDK third party event: sending " + eventName + " event to " + eventUrl + " (session " + sessionId + ")");
        return this._request.get(eventUrl, [], {
            retries: 0,
            retryDelay: 0,
            followRedirects: true,
            retryWithConnectionEvents: false
        });
    };
    EventManager.prototype.diagnosticEvent = function (url, data) {
        return this._request.post(url, data);
    };
    EventManager.prototype.startNewSession = function (id) {
        return Promise.all([this._nativeBridge.Storage.set(StorageType.PRIVATE, EventManager.getSessionTimestampKey(id), Date.now()), this._nativeBridge.Storage.write(StorageType.PRIVATE)]);
    };
    /**
     * 发送所有未发送过的session信息,成功后删除Storage信息
     * @returns {Promise}
     */
    EventManager.prototype.sendUnsentSessions = function () {
        var me = this;
        return this.getUnsentSessions().then(function (sessionIds) {
            var n = sessionIds.map(function (sessionId) {
                return me.isSessionOutdated(sessionId).then(function (isOutdated) {
                    if(isOutdated){
                        return me.deleteSession(sessionId)
                    }else{
                        return me.getUnsentOperativeEvents(sessionId).then(function (events) {
                            return Promise.all(events.map(function (eventId) {
                                return me.resendEvent(sessionId, eventId);
                            }));
                        });
                    }
                });
            });
            return Promise.all(n);
        });
    };
    EventManager.prototype.getUniqueEventId = function () {
        return this._nativeBridge.DeviceInfo.getUniqueEventId();
    };
    EventManager.prototype.getUnsentSessions = function () {
        return this._nativeBridge.Storage.getKeys(StorageType.PRIVATE, "session", false);
    };
    /**
     * session是否过期,过期时间为7天
     * @param sessionId {String}
     * @returns {Promise} resolve(boolean) | reject(true)
     */
    EventManager.prototype.isSessionOutdated = function (sessionId) {
        return this._nativeBridge.Storage.get(StorageType.PRIVATE, EventManager.getSessionTimestampKey(sessionId)).then(function (timestamp) {
            var sevenDaysBefore = new Date().getTime() - 6048e5,
                now = new Date().getTime();
            return !(timestamp > sevenDaysBefore && now > timestamp);
        })["catch"](function () {
            return true;
        });
    };
    /**
     * 获取所有未发送的事件id
     * @param sessionId
     * @returns {Promise} resolve(events:Array)
     */
    EventManager.prototype.getUnsentOperativeEvents = function (sessionId) {
        return this._nativeBridge.Storage.getKeys(StorageType.PRIVATE, "session." + sessionId + ".operative", false);
    };
    /**
     * 发送事件到native,成功后删除Storage的事件记录
     * @param sessionId {String}
     * @param eventId   {String}
     * @returns {Promise} resolve([storageType:String, storageType:String])
     */
    EventManager.prototype.resendEvent = function (sessionId, eventId) {
        var me = this;
        return this.getStoredOperativeEvent(sessionId, eventId).then(function (res) {
            var url = res[0], data = res[1];
            me._nativeBridge.Sdk.logInfo("OneWay SDK operative event: resending operative event to " + url + " (session " + sessionId + ", event " + eventId + ")");
            return me._request.post(url, data);
        }).then(function () {
            return Promise.all([
                me._nativeBridge.Storage["delete"](StorageType.PRIVATE, EventManager.getEventKey(sessionId, eventId)),
                me._nativeBridge.Storage.write(StorageType.PRIVATE)
            ]);
        });
    };
    EventManager.prototype.getStoredOperativeEvent = function (sessionId, eventId) {
        return Promise.all([
            this._nativeBridge.Storage.get(StorageType.PRIVATE, EventManager.getUrlKey(sessionId, eventId)),
            this._nativeBridge.Storage.get(StorageType.PRIVATE, EventManager.getDataKey(sessionId, eventId))
        ]);
    };
    EventManager.prototype.deleteSession = function (sessionId) {
        return Promise.all([
            this._nativeBridge.Storage["delete"](StorageType.PRIVATE, EventManager.getSessionKey(sessionId)),
            this._nativeBridge.Storage.write(StorageType.PRIVATE)]);
    };
    return EventManager;
});


text:
package com.amazonaws.services.cloudsearch.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.cloudsearch.AmazonCloudSearch#describeIndexFields(DescribeIndexFieldsRequest) DescribeIndexFields operation}.
 *

 * Gets information about the index fields configured for the search domain. Can be limited to specific fields by name. Shows all fields by default.
 *

 *
 * @see com.amazonaws.services.cloudsearch.AmazonCloudSearch#describeIndexFields(DescribeIndexFieldsRequest)
 * @deprecated Use {@link com.amazonaws.services.cloudsearchv2.model.DescribeIndexFieldsRequest} instead.
 */
@Deprecated
public class DescribeIndexFieldsRequest extends AmazonWebServiceRequest implements Serializable {

    /**
     * A string that represents the name of a domain. Domain names must be
     * unique across the domains owned by an account within an AWS region.
     * Domain names must start with a letter or number and can contain the
     * following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     * letters and underscores are not allowed.
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     */
    private String domainName;

    /**
     * Limits the DescribeIndexFields response to the specified
     * fields.
     */
    private com.amazonaws.internal.ListWithAutoConstructFlag<String> fieldNames;

    /**
     * A string that represents the name of a domain. Domain names must be
     * unique across the domains owned by an account within an AWS region.
     * Domain names must start with a letter or number and can contain the
     * following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     * letters and underscores are not allowed.
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     *
     * @return A string that represents the name of a domain. Domain names must be
     *         unique across the domains owned by an account within an AWS region.
     *         Domain names must start with a letter or number and can contain the
     *         following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     *         letters and underscores are not allowed.
     */
    public String getDomainName() {
        return domainName;
    }

    /**
     * A string that represents the name of a domain. Domain names must be
     * unique across the domains owned by an account within an AWS region.
     * Domain names must start with a letter or number and can contain the
     * following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     * letters and underscores are not allowed.
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     *
     * @param domainName A string that represents the name of a domain. Domain names must be
     *         unique across the domains owned by an account within an AWS region.
     *         Domain names must start with a letter or number and can contain the
     *         following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     *         letters and underscores are not allowed.
     */
    public void setDomainName(String domainName) {
        this.domainName = domainName;
    }

    /**
     * A string that represents the name of a domain. Domain names must be
     * unique across the domains owned by an account within an AWS region.
     * Domain names must start with a letter or number and can contain the
     * following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     * letters and underscores are not allowed.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 3 - 28

     * Pattern: [a-z][a-z0-9\-]+

     *
     * @param domainName A string that represents the name of a domain. Domain names must be
     *         unique across the domains owned by an account within an AWS region.
     *         Domain names must start with a letter or number and can contain the
     *         following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase
     *         letters and underscores are not allowed.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeIndexFieldsRequest withDomainName(String domainName) {
        this.domainName = domainName;
        return this;
    }

    /**
     * Limits the DescribeIndexFields response to the specified
     * fields.
     *
     * @return Limits the DescribeIndexFields response to the specified
     *         fields.
     */
    public java.util.List<String> getFieldNames() {
        if (fieldNames == null) {
              fieldNames = new com.amazonaws.internal.ListWithAutoConstructFlag<String>();
              fieldNames.setAutoConstruct(true);
        }
        return fieldNames;
    }

    /**
     * Limits the DescribeIndexFields response to the specified
     * fields.
     *
     * @param fieldNames Limits the DescribeIndexFields response to the specified
     *         fields.
     */
    public void setFieldNames(java.util.Collection<String> fieldNames) {
        if (fieldNames == null) {
            this.fieldNames = null;
            return;
        }
        com.amazonaws.internal.ListWithAutoConstructFlag<String> fieldNamesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(fieldNames.size());
        fieldNamesCopy.addAll(fieldNames);
        this.fieldNames = fieldNamesCopy;
    }

    /**
     * Limits the DescribeIndexFields response to the specified
     * fields.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param fieldNames Limits the DescribeIndexFields response to the specified
     *         fields.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeIndexFieldsRequest withFieldNames(String... fieldNames) {
        if (getFieldNames() == null) setFieldNames(new java.util.ArrayList<String>(fieldNames.length));
        for (String value : fieldNames) {
            getFieldNames().add(value);
        }
        return this;
    }

    /**
     * Limits the DescribeIndexFields response to the specified
     * fields.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param fieldNames Limits the DescribeIndexFields response to the specified
     *         fields.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DescribeIndexFieldsRequest withFieldNames(java.util.Collection<String> fieldNames) {
        if (fieldNames == null) {
            this.fieldNames = null;
        } else {
            com.amazonaws.internal.ListWithAutoConstructFlag<String> fieldNamesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(fieldNames.size());
            fieldNamesCopy.addAll(fieldNames);
            this.fieldNames = fieldNamesCopy;
        }

        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDomainName() != null) sb.append("DomainName: " + getDomainName() + ",");
        if (getFieldNames() != null) sb.append("FieldNames: " + getFieldNames() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDomainName() == null) ? 0 : getDomainName().hashCode());
        hashCode = prime * hashCode + ((getFieldNames() == null) ? 0 : getFieldNames().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof DescribeIndexFieldsRequest == false) return false;
        DescribeIndexFieldsRequest other = (DescribeIndexFieldsRequest)obj;

        if (other.getDomainName() == null ^ this.getDomainName() == null) return false;
        if (other.getDomainName() != null && other.getDomainName().equals(this.getDomainName()) == false) return false;
        if (other.getFieldNames() == null ^ this.getFieldNames() == null) return false;
        if (other.getFieldNames() != null && other.getFieldNames().equals(this.getFieldNames()) == false) return false;
        return true;
    }

}


text:
package com.github.kentama7.bleague_live_score.crawler.b2;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.StringJoiner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.github.kentama7.bleague_live_score.mastodon.Mastodon;

import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;

public class BigBullsCrawler extends WebCrawler {
    public static final String BIGBULLS_URL = "http://sportsnavi.ht.kyodo-d.jp/basketball/stats/bleague/teams/schedule/709/";
    public static String CACHE_SCORE = "";

    @Override
    public boolean shouldVisit(Page referringPage, WebURL url) {
        // TOPのみクロール対象とする
        String href = url.getURL();
        return href.equals(BIGBULLS_URL);
    }

    @Override
    public void visit(Page page) {
        String url = page.getWebURL().getURL();
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("M/d"));
        // BigBullsページのみ処理する
        if (url.equals(BIGBULLS_URL)) {
            HtmlParseData data = HtmlParseData.class.cast(page.getParseData());
            // ページのHTMLをJsoupでパース
            Document doc = Jsoup.parse(data.getHtml());
            Element scheduleTable = doc.select("#modBleagueSchedule03 div.partsTable").get(0);
            Elements rows = scheduleTable.getElementsByTag("tr");
            rows.forEach(row -> {
                String date = getElementTextByClass(row, "date");
                String score = getElementTextByClass(row, "score");
                if (!isGameDay(date, today) || isCached(score)) {
                    return;
                }

                String victoryOrDefeat = victoryOrDefeat(row);
                CACHE_SCORE = score;
                String section = getElementTextByClass(row, "cat");
                String place = getElementTextByClass(row, "place");
                String opposition = getElementTextByClass(row, "team").replace("岩手ビッグブルズ", "").trim();

                StringJoiner joiner = new StringJoiner("\n");
                joiner.add(score + victoryOrDefeat);
                joiner.add("vs." + opposition);
                if (place.equals("試合前")) {
                    joiner.add(section + "@" + place);
                }
                joiner.add("#岩手ビッグブルズ #Bリーグ");
                try {
                    Mastodon.toot(joiner.toString());
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(score + victoryOrDefeat);
                System.out.println("vs." + opposition);
                System.out.println(section + "@" + place);
                System.out.println("------------------");
            });
        }
    }

    private static String getElementTextByClass(Element element, String className) {
        return element.getElementsByClass(className).text().trim();
    }

    private boolean isGameDay(String date, String today) {
        return date.startsWith(today);
    }

    private boolean isCached(String score) {
        return score.equals(CACHE_SCORE);
    }

    private static String victoryOrDefeat(Element element) {
        String victoryOrDefeat = getElementTextByClass(element, "win");
        switch (victoryOrDefeat) {
        case "○":
            victoryOrDefeat = " 勝利💪🏼";
            break;
        case "●":
            victoryOrDefeat = " 敗北😭";
            break;
        default:
            break;
        }
        return victoryOrDefeat;
    }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.permission;

import android.net.Uri;

import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content.common.CleanupReference;

/**
 * This class wraps permission request in Chromium side, and can only be created
 * by native side.
 */
@JNINamespace("android_webview")
public class AwPermissionRequest {
    private final Uri mOrigin;
    private final long mResources;
    private boolean mProcessed;

    // AwPermissionRequest native instance.
    private long mNativeAwPermissionRequest;

    // Responsible for deleting native peer.
    private CleanupReference mCleanupReference;

    // This should be same as corresponding definition in PermissionRequest.
    // We duplicate definition because it is used in Android L and afterwards, but is only
    // defined in M.
    // TODO(michaelbai) : Replace "android.webkit.resoruce.MIDI_SYSEX" with
    // PermissionRequest.RESOURCE_MIDI_SYSEX once Android M SDK is used.
    public static final String RESOURCE_MIDI_SYSEX = "android.webkit.resource.MIDI_SYSEX";

    private static final class DestroyRunnable implements Runnable {
        private final long mNativeAwPermissionRequest;

        private DestroyRunnable(long nativeAwPermissionRequest) {
            mNativeAwPermissionRequest = nativeAwPermissionRequest;
        }
        @Override
        public void run() {
            nativeDestroy(mNativeAwPermissionRequest);
        }
    }

    @CalledByNative
    private static AwPermissionRequest create(long nativeAwPermissionRequest, String url,
            long resources) {
        if (nativeAwPermissionRequest == 0) return null;
        Uri origin = Uri.parse(url);
        return new AwPermissionRequest(nativeAwPermissionRequest, origin, resources);
    }

    private AwPermissionRequest(long nativeAwPermissionRequest, Uri origin,
            long resources) {
        mNativeAwPermissionRequest = nativeAwPermissionRequest;
        mOrigin = origin;
        mResources = resources;
        mCleanupReference =
                new CleanupReference(this, new DestroyRunnable(mNativeAwPermissionRequest));
    }

    public Uri getOrigin() {
        return mOrigin;
    }

    public long getResources() {
        return mResources;
    }

    public void grant() {
        validate();
        if (mNativeAwPermissionRequest != 0) {
            nativeOnAccept(mNativeAwPermissionRequest, true);
            destroyNative();
        }
        mProcessed = true;
    }

    public void deny() {
        validate();
        if (mNativeAwPermissionRequest != 0) {
            nativeOnAccept(mNativeAwPermissionRequest, false);
            destroyNative();
        }
        mProcessed = true;
    }

    @CalledByNative
    private void destroyNative() {
        mCleanupReference.cleanupNow();
        mCleanupReference = null;
        mNativeAwPermissionRequest = 0;
    }

    private void validate() {
        if (!ThreadUtils.runningOnUiThread())
            throw new IllegalStateException(
                    "Either grant() or deny() should be called on UI thread");

        if (mProcessed)
            throw new IllegalStateException("Either grant() or deny() has been already called.");
    }

    private native void nativeOnAccept(long nativeAwPermissionRequest, boolean allowed);
    private static native void nativeDestroy(long nativeAwPermissionRequest);
}


text:
/*globals require, module */

var request = require('request'),
    _ = require('lodash');

var getBaseUrl = function (cameraConfiguration) {
  return 'http://' + cameraConfiguration.ip;
};

var call = function (cameraConfiguration, serviceUrl, callback){
  var url = getBaseUrl(cameraConfiguration) + '/' + serviceUrl;
  console.log('Calling url: ' + url);
  request
  .get(url, function (err, res, body) {
     if (!_.isUndefined(callback)) {callback(err, res, body)}
  })
  .auth(cameraConfiguration.username, cameraConfiguration.password, false);
};

module.exports = {
  getBaseUrl: getBaseUrl,
  call: call
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">

        <title>PIDS Installation Guide</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >

Persistent Identifier Service (PIDS) Installation Guide

Pre-requisites

The following software must be avilable in order to install and run the Harvester Service:

Sun's Java 1.5 SDK

Postgres 8.3

Apache Ant

Apache Tomcat 5.x or later

A Local Handle Server registered with CNRI using the default SQL schema in a Postgres database

PIDS was developed to be platform-independent. This distribution has been tested on Mac OS X and RedHat Enterprise Server 4.0.

PIDS Install process

If setting up a local handle server, ensure the database connection information is configured in the handle server's config.dct directory. For example:

storage_type = "sql"
sql_settings = {
sql_url = "jdbc:postgresql://localhost:5432/pids"
sql_driver = "org.postgresql.Driver"
sql_login = "pidmaster"
sql_passwd = "my-password"
sql_read_only = "no"
}

login as the database administrator

Create a database user (pidmaster in this example):
createuser -P pidmaster
and assign a password to the user. Do not make the user a superuser and answer 'n' to all prompts

Create a new database called 'pids':
createdb --encoding="UTF-8" pids

Alter the single INSERT statement at the bottom of $PIDS_SOURCE/etc/database/postgres/database.sql by replacing my_prefix with the existing local handle server's registered prefix

Alter the user in the GRANT statements at the bottom of $PIDS_SOURCE/etc/database/postgres/database.sql to the correct database user (default is pidmaster)

Create the tables and indices:
psql -d pids < $PIDS_SOURCE/etc/database/postgres/database.sql

Ensure servlet-api.jar is in the CLASSPATH. This should be found somewhere in the common library directories of the Tomcat install

Copy the existing Local Handler Server's handle.jar to the $PIDS_SOURCE/lib directory

Build the distribution:
cd $PIDS_SOURCE

ant -Dconfig-dir=<handle config dir> -Dprefix=<registered handle prefix> -Dadmin-ip=<IP of admin server or desktop> build_wars

Configure the default Tomcat datasource (connection pooling) by adding the following entry to the server.xml file's Host element:

<Context path="/pids" docBase="pids" crossContext="true" reloadable="true" debug="1">

                    <Resource name="jdbc/postgres" auth="Container" type="javax.sql.DataSource" driverClassName="org.postgresql.Driver" url="jdbc:postgresql://my-server-ip:5432/pids" username="pidmaster"/>

        </Context>

Ensure the IP and port number in the url attribute reflect the server setup and ensure the pids database user is correctly configured in the Postgres pg_hba.conf</file>.

Download and copy the appropriate postgres jar file to the Tomcat lib directory

Deploy pids.war to the Tomcat webapps directory

It is recommended this service be used only over secure (SSL) connections

Testing and Initialising PIDS

NB: PIDS is a web application intended to be integrated with other applications and as such does not provide a user interface.

Once installed, to ensure PIDS is running try accessing http://localhost:8080/pids/mint. If PIDS is installed correctly this should produce an error response in XML form.

Depending on how PIDS is to be used an initial administrator needs to be registered. For example, if services are to be called via a UI or automated application, then an agent respresenting the UI or application must be registered. To do this use the addTrustedClient service providing the IP address of the trusted client. For example
http://localhost:8080/pids/addClient?ip=111.111.111.111. The XML response will include the application id (appId) for this client.

IMPORTANT: This service should only be run from a secure machine whose IP address is specified at build time and will appear in the web.xml entry for this servlet.

Services

Refer to the javadocs (run ant javadoc to generate these) for details
        on the available services.

Javadocs

The javadocs can be built by running ant javadoc


text:
module Lightbox2
  module Rails
    class Engine < ::Rails::Engine
    end
  end
end


text:
.. Root of VBA API

VBA API
=======

*More to be added here; this is just the beginnings of a skeleton...*

Contents:

.. toctree::
   :maxdepth: 1

   assert
   matrix


text:
package org.bychan.core.langs.json;

import org.bychan.core.basic.*;
import org.bychan.core.dynamic.Language;
import org.bychan.core.dynamic.LanguageBuilder;
import org.bychan.core.langs.json.nodes.*;
import org.bychan.core.utils.StringUtils;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;

public class JsonTest {

    @Test
    public void simpleStringLiteral() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("\"hello\"", p -> p.expr(null, 0)).root();
        assertEquals(new StringLiteralNode("hello"), ast);
    }

    @Test
    public void stringWithQuoteEscape() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("\"\\\"hello\"", p -> p.expr(null, 0)).root();
        assertEquals(new StringLiteralNode("\\\"hello"), ast);
    }

    @Test
    public void stringWithQuotedBackslash() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("\"\\\\\"", p -> p.expr(null, 0)).root();
        assertEquals(new StringLiteralNode("\\\\"), ast);
    }

    @Test
    public void stringWithUnicodeLiteral() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("\"\\uabCD\"", p -> p.expr(null, 0)).root();
        assertEquals(new StringLiteralNode("\\uabCD"), ast);
    }

    @Test
    public void stringWithCrazyText() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        String crazy = "6U閆崬밺뀫颒myj츥휘\uECED:$薈mY햚#\uF6A2rz飏+玭V㭢뾿愴Y\uEC11ꖚX亥ᮉ푊\\u0006垡㐭룝\\\"厓ᔧḅ^Sqpv媫\\\"⤽걒\\\"˽Ἆ?ꇆ䬔未tv{DV鯀Tἆl凸g\\\\㈭ĭ즿UH㽤";
        JsonNode ast = l.newLexParser().tryParse("\"" + crazy + "\"", p -> p.expr(null, 0)).root();
        assertEquals(new StringLiteralNode(crazy), ast);
    }

    @Test
    public void stringWithAnotherCrazyText() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        String crazy = "e\uE7A1浱u\uEFE3p\u007F蔽Cr\u0DE0JK軵xCʨ<뜡癙Y獩ケ齈X/螗唻\uEB3F?<蘡+뷄㩤쳖3偑犾&\\\\첊xz坍崦ݻ\uE2D1鍴\\\"嵥B3㰃詤豺嚼aqJ⑆∥韼@\\u000b㢊\\u0015L臯.샥";
        JsonNode ast = l.newLexParser().tryParse("\"" + crazy + "\"", p -> p.expr(null, 0)).root();
        assertEquals(new StringLiteralNode(crazy), ast);
    }

    @Test
    public void stringWithInvalidEscape() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.stringLiteral(lb);
        Language<JsonNode> l = lb.build();
        String indata = "\"\\phello\"";
        ParseResult<JsonNode> pr = l.newLexParser().tryParse(indata, p -> p.expr(null, 0));
        //noinspection unchecked
        Lexeme<JsonNode> mockLexeme = mock(Lexeme.class);
        LexingPosition<JsonNode> lexingPosition = new LexingPosition<>(StringUtils.getTextPosition(indata, 0), indata, mockLexeme);
        LexingFailedInformation pfi = new LexingFailedInformation("No matching rule", lexingPosition);
        assertEquals(pfi, pr.getErrorMessage());
    }

    @Test
    public void positiveInteger() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.numberLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("1", p -> p.expr(null, 0)).root();
        assertEquals(NumberLiteralNode.fromFloat(1), ast);
    }

    @Test
    public void negativeExponent() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.numberLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("-0.5e-5", p -> p.expr(null, 0)).root();
        assertEquals(new NumberLiteralNode("-0.5e-5"), ast);
    }

    @Test
    public void leadingZeroesForbidden() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.numberLiteral(lb);
        Language<JsonNode> l = lb.build();
        try {
            l.newLexParser().tryParse("01.5", p -> p.expr(null, 0)).root();
            fail("Expected exception");
        } catch (ParsingFailedException e) {
            FailureInformation actual = e.getFailureInformation();
            assertEquals("Parsing failed: 'Current token does not support led parsing' @  position 1:2 (index 1), current lexeme is number_literal(1.5), previous was number_literal(0), and remaining are [END]", actual.toString());
        }
    }

    @Test
    public void bool() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.boolLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("true", p -> p.expr(null, 0)).root();
        assertEquals(new BooleanLiteralNode(true), ast);
    }

    @Test
    public void nul() {
        LanguageBuilder<JsonNode> lb = new LanguageBuilder<>();
        JsonLangBuilder.nullLiteral(lb);
        Language<JsonNode> l = lb.build();
        JsonNode ast = l.newLexParser().tryParse("null", p -> p.expr(null, 0)).root();
        assertEquals(NullLiteral.get(), ast);
    }

    @Test
    public void emptyArray() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse("[]", p -> p.expr(null, 0)).root();
        assertEquals(new ArrayNode(Collections.emptyList()), ast);
    }

    @Test
    public void singleElementArray() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse("[3]", p -> p.expr(null, 0)).root();
        assertEquals(new ArrayNode(Collections.singletonList(NumberLiteralNode.fromFloat(3))), ast);
    }

    @Test
    public void multipleElementArray() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse("[3,2,4]", p -> p.expr(null, 0)).root();
        assertEquals(new ArrayNode(Arrays.asList(NumberLiteralNode.fromFloat(3), NumberLiteralNode.fromFloat(2), NumberLiteralNode.fromFloat(4))), ast);
    }

    @Test
    public void emptyObject() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse("{}", p -> p.expr(null, 0)).root();
        assertEquals(new ObjectNode(Collections.emptyMap()), ast);
    }

    @Test
    public void simpleObject() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse("{\"a\":3}", p -> p.expr(null, 0)).root();
        LinkedHashMap<StringLiteralNode, JsonNode> expected = new LinkedHashMap<>();
        expected.put(new StringLiteralNode("a"), NumberLiteralNode.fromFloat(3));
        assertEquals(new ObjectNode(expected), ast);
    }

    @Test
    public void nestedObject() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse("{\"a\":{\"b\":3}}", p -> p.expr(null, 0)).root();
        LinkedHashMap<StringLiteralNode, JsonNode> inner = new LinkedHashMap<>();
        inner.put(new StringLiteralNode("b"), NumberLiteralNode.fromFloat(3));
        LinkedHashMap<StringLiteralNode, JsonNode> outer = new LinkedHashMap<>();
        outer.put(new StringLiteralNode("a"), new ObjectNode(inner));
        assertEquals(new ObjectNode(outer), ast);
    }

    @Test
    public void whitespace() {
        Language<JsonNode> l = makeJson();
        JsonNode ast = l.newLexParser().tryParse(" { \"a\" :  3 }", p -> p.expr(null, 0)).root();
        LinkedHashMap<StringLiteralNode, JsonNode> outer = new LinkedHashMap<>();
        outer.put(new StringLiteralNode("a"), NumberLiteralNode.fromFloat(3));
        assertEquals(new ObjectNode(outer), ast);
    }

    @Test
    public void document() {
        Language<JsonNode> l = makeJson();
        String data = "{\n" +
                "    \"glossary\": {\n" +
                "        \"title\": \"example glossary\",\n" +
                "\t\t\"GlossDiv\": {\n" +
                "            \"title\": \"S\",\n" +
                "\t\t\t\"GlossList\": {\n" +
                "                \"GlossEntry\": {\n" +
                "                    \"ID\": \"SGML\",\n" +
                "\t\t\t\t\t\"SortAs\": \"SGML\",\n" +
                "\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n" +
                "\t\t\t\t\t\"Acronym\": \"SGML\",\n" +
                "\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\n" +
                "\t\t\t\t\t\"GlossDef\": {\n" +
                "                        \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n" +
                "\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\n" +
                "                    },\n" +
                "\t\t\t\t\t\"GlossSee\": \"markup\"\n" +
                "                }\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}\n";
        JsonNode ast = l.newLexParser().tryParse(data, p -> p.expr(null, 0)).root();
        String output = ast.prettyPrint(0);
        assertEquals("{\n" +
                "\"glossary\": {\n" +
                "  \"title\": \"example glossary\",\n" +
                "  \"GlossDiv\": {\n" +
                "    \"title\": \"S\",\n" +
                "    \"GlossList\": {\n" +
                "      \"GlossEntry\": {\n" +
                "        \"ID\": \"SGML\",\n" +
                "        \"SortAs\": \"SGML\",\n" +
                "        \"GlossTerm\": \"Standard Generalized Markup Language\",\n" +
                "        \"Acronym\": \"SGML\",\n" +
                "        \"Abbrev\": \"ISO 8879:1986\",\n" +
                "        \"GlossDef\": {\n" +
                "          \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n" +
                "          \"GlossSeeAlso\": [\"GML\", \"XML\"]\n" +
                "          },\n" +
                "        \"GlossSee\": \"markup\"\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}", output);
    }

    private Language<JsonNode> makeJson() {
        return new JsonLangBuilder().build();
    }

}


text:
FOUNDATION_EXPORT double PCLBlurEffectAlertVersionNumber;

//! Project version string for PCLBlurEffectAlert.
FOUNDATION_EXPORT const unsigned char PCLBlurEffectAlertVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <PCLBlurEffectAlert/PublicHeader.h>


text:
package fr.imie.tp.jsp;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.imie.archi.AbstractFactory;
import fr.imie.archi.ConcreteFactory;
import fr.imie.archi.DTO.PersonneDTO;
import fr.imie.archi.service.IEcoleService;

/**
 * Servlet implementation class UserFormServlet
 */
@WebServlet("/UserFormServlet")
public class UserFormServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserFormServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Recuperation du parametre envoyer par le client (?id=dfdsfdsfds)
		Integer id = Integer.valueOf(request.getParameter("id"));

		AbstractFactory factory = new ConcreteFactory();
		IEcoleService service = factory.createEcoleService();
		PersonneDTO userSelected = new PersonneDTO();
		userSelected.setId(id);
		userSelected = service.findPersonneById(userSelected);

		/*
		// Recuperation de la liste des DTO
		List<UserDTO> userDTOs = (List<UserDTO>)request.getSession().getAttribute("userDTOs");

		// Recherche du user correspond à l'id
		UserDTO userSelected=null;
		for (UserDTO userDTO : userDTOs)
		{
			if(userDTO.getId()==id)
			{
				userSelected=userDTO;
				break;
			}
		}
		*/

		// Forward du resultat à la jsp
		request.setAttribute("user", userSelected);
		request.getRequestDispatcher("/WEB-INF/UserForm.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TP10 : inclure un bouton pour updater
		String newPassword = request.getParameter("passwordInput");
		Integer id = Integer.valueOf(request.getParameter("id"));

		AbstractFactory factory = new ConcreteFactory();
		IEcoleService service = factory.createEcoleService();
		PersonneDTO personneToUpdate = new PersonneDTO();
		personneToUpdate.setId(id);
		personneToUpdate = service.findPersonneById(personneToUpdate);
		personneToUpdate.setPassword(newPassword);
		service.updatePersonne(personneToUpdate);

		/*
		List<UserDTO> userDTOs = (List<UserDTO>)request.getSession().getAttribute("userDTOs");
		UserDTO userToUpdate = null;
		for (UserDTO userDTO : userDTOs)
		{
			if( userDTO.getId() == id )
			{
				userToUpdate = userDTO;
				break;
			}
		}

		// MAJ du password dans la liste des user DTO
		userToUpdate.setPassword(newPassword);
		*/

		// Redirection du resultat à la servlet user list
		response.sendRedirect("UserListServlet");
	}
}