text:
/**
 * React 数据双向绑定
 */

const LinkedStateMixin = React.addons.LinkedStateMixin;

/*const WithLink = React.createClass({
  mixins: [LinkedStateMixin],
  getInitialState() {
    return {message: 'Hello!'};
  },
  componentWillUpdate() {
    console.log(1)
  },
  render() {
    return
{this.state.message}<input type="text" valueLink={this.linkState('message')}/>
;
  }
});*/

const WithLink = React.createClass({
  getInitialState() {
    return {message: 'Hello!'};
  },
  componentWillUpdate() {
    console.log(1)
  },
  handle(key){
    return {
      value: this.state[key],
      requestChange: (newValue)=>{
        this.setState({[key]:newValue});
      }
    }
  },
  render() {
    return
{this.state.message}<input type="text" valueLink={this.handle("message")}/>
;
  }
});

ReactDOM.render(
    <WithLink/>,
    document.getElementById("container")
);

/*const WithNoLink = React.createClass({
  getInitialState() {
    return {message: 'Hello!'};
  },
  componentWillUpdate() {
    console.log(1)
  },
  change(event) {
    this.setState({
      message:event.target.value
    })
  },
  render() {
    return
{this.state.message}<input type="text" value={this.state.message} onChange={this.change}/>
;
  }
});

ReactDOM.render(
    <WithNoLink/>,
    document.getElementById("container")
);*/


text:
package com.tiny.demo.firstlinecode.guide;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.tiny.demo.firstlinecode.BaseActivity;
import com.tiny.demo.firstlinecode.MainActivity;
import com.tiny.demo.firstlinecode.R;
import com.tiny.demo.firstlinecode.common.utils.PreferencesUtils;

public class GuidePageFragment extends Fragment {
    private int page;
    private static final String PAGE = "page";
    private static String[] titleArray = new String[]{"品牌升级", "AI实验室", "事件炒股"};
    private static String[] subTitleArray = new String[]{"品牌升级 炒股服务更上一层", "人工智能 助你收获更高收益", "优质信息 了解股价涨跌逻辑"};

    public static GuidePageFragment newInstance(int page) {
        GuidePageFragment fragment = new GuidePageFragment();
        Bundle args = new Bundle();
        args.putInt(PAGE, page);
        fragment.setArguments(args);
        return fragment;
    }

    public GuidePageFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            page = getArguments().getInt(PAGE);
        }
    }

    /**
     * 逃过引导
     */
    private void skiperGuid() {
        PreferencesUtils.setBoolean(SplashActivity.SHOW_GUIDE_PAGE, false);
        BaseActivity activity = (BaseActivity) getActivity();
        activity.startActivity(new Intent(activity, MainActivity.class));
        activity.finish();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_guide_page, container, false);
        TextView mSkipView = (TextView) v.findViewById(R.id.guide_page_skip);
        ImageView mBgImageView = (ImageView) v.findViewById(R.id.guide_page_imageview);
        TextView mTitle = (TextView) v.findViewById(R.id.guide_page_title);
        TextView mSubTitle = (TextView) v.findViewById(R.id.guide_page_sutitle);
        mTitle.setText(titleArray[page]);
        mSubTitle.setText(subTitleArray[page]);
        mSkipView.setOnClickListener(v1 -> skiperGuid());

        switch (page) {
            case 0:
                mBgImageView.setImageResource(R.mipmap.guide_page_1);
                mSkipView.setVisibility(View.GONE);
                break;
            case 1:
                mBgImageView.setImageResource(R.mipmap.guide_page_2);
                mSkipView.setVisibility(View.GONE);
                break;
            case 2:
                mBgImageView.setImageResource(R.mipmap.guide_page_3);
                mSkipView.setVisibility(View.VISIBLE);
                break;

        }
        return v;
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'poetics/version'
require 'poetics/syntax'
require 'poetics/parser'
require 'poetics/library'


text:
import { Injectable } from '@angular/core';

@Injectable()
export class PaymentService {
  setCODAsSelectedMode(modes) {
    let selectedMode;
    modes.forEach((mode) => {
      if (mode.name === 'PayPal') {
        selectedMode = mode;
      }
    });

    return selectedMode;
  }

}


text:
(function ($) {

    $.fn.codekeepr = function() {

        var context = this;
        this.mode = '';

        this.init = function() {

            this.find('.chosen').chosen({
                disable_search_threshold: 5
            });

            this.find('input#search').codekeeprSearch().list(
                context.highlight
            );

            this.find('input.autocomplete').each(function (index, value) {
                $(this).codekeeprSearch().autocomplete();
            });

            this.highlight();

            return this;
        };

        this.highlight = function() {
            $('pre code').each(function(i, block) {
                hljs.highlightBlock(block);
            });
        };

        this.setMode = function(mode) {

            mode = mode || this.mode;

            this.mode = mode;

            return this;
        };

        this.update = function() {

            switch (this.mode) {

                case 'main':
                    //this.find('input#search').select();
                    break;

                default:
                    // ...
            }

            return this;
        };

        this.data('context', this);

        return this;
    }

}(jQuery));


text:
require "formula"

class GnuCobol < Formula
  homepage "http://www.opencobol.org/"

  stable do
    url "https://downloads.sourceforge.net/project/open-cobol/gnu-cobol/1.1/gnu-cobol-1.1.tar.gz"
    sha1 "86e928c43cb3372f1f4564f3fd5e1dde668e8c1f"

    fails_with :clang do
      cause <<-EOS.undent
        Building with Clang configures GNU-COBOL to use Clang as its compiler,
        which causes subsequent GNU-COBOL-based builds to fail.
      EOS
    end
  end

  devel do
    version "2.0_nightly_r411"
    url "https://downloads.sourceforge.net/project/open-cobol/gnu-cobol/2.0/gnu-cobol-2.0_nightly_r411.tar.gz"
    sha1 "009215c090b9a90fbf02bbc913095ce2a9b31910"
  end

  bottle do
    revision 1
    sha1 "0faef373e0364a8c92e32b828904e0fc10198aab" => :mavericks
    sha1 "cf08ce9301cfb80a882b37587ef0b9cb5c96f70b" => :mountain_lion
    sha1 "fc50ad8ec550f6d347044778b795688e4f18ad24" => :lion
  end

  depends_on "autoconf" => :build
  depends_on "automake" => :build
  depends_on "berkeley-db4"
  depends_on "gmp"
  depends_on "gcc"

  def install
    # both environment variables are needed to be set
    # the cobol compiler takes these variables for calling cc during its run
    # if the paths to gmp and bdb are not provided, the run of cobc fails
    gmp = Formula["gmp"]
    bdb = Formula["berkeley-db4"]
    ENV.append "CPPFLAGS", "-I#{gmp.opt_include} -I#{bdb.opt_include}"
    ENV.append "LDFLAGS", "-L#{gmp.opt_lib} -L#{bdb.opt_lib}"

    args = ["--prefix=#{prefix}", "--infodir=#{info}"]
    args << "--with-libiconv-prefix=/usr"
    args << "--with-libintl-prefix=/usr"

    if build.stable?
      system "aclocal"

      # fix referencing of libintl and libiconv for ld
      # bug report can be found here: https://sourceforge.net/p/open-cobol/bugs/93/
      inreplace "configure", "-R$found_dir", "-L$found_dir"

      args << "--with-cc=#{ENV.cc}"
    end

    system "./configure", *args
    system "make", "install"
  end

  test do
    (testpath/"hello.cob").write <<-EOS
       IDENTIFICATION DIVISION.
       PROGRAM-ID. hello.
       PROCEDURE DIVISION.
       DISPLAY "Hello World!".
       STOP RUN.
    EOS
    system "#{bin}/cobc", "-x", testpath/"hello.cob"
    system testpath/"hello"
  end
end


text:
package hudson.plugins.report.jck.main.cmdline;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.plugins.report.jck.main.formatters.Formatter;
import hudson.plugins.report.jck.main.formatters.HtmlFormatter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JobsRecognition {

    private static JobsRecognition INSTANCE;
    private static final Map<File, String> cache = new HashMap<>();

    public static JobsRecognition jobsRecognition() {
        if (INSTANCE == null) {
            INSTANCE = new JobsRecognition();
        }
        return INSTANCE;
    }

    private String jenkinsDir;
    private File jobsDir;

    public JobsRecognition() {
        jenkinsDir = System.getProperty("jenkins_home");
        if (jenkinsDir == null) {
            jenkinsDir = System.getenv("JENKINS_HOME");
        }
        jobsDir = new File(jenkinsDir, "jobs");
    }

    public File getJobsDir() {
        return jobsDir;
    }

    public String getJenkinsDir() {
        return jenkinsDir;
    }

    public static String[] getNonNullListing(File f){
        String[] l = f.list();
        if (l == null){
            throw new NullPointerException(f+" do not exists or is file or not accessible or hidden io error occured");
        }
        return l;
    }

    public String[] getPossibleJobs() {
        String[] possibleJobs = getNonNullListing(jobsDir);
        Arrays.sort(possibleJobs, Collections.reverseOrder());
        return possibleJobs;
    }

    public boolean isJob(String jobName) {
        return arrayContains(getPossibleJobs(), jobName);
    }

    private File creteJobFile(String jobName) {
        return new File(jobsDir, jobName);
    }

    private File creteBuildsDir(String jobName) {
        return new File(creteJobFile(jobName), "builds");
    }

    public File creteBuildDir(String jobName, int id) {
        return new File(creteBuildsDir(jobName), String.valueOf(id));
    }

    private File creteLogFile(String jobName, int id) {
        return creteLogFile(creteBuildDir(jobName, id));
    }

    private static File creteLogFile(File dir) {
        return new File(dir, "log");
    }

    public File creteChangelogFile(String jobName, int id) {
        return creteChangelogFile(creteBuildDir(jobName, id));
    }

    private static File creteChangelogFile(File dir) {
        return new File(dir, "changelog.xml");
    }

    public static boolean arrayContains(String[] as, String s) {
        for (String a : as) {
            if (a.equals(s)) {
                return true;
            }
        }
        return false;
    }

    public int getLatestBuildId(String jobName) {
        return getLatestBuildId(creteBuildsDir(jobName));
    }

    private static int getLatestBuildId(File jobDir) {
        if (jobDir.exists() && jobDir.isDirectory()) {
            String[] files = getNonNullListing(jobDir);
            List<Integer> results = new ArrayList<>(files.length);
            for (String file : files) {
                try {
                    Integer i = Integer.valueOf(file);
                    results.add(i);
                } catch (Exception ex) {
                    System.err.println(jobDir + "/" + file + " is not number.");
                }
            }
            Collections.sort(results);
            return results.get(results.size() - 1);
        } else {
            throw new RuntimeException(jobDir + " do not exists or is not directory");
        }
    }

    public void checkJob(String jobName) {
        if (!isJob(jobName)) {
            System.err.println("Possible jobs");
            String[] pj = getPossibleJobs();
            for (String jobs : pj) {
                System.err.println(jobs);
            }
            throw new RuntimeException("Unknown job `" + jobName + "`");
        }
    }

    void printJobInfo(String jobName, Formatter formatter) {
        checkJob(jobName);
        String[] builds = getNonNullListing(creteBuildsDir(jobName));
        List<Integer> results = new ArrayList<>(builds.length);
        for (String build : builds) {
            if (isNumber(build)) {
                results.add(Integer.valueOf(build));
            }
        }
        int latest = getLatestBuildId(jobName);
        Collections.sort(results);
        formatter.initDoc();
        for (Integer result : results) {
            formatter.small();
            File f = creteBuildDir(jobName, result);
            if (isUnknown(f)) {
                formatter.startColor(Formatter.SupportedColors.Magenta);
            } else if (isFailed(f)) {
                formatter.startColor(Formatter.SupportedColors.Red);
            } else if (isAborted(f)) {
                formatter.startColor(Formatter.SupportedColors.LightMagenta);
            } else if (isUnstable(f)) {
                formatter.startColor(Formatter.SupportedColors.Yellow);
            } else if (isPassed(f)) {
                formatter.startColor(Formatter.SupportedColors.Green);
            } else {
                formatter.startColor(Formatter.SupportedColors.Cyan);
            }
            formatter.print("" + result + "(" + (result - latest) + "): ");
            formatter.print("" + getChangelogsNvr(f));
            String tt = JobsRecognition.tail(creteLogFile(jobName, result));
            if (tt != null) {
                //tt = tt.trim();
            }
            formatter.print(" [" + tt + "]");
            if (isUnknown(f)) {
                formatter.print(" [unknown status!]");
            }
            formatter.closeBuildsList();
        }
        formatter.closeDoc();
    }

    public static boolean isNumber(String s) {
        try {
            Integer.valueOf(s);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    private static final Map<File, String> nvrCache = new HashMap<>();

    public static String getChangelogsNvr(File buildPath) {
        File f = creteChangelogFile(buildPath);
        String cached = nvrCache.get(f);
        if (cached != null) {
            return cached;
        }
        try {
            String content = new Scanner(f, "UTF-8").useDelimiter("\\Z").next();
            String[] lines = content.split("[<>]");
            boolean read1 = true;
            boolean read2 = false;
            for (String line : lines) {
                line = line.replaceAll("\\s+", "");
                if (line.isEmpty()) {
                    continue;
                }
                if (read1 && read2) {
                    nvrCache.put(f, line);
                    return line;
                }
                if (line.equals("rpms")) {
                    read1 = false;
                }
                if (line.equals("/rpms")) {
                    read1 = true;
                }
                if (line.equals("nvr")) {
                    read2 = true;
                }
                if (line.equals("/nvr")) {
                    read2 = false;
                }
            }
        } catch (Exception ex) {
            return null;
        }
        return null;
    }

    //maybe linux only, not utf8 valid solution... nto much tested, just copypasted and worked
    public static String tail(File file) {
        if (!file.exists()) {
            return null;
        }
        if (cache.get(file) != null) {
            return cache.get(file);
        }
        RandomAccessFile fileHandler = null;
        try {
            fileHandler = new RandomAccessFile(file, "r");
            long fileLength = fileHandler.length() - 1;
            StringBuilder sb = new StringBuilder();

            for (long filePointer = fileLength; filePointer != -1; filePointer--) {
                fileHandler.seek(filePointer);
                int readByte = fileHandler.readByte();

                if (readByte == 0xA) {
                    if (filePointer == fileLength) {
                        continue;
                    }
                    break;

                } else if (readByte == 0xD) {
                    if (filePointer == fileLength - 1) {
                        continue;
                    }
                    break;
                }

                sb.append((char) readByte);
            }

            String lastLine = sb.reverse().toString();
            cache.put(file, lastLine);
            return lastLine;
        } catch (java.io.FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fileHandler != null) {
                try {
                    fileHandler.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //this is not static in purpose
    public boolean shouldBeSkipped(File f) {
        if (isUnknown(f)) {
            return true;
        }
        return (isAborted(f) || isFailed(f));
    }

    private final Pattern ABRTD = Pattern.compile(".*ABORTED.*");
    private final Pattern FAILD = Pattern.compile(".*FAILURE.*");
    private final Pattern UNSTB = Pattern.compile(".*UNSTABLE.*");
    private final Pattern PASSD = Pattern.compile(".*SUCCESS.*");

    public boolean isAborted(File f) {
        return ABRTD.matcher(tail(creteLogFile(f))).matches();
    }

    public boolean isFailed(File f) {
        return FAILD.matcher(tail(creteLogFile(f))).matches();
    }

    public boolean isUnstable(File f) {
        return UNSTB.matcher(tail(creteLogFile(f))).matches();
    }

    public boolean isPassed(File f) {
        return PASSD.matcher(tail(creteLogFile(f))).matches();
    }

    public boolean isUnknown(File f) {
        if (!f.exists()) {
            return true;
        }
        try {
            return !(isAborted(f) || isFailed(f) || isUnstable(f) || isPassed(f));
        } catch (Exception ex) {
            ex.printStackTrace();
            return true;
        }
    }

}


text:
(function(global, utils) {

"use strict";

%CheckIsBootstrapping();

utils.InstallFunctions(global.Object, DONT_ENUM, $observeObjectMethods);
utils.InstallFunctions(global.Array, DONT_ENUM, $observeArrayMethods);

})


text:
#pragma once

#include "sm-common.h"

#include "dynarray.h"

#include <x86intrin.h>
#include <cstdint>
#include <utility>

// used for sparse bitmaps
typedef __v8hi v8hi;

namespace ermia {

struct sparse_bitset {
  static size_t const GAMUT = size_t(1) + UINT16_MAX;
  static size_t const CAPACITY_BYTES = 2 * sizeof(v8hi);
  static size_t const CAPACITY = CAPACITY_BYTES / sizeof(uint16_t);
  static_assert(not(CAPACITY & (CAPACITY - 1)),
                "CAPACITY must be a power of two");

  typedef uint16_t(Array)[CAPACITY];

  v8hi entries[2];
  static_assert(sizeof(Array) == sizeof(entries), "Fix CAPACITY");

  Array &as_array() { return **(Array **)entries; }

  struct iterator {
    uint16_t *entries;
    size_t i;
    uint16_t &operator*() { return entries[i]; }
    bool operator!=(iterator const &other) {
      return entries != other.entries or i != other.i;
    }
    void operator++() {
      if (not entries[++i]) i = CAPACITY;
    }
  };

  iterator begin() { return iterator{as_array(), 0}; }
  iterator end() { return iterator{as_array(), CAPACITY}; }

  /* Initialize the bitset. We have decreed that bitsets may not be
     empty, so initialize the first value.

     NOTE: we actually use uint16_t, but interpret the value as
     signed to keep the compiler happy.
   */
  void init1(int16_t i) {
    entries[0] = v8hi{i};
    entries[1] = v8hi{0};
  }

  /* Insert a value into the map. Return 0 if the insert succeeded
     normally, 1 if the map became full as a result of this insert,
     and -1 if the map was already full.

     WARNING: does *NOT* check for duplicates!
  */
  int insert(uint16_t i) {
#ifndef __clang__
    v8hi rotr_shufmask = {7, 0, 1, 2, 3, 4, 5, 6};
#endif
    if (not entries[0][7]) {
      /* Still working on the first half. We don't care whether
         [i] is zero, the [where] dance does the right thing
         either way.
      */
      int where = entries[0][0] ? 0 : 1;
#ifdef __clang__
      entries[0] = __builtin_shufflevector(entries[0], entries[0], 7, 0, 1, 2, 3, 4, 5, 6);
#else
      entries[0] = __builtin_shuffle(entries[0], rotr_shufmask);
#endif
      entries[0][where] = i;
      return 0;
    }

    // already full?
    if (entries[1][7]) return -1;

    if (not i) {
      // better not already be there!
      ASSERT(entries[0][0]);
      i = entries[0][0];
      entries[0][0] = 0;
    }

    // working on the second half now
#ifdef __clang__
    entries[1] = __builtin_shufflevector(entries[1], entries[1], 7, 0, 1, 2, 3, 4, 5, 6);
#else
    entries[1] = __builtin_shuffle(entries[1], rotr_shufmask);
#endif
    entries[1][0] = i;
    return entries[1][7] ? 1 : 0;
  }

#ifndef __clang__
  bool contains(uint16_t i) {
    // bit 0 is always first, if present.
    if (not i) return not entries[0][0];

    // otherwise, look for element matches
    int rval = __builtin_ia32_pmovmskb128(entries[0] == i);
    rval |= __builtin_ia32_pmovmskb128(entries[1] == i);
    return rval;
  }
  uint16_t size() {
    int a = __builtin_ia32_pmovmskb128(entries[0] != 0);
    a &= 0x5555;
    int b = __builtin_ia32_pmovmskb128(entries[1] != 0);
    b &= 0xaaaa;
    int c = 1;  // first entry is always present
    return __builtin_popcount(a | b | c);
  }
#endif
  void print(char const *name);
};

/* An allocator has (essentially) two jobs, one trivial, and one
   difficult. The easy job is allocating never-before-used objects,
   which can be done using a simple bump allocator. The hard job is
   recycling previously-freed objects, made difficult because we have
   to *find* those previously-freed objects in order to reuse them
   (which implies a need to efficiently track which ones have been
   freed, also a non-trivial task).

   We have here a multi-level allocator that attempts to strike a
   reasonable balance of time and space overheads versus precision
   (ability to recycle previously-freed objects).

   L0 is the bump allocator. It comprises a simple high water mark
   (identifying the highest OID ever allocated) and a capacity mark,
   that indicates how far bump allocation is allowed to proceed before
   the system attempts to reclaim freed OIDs (more on that later).

   L1 captures recently-freed OIDs. It is an array-based stack with
   several thousand entries, where OIDs are pushed on free and popped
   on allocate; the system will always drain L1 before bumping L0, and
   drains half of L1 to L2 each time L1 overflows.

   L2 serves to collect clusters of recently freed OIDs as they
   trickle in from L1. It uses sparse bitsets that can hold up to 16
   OIDs from a 64k-element swaths of the OID space. Swaths are
   assigned bitsets only if they contain at least one OID, and "full"
   bitsets (containing 16 OIDs) are retired to a list that will be
   drained after L1 is empty (and before bumping L0). Depending on the
   workload, L2 capacity ranges between 64k and 1M OIDs, usually with
   a small fraction of those OIDs available for easy re-allocation. L2
   is sized such there is one physical bitset for each swath of the
   OID space, so overflow can only occur if there are at least two
   full bitsets. By definition, L1 must also be full when L2
   overflows, so inconvenient bitsets drain to L3, one at a time, on
   overflow (see policy below). If L1 and L2 are both empty, the
   implementation prefers to scavenge non-full bitsets from L2
   (placing their OIDs into L1) if doing so would fill a significant
   fraction of L1. Otherwise, it prefers to bump L0.

   L3 is the lowest level of the allocator and captures all worst-case
   scenarios that defeat the higher levels. It is a dense bitmap, with
   one bit for every OID. Because the full bitmap is enormous (512MB),
   L3 starts out as small as possible and grows only if it needs to
   set a bit past the current end-of-storage. To minimize L3 growth,
   we prefer to spill non-full L2 entries that would fit in the
   existing L3 storage space. Failing that, we prefer to spill full L2
   entries that fit in the existing L3. Failing that, we spill
   remaining full L2 entries (at which point L2 is guaranteed to no
   longer be full and we stop).

   Although L1 and L2 should usually be effective at recycling most
   OIDs that are freed, a bad case could result in L1 and L2 both
   underflowing (even after scavenging L2) *and* the bump allocator
   being at capacity. At this point, we have two choices (assuming the
   allocator is not yet full-sized): scavenge L3 or increase the
   allocator's size (thus allowing bump allocation again). To prevent
   the allocator growing endlessly, we impose the policy that the
   allocator is only allowed to grow if doing so would make available
   fewer OIDs than could be reclaimed by scavenging L3. Since growing
   the allocator too much at a time would increase the risk of further
   overflows *and* L3 growth, we prefer to increase allocator size by
   small increments (e.g. 25%), which in turn would require us to
   scavenge L3 if more than 25% of all OIDs reside there. Note that,
   where sizes traditionally grow by doubling (increments of 100%),
   growing by increments of 25% is still geometric growth, and so
   allocation cost remains limited to amortized constant time.

   WARNING: this implementation does *not* deal with concurrency
   control at all, nor does it attempt to resize itself as the
   allocator grows. The user of this class is expected to deal with
   those issues, though the allocator provides helper functions to
   simplify resizing (CC should be as simple as grabbing a mutex).
*/

struct sm_allocator {
  /* We store all the "small" bits of allocator state in a separate
     header to simplify offset calculations and object construction.
   */
  struct header_data {
    /* Initialize this header, taking ownership of its own
       storage, which currently is owned by [self].
     */
    header_data(dynarray &&owner);

    // not copyable, not movable
    header_data() = delete;
    header_data(header_data const &) = delete;
    void operator=(header_data) = delete;

    /* The dynarray whose memory this allocator resides inside.
     */
    dynarray backing_store;

    /* This mark tells how high we are allowed to bump the high
       water mark before we have to consider scavenging L3.
    */
    OID capacity_mark;

    /* This mark is higher than any OID that has yet been
       allocated
     */
    OID hiwater_mark;

    /* How many free entries are in [l1] list?
     */
    uint16_t l1_size;

    /* How many full bitmaps are in [l2], ready to use?
     */
    uint32_t l2_size;

    /* What is the index, in [l2], where the first unused bitset
       resides? A value of zero means L2 does not yet exist.
    */
    uint32_t l2_first_unused;

    /* If we are reduced to scavenging L2 for loose OIDs, run an
       incremental sweep all the way across to avoid re-scanning
       the same areas with each allocation. A hand at position 0
       means no scan in progress (since any scan would examine at
       least one entry).
    */
    uint32_t l2_scan_hand;

    /* How many OIDs reside in non-full L2 bitmaps? We normally
       ignore these as "low grade ore", but it may become
       necessary to scavenge them if the allocator reaches full
       size and we're desperate to find usable OIDs.
    */
    uint32_t l2_loose_oids;

    /* How many words of OID bitmaps can L3 currently track? A
       size of zero means L3 does not exist yet (or any more).

       A full-sized L3 is huge (512MB), so we really prefer not to
       instantiate more than necessary. L1 and L2 already help a
       lot (by delaying the creation of L3 in the first place),
       and we can also give priority in L2 to OIDs that would
       cause L3 to grow.
    */
    uint32_t l3_capacity;

    /* How many OIDs reside in L3? We normally ignore this
       low-grade ore, but if the total reaches 25% of the capacity
       mark we have to scavenge L3 rather than increase capacity
       further.
    */
    uint32_t l3_loose_oids;

    /* Similar to the L2 case, where is the current scan hand, in
       case we are reduced to scavenging L3 for loose OIDs?
    */
    uint32_t l3_scan_hand;
  };

  /* Threads don't directly allocate OIDs from the central
     allocator. Instead, they grab a chunk of OIDs from it and then
     consume that chunk at their leisure, thus amortizing the cost
     of hitting the allocator over 32-64 allocations.

     Similarly, threads don't directly deallocate OIDs; instead,
     they queue them up and release them whenever their cache
     overflows.

     The cache is carefully sized to occupy an integer number of 64B
     cache lines.
   */
  struct thread_cache {
    /* When we ask to fill the cache from the central allocator,
       don't try to fill completely. We want some breathing room
       in case a bunch of OIDS suddenly go free, and also to give
       the allocator some flexibility in doling out OIDs.
     */
    enum : size_t { FILL_TARGET = 64 };
    enum : size_t { N = 126 };

    FID f;
    uint32_t nentries;
    OID entries[N];

    thread_cache(FID fid) : f(fid), nentries(0) {}

    uint32_t space_remaining() { return N - nentries; }
  };
  static_assert(is_aligned(sizeof(thread_cache), 64), "Go fix thread_cache::N");

  /* We will allocate things in chunks of 64kB, which should be
     page-aligned on almost all systems. We ignore huge pages here
     because they're not actually well-suited for our uses.
   */
  static size_t const ASSUMED_PAGE_SIZE = 1 << 16;

  /* How many bytes does an L1 allocator occupy? init() expects at
     least this many to be valid.
   */
  static size_t l1_alloc_size() {
    return OFFSETOF(sm_allocator, l1[L1_CAPACITY]);
  }

  /* How many bytes does an L2 allocator occupy? init2() expects at
     least this many to be valid.
   */
  static size_t l2_alloc_size() {
    return OFFSETOF(sm_allocator, l2_maps[L2_CAPACITY]);
  }

  /* How many bytes does an L3 allocator occupy if [end_word] marks
     the larger of its old and new end of storage? init3() expects
     at least this many to be valid.
   */
  static size_t l3_alloc_size(uint32_t end_word = L3_MAX_WORDS) {
    return OFFSETOF(sm_allocator, l3_words[end_word]);
  }

  static size_t max_alloc_size() { return l3_alloc_size(); };

  /* Used by template functions below */
  struct _nop_filter {
    bool operator()(OID) const { return true; }
  };

  /* Create a new, empty allocator. It contains only L0/L1, and
     attempts to access L2 or L3 are likely to fault.
  */
  static sm_allocator *make();

  static void destroy(sm_allocator *alloc);

 private:
  sm_allocator(dynarray &&self);

 public:
  /* Initialize a newly-available L2. L0 and L1 are left as-is, and
     L2 is empty.
   */
  void init_l2();
  bool l2_valid() const { return head.l2_first_unused; }

  /* Initialize L3 or change its size. L0-L2, and any existing parts
     of L3 not removed by this call, are left as-is. Because L3
     grows (and potentially shrinks) over time, this function can be
     called multiple times. The single arg specifies the number of
   */
  void init_l3(OID end_word);
  bool l3_valid() const { return head.l3_capacity; }
  OID l3_end() const { return head.l3_capacity * L3_BITS_PER_WORD; }

  /* How many bytes does the allocator currently use?
   */
  size_t alloc_size();

  /* If we were to grow the allocator, how large should it become?
     The caller would like the delta to be a multiple of [align] for
     space management reasons.

     Return zero if the allocator is full.

     NOTE: increasing capacity does not necessarily increase the
     number of byte the allocator occupies. The latter depends on
     the number of free OIDS and how inconvenient they are to
     record.
   */
  OID propose_capacity(size_t align);

  /* Place up to 64 OIDs in [tc], returning false if fewer than 64
     OIDs were available. Failure may indicate a need to grow or
     scavenge the allocator, or it may be that the allocator is
     truly full.
  */
  bool fill_cache(thread_cache *tc);

  /* Remove up to [target] entries from [tc] (all of them if
     [target]=0), returning false if the allocator was unable to
     absorb all entries.
   */
  bool drain_cache(thread_cache *tc, uint32_t target = 0);

  /* Run some consistency checks to see if there are any obvious
     problems with the current state of this allocator.
   */
  void sanity_check();

  /* Attempt to move [n] OIDs from L1 to [tc], returning the number
     that could not be placed.
   */
  int32_t _fill_from_l1(thread_cache *tc, uint32_t target);

  /* Attempt to drain [n] entries from L1 to L2. Return the number
     of entries that were not drained (positive implies full L2).
   */
  int32_t _drain_l1(uint32_t n);

  /* Scan L2 attempting to reclaim [n] OIDs from full
     bitsets. Whenever a full bitset is found, pass its base OID to
     filter(). If the latter returns false, skip that bitset;
     otherwise pass each OID it contains to sink() and deallocate
     the bitset.

     Return the number of OIDs (out of [n]) that were *not*
     reclaimed.

     WARNING: this function works with bitsets, not OIDS, and so the
     target might be passed by part of a bitset's capacity; the
     amount of overrun will be reported as a negative return value.
   */
  template <typename Filter, typename Sink>
  int32_t _scan_l2(uint32_t n, Filter const &filter, Sink const &sink);

  template <typename Sink>
  int32_t _scan_l2(uint32_t n, Sink const &sink) {
    return _scan_l2(n, _nop_filter(), sink);
  }

  /* Attempt to move at least [n] (and less than
     [n+sparse_bitset::CAPACITY] OIDs from L2 to [tc], returning the
     number that could not be placed.

     WARNING: This function deals only in full bitsets, so [tc] must
     have enough room to absorb a full bitset (minus one) worth of
     OIDs beyond those asked for.
   */
  int32_t _fill_from_l2(thread_cache *tc, uint32_t n);

  /* Scavenge L2 attempting to reclaim [n] loose OIDs. Whenever a
     non-empty bitset is found, pass its base OID to filter(). If
     the latter returns false, skip the bitset; otherwise pass each
     OID it contains to sink() and deallocate the bitset.

     Return the number of OIDs (out of [n]) that were *not*
     reclaimed.

     WARNING: this function works with bitsets, not OIDS, and so the
     target might be passed by part of a bitset's capacity; the
     amount of overrun will be reported as a negative return value.
   */
  template <typename Filter, typename Sink>
  int32_t _scavenge_l2(uint32_t n, Filter const &filter, Sink const &sink);

  template <typename Sink>
  int32_t _scavenge_l2(uint32_t n, Sink const &sink) {
    return _scavenge_l2(n, _nop_filter(), sink);
  }

  /* Scavenge L2 for [n] loose OIDs that can be placed in L1. If at
     least [n] were available, reclaim them and return
     [true]. Otherwise, do nothing and return [false].

     WARNING: All OIDs in a bitset are reclaimed at once, so [n] may
     be passed by part of a bitset's capacity.
  */
  int32_t _scavenge_l2(uint32_t n);

  /* Attempt to drain [n] entries from L2 to L3. Return the number
     of entries that were not drained (so non-zero means L3 could
     not accept them all, probably because L3 needs to grow).

     Return a negative number if the target was overrun (by
     something less than a bitset's capacity).
   */
  int32_t _drain_l2(uint32_t n);

  /* Add an OID to L3
   */
  void _insert_l3(OID x);

  /* Scavenge L3 attempting to reclaim [n] loose OIDs. Whenever a
     non-empty bitset is found, pass its base OID to filter(). If
     the latter returns false, skip the bitset; otherwise pass each
     OID it contains to sink() and deallocate the bitset.

     Return the number of OIDs (out of [n]) that were *not*
     reclaimed.

     WARNING: this function works with dense bitmaps, not OIDS, and
     so the target might be passed by up to L3_BITS_PER_WORD; the
     amount of overrun will be reported as a negative return value.
   */
  template <typename Filter, typename Sink>
  int32_t _scavenge_l3(uint32_t n, Filter const &filter, Sink const &sink);

  template <typename Sink>
  int32_t _scavenge_l3(uint32_t n, Sink const &sink) {
    return _scavenge_l3(n, _nop_filter(), sink);
  }

  /* Scavenge L3 for up to [n] loose OIDs that can be placed in L1
     and L2. Return the number of OIDs that could not be reclaimed.
  */
  int32_t _scavenge_l3(uint32_t n);

  /**********************************************
   * * * * Header (always safe to access) * * * *
   **********************************************/
  static size_t const MAX_CAPACITY_MARK = OID(~OID(0)) - 1;
  header_data head;

  /******************************************
   * * * * L1 (always safe to access) * * * *
   ******************************************/

  static size_t const L1_CAPACITY_BYTES = ASSUMED_PAGE_SIZE - sizeof(head);
  static size_t const L1_CAPACITY = L1_CAPACITY_BYTES / sizeof(OID);

  OID l1[L1_CAPACITY];

  /********************************************************
   * * * * L2 (only safe if header.l2_capacity > 0) * * * *
   ********************************************************/

  /* In theory, we could grow L2 gradually, the way we do for L3,
     but the complexity is just not worth it: L2 only occupies a bit
     more than 2MB anyway.
   */
  static size_t const L2_CAPACITY = size_t(1) + UINT16_MAX;

  /* This array holds full sparse maps that are ready to use. The
     low 16 bits identify which sparse map is involved. Masking off
     the low 16 bits gives the first OID of the span.

     NOTE: we "borrow" the unused space in this array to hold unused
     bitsets. Unused bitsets are stored at the right side of the
     array, with the leftmost (first) residing at []. The fixed
     number of bitsets means there is always room for both (probably
     with room to spare, since most bitsets will be in-use but
     non-full.
   */
  uint32_t l2[L2_CAPACITY];

  /* Each span of 64k OIDs in the OID space can be covered by a
     sparse bitmap. Record here which bitmap a given span is
     assigned (0 if none). Note that this means bitmap 0 is unused.
   */
  uint16_t l2_assignments[L2_CAPACITY];

  /* We break the 32-bit OID space into 64k spans of 64k OIDs
     each. We can thus save space by liberal use of 16-bit
     integers. Note: we allocate a potentially smaller number of
     bitsets to spans on an as-needed basis (see [l2_capacity]).
   */
  sparse_bitset l2_maps[L2_CAPACITY];

  /********************************************************
   * * * * L3 (only safe if header.l3_capacity > 0) * * * *
   ********************************************************/

  static size_t const L3_BITS_PER_WORD = 8 * sizeof(uint64_t);
  static size_t const L3_MAX_WORDS = UINT32_MAX / L3_BITS_PER_WORD + 1;

  /* The bitmap data that comprises L3. Hopefully we never need it,
     but if L2 fails, L3 can capture *anything* an adversary throws
     at it.
   */
  uint64_t l3_words[];
};

//static_assert(sm_allocator::l1_alloc_size() == sm_allocator::ASSUMED_PAGE_SIZE,
//              "Go fix allocator::L1_CAPACITY");
//static_assert(is_aligned(sm_allocator::l2_alloc_size(),
//                         sm_allocator::ASSUMED_PAGE_SIZE),
//              "Something went wrong with L2 sizing");
}  // namespace ermia


text:
import io
from os import path
from unittest.mock import Mock

import pytest

from pattern_matcher.io import Output, Input
from pattern_matcher.pattern_matcher import PathMatcher
from pattern_matcher.patterns import MultipleMatchesError

TEST_DIR = path.dirname(path.abspath(__file__))
TEST_DATA_DIR = path.join(TEST_DIR, 'test_data')

class TestPathMatcher(object):

    def test_match(self):
        with open(path.join(TEST_DATA_DIR, 'input1.txt')) as f:
            patterns, _input = Input.parse(f)
            output = Output(io.StringIO())

            pm = PathMatcher(patterns, _input, output)
            pm.match()

        matches = output.stream.getvalue()
        matches = [match for match in matches.split('\n') if match]
        no_matches = [match for match in matches if match == 'NO MATCH']

        assert len(matches) == 5
        assert len(no_matches) == 2

    def test_find_best_match_finds_match(self):
        _input = Mock(spec=Input)
        output = Mock(spec=Output)
        patterns = '*,bar\n'
        pm = PathMatcher(patterns, _input, output)

        match = pm.find_best_match('foo/bar')
        assert str(match) == '*,bar'

    def test_find_best_match_finds_no_match(self):
        _input = Mock(spec=Input)
        output = Mock(spec=Output)
        patterns = ''
        pm = PathMatcher(patterns, _input, output)

        match = pm.find_best_match('foo/bar')
        assert match == 'NO MATCH'

    def test_find_best_match_gets_exception(self):
        _input = Mock(spec=Input)
        output = Mock(spec=Output)
        patterns = 'foo,bar\nfoo,bar\n'
        pm = PathMatcher(patterns, _input, output)

        with pytest.raises(MultipleMatchesError):
            pm.find_best_match('foo/bar')


text:
//
// Novell.Directory.Ldap.LdapException.cs
//
// Author:
//   Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//

using System;
using Novell.Directory.LDAP.VQ.Utilclass;

namespace Novell.Directory.LDAP.VQ
{
    ///   Thrown to indicate that an Ldap exception has occurred. This is a general
    /// exception which includes a message and an Ldap result code.
    ///
    /// An LdapException can result from physical problems (such as
    /// network errors) as well as problems with Ldap operations detected
    /// by the server. For example, if an Ldap add operation fails because of a
    /// duplicate entry, the server returns a result code.
    ///
    /// Five possible sources of information are available from LdapException:
    ///

    ///
Result Code:

    ///
The getResultCode method returns a result code,
    /// which can be compared against standard Ldap result codes.

    ///
Message:

    ///
The getMessage method returns a localized message
    /// from the message resource that corresponds to the result code.
    ///

    ///
Ldap server Message:

    ///
The getLdapErrorMessage method returns any error
    /// message received from the Ldap server.

    ///
Matched DN:

    ///
The getMatchedDN method retrieves the part of a
    /// submitted distinguished name which could be matched by the server

    ///
Root Cause:

    ///
The getCause method returns the a nested exception
    /// that was the original cause for the error.

    ///

    ///
    /// The ToString method returns a string containing all
    /// the above sources of information, if they have a value.
    ///
    /// Exceptions generated by the API, i.e. that are not a result
    /// of a server response, can be identified as <tt>instanceof
    /// {@link LdapLocalException}</tt>
    ///
    /// The following table lists the standard Ldap result codes.
    /// See RFC2251 for a discussion of the meanings of the result codes.
    /// The corresponding ASN.1 definition from RFC2251 is provided in parentheses.
    ///

    ///

    /// Value
    /// Result Code
    ///

    ///
 0	{@link #SUCCESS} (success)

    ///
 1	{@link #OPERATIONS_ERROR} (operationsError)

    ///
 2	{@link #PROTOCOL_ERROR} (protocolError)

    ///
 3	{@link #TIME_LIMIT_EXCEEDED} (timeLimitExceeded)

    ///
 4	{@link #SIZE_LIMIT_EXCEEDED} (sizeLimitExceeded)

    ///
 5	{@link #COMPARE_FALSE} (compareFalse)

    ///
 6	{@link #COMPARE_TRUE} (compareTrue)

    ///
 7	{@link #AUTH_METHOD_NOT_SUPPORTED} (authMethodNotSupported)

    ///
 8	{@link #STRONG_AUTH_REQUIRED} (strongAuthRequired)

    ///
 10	{@link #REFERRAL} (referral)

    ///
 11	{@link #ADMIN_LIMIT_EXCEEDED} (adminLimitExceeded)

    ///
 12	{@link #UNAVAILABLE_CRITICAL_EXTENSION} (unavailableCriticalExtension)

    ///
 13	{@link #CONFIDENTIALITY_REQUIRED} (confidentialityRequired)

    ///
 14	{@link #SASL_BIND_IN_PROGRESS} (saslBindInProgress)

    ///
 16	{@link #NO_SUCH_ATTRIBUTE} (noSuchAttribute)

    ///
 17	{@link #UNDEFINED_ATTRIBUTE_TYPE} (undefinedAttributeType)

    ///
 18	{@link #INAPPROPRIATE_MATCHING} (inappropriateMatching)

    ///
 19	{@link #CONSTRAINT_VIOLATION} (constraintViolation)

    ///
 20	{@link #ATTRIBUTE_OR_VALUE_EXISTS} (AttributeOrValueExists)

    ///
 21	{@link #INVALID_ATTRIBUTE_SYNTAX} (invalidAttributeSyntax)

    ///
 32	{@link #NO_SUCH_OBJECT} (noSuchObject)

    ///
 33	{@link #ALIAS_PROBLEM} (aliasProblem)

    ///
 34	{@link #INVALID_DN_SYNTAX} (invalidDNSyntax)

    ///
 35	{@link #IS_LEAF} (isLeaf)

    ///
 36	{@link #ALIAS_DEREFERENCING_PROBLEM} (aliasDereferencingProblem)

    ///
 48	{@link #INAPPROPRIATE_AUTHENTICATION} (inappropriateAuthentication)

    ///
 49	{@link #INVALID_CREDENTIALS} (invalidCredentials)

    ///
 50	{@link #INSUFFICIENT_ACCESS_RIGHTS} (insufficientAccessRights)

    ///
 51	{@link #BUSY} (busy)

    ///
 52	{@link #UNAVAILABLE} (unavailable)

    ///
 53	{@link #UNWILLING_TO_PERFORM} (unwillingToPerform)

    ///
 54	{@link #LOOP_DETECT} (loopDetect)

    ///
 64	{@link #NAMING_VIOLATION} (namingViolation)

    ///
 65	{@link #OBJECT_CLASS_VIOLATION} (objectClassViolation)

    ///
 66	{@link #NOT_ALLOWED_ON_NONLEAF} (notAllowedOnNonLeaf)

    ///
 67	{@link #NOT_ALLOWED_ON_RDN} (notAllowedOnRDN)

    ///
 68	{@link #ENTRY_ALREADY_EXISTS} (entryAlreadyExists)

    ///
 69	{@link #OBJECT_CLASS_MODS_PROHIBITED} (objectClassModsProhibited)

    ///
 71	{@link #AFFECTS_MULTIPLE_DSAS} (affectsMultipleDSAs

    ///
 80	{@link #OTHER} (other)

    ///

    ///
    /// Local errors, resulting from actions other than an operation on a
    /// server.
    ///
    ///

    ///

    /// Value
    /// Result Code
    ///

    ///
81	{@link #SERVER_DOWN}

    ///
82	{@link #LOCAL_ERROR}

    ///
83	{@link #ENCODING_ERROR}

    ///
84	{@link #DECODING_ERROR}

    ///
85	{@link #Ldap_TIMEOUT}

    ///
86	{@link #AUTH_UNKNOWN}

    ///
87	{@link #FILTER_ERROR}

    ///
88	{@link #USER_CANCELLED}

    ///
90	{@link #NO_MEMORY}

    ///
91	{@link #CONNECT_ERROR}

    ///
92	{@link #Ldap_NOT_SUPPORTED}

    ///
93	{@link #CONTROL_NOT_FOUND}

    ///
94	{@link #NO_RESULTS_RETURNED}

    ///
95	{@link #MORE_RESULTS_TO_RETURN}

    ///
96	{@link #CLIENT_LOOP}

    ///
97	{@link #REFERRAL_LIMIT_EXCEEDED}

    ///
100	{@link #INVALID_RESPONSE}

    ///
101	{@link #AMBIGUOUS_RESPONSE}

    ///
112	{@link #TLS_NOT_SUPPORTED}

    ///

    ///

    public class LdapException : Exception
    {
        ///  Returns the error message from the Ldap server, if this message is
        /// available (that is, if this message was set). If the message was not set,
        /// this method returns null.
        ///
        ///
        /// <returns> The error message or null if the message was not set.
        ///
        /// </returns>
        virtual public string LdapErrorMessage
        {
            get
            {
                if (((object)serverMessage != null) && (serverMessage.Length == 0))
                {
                    return null;
                }
                return serverMessage;
            }
        }
        ///  Returns the lower level Exception which caused the failure, if any.
        /// For example, an IOException with additional information may be returned
        /// on a CONNECT_ERROR failure.
        ///
        virtual public Exception Cause
        {
            get
            {
                return rootException;
            }
        }
        ///  Returns the result code from the exception.
        ///
        /// The codes are defined as public final static int members
        /// of the Ldap Exception class. If the exception is a
        /// result of error information returned from a directory operation, the
        /// code will be one of those defined for the class. Otherwise, a local error
        /// code is returned.
        ///
        virtual public int ResultCode
        {
            get
            {
                return resultCode;
            }
        }
        ///  Returns the part of a submitted distinguished name which could be
        /// matched by the server.
        ///
        /// If the exception was caused by a local error, such as no server
        /// available, the return value is null. If the exception resulted from
        /// an operation being executed on a server, the value is an empty string
        /// except when the result of the operation was one of the following:
        ///

        ///
NO_SUCH_OBJECT

        ///
ALIAS_PROBLEM

        ///
INVALID_DN_SYNTAX

        ///
ALIAS_DEREFERENCING_PROBLEM

        ///

        ///
        ///
        /// <returns> The part of a submitted distinguished name which could be
        /// matched by the server or null if the error is a local error.
        /// </returns>
        virtual public string MatchedDN
        {
            get
            {
                return matchedDN;
            }
        }

        public override string Message
        {
            get
            {
                return resultCodeToString();
            }
        }
        /*	public override string Message
            {
                get
                {
                    return resultCodeToString();
                }

            }
        */
        // The Result Code
        private int resultCode = 0;
        // The localized message
        private string messageOrKey = null;
        // The arguments associated with the localized message
        private object[] arguments = null;
        // The Matched DN
        private string matchedDN = null;
        // The Root Cause
        private Exception rootException = null;
        // A message from the server
        private string serverMessage = null;

        /// Indicates the requested client operation completed successfully.
        ///
        /// SUCCESS = 0

        ///
        public const int SUCCESS = 0;

        ///  Indicates an internal error.
        ///
        /// The server is unable to respond with a more specific error and is
        /// also unable to properly respond to a request. It does not indicate
        /// that the client has sent an erroneous message.
        ///
        /// OPERATIONS_ERROR = 1
        ///
        public const int OPERATIONS_ERROR = 1;

        ///  Indicates that the server has received an invalid or malformed request
        /// from the client.
        ///
        /// PROTOCOL_ERROR = 2
        ///
        public const int PROTOCOL_ERROR = 2;

        ///  Indicates that the operation's time limit specified by either the
        /// client or the server has been exceeded.
        ///
        /// On search operations, incomplete results are returned.
        ///
        /// TIME_LIMIT_EXCEEDED = 3
        ///
        public const int TIME_LIMIT_EXCEEDED = 3;

        ///  Indicates that in a search operation, the size limit specified by
        /// the client or the server has been exceeded. Incomplete results are
        /// returned.
        ///
        /// SIZE_LIMIT_EXCEEDED = 4
        ///
        public const int SIZE_LIMIT_EXCEEDED = 4;

        ///  Does not indicate an error condition. Indicates that the results of
        /// a compare operation are false.
        ///
        /// COMPARE_FALSE = 5
        ///
        public const int COMPARE_FALSE = 5;

        ///  Does not indicate an error condition. Indicates that the results of a
        /// compare operation are true.
        ///
        /// COMPARE_TRUE = 6
        ///
        public const int COMPARE_TRUE = 6;

        ///  Indicates that during a bind operation the client requested an
        /// authentication method not supported by the Ldap server.
        ///
        /// AUTH_METHOD_NOT_SUPPORTED = 7
        ///
        public const int AUTH_METHOD_NOT_SUPPORTED = 7;

        /// Indicates a problem with the level of authentication.
        ///
        /// One of the following has occurred:
        ///

        ///
In bind requests, the Ldap server accepts only strong
        /// authentication.

        ///
In a client request, the client requested an operation such as delete
        /// that requires strong authentication.

        ///
In an unsolicited notice of disconnection, the Ldap server discovers
        /// the security protecting the communication between the client and
        /// server has unexpectedly failed or been compromised.

        ///

        /// STRONG_AUTH_REQUIRED = 8
        ///
        public const int STRONG_AUTH_REQUIRED = 8;

        ///  Returned by some Ldap servers to Ldapv2 clients to indicate that a referral
        /// has been returned in the error string.
        ///
        /// Ldap_PARTIAL_RESULTS = 9
        ///
        public const int Ldap_PARTIAL_RESULTS = 9;

        ///  Does not indicate an error condition. In Ldapv3, indicates that the server
        /// does not hold the target entry of the request, but that the servers in the
        /// referral field may.
        ///
        /// REFERRAL = 10
        ///
        public const int REFERRAL = 10;

        ///  Indicates that an Ldap server limit set by an administrative authority
        /// has been exceeded.
        ///
        /// ADMIN_LIMIT_EXCEEDED = 11
        ///
        public const int ADMIN_LIMIT_EXCEEDED = 11;

        ///  Indicates that the Ldap server was unable to satisfy a request because
        /// one or more critical extensions were not available.
        ///
        /// Either the server does not support the control or the control is not
        /// appropriate for the operation type.
        ///
        /// UNAVAILABLE_CRITICAL_EXTENSION = 12
        ///
        public const int UNAVAILABLE_CRITICAL_EXTENSION = 12;

        ///  Indicates that the session is not protected by a protocol such as
        /// Transport Layer Security (TLS), which provides session confidentiality.
        ///
        /// CONFIDENTIALITY_REQUIRED = 13
        ///
        public const int CONFIDENTIALITY_REQUIRED = 13;

        ///  Does not indicate an error condition, but indicates that the server is
        /// ready for the next step in the process. The client must send the server
        /// the same SASL mechanism to continue the process.
        ///
        /// SASL_BIND_IN_PROGRESS = 14
        ///
        public const int SASL_BIND_IN_PROGRESS = 14;

        ///  Indicates that the attribute specified in the modify or compare
        /// operation does not exist in the entry.
        ///
        /// NO_SUCH_ATTRIBUTE = 16
        ///
        public const int NO_SUCH_ATTRIBUTE = 16;

        ///  Indicates that the attribute specified in the modify or add operation
        /// does not exist in the Ldap server's schema.
        ///
        /// UNDEFINED_ATTRIBUTE_TYPE = 17
        ///
        public const int UNDEFINED_ATTRIBUTE_TYPE = 17;

        ///  Indicates that the matching rule specified in the search filter does
        /// not match a rule defined for the attribute's syntax.
        ///
        /// INAPPROPRIATE_MATCHING = 18
        ///
        public const int INAPPROPRIATE_MATCHING = 18;

        ///  Indicates that the attribute value specified in a modify, add, or
        /// modify DN operation violates constraints placed on the attribute. The
        /// constraint can be one of size or content (for example, string only,
        /// no binary data).
        ///
        /// CONSTRAINT_VIOLATION = 19
        ///
        public const int CONSTRAINT_VIOLATION = 19;

        ///  Indicates that the attribute value specified in a modify or add
        /// operation already exists as a value for that attribute.
        ///
        /// ATTRIBUTE_OR_VALUE_EXISTS = 20
        ///
        public const int ATTRIBUTE_OR_VALUE_EXISTS = 20;

        ///  Indicates that the attribute value specified in an add, compare, or
        /// modify operation is an unrecognized or invalid syntax for the attribute.
        ///
        /// INVALID_ATTRIBUTE_SYNTAX = 21
        ///
        public const int INVALID_ATTRIBUTE_SYNTAX = 21;

        ///  Indicates the target object cannot be found.
        ///
        /// This code is not returned on the following operations:
        ///

        ///
Search operations that find the search base but cannot find any
        /// entries that match the search filter.

        ///
Bind operations.

        ///

        /// NO_SUCH_OBJECT = 32
        ///
        public const int NO_SUCH_OBJECT = 32;

        ///  Indicates that an error occurred when an alias was dereferenced.
        ///
        /// ALIAS_PROBLEM = 33
        ///
        public const int ALIAS_PROBLEM = 33;

        ///  Indicates that the syntax of the DN is incorrect.
        ///
        /// If the DN syntax is correct, but the Ldap server's structure
        /// rules do not permit the operation, the server returns
        /// Ldap_UNWILLING_TO_PERFORM.
        ///
        /// INVALID_DN_SYNTAX = 34
        ///
        public const int INVALID_DN_SYNTAX = 34;

        ///  Indicates that the specified operation cannot be performed on a
        /// leaf entry.
        ///
        /// This code is not currently in the Ldap specifications, but is
        /// reserved for this constant.
        ///
        /// IS_LEAF = 35
        ///
        public const int IS_LEAF = 35;

        ///  Indicates that during a search operation, either the client does not
        /// have access rights to read the aliased object's name or dereferencing
        /// is not allowed.
        ///
        /// ALIAS_DEREFERENCING_PROBLEM = 36
        ///
        public const int ALIAS_DEREFERENCING_PROBLEM = 36;

        ///  Indicates that during a bind operation, the client is attempting to use
        /// an authentication method that the client cannot use correctly.
        ///
        ///  For example, either of the following cause this error:
        ///

        ///
The client returns simple credentials when strong credentials are
        /// required.

        ///
The client returns a DN and a password for a simple bind when the
        /// entry does not have a password defined.

        ///

        /// INAPPROPRIATE_AUTHENTICATION = 48
        ///
        public const int INAPPROPRIATE_AUTHENTICATION = 48;

        ///  Indicates that invalid information was passed during a bind operation.
        ///
        /// One of the following occurred:
        ///

        ///
 The client passed either an incorrect DN or password.

        ///
 The password is incorrect because it has expired, intruder detection
        /// has locked the account, or some other similar reason.

        ///

        /// INVALID_CREDENTIALS = 49
        ///
        public const int INVALID_CREDENTIALS = 49;

        ///  Indicates that the caller does not have sufficient rights to perform
        /// the requested operation.
        ///
        /// INSUFFICIENT_ACCESS_RIGHTS = 50
        ///
        public const int INSUFFICIENT_ACCESS_RIGHTS = 50;

        ///  Indicates that the Ldap server is too busy to process the client request
        /// at this time, but if the client waits and resubmits the request, the
        /// server may be able to process it then.
        ///
        /// BUSY = 51
        ///
        public const int BUSY = 51;

        ///  Indicates that the Ldap server cannot process the client's bind
        /// request, usually because it is shutting down.
        ///
        /// UNAVAILABLE = 52
        ///
        public const int UNAVAILABLE = 52;

        ///  Indicates that the Ldap server cannot process the request because of
        /// server-defined restrictions.
        ///
        /// This error is returned for the following reasons:
        ///

        ///
The add entry request violates the server's structure rules.

        ///
The modify attribute request specifies attributes that users
        /// cannot modify.

        ///

        /// UNWILLING_TO_PERFORM = 53
        ///
        public const int UNWILLING_TO_PERFORM = 53;

        ///  Indicates that the client discovered an alias or referral loop,
        /// and is thus unable to complete this request.
        ///
        /// LOOP_DETECT = 54
        ///
        public const int LOOP_DETECT = 54;

        ///  Indicates that the add or modify DN operation violates the schema's
        /// structure rules.
        ///
        /// For example,
        ///

        ///
The request places the entry subordinate to an alias.

        ///
The request places the entry subordinate to a container that
        /// is forbidden by the containment rules.

        ///
The RDN for the entry uses a forbidden attribute type.

        ///

        /// NAMING_VIOLATION = 64
        ///
        public const int NAMING_VIOLATION = 64;

        ///  Indicates that the add, modify, or modify DN operation violates the
        /// object class rules for the entry.
        ///
        /// For example, the following types of request return this error:
        ///

        ///
The add or modify operation tries to add an entry without a value
        /// for a required attribute.

        ///
The add or modify operation tries to add an entry with a value for
        /// an attribute which the class definition does not contain.

        ///
The modify operation tries to remove a required attribute without
        /// removing the auxiliary class that defines the attribute as required.

        ///

        /// OBJECT_CLASS_VIOLATION = 65
        ///
        public const int OBJECT_CLASS_VIOLATION = 65;

        ///  Indicates that the requested operation is permitted only on leaf entries.
        ///
        /// For example, the following types of requests return this error:
        ///

        ///
The client requests a delete operation on a parent entry.

        ///
 The client request a modify DN operation on a parent entry.

        ///

        /// NOT_ALLOWED_ON_NONLEAF = 66
        ///
        public const int NOT_ALLOWED_ON_NONLEAF = 66;

        ///  Indicates that the modify operation attempted to remove an attribute
        /// value that forms the entry's relative distinguished name.
        ///
        /// NOT_ALLOWED_ON_RDN = 67
        ///
        public const int NOT_ALLOWED_ON_RDN = 67;

        ///  Indicates that the add operation attempted to add an entry that already
        /// exists, or that the modify operation attempted to rename an entry to the
        /// name of an entry that already exists.
        ///
        /// ENTRY_ALREADY_EXISTS = 68
        ///
        public const int ENTRY_ALREADY_EXISTS = 68;

        ///  Indicates that the modify operation attempted to modify the structure
        /// rules of an object class.
        ///
        /// OBJECT_CLASS_MODS_PROHIBITED = 69
        ///
        public const int OBJECT_CLASS_MODS_PROHIBITED = 69;

        ///  Indicates that the modify DN operation moves the entry from one Ldap
        /// server to another and thus requires more than one Ldap server.
        ///
        /// AFFECTS_MULTIPLE_DSAS = 71
        ///
        public const int AFFECTS_MULTIPLE_DSAS = 71;

        ///  Indicates an unknown error condition.
        ///
        /// OTHER = 80
        ///
        public const int OTHER = 80;

        /////////////////////////////////////////////////////////////////////////////
        // Local Errors, resulting from actions other than an operation on a server
        /////////////////////////////////////////////////////////////////////////////

        ///  Indicates that the Ldap libraries cannot establish an initial connection
        /// with the Ldap server. Either the Ldap server is down or the specified
        /// host name or port number is incorrect.
        ///
        /// SERVER_DOWN = 81
        ///
        public const int SERVER_DOWN = 81;

        ///  Indicates that the Ldap client has an error. This is usually a failed
        /// dynamic memory allocation error.
        ///
        /// LOCAL_ERROR = 82
        ///
        public const int LOCAL_ERROR = 82;

        ///  Indicates that the Ldap client encountered errors when encoding an
        /// Ldap request intended for the Ldap server.
        ///
        /// ENCODING_ERROR = 83
        ///
        public const int ENCODING_ERROR = 83;

        ///  Indicates that the Ldap client encountered errors when decoding an
        /// Ldap response from the Ldap server.
        ///
        /// DECODING_ERROR = 84
        ///
        public const int DECODING_ERROR = 84;

        ///  Indicates that the time limit of the Ldap client was exceeded while
        /// waiting for a result.
        ///
        /// Ldap_TIMEOUT = 85
        ///
        public const int Ldap_TIMEOUT = 85;

        ///  Indicates that a bind method was called with an unknown
        /// authentication method.
        ///
        /// AUTH_UNKNOWN = 86
        ///
        public const int AUTH_UNKNOWN = 86;

        ///  Indicates that the search method was called with an invalid
        /// search filter.
        ///
        /// FILTER_ERROR = 87
        ///
        public const int FILTER_ERROR = 87;

        ///  Indicates that the user cancelled the Ldap operation.
        ///
        /// USER_CANCELLED = 88
        ///
        public const int USER_CANCELLED = 88;

        ///  Indicates that a dynamic memory allocation method failed when calling
        /// an Ldap method.
        ///
        /// NO_MEMORY = 90
        ///
        public const int NO_MEMORY = 90;

        ///  Indicates that the Ldap client has lost either its connection or
        /// cannot establish a connection to the Ldap server.
        ///
        /// CONNECT_ERROR = 91
        ///
        public const int CONNECT_ERROR = 91;

        ///  Indicates that the requested functionality is not supported by the
        /// client. For example, if the Ldap client is established as an Ldapv2
        /// client, the libraries set this error code when the client requests
        /// Ldapv3 functionality.
        ///
        /// Ldap_NOT_SUPPORTED = 92
        ///
        public const int Ldap_NOT_SUPPORTED = 92;

        ///  Indicates that the client requested a control that the libraries
        /// cannot find in the list of supported controls sent by the Ldap server.
        ///
        /// CONTROL_NOT_FOUND = 93
        ///
        public const int CONTROL_NOT_FOUND = 93;

        ///  Indicates that the Ldap server sent no results.
        ///
        /// NO_RESULTS_RETURNED = 94
        ///
        public const int NO_RESULTS_RETURNED = 94;

        ///  Indicates that more results are chained in the result message.
        ///
        /// MORE_RESULTS_TO_RETURN = 95
        ///
        public const int MORE_RESULTS_TO_RETURN = 95;

        ///  Indicates the Ldap libraries detected a loop. Usually this happens
        /// when following referrals.
        ///
        /// CLIENT_LOOP = 96
        ///
        public const int CLIENT_LOOP = 96;

        ///  Indicates that the referral exceeds the hop limit. The default hop
        /// limit is ten.
        ///
        /// The hop limit determines how many servers the client can hop through
        /// to retrieve data. For example, suppose the following conditions:
        ///

        ///
Suppose the hop limit is two.

        ///
 If the referral is to server D which can be contacted only through
        /// server B (1 hop) which contacts server C (2 hops) which contacts
        /// server D (3 hops).

        ///

        ///  With these conditions, the hop limit is exceeded and the Ldap
        /// libraries set this code.
        ///
        /// REFERRAL_LIMIT_EXCEEDED = 97
        ///
        public const int REFERRAL_LIMIT_EXCEEDED = 97;

        ///  Indicates that the server response to a request is invalid.
        ///
        /// INVALID_RESPONSE = 100
        ///
        public const int INVALID_RESPONSE = 100;

        ///  Indicates that the server response to a request is ambiguous.
        ///
        /// AMBIGUOUS_RESPONSE = 101
        ///
        public const int AMBIGUOUS_RESPONSE = 101;

        ///  Indicates that TLS is not supported on the server.
        ///
        /// TLS_NOT_SUPPORTED = 112
        ///
        public const int TLS_NOT_SUPPORTED = 112;

        ///  Indicates that SSL Handshake could not succeed.
        ///
        /// SSL_HANDSHAKE_FAILED = 113
        ///
        public const int SSL_HANDSHAKE_FAILED = 113;

        ///  Indicates that SSL Provider could not be found.
        ///
        /// SSL_PROVIDER_NOT_FOUND = 114
        ///
        public const int SSL_PROVIDER_NOT_FOUND = 114;
        /*
		* Note: Error strings have been pulled out into
		* ResultCodeMessages.txt
		*/

        ///  Constructs a default exception with no specific error information.
        public LdapException() : base()
        {
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String, the result code,
        /// and a server meessage.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        /// </param>
        public LdapException(string messageOrKey, int resultCode, string serverMsg) : this(messageOrKey, null, resultCode, serverMsg, null, null)
        {
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String and modifying arguments.
        /// Additional parameters specify the result code and server message.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        /// The message in the default locale is built with the supplied arguments,
        /// which are saved to be used for building messages for other locales.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="arguments">   The modifying arguments to be included in the
        /// message string.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        /// </param>
        public LdapException(string messageOrKey, object[] arguments, int resultCode, string serverMsg) : this(messageOrKey, arguments, resultCode, serverMsg, null, null)
        {
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String.
        /// Additional parameters specify the result code, the server message, and a
        /// rootException which is the underlying cause of an error on the client.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        ///
        /// </param>
        /// <param name="rootException"> A throwable which is the underlying cause
        /// of the LdapException.
        /// </param>
        public LdapException(string messageOrKey, int resultCode, string serverMsg, Exception rootException) : this(messageOrKey, null, resultCode, serverMsg, null, rootException)
        {
            return;
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String and modifying arguments.
        /// Additional parameters specify the result code, the server message,
        /// and a rootException which is the underlying cause of an error
        /// on the client.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        /// The message in the default locale is built with the supplied arguments,
        /// which are saved to be used for building messages for other locales.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="arguments">   The modifying arguments to be included in the
        /// message string.
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        ///
        /// </param>
        /// <param name="rootException"> A throwable which is the underlying cause
        /// of the LdapException.
        /// </param>
        public LdapException(string messageOrKey, object[] arguments, int resultCode, string serverMsg, Exception rootException) : this(messageOrKey, arguments, resultCode, serverMsg, null, rootException)
        {
            return;
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String.
        /// Additional parameters specify the result code, the message returned
        /// from the server, and a matchedDN returned from the server.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        ///
        /// </param>
        /// <param name="matchedDN">     The maximal subset of a specified DN which could
        /// be matched by the server on a search operation.
        /// </param>
        public LdapException(string messageOrKey, int resultCode, string serverMsg, string matchedDN) : this(messageOrKey, null, resultCode, serverMsg, matchedDN, null)
        {
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String and modifying arguments.
        /// Additional parameters specify the result code, a message returned from
        /// the server, and a matchedDN returned from the server.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        /// The message in the default locale is built with the supplied arguments,
        /// which are saved to be used for building messages for other locales.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="arguments">   The modifying arguments to be included in the
        /// message string.
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        ///
        /// </param>
        /// <param name="matchedDN">     The maximal subset of a specified DN which could
        /// be matched by the server on a search operation.
        /// </param>
        public LdapException(string messageOrKey, object[] arguments, int resultCode, string serverMsg, string matchedDN) : this(messageOrKey, arguments, resultCode, serverMsg, matchedDN, null)
        {
        }

        ///  Constructs an exception with a detailed message obtained from the
        /// specified MessageOrKey String and modifying arguments.
        /// Additional parameters specify the result code, a message returned
        /// from the server, a matchedDN returned from
        /// the server, and a rootException which is the underlying cause of an error
        /// on the client.
        ///
        /// The String is used either as a message key to obtain a localized
        /// messsage from ExceptionMessages, or if there is no key in the
        /// resource matching the text, it is used as the detailed message itself.
        ///
        /// The message in the default locale is built with the supplied arguments,
        /// which are saved to be used for building messages for other locales.
        ///
        ///
        /// <param name="messageOrKey"> Key to addition result information, a key into
        /// ExceptionMessages, or the information
        /// itself if the key doesn't exist.
        ///
        /// </param>
        /// <param name="arguments">   The modifying arguments to be included in the
        /// message string.
        ///
        /// </param>
        /// <param name="resultCode">   The result code returned.
        ///
        /// </param>
        /// <param name="serverMsg">    Error message specifying additional information
        /// from the server
        ///
        /// </param>
        /// <param name="rootException"> A throwable which is the underlying cause
        /// of the LdapException.
        ///
        /// </param>
        /// <param name="matchedDN">     The maximal subset of a specified DN which could
        /// be matched by the server on a search operation.
        /// </param>
        /* package */
        internal LdapException(string messageOrKey, object[] arguments, int resultCode, string serverMsg, string matchedDN, Exception rootException)
        //:base(Novell.Directory.Ldap.Utilclass.ResourcesHandler.getMessage(messageOrKey, arguments))
        //Once resorcehandler starts working properly need to uncomment
        {
            this.messageOrKey = messageOrKey;
            this.arguments = arguments;
            this.resultCode = resultCode;
            this.rootException = rootException;
            this.matchedDN = matchedDN;
            serverMessage = serverMsg;
        }

        ///  Returns a string representing the result code in the default
        /// locale.
        ///
        ///
        /// <returns> The message for the result code in the LdapException object.
        /// </returns>
        public virtual string resultCodeToString()
        {
            return ResourcesHandler.getResultString(resultCode);
        }

        ///  Returns a string representing the specified result code in the default
        /// locale.
        ///
        ///
        /// <param name="code"> The result code for which a message is to be returned.
        ///
        /// </param>
        /// <returns> The message corresponding to the specified result code, or
        /// or null if the message is not available for the default locale.
        /// </returns>
        public static string resultCodeToString(int code)
        {
            return ResourcesHandler.getResultString(code);
        }

        ///  Returns a string representing the result code in the
        /// specified locale.
        ///
        ///
        /// <param name="locale">The locale in which to render the error message.
        ///
        /// </param>
        /// <returns> A message corresponding to the result code in the
        /// specified locale, or null if the message is not available
        /// for the requested locale.
        /// </returns>
        public virtual string resultCodeToString(System.Globalization.CultureInfo locale)
        {
            return ResourcesHandler.getResultString(resultCode, locale);
        }

        ///  Returns a string representing the specified error code in the
        /// specified locale.
        ///
        ///
        /// <param name="code">    The result code for which a message is to be
        /// returned.
        ///
        /// </param>
        /// <param name="locale">  The locale in which to render the message.
        ///
        /// </param>
        /// <returns> A message corresponding to the result code in the
        /// specified locale, or null if the message is not available
        /// for the requested locale.
        /// </returns>
        public static string resultCodeToString(int code, System.Globalization.CultureInfo locale)
        {
            return ResourcesHandler.getResultString(code, locale);
        }

        ///  returns a string of information about the exception and the
        /// the nested exceptions, if any.
        ///
        public override string ToString()
        {
            return getExceptionString("LdapException");
        }

        ///  builds a string of information about the exception and the
        /// the nested exceptions, if any.
        ///
        ///
        /// <param name="exception">The name of the exception class
        /// </param>
        /* package */
        internal virtual string getExceptionString(string exception)
        {
            string tmsg;

            // Format the basic exception information

            // Craft a string from the resouce file
            string msg = ResourcesHandler.getMessage("TOSTRING", new object[] { exception, base.Message, resultCode, resultCodeToString() });
            // If found no string from resource file, use a default string
            if (msg.ToUpper().Equals("TOSTRING".ToUpper()))
            {
                msg = exception + ": (" + resultCode + ") " + resultCodeToString();
            }

            // Add server message
            if (((object)serverMessage != null) && (serverMessage.Length != 0))
            {
                tmsg = ResourcesHandler.getMessage("SERVER_MSG", new object[] { exception, serverMessage });
                // If found no string from resource file, use a default string
                if (tmsg.ToUpper().Equals("SERVER_MSG".ToUpper()))
                {
                    tmsg = exception + ": Server Message: " + serverMessage;
                }

                msg = msg + '\n' + tmsg;
            }

            // Add Matched DN message
            if ((object)matchedDN != null)
            {
                tmsg = ResourcesHandler.getMessage("MATCHED_DN", new object[] { exception, matchedDN });
                // If found no string from resource file, use a default string
                if (tmsg.ToUpper().Equals("MATCHED_DN".ToUpper()))
                {
                    tmsg = exception + ": Matched DN: " + matchedDN;
                }

                msg = msg + '\n' + tmsg;
            }

            if (rootException != null)
            {
                msg = msg + '\n' + rootException.ToString();
            }
            return msg;
        }
    }
}


text:
namespace base {

// A very basic implementation for Android. On Android tests can run in an APK
// and we don't have an executable to exec*. This implementation does the bare
// minimum to execute the method specified by procname (in the child process).
//  - |base_command_line| is ignored.
//  - All options except |fds_to_remap| are ignored.
ProcessHandle SpawnMultiProcessTestChild(const std::string& procname,
                                         const CommandLine& base_command_line,
                                         const LaunchOptions& options) {
  // TODO(viettrungluu): The FD-remapping done below is wrong in the presence of
  // cycles (e.g., fd1 -> fd2, fd2 -> fd1). crbug.com/326576
  FileHandleMappingVector empty;
  const FileHandleMappingVector* fds_to_remap =
      options.fds_to_remap ? options.fds_to_remap : ∅

  pid_t pid = fork();

  if (pid < 0) {
    PLOG(ERROR) << "fork";
    return kNullProcessHandle;
  }
  if (pid > 0) {
    // Parent process.
    return pid;
  }
  // Child process.
  std::hash_set<int> fds_to_keep_open;
  for (FileHandleMappingVector::const_iterator it = fds_to_remap->begin();
       it != fds_to_remap->end(); ++it) {
    fds_to_keep_open.insert(it->first);
  }
  // Keep standard FDs (stdin, stdout, stderr, etc.) open since this
  // is not meant to spawn a daemon.
  int base = GlobalDescriptors::kBaseDescriptor;
  for (int fd = base; fd < getdtablesize(); ++fd) {
    if (fds_to_keep_open.find(fd) == fds_to_keep_open.end()) {
      close(fd);
    }
  }
  for (FileHandleMappingVector::const_iterator it = fds_to_remap->begin();
       it != fds_to_remap->end(); ++it) {
    int old_fd = it->first;
    int new_fd = it->second;
    if (dup2(old_fd, new_fd) < 0) {
      PLOG(FATAL) << "dup2";
    }
    close(old_fd);
  }
  _exit(multi_process_function_list::InvokeChildProcessTest(procname));
  return 0;
}

}  // namespace base


text:
'Copyright 2019 Esri

'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at

'    http://www.apache.org/licenses/LICENSE-2.0

'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

'See the License for the specific language governing permissions and
'limitations under the License.
Imports Microsoft.VisualBasic
Imports System
Imports ESRI.ArcGIS.Geometry
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Analyst3D
Imports ESRI.ArcGIS.Display
Imports ESRI.ArcGIS.GlobeCore

Namespace GlobeGraphicsToolbar
	Public Class StyleElement
		Private _element As IElement
		Private _elementProperties As IGlobeGraphicsElementProperties

		Public Sub New(ByVal geometry As IGeometry, ByVal size As Double, ByVal styleGalleryItem As IStyleGalleryItem)
			_element = GetElement(geometry, size, styleGalleryItem)
			_elementProperties = GetElementProperties()
		End Sub

		Private Function GetElement(ByVal geometry As IGeometry, ByVal size As Double, ByVal styleGalleryItem As IStyleGalleryItem) As IElement
			Dim element As IElement

			Dim markerElement As IMarkerElement = New MarkerElementClass()
			element = TryCast(markerElement, IElement)

			Dim markerSymbol As IMarkerSymbol = TryCast(styleGalleryItem.Item, IMarkerSymbol)
			markerSymbol.Size = size

			element.Geometry = geometry

			markerElement.Symbol = markerSymbol

			Return element
		End Function

		Private Function GetElementProperties() As IGlobeGraphicsElementProperties
			Dim elementProperties As IGlobeGraphicsElementProperties = New GlobeGraphicsElementPropertiesClass()
			elementProperties.DrapeElement = True
			elementProperties.Illuminate = True

			Return elementProperties
		End Function

		Public ReadOnly Property Element() As IElement
			Get
				Return _element
			End Get
		End Property

		Public ReadOnly Property ElementProperties() As IGlobeGraphicsElementProperties
			Get
				Return _elementProperties
			End Get
		End Property
	End Class
End Namespace


text:
namespace mx
{
    namespace core
    {
        MeasureAttributes::MeasureAttributes()
        :number()
        ,implicit( YesNo::no )
        ,nonControlling( YesNo::no )
        ,width()
        ,hasNumber( true )
        ,hasImplicit( false )
        ,hasNonControlling( false )
        ,hasWidth( false )
        {}

        bool MeasureAttributes::hasValues() const
        {
            return hasNumber ||
            hasImplicit ||
            hasNonControlling ||
            hasWidth;
        }

        std::ostream& MeasureAttributes::toStream( std::ostream& os ) const
        {
            if ( hasValues() )
            {
                streamAttribute( os, number, "number", hasNumber );
                streamAttribute( os, implicit, "implicit", hasImplicit );
                streamAttribute( os, nonControlling, "non-controlling", hasNonControlling );
                streamAttribute( os, width, "width", hasWidth );
            }
            return os;
        }

        bool MeasureAttributes::fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement )
        {
            const char* const className = "MeasureAttributes";
            bool isSuccess = true;
            bool isNumberFound = false;

            auto it = xelement.attributesBegin();
            auto endIter = xelement.attributesEnd();

            for( ; it != endIter; ++it )
            {
                if( parseAttribute( message, it, className, isSuccess, number, isNumberFound, "number" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, implicit, hasImplicit, "implicit", &parseYesNo ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, nonControlling, hasNonControlling, "non-controlling", &parseYesNo ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, width, hasWidth, "width" ) ) { continue; }
            }

            if( !isNumberFound )
            {
                isSuccess = false;
                message << className << ": 'number' is a required attribute but was not found" << std::endl;
            }

            return isSuccess;
        }

    }
}


text:
ROOT_DIR=$(mktemp -d)
DEPS_DIR=$ROOT_DIR/deps
BUILD_DIR=$ROOT_DIR/app
INDEX_DIR=$DEPS_DIR/0
MICROGATEWAY_DIR=$INDEX_DIR/microgateway

bin_dir=$(pwd)/../bin
util_dir=$bin_dir/util
lib_dir=$(pwd)/../lib
custom_plugins=$(pwd)/resources/plugins

setup() {
    echo "Setting up tests..."
    mkdir -p $INDEX_DIR && mkdir -p $BUILD_DIR && mkdir -p $MICROGATEWAY_DIR
    cp -r $bin_dir $ROOT_DIR/bin && cp -r $lib_dir $ROOT_DIR/lib
    cd $ROOT_DIR/bin/util
}

cleanup() {
    echo "Removing temp dir"
    rm -rf $ROOT_DIR
}

cleanup_mg() {
    rm -rf $INDEX_DIR/microgateway/.*
    rm -rf $INDEX_DIR/microgateway/*
}

error_check() {
    expected_code=$1
    actual_code=$2
    error_message=$3
    if [ $actual_code -ne $expected_code ]; then
        echo "FAIL: $error_message"
        cleanup
        exit 1
    else
        cleanup_mg
        printf "SUCCESS\n\n------------------------------\n\n"
    fi
}

test_microgateway_install_default() {
    echo "Testing default values"
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected default setup to not fail"
}

test_microgateway_install_custom() {
    echo "Testing valid custom version with \"v\""
    export APIGEE_MICROGATEWAY_VERSION="v2.5.10"
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected $APIGEE_MICROGATEWAY_VERSION setup to not fail"

    echo "Testing valid custom version without \"v\""
    export APIGEE_MICROGATEWAY_VERSION="2.5.10"
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected $APIGEE_MICROGATEWAY_VERSION setup to not fail"

    echo "Testing invalid custom version"
    export APIGEE_MICROGATEWAY_VERSION="v10.5.10"
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 1 $? "Expected $APIGEE_MICROGATEWAY_VERSION setup to fail"

    unset APIGEE_MICROGATEWAY_VERSION
}

test_microgateway_install_local() {
    (cd $ROOT_DIR/lib && git clone https://github.com/apigee-internal/microgateway.git)
    echo "Testing non-preinstalled local version"
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected non-preinstalled local version to not fail"

    echo "Testing preinstalled local version"
    npm install --prefix $ROOT_DIR/lib/microgateway #install dependencies before trying install
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected pre-installed local version to not fail"

    rm -rf $ROOT_DIR/lib/microgateway
}

test_microgateway_install_custom_plugins() {
    echo "Testing non-preinstalled custom plugins"
    cp -r $custom_plugins $BUILD_DIR
    export APIGEE_MICROGATEWAY_CUST_PLUGINS=plugins
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected non-preinstalled custom plugins to not fail"

    echo "Testing preinstalled plugins"
    ./microgateway_install $ROOT_DIR $BUILD_DIR $MICROGATEWAY_DIR
    error_check 0 $? "Expected pre-installed custom plugins to not fail"

    unset $APIGEE_MICROGATEWAY_CUST_PLUGINS
}

setup
test_microgateway_install_default
test_microgateway_install_custom
test_microgateway_install_local
test_microgateway_install_custom_plugins
cleanup


text:
<?php

declare(strict_types=1);

namespace Doctrine\Migrations\Configuration\Migration\Exception;

use Doctrine\Migrations\Configuration\Exception\ConfigurationException;
use LogicException;

final class YamlNotAvailable extends LogicException implements ConfigurationException
{
    public static function new() : self
    {
        return new self(
            'Unable to load yaml configuration files, please run '
            . '`composer require symfony/yaml` to load yaml configuration files.'
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demomsxk.Lang
{
    interface IGameLanguage
    {
        #region
        /// <summary>
        /// 君主帐号
        /// </summary>
        int SystemUserId { get; }
        /// <summary>
        /// 玩家名称
        /// </summary>
        string KingName { get; }
        string Date_Yesterday { get; }
        string Date_BeforeYesterday { get; }
        string Date_Day { get; }
        string St1002_GetRegisterPassportIDError { get; }
        string St1005_NickNameOutRange { get; }
        string St1005_NickNameExistKeyword { get; }
        string St1005_NickNameExist { get; }
        string St1006_PasswordTooLong { get; }
        string St1006_ChangePasswordError { get; }
        string St1006_PasswordError { get; }
        string St1066_PayError { get; }

        #endregion
    }
}


text:
using System.Collections.Generic;
using System.IO;

namespace VenoMpie.Common.IO.FileSignatures.Emulation
{
    public class NES : FileSignatureBase
    {
        const int HeaderLength = 4;
        public override IList<string> FileExtensions { get { return new List<string> { ".nes" }; } }
        public override IList<byte[]> HeaderSignature { get { return new List<byte[]>() {
            new byte[HeaderLength] { 0x4E, 0x45, 0x53, 0x1A } //'N','E','S','.'
        }; } }

        public NES(string fileName) : base(fileName) { }
        public NES(FileInfo fileInfo) : base(fileInfo) { }

        public override bool FileExtensionMatches()
        {
            return GenericFileExtensionMatches();
        }

        public override bool FileSignatureMatches()
        {
            return GenericFileSignatureMatches(HeaderLength, 0);
        }
    }
}