text:
"""Makes sure files have the right permissions.

Some developers have broken SCM configurations that flip the executable
permission on for no good reason. Unix developers who run ls --color will then
see .cc files in green and get confused.

- For file extensions that must be executable, add it to EXECUTABLE_EXTENSIONS.
- For file extensions that must not be executable, add it to
  NOT_EXECUTABLE_EXTENSIONS.
- To ignore all the files inside a directory, add it to IGNORED_PATHS.
- For file base name with ambiguous state and that should not be checked for
  shebang, add it to IGNORED_FILENAMES.

Any file not matching the above will be opened and looked if it has a shebang
or an ELF header. If this does not match the executable bit on the file, the
file will be flagged.

Note that all directory separators must be slashes (Unix-style) and not
backslashes. All directories should be relative to the source root and all
file paths should be only lowercase.
"""

import json
import logging
import optparse
import os
import stat
import string
import subprocess
import sys

#### USER EDITABLE SECTION STARTS HERE ####

# Files with these extensions must have executable bit set.
#
# Case-sensitive.
EXECUTABLE_EXTENSIONS = (
  'bat',
  'dll',
  'dylib',
  'exe',
)

# These files must have executable bit set.
#
# Case-insensitive, lower-case only.
EXECUTABLE_PATHS = (
  'chrome/test/data/app_shim/app_shim_32_bit.app/contents/'
      'macos/app_mode_loader',
  'chrome/test/data/extensions/uitest/plugins/plugin.plugin/contents/'
      'macos/testnetscapeplugin',
  'chrome/test/data/extensions/uitest/plugins_private/plugin.plugin/contents/'
      'macos/testnetscapeplugin',
)

# These files must not have the executable bit set. This is mainly a performance
# optimization as these files are not checked for shebang. The list was
# partially generated from:
# git ls-files | grep "\\." | sed 's/.*\.//' | sort | uniq -c | sort -b -g
#
# Case-sensitive.
NON_EXECUTABLE_EXTENSIONS = (
  '1',
  '3ds',
  'S',
  'am',
  'applescript',
  'asm',
  'c',
  'cc',
  'cfg',
  'chromium',
  'cpp',
  'crx',
  'cs',
  'css',
  'cur',
  'def',
  'der',
  'expected',
  'gif',
  'grd',
  'gyp',
  'gypi',
  'h',
  'hh',
  'htm',
  'html',
  'hyph',
  'ico',
  'idl',
  'java',
  'jpg',
  'js',
  'json',
  'm',
  'm4',
  'mm',
  'mms',
  'mock-http-headers',
  'nexe',
  'nmf',
  'onc',
  'pat',
  'patch',
  'pdf',
  'pem',
  'plist',
  'png',
  'proto',
  'rc',
  'rfx',
  'rgs',
  'rules',
  'spec',
  'sql',
  'srpc',
  'svg',
  'tcl',
  'test',
  'tga',
  'txt',
  'vcproj',
  'vsprops',
  'webm',
  'word',
  'xib',
  'xml',
  'xtb',
  'zip',
)

# These files must not have executable bit set.
#
# Case-insensitive, lower-case only.
NON_EXECUTABLE_PATHS = (
  'build/android/tests/symbolize/liba.so',
  'build/android/tests/symbolize/libb.so',
  'chrome/installer/mac/sign_app.sh.in',
  'chrome/installer/mac/sign_versioned_dir.sh.in',
  'chrome/test/data/extensions/uitest/plugins/plugin32.so',
  'chrome/test/data/extensions/uitest/plugins/plugin64.so',
  'chrome/test/data/extensions/uitest/plugins_private/plugin32.so',
  'chrome/test/data/extensions/uitest/plugins_private/plugin64.so',
  'courgette/testdata/elf-32-1',
  'courgette/testdata/elf-32-2',
  'courgette/testdata/elf-64',
)

# File names that are always whitelisted.  (These are mostly autoconf spew.)
#
# Case-sensitive.
IGNORED_FILENAMES = (
  'config.guess',
  'config.sub',
  'configure',
  'depcomp',
  'install-sh',
  'missing',
  'mkinstalldirs',
  'naclsdk',
  'scons',
)

# File paths starting with one of these will be ignored as well.
# Please consider fixing your file permissions, rather than adding to this list.
#
# Case-insensitive, lower-case only.
IGNORED_PATHS = (
  'native_client_sdk/src/build_tools/sdk_tools/third_party/fancy_urllib/'
      '__init__.py',
  'out/',
  # TODO(maruel): Fix these.
  'third_party/bintrees/',
  'third_party/closure_linter/',
  'third_party/devscripts/licensecheck.pl.vanilla',
  'third_party/hyphen/',
  'third_party/jemalloc/',
  'third_party/lcov-1.9/contrib/galaxy/conglomerate_functions.pl',
  'third_party/lcov-1.9/contrib/galaxy/gen_makefile.sh',
  'third_party/lcov/contrib/galaxy/conglomerate_functions.pl',
  'third_party/lcov/contrib/galaxy/gen_makefile.sh',
  'third_party/libevent/autogen.sh',
  'third_party/libevent/test/test.sh',
  'third_party/libxml/linux/xml2-config',
  'third_party/libxml/src/ltmain.sh',
  'third_party/mesa/',
  'third_party/protobuf/',
  'third_party/python_gflags/gflags.py',
  'third_party/sqlite/',
  'third_party/talloc/script/mksyms.sh',
  'third_party/tcmalloc/',
  'third_party/tlslite/setup.py',
  # TODO(nednguyen): Remove this when telemetry is moved to catapult
  'tools/telemetry/third_party/',
)

#### USER EDITABLE SECTION ENDS HERE ####

assert set(EXECUTABLE_EXTENSIONS) & set(NON_EXECUTABLE_EXTENSIONS) == set()
assert set(EXECUTABLE_PATHS) & set(NON_EXECUTABLE_PATHS) == set()

VALID_CHARS = set(string.ascii_lowercase + string.digits + '/-_.')
for paths in (EXECUTABLE_PATHS, NON_EXECUTABLE_PATHS, IGNORED_PATHS):
  assert all([set(path).issubset(VALID_CHARS) for path in paths])

def capture(cmd, cwd):
  """Returns the output of a command.

  Ignores the error code or stderr.
  """
  logging.debug('%s; cwd=%s' % (' '.join(cmd), cwd))
  env = os.environ.copy()
  env['LANGUAGE'] = 'en_US.UTF-8'
  p = subprocess.Popen(
      cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env)
  return p.communicate()[0]

def get_git_root(dir_path):
  """Returns the git checkout root or None."""
  root = capture(['git', 'rev-parse', '--show-toplevel'], dir_path).strip()
  if root:
    return root

def is_ignored(rel_path):
  """Returns True if rel_path is in our whitelist of files to ignore."""
  rel_path = rel_path.lower()
  return (
      os.path.basename(rel_path) in IGNORED_FILENAMES or
      rel_path.lower().startswith(IGNORED_PATHS))

def must_be_executable(rel_path):
  """The file name represents a file type that must have the executable bit
  set.
  """
  return (os.path.splitext(rel_path)[1][1:] in EXECUTABLE_EXTENSIONS or
          rel_path.lower() in EXECUTABLE_PATHS)

def must_not_be_executable(rel_path):
  """The file name represents a file type that must not have the executable
  bit set.
  """
  return (os.path.splitext(rel_path)[1][1:] in NON_EXECUTABLE_EXTENSIONS or
          rel_path.lower() in NON_EXECUTABLE_PATHS)

def has_executable_bit(full_path):
  """Returns if any executable bit is set."""
  permission = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
  return bool(permission & os.stat(full_path).st_mode)

def has_shebang_or_is_elf(full_path):
  """Returns if the file starts with #!/ or is an ELF binary.

  full_path is the absolute path to the file.
  """
  with open(full_path, 'rb') as f:
    data = f.read(4)
    return (data[:3] == '#!/' or data == '#! /', data == '\x7fELF')

def check_file(root_path, rel_path):
  """Checks the permissions of the file whose path is root_path + rel_path and
  returns an error if it is inconsistent. Returns None on success.

  It is assumed that the file is not ignored by is_ignored().

  If the file name is matched with must_be_executable() or
  must_not_be_executable(), only its executable bit is checked.
  Otherwise, the first few bytes of the file are read to verify if it has a
  shebang or ELF header and compares this with the executable bit on the file.
  """
  full_path = os.path.join(root_path, rel_path)
  def result_dict(error):
    return {
      'error': error,
      'full_path': full_path,
      'rel_path': rel_path,
    }
  try:
    bit = has_executable_bit(full_path)
  except OSError:
    # It's faster to catch exception than call os.path.islink(). Chromium
    # tree happens to have invalid symlinks under
    # third_party/openssl/openssl/test/.
    return None

  if must_be_executable(rel_path):
    if not bit:
      return result_dict('Must have executable bit set')
    return
  if must_not_be_executable(rel_path):
    if bit:
      return result_dict('Must not have executable bit set')
    return

  # For the others, it depends on the file header.
  (shebang, elf) = has_shebang_or_is_elf(full_path)
  if bit != (shebang or elf):
    if bit:
      return result_dict('Has executable bit but not shebang or ELF header')
    if shebang:
      return result_dict('Has shebang but not executable bit')
    return result_dict('Has ELF header but not executable bit')

def check_files(root, files):
  gen = (check_file(root, f) for f in files if not is_ignored(f))
  return filter(None, gen)

class ApiBase(object):
  def __init__(self, root_dir, bare_output):
    self.root_dir = root_dir
    self.bare_output = bare_output
    self.count = 0
    self.count_read_header = 0

  def check_file(self, rel_path):
    logging.debug('check_file(%s)' % rel_path)
    self.count += 1

    if (not must_be_executable(rel_path) and
        not must_not_be_executable(rel_path)):
      self.count_read_header += 1

    return check_file(self.root_dir, rel_path)

  def check_dir(self, rel_path):
    return self.check(rel_path)

  def check(self, start_dir):
    """Check the files in start_dir, recursively check its subdirectories."""
    errors = []
    items = self.list_dir(start_dir)
    logging.info('check(%s) -> %d' % (start_dir, len(items)))
    for item in items:
      full_path = os.path.join(self.root_dir, start_dir, item)
      rel_path = full_path[len(self.root_dir) + 1:]
      if is_ignored(rel_path):
        continue
      if os.path.isdir(full_path):
        # Depth first.
        errors.extend(self.check_dir(rel_path))
      else:
        error = self.check_file(rel_path)
        if error:
          errors.append(error)
    return errors

  def list_dir(self, start_dir):
    """Lists all the files and directory inside start_dir."""
    return sorted(
      x for x in os.listdir(os.path.join(self.root_dir, start_dir))
      if not x.startswith('.')
    )

class ApiAllFilesAtOnceBase(ApiBase):
  _files = None

  def list_dir(self, start_dir):
    """Lists all the files and directory inside start_dir."""
    if self._files is None:
      self._files = sorted(self._get_all_files())
      if not self.bare_output:
        print 'Found %s files' % len(self._files)
    start_dir = start_dir[len(self.root_dir) + 1:]
    return [
      x[len(start_dir):] for x in self._files if x.startswith(start_dir)
    ]

  def _get_all_files(self):
    """Lists all the files and directory inside self._root_dir."""
    raise NotImplementedError()

class ApiGit(ApiAllFilesAtOnceBase):
  def _get_all_files(self):
    return capture(['git', 'ls-files'], cwd=self.root_dir).splitlines()

def get_scm(dir_path, bare):
  """Returns a properly configured ApiBase instance."""
  cwd = os.getcwd()
  root = get_git_root(dir_path or cwd)
  if root:
    if not bare:
      print('Found git repository at %s' % root)
    return ApiGit(dir_path or root, bare)

  # Returns a non-scm aware checker.
  if not bare:
    print('Failed to determine the SCM for %s' % dir_path)
  return ApiBase(dir_path or cwd, bare)

def main():
  usage = """Usage: python %prog [--root <root>] [tocheck]
  tocheck  Specifies the directory, relative to root, to check. This defaults
           to "." so it checks everything.

Examples:
  python %prog
  python %prog --root /path/to/source chrome"""

  parser = optparse.OptionParser(usage=usage)
  parser.add_option(
      '--root',
      help='Specifies the repository root. This defaults '
           'to the checkout repository root')
  parser.add_option(
      '-v', '--verbose', action='count', default=0, help='Print debug logging')
  parser.add_option(
      '--bare',
      action='store_true',
      default=False,
      help='Prints the bare filename triggering the checks')
  parser.add_option(
      '--file', action='append', dest='files',
      help='Specifics a list of files to check the permissions of. Only these '
      'files will be checked')
  parser.add_option('--json', help='Path to JSON output file')
  options, args = parser.parse_args()

  levels = [logging.ERROR, logging.INFO, logging.DEBUG]
  logging.basicConfig(level=levels[min(len(levels) - 1, options.verbose)])

  if len(args) > 1:
    parser.error('Too many arguments used')

  if options.root:
    options.root = os.path.abspath(options.root)

  if options.files:
    # --file implies --bare (for PRESUBMIT.py).
    options.bare = True

    errors = check_files(options.root, options.files)
  else:
    api = get_scm(options.root, options.bare)
    start_dir = args[0] if args else api.root_dir
    errors = api.check(start_dir)

    if not options.bare:
      print('Processed %s files, %d files where tested for shebang/ELF '
            'header' % (api.count, api.count_read_header))

  if options.json:
    with open(options.json, 'w') as f:
      json.dump(errors, f)

  if errors:
    if options.bare:
      print '\n'.join(e['full_path'] for e in errors)
    else:
      print '\nFAILED\n'
      print '\n'.join('%s: %s' % (e['full_path'], e['error']) for e in errors)
    return 1
  if not options.bare:
    print '\nSUCCESS\n'
  return 0

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


text:
package org.jetbrains.idea.svn;

import com.intellij.ide.FrameStateListener;
import com.intellij.ide.FrameStateManager;
import com.intellij.notification.*;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.annotate.AnnotationProvider;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.diff.DiffProvider;
import com.intellij.openapi.vcs.history.VcsHistoryProvider;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.merge.MergeProvider;
import com.intellij.openapi.vcs.rollback.RollbackEnvironment;
import com.intellij.openapi.vcs.update.UpdateEnvironment;
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.SoftHashMap;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.actions.ShowPropertiesDiffWithLocalAction;
import org.jetbrains.idea.svn.actions.SvnMergeProvider;
import org.jetbrains.idea.svn.annotate.SvnAnnotationProvider;
import org.jetbrains.idea.svn.checkin.SvnCheckinEnvironment;
import org.jetbrains.idea.svn.dialogs.SvnFormatWorker;
import org.jetbrains.idea.svn.dialogs.WCInfo;
import org.jetbrains.idea.svn.history.LoadedRevisionsCache;
import org.jetbrains.idea.svn.history.SvnChangeList;
import org.jetbrains.idea.svn.history.SvnCommittedChangesProvider;
import org.jetbrains.idea.svn.history.SvnHistoryProvider;
import org.jetbrains.idea.svn.rollback.SvnRollbackEnvironment;
import org.jetbrains.idea.svn.update.SvnIntegrateEnvironment;
import org.jetbrains.idea.svn.update.SvnUpdateEnvironment;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.util.jna.SVNJNAUtil;
import org.tmatesoft.svn.core.internal.wc.SVNAdminUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea14;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminAreaFactory;
import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.*;
import org.tmatesoft.svn.util.SVNDebugLog;
import org.tmatesoft.svn.util.SVNDebugLogAdapter;
import org.tmatesoft.svn.util.SVNLogType;

import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.logging.Level;

@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
public class SvnVcs extends AbstractVcs {
  private final static Logger REFRESH_LOG = Logger.getInstance("#svn_refresh");

  private static final Logger LOG = Logger.getInstance("org.jetbrains.idea.svn.SvnVcs");
  @NonNls public static final String VCS_NAME = "svn";
  private static final VcsKey ourKey = createKey(VCS_NAME);
  private final Map<String, Map<String, Pair<SVNPropertyValue, Trinity<Long, Long, Long>>>> myPropertyCache = new SoftHashMap<String, Map<String, Pair<SVNPropertyValue, Trinity<Long, Long, Long>>>>();

  private final SvnConfiguration myConfiguration;
  private final SvnEntriesFileListener myEntriesFileListener;

  private CheckinEnvironment myCheckinEnvironment;
  private RollbackEnvironment myRollbackEnvironment;
  private UpdateEnvironment mySvnUpdateEnvironment;
  private UpdateEnvironment mySvnIntegrateEnvironment;
  private VcsHistoryProvider mySvnHistoryProvider;
  private AnnotationProvider myAnnotationProvider;
  private DiffProvider mySvnDiffProvider;
  private final VcsShowConfirmationOption myAddConfirmation;
  private final VcsShowConfirmationOption myDeleteConfirmation;
  private EditFileProvider myEditFilesProvider;
  private SvnCommittedChangesProvider myCommittedChangesProvider;
  private final VcsShowSettingOption myCheckoutOptions;

  private ChangeProvider myChangeProvider;
  private MergeProvider myMergeProvider;

  @NonNls public static final String LOG_PARAMETER_NAME = "javasvn.log";
  public static final String pathToEntries = SvnUtil.SVN_ADMIN_DIR_NAME + File.separatorChar + SvnUtil.ENTRIES_FILE_NAME;
  public static final String pathToDirProps = SvnUtil.SVN_ADMIN_DIR_NAME + File.separatorChar + SvnUtil.DIR_PROPS_FILE_NAME;
  private final SvnChangelistListener myChangeListListener;

  private SvnCopiesRefreshManager myCopiesRefreshManager;
  private SvnFileUrlMappingImpl myMapping;
  private final MyFrameStateListener myFrameStateListener;

  public static final Topic<Runnable> ROOTS_RELOADED = new Topic<Runnable>("ROOTS_RELOADED", Runnable.class);
  private VcsListener myVcsListener;

  static {
    SvnHttpAuthMethodsDefaultChecker.check();

    //noinspection UseOfArchaicSystemPropertyAccessors
    final JavaSVNDebugLogger logger = new JavaSVNDebugLogger(Boolean.getBoolean(LOG_PARAMETER_NAME), LOG);
    SVNDebugLog.setDefaultLog(logger);
    SVNAdminAreaFactory.setSelector(new SvnFormatSelector());

    DAVRepositoryFactory.setup();
    SVNRepositoryFactoryImpl.setup();
    FSRepositoryFactory.setup();

    // non-optimized writing is fast enough on Linux/MacOS, and somewhat more reliable
    if (SystemInfo.isWindows) {
      SVNAdminArea14.setOptimizedWritingEnabled(true);
    }

    if (! SVNJNAUtil.isJNAPresent()) {
      LOG.warn("JNA is not found by svnkit library");
    }
  }

  private static Boolean booleanProperty(final String systemParameterName) {
    return Boolean.valueOf(System.getProperty(systemParameterName));
  }

  public SvnVcs(final Project project, MessageBus bus, SvnConfiguration svnConfiguration, final ChangeListManager changeListManager,
                final VcsDirtyScopeManager vcsDirtyScopeManager, final StartupManager startupManager) {
    super(project, VCS_NAME);
    LOG.debug("ct");
    myConfiguration = svnConfiguration;

    dumpFileStatus(FileStatus.ADDED);
    dumpFileStatus(FileStatus.DELETED);
    dumpFileStatus(FileStatus.MERGE);
    dumpFileStatus(FileStatus.MODIFIED);
    dumpFileStatus(FileStatus.NOT_CHANGED);
    dumpFileStatus(FileStatus.UNKNOWN);

    dumpFileStatus(SvnFileStatus.REPLACED);
    dumpFileStatus(SvnFileStatus.EXTERNAL);
    dumpFileStatus(SvnFileStatus.OBSTRUCTED);

    myEntriesFileListener = new SvnEntriesFileListener(project);

    final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
    myAddConfirmation = vcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.ADD, this);
    myDeleteConfirmation = vcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.REMOVE, this);
    myCheckoutOptions = vcsManager.getStandardOption(VcsConfiguration.StandardOption.CHECKOUT, this);

    if (myProject.isDefault()) {
      myChangeListListener = null;
    }
    else {
      upgradeIfNeeded(bus);

      myChangeListListener = new SvnChangelistListener(myProject, createChangelistClient());

      myVcsListener = new VcsListener() {
        public void directoryMappingChanged() {
          invokeRefreshSvnRoots(true);
        }
      };
    }

    // do one time after project loaded
    startupManager.runWhenProjectIsInitialized(new DumbAwareRunnable() {
      public void run() {
        postStartup();

        // for IDEA, it takes 2 minutes - and anyway this can be done in background, no sence...
        // once it could be mistaken about copies for 2 minutes on start...

        /*if (! myMapping.getAllWcInfos().isEmpty()) {
          invokeRefreshSvnRoots();
          return;
        }
        ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
          public void run() {
            myCopiesRefreshManager.getCopiesRefresh().ensureInit();
          }
        }, SvnBundle.message("refreshing.working.copies.roots.progress.text"), true, myProject);*/
      }
    });

    myFrameStateListener = new MyFrameStateListener(changeListManager, vcsDirtyScopeManager);
  }

  public void postStartup() {
    if (myProject.isDefault()) return;
    myCopiesRefreshManager = new SvnCopiesRefreshManager(myProject, (SvnFileUrlMappingImpl) getSvnFileUrlMapping());

    invokeRefreshSvnRoots(true);
  }

  public void invokeRefreshSvnRoots(final boolean asynchronous) {
    REFRESH_LOG.debug("refresh: ", new Throwable());
    if (myCopiesRefreshManager != null) {
      if (asynchronous) {
        myCopiesRefreshManager.getCopiesRefresh().asynchRequest();
      } else {
        ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
          public void run() {
            myCopiesRefreshManager.getCopiesRefresh().synchRequest();
          }
        }, SvnBundle.message("refreshing.working.copies.roots.progress.text"), true, myProject);
      }
    }
  }

  @Override
  public boolean checkImmediateParentsBeforeCommit() {
    return true;
  }

  private void upgradeIfNeeded(final MessageBus bus) {
      final MessageBusConnection connection = bus.connect();
      connection.subscribe(ChangeListManagerImpl.LISTS_LOADED, new LocalChangeListsLoadedListener() {
        public void processLoadedLists(final List<LocalChangeList> lists) {
          SvnConfiguration.SvnSupportOptions supportOptions = null;
          try {
            ChangeListManager.getInstanceChecked(myProject).setReadOnly(SvnChangeProvider.ourDefaultListName, true);

            supportOptions = myConfiguration.getSupportOptions();

            upgradeToRecentVersion(supportOptions);
            if (! supportOptions.changeListsSynchronized()) {
              processChangeLists(lists);
            }
          }
          catch (ProcessCanceledException e) {
            //
          } finally {
            if (supportOptions != null) {
              supportOptions.upgrade();
            }
          }

          connection.disconnect();
        }
      });
  }

  public void processChangeLists(final List<LocalChangeList> lists) {
    final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstanceChecked(myProject);
    plVcsManager.startBackgroundVcsOperation();
    try {
      final SVNChangelistClient client = createChangelistClient();
      for (LocalChangeList list : lists) {
        if (! list.isDefault()) {
          final Collection<Change> changes = list.getChanges();
          for (Change change : changes) {
            correctListForRevision(plVcsManager, change.getBeforeRevision(), client, list.getName());
            correctListForRevision(plVcsManager, change.getAfterRevision(), client, list.getName());
          }
        }
      }
    }
    finally {
      final Application appManager = ApplicationManager.getApplication();
      if (appManager.isDispatchThread()) {
        appManager.executeOnPooledThread(new Runnable() {
          public void run() {
            plVcsManager.stopBackgroundVcsOperation();
          }
        });
      } else {
        plVcsManager.stopBackgroundVcsOperation();
      }
    }
  }

  private void correctListForRevision(final ProjectLevelVcsManager plVcsManager, final ContentRevision revision,
                                      final SVNChangelistClient client, final String name) {
    if (revision != null) {
      final FilePath path = revision.getFile();
      final AbstractVcs vcs = plVcsManager.getVcsFor(path);
      if ((vcs != null) && VCS_NAME.equals(vcs.getName())) {
        try {
          client.doAddToChangelist(new File[] {path.getIOFile()}, SVNDepth.EMPTY, name, null);
        }
        catch (SVNException e) {
          // left in default list
        }
      }
    }
  }

  private final static String UPGRADE_SUBVERSION_FORMAT = "Subversion";

  private void upgradeToRecentVersion(final SvnConfiguration.SvnSupportOptions supportOptions) {
    if (! supportOptions.upgradeTo16Asked()) {
      final SvnWorkingCopyChecker workingCopyChecker = new SvnWorkingCopyChecker();

      if (workingCopyChecker.upgradeNeeded()) {

        Notifications.Bus.notify(new Notification(UPGRADE_SUBVERSION_FORMAT, SvnBundle.message("upgrade.format.to16.question.title"),
                                                  "Old format Subversion working copies could be upgraded to version 1.6.",
                                                  NotificationType.INFORMATION, new NotificationListener() {
            public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
              final int upgradeAnswer = Messages.showYesNoDialog(SvnBundle.message("upgrade.format.to16.question.text",
                  SvnBundle.message("label.where.svn.format.can.be.changed.text", SvnBundle.message("action.show.svn.map.text"))),
                  SvnBundle.message("upgrade.format.to16.question.title"), Messages.getWarningIcon());
              if (DialogWrapper.OK_EXIT_CODE == upgradeAnswer) {
                workingCopyChecker.doUpgrade();
              }

              notification.expire();
            }
          }));
      }
    }
  }

  @Override
  public void activate() {
    if (! myProject.isDefault()) {
      ChangeListManager.getInstance(myProject).addChangeListListener(myChangeListListener);
      ProjectLevelVcsManager.getInstance(myProject).addVcsListener(myVcsListener);
    }

    SvnApplicationSettings.getInstance().svnActivated();
    VirtualFileManager.getInstance().addVirtualFileListener(myEntriesFileListener);
    // this will initialize its inner listener for committed changes upload
    LoadedRevisionsCache.getInstance(myProject);
    FrameStateManager.getInstance().addListener(myFrameStateListener);
  }

  @Override
  public void deactivate() {
    FrameStateManager.getInstance().removeListener(myFrameStateListener);

    if (myVcsListener != null) {
      ProjectLevelVcsManager.getInstance(myProject).removeVcsListener(myVcsListener);
    }

    VirtualFileManager.getInstance().removeVirtualFileListener(myEntriesFileListener);
    SvnApplicationSettings.getInstance().svnDeactivated();
    new DefaultSVNRepositoryPool(null, null).shutdownConnections(true);
    if (myCommittedChangesProvider != null) {
      myCommittedChangesProvider.deactivate();
    }
    if (myChangeListListener != null && (! myProject.isDefault())) {
      ChangeListManager.getInstance(myProject).removeChangeListListener(myChangeListListener);
    }
  }

  public VcsShowConfirmationOption getAddConfirmation() {
    return myAddConfirmation;
  }

  public VcsShowConfirmationOption getDeleteConfirmation() {
    return myDeleteConfirmation;
  }

  public VcsShowSettingOption getCheckoutOptions() {
    return myCheckoutOptions;
  }

  public EditFileProvider getEditFileProvider() {
    if (myEditFilesProvider == null) {
      myEditFilesProvider = new SvnEditFileProvider(this);
    }
    return myEditFilesProvider;
  }

  @NotNull
  public ChangeProvider getChangeProvider() {
    if (myChangeProvider == null) {
      myChangeProvider = new SvnChangeProvider(this);
    }
    return myChangeProvider;
  }

  public SVNRepository createRepository(String url) throws SVNException {
    SVNRepository repos = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
    repos.setAuthenticationManager(myConfiguration.getAuthenticationManager(myProject));
    repos.setTunnelProvider(myConfiguration.getOptions(myProject));
    return repos;
  }

  public SVNRepository createRepository(SVNURL url) throws SVNException {
    SVNRepository repos = SVNRepositoryFactory.create(url);
    repos.setAuthenticationManager(myConfiguration.getAuthenticationManager(myProject));
    repos.setTunnelProvider(myConfiguration.getOptions(myProject));
    return repos;
  }

  public SVNUpdateClient createUpdateClient() {
    return new SVNUpdateClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNStatusClient createStatusClient() {
    return new SVNStatusClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNWCClient createWCClient() {
    return new SVNWCClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNCopyClient createCopyClient() {
    return new SVNCopyClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNMoveClient createMoveClient() {
    return new SVNMoveClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNLogClient createLogClient() {
    return new SVNLogClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNCommitClient createCommitClient() {
    return new SVNCommitClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNDiffClient createDiffClient() {
    return new SVNDiffClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNChangelistClient createChangelistClient() {
    return new SVNChangelistClient(myConfiguration.getAuthenticationManager(myProject), myConfiguration.getOptions(myProject));
  }

  public SVNWCAccess createWCAccess() {
    final SVNWCAccess access = SVNWCAccess.newInstance(null);
    access.setOptions(myConfiguration.getOptions(myProject));
    return access;
  }

  public ISVNOptions getSvnOptions() {
    return myConfiguration.getOptions(myProject);
  }

  public ISVNAuthenticationManager getSvnAuthenticationManager() {
    return myConfiguration.getAuthenticationManager(myProject);
  }

  void dumpFileStatus(FileStatus fs) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("FileStatus:" + fs.getText() + " " + fs.getColor() + " " + " " + fs.getClass().getName());
    }
  }

  public UpdateEnvironment getIntegrateEnvironment() {
    if (mySvnIntegrateEnvironment == null) {
      mySvnIntegrateEnvironment = new SvnIntegrateEnvironment(this);
    }
    return mySvnIntegrateEnvironment;
  }

  public UpdateEnvironment getUpdateEnvironment() {
    if (mySvnUpdateEnvironment == null) {
      mySvnUpdateEnvironment = new SvnUpdateEnvironment(this);
    }
    return mySvnUpdateEnvironment;
  }

  public String getDisplayName() {
    LOG.debug("getDisplayName");
    return "Subversion";
  }

  public Configurable getConfigurable() {
    LOG.debug("createConfigurable");
    return new SvnConfigurable(myProject);
  }

  public SvnConfiguration getSvnConfiguration() {
    return myConfiguration;
  }

  public static SvnVcs getInstance(Project project) {
    return (SvnVcs) ProjectLevelVcsManager.getInstance(project).findVcsByName(VCS_NAME);
  }

  @NotNull
  public CheckinEnvironment getCheckinEnvironment() {
    if (myCheckinEnvironment == null) {
      myCheckinEnvironment = new SvnCheckinEnvironment(this);
    }
    return myCheckinEnvironment;
  }

  @NotNull
  public RollbackEnvironment getRollbackEnvironment() {
    if (myRollbackEnvironment == null) {
      myRollbackEnvironment = new SvnRollbackEnvironment(this);
    }
    return myRollbackEnvironment;
  }

  public VcsHistoryProvider getVcsHistoryProvider() {
    // no heavy state, but it would be useful to have place to keep state in -> do not reuse instance
    return new SvnHistoryProvider(this);
  }

  public VcsHistoryProvider getVcsBlockHistoryProvider() {
    return getVcsHistoryProvider();
  }

  public AnnotationProvider getAnnotationProvider() {
    if (myAnnotationProvider == null) {
      myAnnotationProvider = new SvnAnnotationProvider(this);
    }
    return myAnnotationProvider;
  }

  public SvnEntriesFileListener getSvnEntriesFileListener() {
    return myEntriesFileListener;
  }

  public DiffProvider getDiffProvider() {
    if (mySvnDiffProvider == null) {
      mySvnDiffProvider = new SvnDiffProvider(this);
    }
    return mySvnDiffProvider;
  }

  private Trinity<Long, Long, Long> getTimestampForPropertiesChange(final File ioFile, final boolean isDir) {
    final File dir = isDir ? ioFile : ioFile.getParentFile();
    final String relPath = SVNAdminUtil.getPropPath(ioFile.getName(), isDir ? SVNNodeKind.DIR : SVNNodeKind.FILE, false);
    final String relPathBase = SVNAdminUtil.getPropBasePath(ioFile.getName(), isDir ? SVNNodeKind.DIR : SVNNodeKind.FILE, false);
    final String relPathRevert = SVNAdminUtil.getPropRevertPath(ioFile.getName(), isDir ? SVNNodeKind.DIR : SVNNodeKind.FILE, false);
    return new Trinity<Long, Long, Long>(new File(dir, relPath).lastModified(), new File(dir, relPathBase).lastModified(),
                                         new File(dir, relPathRevert).lastModified());
  }

  private boolean trinitiesEqual(final Trinity<Long, Long, Long> t1, final Trinity<Long, Long, Long> t2) {
    if (t2.first == 0 && t2.second == 0 && t2.third == 0) return false;
    return t1.equals(t2);
  }

  @Nullable
  public SVNPropertyValue getPropertyWithCaching(final VirtualFile file, final String propName) throws SVNException {
    Map<String, Pair<SVNPropertyValue, Trinity<Long, Long, Long>>> cachedMap = myPropertyCache.get(keyForVf(file));
    final Pair<SVNPropertyValue, Trinity<Long, Long, Long>> cachedValue = (cachedMap == null) ? null : cachedMap.get(propName);

    final File ioFile = new File(file.getPath());
    final Trinity<Long, Long, Long> tsTrinity = getTimestampForPropertiesChange(ioFile, file.isDirectory());

    if (cachedValue != null) {
      // zero means that a file was not found
      if (trinitiesEqual(cachedValue.getSecond(), tsTrinity)) {
        return cachedValue.getFirst();
      }
    }

    final SVNPropertyData value = createWCClient().doGetProperty(ioFile, propName, SVNRevision.WORKING, SVNRevision.WORKING);
    final SVNPropertyValue propValue = (value == null) ? null : value.getValue();

    if (cachedMap == null) {
      cachedMap = new HashMap<String, Pair<SVNPropertyValue, Trinity<Long, Long, Long>>>();
      myPropertyCache.put(keyForVf(file), cachedMap);
    }

    cachedMap.put(propName, new Pair<SVNPropertyValue, Trinity<Long, Long, Long>>(propValue, tsTrinity));

    return propValue;
  }

  public boolean fileExistsInVcs(FilePath path) {
    File file = path.getIOFile();
    SVNStatus status;
    try {
      status = createStatusClient().doStatus(file, false);
      if (status != null) {
        final SVNStatusType statusType = status.getContentsStatus();
        if (statusType == SVNStatusType.STATUS_ADDED) {
          return status.isCopied();
        }
        return !(status.getContentsStatus() == SVNStatusType.STATUS_UNVERSIONED ||
                 status.getContentsStatus() == SVNStatusType.STATUS_IGNORED ||
                 status.getContentsStatus() == SVNStatusType.STATUS_OBSTRUCTED);
      }
    }
    catch (SVNException e) {
      //
    }
    return false;
  }

  public boolean fileIsUnderVcs(FilePath path) {
    final ChangeListManager clManager = ChangeListManager.getInstance(myProject);
    return (! SvnStatusUtil.isIgnoredInAnySense(clManager, path.getVirtualFile())) && (! clManager.isUnversioned(path.getVirtualFile()));
  }

  private static File getEntriesFile(File file) {
    return file.isDirectory() ? new File(file, pathToEntries) : new File(file.getParentFile(), pathToEntries);
  }

  private static File getDirPropsFile(File file) {
    return new File(file, pathToDirProps);
  }

  @Nullable
  public SVNInfo getInfo(final VirtualFile file) {
    try {
      SVNWCClient wcClient = new SVNWCClient(getSvnAuthenticationManager(), getSvnOptions());
      SVNInfo info = wcClient.doInfo(new File(file.getPath()), SVNRevision.WORKING);
      if (info == null || info.getRepositoryRootURL() == null) {
        info = wcClient.doInfo(new File(file.getPath()), SVNRevision.HEAD);
      }
      return info;
    }
    catch (SVNException e) {
      return null;
    }
  }

  public static class SVNStatusHolder {

    private final SVNStatus myValue;
    private final long myEntriesTimestamp;
    private final long myFileTimestamp;
    private final boolean myIsLocked;

    public SVNStatusHolder(long entriesStamp, long fileStamp, SVNStatus value) {
      myValue = value;
      myEntriesTimestamp = entriesStamp;
      myFileTimestamp = fileStamp;
      myIsLocked = value != null && value.isLocked();
    }

    public long getEntriesTimestamp() {
      return myEntriesTimestamp;
    }

    public long getFileTimestamp() {
      return myFileTimestamp;
    }

    public boolean isLocked() {
      return myIsLocked;
    }

    public SVNStatus getStatus() {
      return myValue;
    }
  }

  public static class SVNInfoHolder {

    private final SVNInfo myValue;
    private final long myEntriesTimestamp;
    private final long myFileTimestamp;

    public SVNInfoHolder(long entriesStamp, long fileStamp, SVNInfo value) {
      myValue = value;
      myEntriesTimestamp = entriesStamp;
      myFileTimestamp = fileStamp;
    }

    public long getEntriesTimestamp() {
      return myEntriesTimestamp;
    }

    public long getFileTimestamp() {
      return myFileTimestamp;
    }

    public SVNInfo getInfo() {
      return myValue;
    }
  }

  private static class JavaSVNDebugLogger extends SVNDebugLogAdapter {
    private final boolean myLoggingEnabled;
    private final Logger myLog;
    @NonNls public static final String TRACE_LOG_PARAMETER_NAME = "javasvn.log.trace";

    public JavaSVNDebugLogger(boolean loggingEnabled, Logger log) {
      myLoggingEnabled = loggingEnabled;
      myLog = log;
    }

    public void log(final SVNLogType logType, final Throwable th, final Level logLevel) {
      if (myLoggingEnabled) {
        myLog.info(th);
      }
    }

    public void log(final SVNLogType logType, final String message, final Level logLevel) {
      if (myLoggingEnabled) {
        myLog.info(message);
      }
    }

    public void log(final SVNLogType logType, final String message, final byte[] data) {
      if (myLoggingEnabled) {
        if (data != null) {
          try {
            myLog.info(message + "\n" + new String(data, "UTF-8"));
          }
          catch (UnsupportedEncodingException e) {
            myLog.info(message + "\n" + new String(data));
          }
        } else {
          myLog.info(message);
        }
      }
    }
  }

  public FileStatus[] getProvidedStatuses() {
    return new FileStatus[]{SvnFileStatus.EXTERNAL,
      SvnFileStatus.OBSTRUCTED,
      SvnFileStatus.REPLACED};
  }

  @Override @NotNull
  public CommittedChangesProvider<SvnChangeList, ChangeBrowserSettings> getCommittedChangesProvider() {
    if (myCommittedChangesProvider == null) {
      myCommittedChangesProvider = new SvnCommittedChangesProvider(myProject);
    }
    return myCommittedChangesProvider;
  }

  @Nullable
  @Override
  public VcsRevisionNumber parseRevisionNumber(final String revisionNumberString) {
    final SVNRevision revision = SVNRevision.parse(revisionNumberString);
    if (revision.equals(SVNRevision.UNDEFINED)) {
      return null;
    }
    return new SvnRevisionNumber(revision);
  }

  @Override
  public String getRevisionPattern() {
    return ourIntegerPattern;
  }

  @Override
  public boolean isVersionedDirectory(final VirtualFile dir) {
    return SvnUtil.seemsLikeVersionedDir(dir);
  }

  @NotNull
  public SvnFileUrlMapping getSvnFileUrlMapping() {
    if (myMapping == null) {
      myMapping = SvnFileUrlMappingImpl.getInstance(myProject);
    }
    return myMapping;
  }

  /**
   * Returns real working copies roots - if there is <Project Root> -> Subversion setting,
   * and there is one working copy, will return one root
   */
  public List<WCInfo> getAllWcInfos() {
    final SvnFileUrlMapping urlMapping = getSvnFileUrlMapping();

    final List<RootUrlInfo> infoList = urlMapping.getAllWcInfos();
    final List<WCInfo> infos = new ArrayList<WCInfo>();
    for (RootUrlInfo info : infoList) {
      final File file = info.getIoFile();
      infos.add(new WCInfo(file.getAbsolutePath(), info.getAbsoluteUrlAsUrl(),
                           SvnFormatSelector.getWorkingCopyFormat(file), info.getRepositoryUrl(), SvnUtil.isWorkingCopyRoot(file)));
    }
    return infos;
  }

  private class SvnWorkingCopyChecker {
    private List<WCInfo> myAllWcInfos;

    public boolean upgradeNeeded() {
      myAllWcInfos = getAllWcInfos();
      for (WCInfo info : myAllWcInfos) {
        if (! WorkingCopyFormat.ONE_DOT_SIX.equals(info.getFormat())) {
          return true;
        }
      }
      return false;
    }

    public void doUpgrade() {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        public void run() {
          final SvnFormatWorker formatWorker = new SvnFormatWorker(myProject, WorkingCopyFormat.ONE_DOT_SIX, myAllWcInfos);
          // additionally ask about working copies with roots above the project root
          formatWorker.checkForOutsideCopies();
          if (formatWorker.haveStuffToConvert()) {
            ProgressManager.getInstance().run(formatWorker);
          }
        }
      });
    }
  }

  @Override
  public RootsConvertor getCustomConvertor() {
    return getSvnFileUrlMapping();
  }

  @Override
  public MergeProvider getMergeProvider() {
    if (myMergeProvider == null) {
      myMergeProvider = new SvnMergeProvider(myProject);
    }
    return myMergeProvider;
  }

  @Override
  public List<AnAction> getAdditionalActionsForLocalChange() {
    return Arrays.<AnAction>asList(new ShowPropertiesDiffWithLocalAction());
  }

  public void pathChanged(final File from, final File to) throws SVNException {
    myChangeListListener.pathChanged(from, to);
  }

  private String keyForVf(final VirtualFile vf) {
    return vf.getUrl();
  }

  @Override
  public boolean allowsNestedRoots() {
    return SvnConfiguration.getInstance(myProject).DETECT_NESTED_COPIES;
  }

  @Override
  public <S> List<S> filterUniqueRoots(final List<S> in, final Convertor<S, VirtualFile> convertor) {
    if (in.size() <= 1) return in;

    final List<MyPair<S>> infos = new ArrayList<MyPair<S>>(in.size());
    final SvnFileUrlMappingImpl mapping = (SvnFileUrlMappingImpl) getSvnFileUrlMapping();
    for (S s : in) {
      final VirtualFile vf = convertor.convert(s);

      final File ioFile = new File(vf.getPath());
      final SVNURL url = mapping.getUrlForFile(ioFile);
      if (url == null) continue;
      infos.add(new MyPair<S>(vf, url.toString(), s));
    }
    final List<MyPair<S>> filtered = new ArrayList<MyPair<S>>(infos.size());
    ForNestedRootChecker.filterOutSuperfluousChildren(this, infos, filtered);

    return ObjectsConvertor.convert(filtered, new Convertor<MyPair<S>, S>() {
      public S convert(final MyPair<S> o) {
        return o.getSrc();
      }
    });
  }

  private static class MyPair<T> implements RootUrlPair {
    private final VirtualFile myFile;
    private final String myUrl;
    private final T mySrc;

    private MyPair(VirtualFile file, String url, T src) {
      myFile = file;
      myUrl = url;
      mySrc = src;
    }

    public T getSrc() {
      return mySrc;
    }

    public VirtualFile getVirtualFile() {
      return myFile;
    }

    public String getUrl() {
      return myUrl;
    }
  }

  private static class MyFrameStateListener implements FrameStateListener {
    private final ChangeListManager myClManager;
    private final VcsDirtyScopeManager myDirtyScopeManager;

    private MyFrameStateListener(ChangeListManager clManager, VcsDirtyScopeManager dirtyScopeManager) {
      myClManager = clManager;
      myDirtyScopeManager = dirtyScopeManager;
    }

    public void onFrameDeactivated() {
    }

    public void onFrameActivated() {
      final List<VirtualFile> folders = ((ChangeListManagerImpl)myClManager).getLockedFolders();
      if (! folders.isEmpty()) {
        myDirtyScopeManager.filesDirty(null, folders);
      }
    }
  }

  public static VcsKey getKey() {
    return ourKey;
  }
}

redpajama_set_name: RedPajamaGithub


text:
require 'medusa/cookie_store'

module Medusa
  RSpec.describe CookieStore do

    it "should start out empty if no cookies are specified" do
      expect(CookieStore.new.empty?).to be true
    end

    it "should accept a Hash of cookies in the constructor" do
      expect(CookieStore.new({'test' => 'cookie'})['test'].value).to eq('cookie')
    end

    it "should be able to merge an HTTP cookie string" do
      cs = CookieStore.new({'a' => 'a', 'b' => 'b'})
      cs.merge! "a=A; path=/, c=C; path=/"
      expect(cs['a'].value).to eq('A')
      expect(cs['b'].value).to eq('b')
      expect(cs['c'].value).to eq('C')
    end

    it "should have a to_s method to turn the cookies into a string for the HTTP Cookie header" do
      expect(CookieStore.new({'a' => 'a', 'b' => 'b'}).to_s).to eq('a=a;b=b')
    end

  end
end


text:
package com.github.xyalan.model.v2;

import java.util.ArrayList;
import java.util.Collection;

import com.github.xyalan.utils.ModelUtils;

public class ContainerInfo {
	private String image;
	private Collection<String> options;

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public Collection<String> getOptions() {
		return options;
	}

	public void setOptions(Collection<String> options) {
		this.options = options;
	}

	public void addOption(String option) {
		if (options == null) {
			options = new ArrayList<String>();
		}
		options.add(option);
	}

	@Override
	public String toString() {
		return ModelUtils.toString(this);
	}

}


text:
package com.vaadin.tests.components.grid;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.SelectionMode;

public class GridAddRow extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {

        final Grid grid = new Grid();
        grid.setSelectionMode(SelectionMode.MULTI);
        grid.addColumn("firstName");
        grid.addColumn("age", Integer.class);

        grid.addRow("Lorem", Integer.valueOf(1));
        grid.addRow("Ipsum", Integer.valueOf(2));

        addComponent(grid);

        addComponent(new Button("Add new row", new Button.ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                grid.addRow("Dolor", Integer.valueOf(3));
            }
        }));

    }

}


text:
export default class FollowUsecase {

  /**
   * @param {TwitterClient} twitterClient
   */
  constructor(twitterClient) {
    this.twitterClient = twitterClient;
  }

  get defaultCount() {
    return 50;
  }

  /**
   * @param {string} myId
   * @param {number} count
   * @returns {Promise<Object>}
   */
  getFollowing(myId, count = this.defaultCount) {
    return this.twitterClient.friendsList({ userId: myId, count: count });
  }

  /**
   * @param {string} myId
   * @param {string} nextCursor
   * @param {number} count
   * @returns {Promise.<Object>}
   */
  getFollowingOlderThan(myId, nextCursor, count = this.defaultCount) {
    return this.twitterClient.friendsList({ userId: myId, cursor: nextCursor, count: count });
  }

  /**
   * @param {string} userId
   * @param {number} count
   * @returns {Promise<Object>}
   */
  getFollowers(userId, count = this.defaultCount) {
    return this.twitterClient.followersList({ userId: userId, count: count });
  }

  /**
   * @param {string} userId
   * @param {string} nextCursor
   * @param {number} count
   * @returns {Promise.<Object>}
   */
  getFollowersOlderThan(userId, nextCursor, count = this.defaultCount) {
    return this.twitterClient.followersList({ userId: userId, cursor: nextCursor, count: count });
  }

}


text:
<?php

namespace Events\Factory;

use Events\Controller\IndexController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Events\Factory\IndexControllerFactory
 *
 * Fabryka tworząca obiekt klasy IndexController
 */
class IndexControllerFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return IndexController
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $sm = $serviceLocator->getServiceLocator();
        return new IndexController(
                $sm->get('Events\Service\EventServiceInterface')
        );
    }

}


text:
package proxy

import (
	"github.com/docker/docker/daemon/graphdriver/overlay"
	"github.com/libopenstorage/openstorage/api"
	"github.com/libopenstorage/openstorage/graph"
)

const (
	// Name of the driver
	Name = "proxy"
	// Type of the driver
	Type = api.DriverType_DRIVER_TYPE_GRAPH
)

func init() {
	graph.Register(Name, overlay.Init)
}


text:
import _ from 'lodash'
import { loadItems, } from './actions'
import { keyedIdToArray, } from '../selector-helpers'
import { getDispatch, } from '../'

let throttleLoadItems = false

export function feeds(state) {
  const feeds = keyedIdToArray(state.feeds.feeds)

  return _.orderBy(feeds, ['name',]).filter(f => f.unread_count > 0)
}

export function currentFeed(state) {
  return state.feeds.currentFeed
}

export function currentItem(state) {
  return state.feeds.currentItem
}

export function items(state) {
  const { currentFeed, } = state.feeds
  let items = keyedIdToArray(state.feeds.items)
  if (currentFeed) {
    items = items.filter(item => item.feed_id === currentFeed.id)
  }

  return _.orderBy(items, 'published_at', 'asc')
}

export function displayItems(state) {
  const allItems = items(state)
  const current = currentItem(state)
  let previous, next
  if (current) {
    previous = allItems.filter(
      item =>
        item.published_at <= current.published_at &&
        item.read_at &&
        item.id !== current.id
    )
    if (previous.length > 5) {
      previous = previous.slice(Math.max(previous.length - 5, 1))
    }
    next = allItems.filter(
      item => item.published_at > current.published_at || !item.read_at
    )
  } else {
    previous = []
    next = allItems
  }

  if (next.length < 5 && !throttleLoadItems) {
    throttleLoadItems = true
    const { currentFeed, } = state.feeds
    const dispatch = getDispatch()
    const feedId = currentFeed ? currentFeed.id : -1
    dispatch(loadItems(feedId))
    setTimeout(() => {
      throttleLoadItems = false
    }, 30000)
  }

  return {
    previousItem: _.last(previous),
    previous,
    nextItem: _.first(next),
    next,
    current,
  }
}


text:
The header of the grid.

    String, default = ''

The header can be simple text or HTML. If you change .header property, you will need to call
.refresh() method to refresh the grid.

Header can be defined during object creation:

<textarea class="javascript">
let grid = new w2grid({
    name    : 'grid',
    header  : 'Grid Header',
    show : {
        header : true
    },
    columns: [
        { field: 'recid', text: 'ID', size: '50px' },
        { field: 'lname', text: 'Last Name', size: '30%' },
        { field: 'fname', text: 'First Name', size: '30%' },
        { field: 'email', text: 'Email', size: '40%' },
        { field: 'sdate', text: 'Start Date', size: '120px' },
        { field: 'sdate', text: 'End Date', size: '120px' }
    ]
});
</textarea>

Or any time after the grid has been created:

<textarea class="javascript">
grid.header = 'Grid Header';
grid.refresh();
</textarea>

Please note that you will need to set .show.header to true, which is false by default.


text:
/**
 * Created by cqb on 2014/9/22.
 */
(function(){
    var http = require("http");
    var url = require("url");
    var path = require("path");
    var querystring = require("querystring");
    CT.Service = function(options){
        this._init(options);
    }

    CT.Service.prototype = {
        port: "8415",

        root: null,

        layer: null,

        _init: function(options){
            CT.extend(this, options);

            this.createService();
        },

        createService: function(){
            var scope = this;
            var server = http.createServer(function(req, res){
                var pathname = url.parse(req.url).pathname;

                if(pathname == "/wmts"){
                    var params = querystring.parse(url.parse(req.url).query);
                    var layer = params["LAYER"];
                    var matrixset = params["TILEMATRIXSET"];
                    var tilematrixset = params["TILEMATRIX"];
                    var level = parseInt(tilematrixset.split(":")[1]);
                    var tilerow = params["TILEROW"];
                    var tilecol = params["TILECOL"];
                    var format = params["FORMAT"];
                    var tilepath = scope.getTilePath(tilecol, tilerow, level, layer, format, matrixset);
                    if (fs.existsSync(tilepath)) {
                        fs.readFile(tilepath, function (err, data) {
                            if (data) {
                                res.end(data);
                            }
                        });
                    }else {
                        fs.readFile("./lib/ol2/theme/default/img/blank.gif", function (err, data) {
                            if (data) {
                                res.end(data);
                            }
                        });
                    }
                }else {
                    var tilepath = path.join(scope.getRoot() + "", pathname);
                    if (fs.existsSync(tilepath)) {
                        fs.readFile(tilepath, function (err, data) {
                            if (data) {
                                res.end(data);
                            }
                        });
                    } else {
                        fs.readFile("./lib/ol2/theme/default/img/blank.gif", function (err, data) {
                            if (data) {
                                res.end(data);
                            }
                        });
                    }
                }
            });
            server.listen(this.port, function(){
                console.log("inner server listen to port "+scope.port);
            });

            server.on('error', function (e) {
                if (e.code == 'EADDRINUSE') {
                    console.log('Address or Port '+scope.port+' in use retrying ...');
                    setTimeout(function () {
                        server.close();
                        server.listen(scope.port);
                    }, 100);
                }
            });
        },

        setRoot: function(root){
            this.root = root;
        },

        getRoot: function(){
            return this.root;
        },

        setLayer: function(layer){
            this.layer = layer;
            this.setRoot(layer.dir);
        },

        /**
         * 存放地址
         * @param x
         * @param y
         * @param z
         */
        getTilePath: function(x, y, z, layername, format, maxtrixset){
            var ext = CT.FROMATEXTS[format];
            var despath = "";
            var level = z < 10 ? maxtrixset + "_0" + z : maxtrixset+"_"+z;
            var shift = z / 2;
            var half = 2 << shift;
            var digits = 1;
            if (half > 10){
                digits = parseInt(Math.log(half)/Math.log(10)) + 1;
            }
            var halfx = this.zeroPadder(digits, parseInt(x / half));
            var halfy = this.zeroPadder(digits, parseInt(y / half));

            x = this.zeroPadder(2*digits, x);
            y = this.zeroPadder(2*digits, y);
            despath = this.root + "/" + layername + "/" + level + "/" + halfx+"_"+halfy + "/" + x+"_"+y+ext;
            return despath;
        },

        /**
         * 行列前面加0
         * @param order
         * @param number
         */
        zeroPadder: function(order, number) {
            var numberOrder = 1;
            var prefix = "";
            if (number > 9) {
                if (number > 11) {
                    numberOrder = parseInt(Math.ceil(Math.log(number)/Math.log(10) - 0.001));
                } else {
                    numberOrder = 2;
                }
            }

            var diffOrder = order - numberOrder;

            if (diffOrder > 0) {
                while (diffOrder > 0) {
                    prefix += '0';
                    diffOrder--;
                }
                prefix += number;
            } else {
                prefix += number;
            }

            return prefix;
        }
    }
})();


text:
angularify.semantic.wizard
===============================

`angularify.semantic.wizard` - wizard/steps directive for angular.js.

CREDIT
--------------------

This Wizard is a port of the angular-wizard by mgonto from [github](https://github.com/mgonto/angular-wizard)

Usage
--------------------
```html
<wizard fullwidth="true">
	<wizard-pane title="Step1">
		<h1>Step 1</h1>
		<form name="step1form">
			<input type="text">
			<input type="submit" wz-next>
		</form>
	</wizard-pane>
	<wizard-pane title="Step2">
		<h1>Step 2</h1>
		<form name="step2form">
			<input type="text">
			<input type="submit" wz-finish>
	</wizard-pane>
</wizard>
```

`wizard` - can have following attributes:

  * `fullwidth` - Go fullwidth for the steps bar;

`wizard-pane` - can have the following attributes

  * `title` - Title of the Step in the wizard

`Buttons` - There are 4 types of buttons that go in forms to move a wizards direction

  * `wz-next` - next page
  * `wz-previous` - previous page
  * `wz-finish` - finish Wizard
  * `wz-cancel` - cancel wizard


text:
package google

import (
	"errors"
	"fmt"
	"net"
	"strings"

	"github.com/docker/machine/libmachine/drivers"
	"github.com/docker/machine/libmachine/log"
	"github.com/docker/machine/libmachine/mcnflag"
	"github.com/docker/machine/libmachine/ssh"
	"github.com/docker/machine/libmachine/state"
)

// Driver is a struct compatible with the docker.hosts.drivers.Driver interface.
type Driver struct {
	*drivers.BaseDriver
	Zone              string
	MachineType       string
	MachineImage      string
	DiskType          string
	Address           string
	Network           string
	Subnetwork        string
	Preemptible       bool
	UseInternalIP     bool
	UseInternalIPOnly bool
	Scopes            string
	DiskSize          int
	Project           string
	Tags              string
	UseExisting       bool
	OpenPorts         []string
}

const (
	defaultZone        = "us-central1-a"
	defaultUser        = "docker-user"
	defaultMachineType = "n1-standard-1"
	defaultImageName   = "ubuntu-os-cloud/global/images/ubuntu-1604-xenial-v20170721"
	defaultScopes      = "https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write"
	defaultDiskType    = "pd-standard"
	defaultDiskSize    = 10
	defaultNetwork     = "default"
	defaultSubnetwork  = ""
)

// GetCreateFlags registers the flags this driver adds to
// "docker hosts create"
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
	return []mcnflag.Flag{
		mcnflag.StringFlag{
			Name:   "google-zone",
			Usage:  "GCE Zone",
			Value:  defaultZone,
			EnvVar: "GOOGLE_ZONE",
		},
		mcnflag.StringFlag{
			Name:   "google-machine-type",
			Usage:  "GCE Machine Type",
			Value:  defaultMachineType,
			EnvVar: "GOOGLE_MACHINE_TYPE",
		},
		mcnflag.StringFlag{
			Name:   "google-machine-image",
			Usage:  "GCE Machine Image Absolute URL",
			Value:  defaultImageName,
			EnvVar: "GOOGLE_MACHINE_IMAGE",
		},
		mcnflag.StringFlag{
			Name:   "google-username",
			Usage:  "GCE User Name",
			Value:  defaultUser,
			EnvVar: "GOOGLE_USERNAME",
		},
		mcnflag.StringFlag{
			Name:   "google-project",
			Usage:  "GCE Project",
			EnvVar: "GOOGLE_PROJECT",
		},
		mcnflag.StringFlag{
			Name:   "google-scopes",
			Usage:  "GCE Scopes (comma-separated if multiple scopes)",
			Value:  defaultScopes,
			EnvVar: "GOOGLE_SCOPES",
		},
		mcnflag.IntFlag{
			Name:   "google-disk-size",
			Usage:  "GCE Instance Disk Size (in GB)",
			Value:  defaultDiskSize,
			EnvVar: "GOOGLE_DISK_SIZE",
		},
		mcnflag.StringFlag{
			Name:   "google-disk-type",
			Usage:  "GCE Instance Disk type",
			Value:  defaultDiskType,
			EnvVar: "GOOGLE_DISK_TYPE",
		},
		mcnflag.StringFlag{
			Name:   "google-network",
			Usage:  "Specify network in which to provision vm",
			Value:  defaultNetwork,
			EnvVar: "GOOGLE_NETWORK",
		},
		mcnflag.StringFlag{
			Name:   "google-subnetwork",
			Usage:  "Specify subnetwork in which to provision vm",
			Value:  defaultSubnetwork,
			EnvVar: "GOOGLE_SUBNETWORK",
		},
		mcnflag.StringFlag{
			Name:   "google-address",
			Usage:  "GCE Instance External IP",
			EnvVar: "GOOGLE_ADDRESS",
		},
		mcnflag.BoolFlag{
			Name:   "google-preemptible",
			Usage:  "GCE Instance Preemptibility",
			EnvVar: "GOOGLE_PREEMPTIBLE",
		},
		mcnflag.StringFlag{
			Name:   "google-tags",
			Usage:  "GCE Instance Tags (comma-separated)",
			EnvVar: "GOOGLE_TAGS",
			Value:  "",
		},
		mcnflag.BoolFlag{
			Name:   "google-use-internal-ip",
			Usage:  "Use internal GCE Instance IP rather than public one",
			EnvVar: "GOOGLE_USE_INTERNAL_IP",
		},
		mcnflag.BoolFlag{
			Name:   "google-use-internal-ip-only",
			Usage:  "Configure GCE instance to not have an external IP address",
			EnvVar: "GOOGLE_USE_INTERNAL_IP_ONLY",
		},
		mcnflag.BoolFlag{
			Name:   "google-use-existing",
			Usage:  "Don't create a new VM, use an existing one",
			EnvVar: "GOOGLE_USE_EXISTING",
		},
		mcnflag.StringSliceFlag{
			Name:  "google-open-port",
			Usage: "Make the specified port number accessible from the Internet, e.g, 8080/tcp",
		},
	}
}

// NewDriver creates a Driver with the specified storePath.
func NewDriver(machineName string, storePath string) *Driver {
	return &Driver{
		Zone:         defaultZone,
		DiskType:     defaultDiskType,
		DiskSize:     defaultDiskSize,
		MachineType:  defaultMachineType,
		MachineImage: defaultImageName,
		Network:      defaultNetwork,
		Subnetwork:   defaultSubnetwork,
		Scopes:       defaultScopes,
		BaseDriver: &drivers.BaseDriver{
			SSHUser:     defaultUser,
			MachineName: machineName,
			StorePath:   storePath,
		},
	}
}

// GetSSHHostname returns hostname for use with ssh
func (d *Driver) GetSSHHostname() (string, error) {
	return d.GetIP()
}

// GetSSHUsername returns username for use with ssh
func (d *Driver) GetSSHUsername() string {
	if d.SSHUser == "" {
		d.SSHUser = "docker-user"
	}
	return d.SSHUser
}

// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
	return "google"
}

// SetConfigFromFlags initializes the driver based on the command line flags.
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
	d.Project = flags.String("google-project")
	if d.Project == "" {
		return errors.New("no Google Cloud Project name specified (--google-project)")
	}

	d.Zone = flags.String("google-zone")
	d.UseExisting = flags.Bool("google-use-existing")
	if !d.UseExisting {
		d.MachineType = flags.String("google-machine-type")
		d.MachineImage = flags.String("google-machine-image")
		d.MachineImage = strings.TrimPrefix(d.MachineImage, "https://www.googleapis.com/compute/v1/projects/")
		d.DiskSize = flags.Int("google-disk-size")
		d.DiskType = flags.String("google-disk-type")
		d.Address = flags.String("google-address")
		d.Network = flags.String("google-network")
		d.Subnetwork = flags.String("google-subnetwork")
		d.Preemptible = flags.Bool("google-preemptible")
		d.UseInternalIP = flags.Bool("google-use-internal-ip") || flags.Bool("google-use-internal-ip-only")
		d.UseInternalIPOnly = flags.Bool("google-use-internal-ip-only")
		d.Scopes = flags.String("google-scopes")
		d.Tags = flags.String("google-tags")
		d.OpenPorts = flags.StringSlice("google-open-port")
	}
	d.SSHUser = flags.String("google-username")
	d.SSHPort = 22
	d.SetSwarmConfigFromFlags(flags)

	return nil
}

// PreCreateCheck is called to enforce pre-creation steps
func (d *Driver) PreCreateCheck() error {
	c, err := newComputeUtil(d)
	if err != nil {
		return err
	}

	// Check that the project exists. It will also check the credentials
	// at the same time.
	log.Infof("Check that the project exists")

	if _, err = c.service.Projects.Get(d.Project).Do(); err != nil {
		return fmt.Errorf("Project with ID %q not found. %v", d.Project, err)
	}

	// Check if the instance already exists. There will be an error if the instance
	// doesn't exist, so just check instance for nil.
	log.Infof("Check if the instance already exists")

	instance, _ := c.instance()
	if d.UseExisting {
		if instance == nil {
			return fmt.Errorf("unable to find instance %q in zone %q", d.MachineName, d.Zone)
		}
	} else {
		if instance != nil {
			return fmt.Errorf("instance %q already exists in zone %q", d.MachineName, d.Zone)
		}
	}

	return nil
}

// Create creates a GCE VM instance acting as a docker host.
func (d *Driver) Create() error {
	log.Infof("Generating SSH Key")

	if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
		return err
	}

	log.Infof("Creating host...")

	c, err := newComputeUtil(d)
	if err != nil {
		return err
	}

	if err := c.openFirewallPorts(d); err != nil {
		return err
	}

	if d.UseExisting {
		return c.configureInstance(d)
	}
	return c.createInstance(d)
}

// GetURL returns the URL of the remote docker daemon.
func (d *Driver) GetURL() (string, error) {
	ip, err := d.GetIP()
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil
}

// GetIP returns the IP address of the GCE instance.
func (d *Driver) GetIP() (string, error) {
	c, err := newComputeUtil(d)
	if err != nil {
		return "", err
	}

	ip, err := c.ip()
	if err != nil {
		return "", err
	}
	if ip == "" {
		return "", drivers.ErrHostIsNotRunning
	}

	return ip, nil
}

// GetState returns a docker.hosts.state.State value representing the current state of the host.
func (d *Driver) GetState() (state.State, error) {
	c, err := newComputeUtil(d)
	if err != nil {
		return state.None, err
	}

	// All we care about is whether the disk exists, so we just check disk for a nil value.
	// There will be no error if disk is not nil.
	instance, _ := c.instance()
	if instance == nil {
		disk, _ := c.disk()
		if disk == nil {
			return state.None, nil
		}
		return state.Stopped, nil
	}

	switch instance.Status {
	case "PROVISIONING", "STAGING":
		return state.Starting, nil
	case "RUNNING":
		return state.Running, nil
	case "STOPPING", "STOPPED", "TERMINATED":
		return state.Stopped, nil
	}
	return state.None, nil
}

// Start starts an existing GCE instance or create an instance with an existing disk.
func (d *Driver) Start() error {
	c, err := newComputeUtil(d)
	if err != nil {
		return err
	}

	instance, err := c.instance()
	if err != nil {
		if !strings.Contains(err.Error(), "notFound") {
			return err
		}
	}

	if instance == nil {
		if err = c.createInstance(d); err != nil {
			return err
		}
	} else {
		if err := c.startInstance(); err != nil {
			return err
		}
	}

	d.IPAddress, err = d.GetIP()
	return err
}

// Stop stops an existing GCE instance.
func (d *Driver) Stop() error {
	c, err := newComputeUtil(d)
	if err != nil {
		return err
	}

	if err := c.stopInstance(); err != nil {
		return err
	}

	d.IPAddress = ""
	return nil
}

// Restart restarts a machine which is known to be running.
func (d *Driver) Restart() error {
	if err := d.Stop(); err != nil {
		return err
	}

	return d.Start()
}

// Kill stops an existing GCE instance.
func (d *Driver) Kill() error {
	return d.Stop()
}

// Remove deletes the GCE instance and the disk.
func (d *Driver) Remove() error {
	c, err := newComputeUtil(d)
	if err != nil {
		return err
	}

	if err := c.deleteInstance(); err != nil {
		return err
	}

	return c.deleteDisk()
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

    <!-- ========== -->
    <!-- = Parent = -->
    <!-- ========== -->
    <parent>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-jdbc-examples</artifactId>
        <version>3.2.0</version>
    </parent>

	<!-- =========== -->
	<!-- = General = -->
	<!-- =========== -->
	<artifactId>neo4j-jdbc-examples-mybatis</artifactId>
	<packaging>jar</packaging>
	<name>Neo4j JDBC Driver Example with Mybatis</name>
	<description>POM for Neo4j JDBC Driver Example with Mybatis</description>

    <!-- ============================= -->
    <!-- = Dependency                = -->
    <!-- ============================= -->
    <dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.1</version>
		</dependency>
    </dependencies>

</project>


text:
namespace draco {

Status MeshCleanup::Cleanup(Mesh *mesh, const MeshCleanupOptions &options) {
  if (!options.remove_degenerated_faces && !options.remove_unused_attributes &&
      !options.remove_duplicate_faces && !options.make_geometry_manifold) {
    return OkStatus();  // Nothing to cleanup.
  }
  const PointAttribute *const pos_att =
      mesh->GetNamedAttribute(GeometryAttribute::POSITION);
  if (pos_att == nullptr) {
    return Status(Status::DRACO_ERROR, "Missing position attribute.");
  }

  if (options.remove_degenerated_faces) {
    RemoveDegeneratedFaces(mesh);
  }

  if (options.remove_duplicate_faces) {
    RemoveDuplicateFaces(mesh);
  }

  if (options.remove_unused_attributes) {
    RemoveUnusedAttributes(mesh);
  }

  return OkStatus();
}

void MeshCleanup::RemoveDegeneratedFaces(Mesh *mesh) {
  const PointAttribute *const pos_att =
      mesh->GetNamedAttribute(GeometryAttribute::POSITION);
  FaceIndex::ValueType num_degenerated_faces = 0;
  // Array for storing position indices on a face.
  std::array<AttributeValueIndex, 3> pos_indices;
  for (FaceIndex f(0); f < mesh->num_faces(); ++f) {
    const Mesh::Face &face = mesh->face(f);
    for (int p = 0; p < 3; ++p) {
      pos_indices[p] = pos_att->mapped_index(face[p]);
    }
    if (pos_indices[0] == pos_indices[1] || pos_indices[0] == pos_indices[2] ||
        pos_indices[1] == pos_indices[2]) {
      ++num_degenerated_faces;
    } else if (num_degenerated_faces > 0) {
      // Copy the face to its new location.
      mesh->SetFace(f - num_degenerated_faces, face);
    }
  }
  if (num_degenerated_faces > 0) {
    mesh->SetNumFaces(mesh->num_faces() - num_degenerated_faces);
  }
}

void MeshCleanup::RemoveDuplicateFaces(Mesh *mesh) {
  const PointAttribute *const pos_att =
      mesh->GetNamedAttribute(GeometryAttribute::POSITION);

  typedef std::array<AttributeValueIndex::ValueType, 3> PosTriplet;
  PosTriplet pos_indices;
  std::unordered_set<PosTriplet, HashArray<PosTriplet>> is_face_used;

  uint32_t num_duplicate_faces = 0;
  for (FaceIndex fi(0); fi < mesh->num_faces(); ++fi) {
    const auto f = mesh->face(fi);
    for (int c = 0; c < 3; ++c) {
      pos_indices[c] = pos_att->mapped_index(f[c]).value();
    }
    // Shift the position indices until the smallest index is the first one.
    while (pos_indices[0] > pos_indices[1] || pos_indices[0] > pos_indices[2]) {
      // Shift to the left.
      std::swap(pos_indices[0], pos_indices[1]);
      std::swap(pos_indices[1], pos_indices[2]);
    }
    // Check if have encountered the same position triplet on a different face.
    if (is_face_used.find(pos_indices) != is_face_used.end()) {
      // Duplicate face. Ignore it.
      num_duplicate_faces++;
    } else {
      // Insert new face to the set.
      is_face_used.insert(pos_indices);
      if (num_duplicate_faces > 0) {
        // Copy the face to its new location.
        mesh->SetFace(fi - num_duplicate_faces, f);
      }
    }
  }
  if (num_duplicate_faces > 0) {
    mesh->SetNumFaces(mesh->num_faces() - num_duplicate_faces);
  }
}

void MeshCleanup::RemoveUnusedAttributes(Mesh *mesh) {
  // Array that is going to store whether a corresponding point is used.
  std::vector<bool> is_point_used;
  PointIndex::ValueType num_new_points = 0;
  is_point_used.resize(mesh->num_points(), false);
  for (FaceIndex f(0); f < mesh->num_faces(); ++f) {
    const Mesh::Face &face = mesh->face(f);
    for (int p = 0; p < 3; ++p) {
      if (!is_point_used[face[p].value()]) {
        is_point_used[face[p].value()] = true;
        ++num_new_points;
      }
    }
  }

  bool points_changed = false;
  const PointIndex::ValueType num_original_points = mesh->num_points();
  // Map from old points to the new ones.
  IndexTypeVector<PointIndex, PointIndex> point_map(num_original_points);
  if (num_new_points < static_cast<int>(mesh->num_points())) {
    // Some of the points were removed. We need to remap the old points to the
    // new ones.
    num_new_points = 0;
    for (PointIndex i(0); i < num_original_points; ++i) {
      if (is_point_used[i.value()]) {
        point_map[i] = num_new_points++;
      } else {
        point_map[i] = kInvalidPointIndex;
      }
    }
    // Go over faces and update their points.
    for (FaceIndex f(0); f < mesh->num_faces(); ++f) {
      Mesh::Face face = mesh->face(f);
      for (int p = 0; p < 3; ++p) {
        face[p] = point_map[face[p]];
      }
      mesh->SetFace(f, face);
    }
    // Set the new number of points.
    mesh->set_num_points(num_new_points);
    points_changed = true;
  } else {
    // No points were removed. Initialize identity map between the old and new
    // points.
    for (PointIndex i(0); i < num_original_points; ++i) {
      point_map[i] = i;
    }
  }

  // Update index mapping for attributes.
  IndexTypeVector<AttributeValueIndex, uint8_t> is_att_index_used;
  IndexTypeVector<AttributeValueIndex, AttributeValueIndex> att_index_map;
  for (int a = 0; a < mesh->num_attributes(); ++a) {
    PointAttribute *const att = mesh->attribute(a);
    // First detect which attribute entries are used (included in a point).
    is_att_index_used.assign(att->size(), 0);
    att_index_map.clear();
    AttributeValueIndex::ValueType num_used_entries = 0;
    for (PointIndex i(0); i < num_original_points; ++i) {
      if (point_map[i] != kInvalidPointIndex) {
        const AttributeValueIndex entry_id = att->mapped_index(i);
        if (!is_att_index_used[entry_id]) {
          is_att_index_used[entry_id] = 1;
          ++num_used_entries;
        }
      }
    }
    bool att_indices_changed = false;
    // If there are some unused attribute entries, remap the attribute values
    // in the attribute buffer.
    if (num_used_entries < static_cast<int>(att->size())) {
      att_index_map.resize(att->size());
      num_used_entries = 0;
      for (AttributeValueIndex i(0); i < static_cast<uint32_t>(att->size());
           ++i) {
        if (is_att_index_used[i]) {
          att_index_map[i] = num_used_entries;
          if (i > num_used_entries) {
            const uint8_t *const src_add = att->GetAddress(i);
            att->buffer()->Write(
                att->GetBytePos(AttributeValueIndex(num_used_entries)), src_add,
                att->byte_stride());
          }
          ++num_used_entries;
        }
      }
      // Update the number of unique entries in the vertex buffer.
      att->Resize(num_used_entries);
      att_indices_changed = true;
    }
    // If either the points or attribute indices have changed, we need to
    // update the attribute index mapping.
    if (points_changed || att_indices_changed) {
      if (att->is_mapping_identity()) {
        // The mapping was identity. It'll remain identity only if the
        // number of point and attribute indices is still the same.
        if (num_used_entries != static_cast<int>(mesh->num_points())) {
          // We need to create an explicit mapping.
          // First we need to initialize the explicit map to the original
          // number of points to recreate the original identity map.
          att->SetExplicitMapping(num_original_points);
          // Set the entries of the explicit map to identity.
          for (PointIndex::ValueType i = 0; i < num_original_points; ++i) {
            att->SetPointMapEntry(PointIndex(i), AttributeValueIndex(i));
          }
        }
      }
      if (!att->is_mapping_identity()) {
        // Explicit mapping between points and local attribute indices.
        for (PointIndex i(0); i < num_original_points; ++i) {
          // The new point id that maps to the currently processed attribute
          // entry.
          const PointIndex new_point_id = point_map[i];
          if (new_point_id == kInvalidPointIndex) {
            continue;
          }
          // Index of the currently processed attribute entry in the original
          // mesh.
          const AttributeValueIndex original_entry_index = att->mapped_index(i);
          // New index of the same entry after unused entries were removed.
          const AttributeValueIndex new_entry_index =
              att_indices_changed ? att_index_map[original_entry_index]
                                  : original_entry_index;

          // Update the mapping. Note that the new point index is always smaller
          // than the processed index |i|, making this operation safe.
          att->SetPointMapEntry(new_point_id, new_entry_index);
        }
        // If the number of points changed, we need to set a new explicit map
        // size.
        att->SetExplicitMapping(mesh->num_points());
      }
    }
  }
}

Status MeshCleanup::MakeGeometryManifold(Mesh *mesh) {
  return Status(Status::DRACO_ERROR, "Unsupported function.");
}

}  // namespace draco


text:
module Autoparts
  module Packages
    class Libpcap < Package
      name 'libpcap'
      version '1.6.2'
      description 'Libpcap: provides a portable framework for low-level network monitoring. Applications include network statistics collection, security monitoring, network debugging, etc.'
      category Category::UTILITIES

      source_url 'http://www.tcpdump.org/release/libpcap-1.6.2.tar.gz'
      source_sha1 '7efc7d56f4959de8bb33a92de2e15d92105eac32'
      source_filetype 'tar.gz'

      def compile
        args = [
          "--prefix=#{prefix_path}",
        ]

        Dir.chdir(name_with_version) do
          execute './configure', *args
          execute 'make'
        end
      end

      def install
        Dir.chdir(name_with_version) do
          execute 'make install'
        end
      end
    end
  end
end


text:
var ozpIwc = ozpIwc || {};
ozpIwc.api = ozpIwc.api || {};
ozpIwc.api.filter = ozpIwc.api.filter || {};
/**
 * @module ozpIwc.api
 * @submodule ozpIwc.api.filter
 */

/**
 * Wrappers that return the list of filters for the standard actions supported by the base api.
 *
 * @class standard
 * @namespace ozpIwc.api.filter
 * @static
 */
ozpIwc.api.filter.standard = (function (filter) {
    var standard = {
        /**
         * Returns the filter collection generator for the given action.
         * @method forAction
         * @param {String} a
         * @return {Function}
         */
        forAction: function (a) {
            return standard[a + "Filters"];
        },

        /**
         * Filters for the set action.
         * @method setFilters
         * @param nodeType
         * @param contentType
         * @return {Function[]} array of filters
         */
        setFilters: function (nodeType, contentType) {
            return [
                filter.base.checkAuthorization(),
                filter.base.createResource(nodeType),
                filter.base.checkContentType(contentType),
                filter.base.checkVersion(),
                filter.base.checkCollect(),
                filter.base.markResourceAsChanged()
            ];
        },

        /**
         * Filters for the delete action.
         * @method deleteFilters
         * @return {Function[]} array of filters
         */
        deleteFilters: function () {
            return [
                filter.base.checkAuthorization(),
                filter.base.checkVersion(),
                filter.base.markResourceAsChanged()
            ];
        },

        /**
         * Filters for the get action.
         * @method getFilters
         * @return {Function[]} array of filters
         */
        getFilters: function () {
            return [
                filter.base.requireResource(),
                filter.base.checkAuthorization(),
                filter.base.checkCollect()
            ];
        },
        watchFilters: function() {
            return [
                filter.base.checkAuthorization(),
                filter.base.checkCollect()
            ];
        },
        collectFilters: function(nodeType, contentType) {
            return [
                filter.base.checkAuthorization(),
                filter.base.createResource(nodeType),
                filter.base.checkContentType(contentType),
                filter.base.checkVersion(),
                filter.base.checkCollect()
            ];
        },
        /**
         * Filters for set-like actions that need to mark the resource as a collector.
         * @method getFilters
         * @return {Function[]} array of filters
         */
        createAndCollectFilters: function (nodeType, contentType) {
            return [
                filter.base.checkAuthorization(),
                filter.base.createResource(nodeType),
                filter.base.checkCollect(),
                filter.base.checkContentType(contentType),
                filter.base.checkVersion()
            ];
        }
    };

    return standard;
}(ozpIwc.api.filter));


text:
import org.apache.crunch.scrunch._
import org.apache.crunch.scrunch.Mem._

case class UrlData(pageRank: Float, oldPageRank: Float, links: List[String]) {
  def this() = this(1.0f, 0.0f, Nil)

  def this(links: String*) = this(1.0f, 0.0f, List(links:_*))

  def this(links: Iterable[String]) = this(1.0f, 0.0f, links.toList)

  def delta = math.abs(pageRank - oldPageRank)

  def next(newPageRank: Float) = new UrlData(newPageRank, pageRank, links)

  def outboundScores = links.map(link => (link, pageRank / links.size))
}

object ClassyPageRank extends PipelineApp {

  def initialize(file: String) = {
    read(from.textFile(file))
      .map(line => { val urls = line.split("\\s+"); (urls(0), urls(2)) })
      .groupByKey
      .map((url, links) => (url, new UrlData(links)))
  }

  def update(prev: PTable[String, UrlData], d: Float) = {
    val outbound = prev.values.flatMap(_.outboundScores)

    cogroup(prev, outbound).mapValues(data => {
      val (prd, outboundScores) = data
      val newPageRank = (1 - d) + d * outboundScores.sum
      if (!prd.isEmpty) {
        prd.head.next(newPageRank)
      } else {
        new UrlData(newPageRank, 0, Nil)
      }
    })
  }

  var index = 0
  var delta = 10.0f
  fs.mkdirs("prank/")
  var curr = initialize(args(0))
  while (delta > 1.0f) {
    index = index + 1
    curr = update(curr, 0.5f)
    write(curr, to.avroFile("prank/" + index))
    delta = curr.values.map(_.delta).max.materialize.head
    println("Current delta = " + delta)
  }
  fs.rename("prank/" + index, args(1))
  fs.delete("prank/", true)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface psidev.psi.mi.jami.bridges.ontologymanager.MIOntologyTermI (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)</title>
<meta name="date" content="2021-08-20">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
psidev.psi.mi.jami.bridges.ontologymanager.MIOntologyTermI

Packages that use MIOntologyTermI

Package
Description

psidev.psi.mi.jami.bridges.ontologymanager

psidev.psi.mi.jami.bridges.ontologymanager.impl

Uses of MIOntologyTermI in psidev.psi.mi.jami.bridges.ontologymanager

Methods in psidev.psi.mi.jami.bridges.ontologymanager that return types with arguments of type MIOntologyTermI

Modifier and Type
Method and Description

Collection<MIOntologyTermI>
MIOntologyAccess.getRootTerms()

getRootTerms.

Uses of MIOntologyTermI in psidev.psi.mi.jami.bridges.ontologymanager.impl

Classes in psidev.psi.mi.jami.bridges.ontologymanager.impl that implement MIOntologyTermI

Modifier and Type
Class and Description

class
OntologyTermWrapper

Ontology term for PSI-MI JAMI

Methods in psidev.psi.mi.jami.bridges.ontologymanager.impl that return MIOntologyTermI

Modifier and Type
Method and Description

protected MIOntologyTermI
AbstractMIOntologyAccess.createNewOntologyTerm(String identifier,
                     String name)

createNewOntologyTerm.

MIOntologyTermI
AbstractMIOntologyAccess.getTermForAccession(String accession)

Methods in psidev.psi.mi.jami.bridges.ontologymanager.impl that return types with arguments of type MIOntologyTermI

Modifier and Type
Method and Description

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getAllChildren(MIOntologyTermI term)

getAllChildren.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getAllParents(MIOntologyTermI term)

getAllParents.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getDirectChildren(MIOntologyTermI term)

getDirectChildren.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getDirectParents(MIOntologyTermI term)

getDirectParents.

Collection<MIOntologyTermI>
AbstractMIOntologyAccess.getRootTerms()

getRootTerms.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getValidTerms(String accession,
             boolean allowChildren,
             boolean useTerm)

 Method that is used by the validator to determine a Set of Ontology terms that are valid terms
 for a particular rule.

Methods in psidev.psi.mi.jami.bridges.ontologymanager.impl with parameters of type MIOntologyTermI

Modifier and Type
Method and Description

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getAllChildren(MIOntologyTermI term)

getAllChildren.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getAllParents(MIOntologyTermI term)

getAllParents.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getDirectChildren(MIOntologyTermI term)

getDirectChildren.

Set<MIOntologyTermI>
AbstractMIOntologyAccess.getDirectParents(MIOntologyTermI term)

getDirectParents.

boolean
AbstractMIOntologyAccess.isObsolete(MIOntologyTermI term)

isObsolete.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2021. All rights reserved.