text:
package org.codehaus.groovy.grails.web.servlet.view;

import groovy.text.Template;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.pages.GroovyPageTemplate;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper;
import org.springframework.core.io.Resource;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

/**
 * A Spring View that renders Groovy Server Pages to the response. It requires an instance
 * of GroovyPagesTemplateEngine to be set and will render to view returned by the getUrl()
 * method of AbstractUrlBasedView
 *
 * This view also requires an instance of GrailsWebRequest to be bound to the currently
 * executing Thread using Spring's RequestContextHolder. This can be done with by adding
 * the GrailsWebRequestFilter.
 *
 * @see #getUrl()
 * @see org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine
 * @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequestFilter
 * @see org.springframework.web.context.request.RequestContextHolder
 *
 * @author Graeme Rocher
 * @since 0.4
 */
public class GroovyPageView extends AbstractUrlBasedView {

    private static final Log LOG = LogFactory.getLog(GroovyPageView.class);
    protected GroovyPagesTemplateEngine templateEngine;
    private long createTimestamp = System.currentTimeMillis();
    private static final long LASTMODIFIED_CHECK_INTERVAL =  Long.getLong("grails.gsp.reload.interval", 5000).longValue();
    private ScriptSource scriptSource;
    protected Template template;
    public static final String EXCEPTION_MODEL_KEY = "exception";

    /**
     * Delegates to renderMergedOutputModel(..)
     *
     * @see #renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     *
     * @param model The view model
     * @param request The HttpServletRequest
     * @param response The HttpServletResponse
     * @throws Exception When an error occurs rendering the view
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    protected final void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // templateEngine is always same instance in context, can use cached; removed static cache in GrailsViewResolver
        Assert.state(templateEngine != null, "No GroovyPagesTemplateEngine found in ApplicationContext!");

        exposeModelAsRequestAttributes(model, request);
        renderWithTemplateEngine(templateEngine,model, response, request); // new ModelExposingHttpRequestWrapper(request, model)
    }

    /**
     * Replaces the requirement for "super.exposeModelAsRequestAttributes(model, request);" in renderMergedOutputModel.
     *
     *  not in use, since causes bugs, could improve performance
     *
     * @author Lari Hotari
    private static class ModelExposingHttpRequestWrapper extends HttpServletRequestWrapper {
        Map model;

        public ModelExposingHttpRequestWrapper(HttpServletRequest request, Map model) {
            super(request);
            this.model = model;
        }

        @Override
        public Object getAttribute(String name) {
            Object value = super.getAttribute(name);
            if (value == null) {
                return model.get(name);
            }
            return value;
        }

        @Override
        public Enumeration<?> getAttributeNames() {
            return CollectionUtils.append(super.getAttributeNames(),
                    CollectionUtils.asEnumeration(model.keySet().iterator()));
        }

        @Override
        public void removeAttribute(String name) {
            super.removeAttribute(name);
            model.remove(name);
        }

        @Override
        public void setAttribute(String name, Object o) {
            super.setAttribute(name, o);
            if (o == null) {
                model.remove(name);
            }
        }
    }
    */

    /**
     * Renders a page with the specified TemplateEngine, mode and response.
     *
     * @param engine The TemplateEngine to use
     * @param model The model to use
     * @param response The HttpServletResponse instance
     * @param request The HttpServletRequest
     *
     * @throws java.io.IOException Thrown when an error occurs writing the response
     */
    @SuppressWarnings("rawtypes")
    protected void renderWithTemplateEngine(GroovyPagesTemplateEngine engine, Map model,
            HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setAttribute(GrailsLayoutDecoratorMapper.RENDERING_VIEW, Boolean.TRUE);
        GSPResponseWriter out = null;
        try {
            out = createResponseWriter(response);
            template.make(model).writeTo(out);
        }
        catch (Exception e) {
            out.setError();
            handleException(e, engine);
        }
        finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * Performs exception handling by attempting to render the Errors view.
     *
     * @param exception The exception that occured

     * @param engine The GSP engine
     */
    protected void handleException(Exception exception,
            GroovyPagesTemplateEngine engine)  {

        LOG.debug("Error processing GroovyPageView: " + exception.getMessage(), exception);
        if (exception instanceof GroovyPagesException) {
            throw (GroovyPagesException) exception;
        }

        if (engine == null) {
            throw new GroovyPagesException("Error processing GroovyPageView: " + exception.getMessage(),
                 exception, -1, getUrl());
        }

        throw createGroovyPageException(exception, engine, getUrl());
    }

    public static GroovyPagesException createGroovyPageException(Exception exception, GroovyPagesTemplateEngine engine, String pageUrl) {
        GroovyPageTemplate t = (GroovyPageTemplate) engine.createTemplate(pageUrl);
        StackTraceElement[] stackTrace = exception.getStackTrace();
        String className = stackTrace[0].getClassName();
        int lineNumber = stackTrace[0].getLineNumber();
        if (className.contains("_gsp")) {
            int[] lineNumbers = t.getMetaInfo().getLineNumbers();
            if (lineNumber < lineNumbers.length) {
                lineNumber = lineNumbers[lineNumber - 1];
            }
        }

        Resource resource = pageUrl != null ? engine.getResourceForUri(pageUrl) : null;
        String file;
        try {
            file = resource != null && resource.exists() ? resource.getFile().getAbsolutePath() : pageUrl;
        } catch (IOException e) {
            file = pageUrl;
        }

        return new GroovyPagesException("Error processing GroovyPageView: " + exception.getMessage(),
                exception, lineNumber, file);
    }

    /**
     * Creates the Response Writer for the specified HttpServletResponse instance.
     *
     * @param response The HttpServletResponse instance
     * @return A response Writer
     */
    //TODO this method is dupe'd across GSP servlet, reload servlet and here...
    protected GSPResponseWriter createResponseWriter(HttpServletResponse response) {
        GSPResponseWriter out = GSPResponseWriter.getInstance(response);
        GrailsWebRequest webRequest =  (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
        webRequest.setOut(out);
        return out;
    }

    public void setTemplateEngine(GroovyPagesTemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    public boolean isExpired() {
        return System.currentTimeMillis() - createTimestamp > LASTMODIFIED_CHECK_INTERVAL;
    }

    public void setScriptSource(ScriptSource scriptSource) {
        this.scriptSource = scriptSource;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        try {
            initTemplate();
        } catch(Exception e) {
            handleException(e, templateEngine);
        }
    }

    protected void initTemplate() throws IOException {
        if (scriptSource == null) {
            template = templateEngine.createTemplate(getUrl());
        } else {
            template = templateEngine.createTemplate(scriptSource);
        }
        if (template instanceof GroovyPageTemplate) {
            ((GroovyPageTemplate)template).setAllowSettingContentType(true);
        }
    }
}


text:
class AuthorizationObserver < ActiveRecord::Observer
  def before_destroy(authorization)
    authorization.user.update_column column_name(authorization), nil
  end

  def after_commit(authorization)
    Webhook::EventRegister.new(authorization, created: just_created?(authorization))
  end

  private

  def column_name(authorization)
    case authorization.oauth_provider.name
    when 'facebook'
      return :facebook_url
    when 'twitter'
      return :twitter_url
    when 'linkedin'
      return :linkedin_url
    end
  end

  def just_created?(authorization)
    !!authorization.send(:transaction_record_state, :new_record)
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace net {

namespace nqe {

namespace internal {

// CachedNetworkQuality stores the quality of a previously seen network.
class NET_EXPORT_PRIVATE CachedNetworkQuality {
 public:
  explicit CachedNetworkQuality(const NetworkQuality& network_quality);
  CachedNetworkQuality(const CachedNetworkQuality& other);
  ~CachedNetworkQuality();

  // Returns the network quality associated with this cached entry.
  const NetworkQuality& network_quality() const { return network_quality_; }

  // Returns true if this cache entry was updated before
  // |cached_network_quality|.
  bool OlderThan(const CachedNetworkQuality& cached_network_quality) const;

  // Time when this cache entry was last updated.
  const base::TimeTicks last_update_time_;

  // Quality of this cached network.
  const NetworkQuality network_quality_;

 private:
  DISALLOW_ASSIGN(CachedNetworkQuality);
};

}  // namespace internal

}  // namespace nqe

}  // namespace net

#endif  // NET_NQE_CACHED_NETWORK_QUALITY_H_


text:
class FileDialog: public wxGenericFileDialog
{
public:
   FileDialog() { }

   FileDialog(wxWindow *parent,
              const wxString& message = wxFileSelectorPromptStr,
              const wxString& defaultDir = wxEmptyString,
              const wxString& defaultFile = wxEmptyString,
              const wxString& wildCard = wxFileSelectorDefaultWildcardStr,
              long style = 0,
              const wxPoint& pos = wxDefaultPosition);

   virtual ~FileDialog();

   virtual wxString GetPath() const;
   virtual void GetPaths(wxArrayString& paths) const;
   virtual wxString GetDirectory() const;
   virtual wxString GetFilename() const;
   virtual void GetFilenames(wxArrayString& files) const;
   virtual int GetFilterIndex() const;

   virtual void SetMessage(const wxString& message);
   virtual void SetPath(const wxString& path);
   virtual void SetDirectory(const wxString& dir);
   virtual void SetFilename(const wxString& name);
   virtual void SetWildcard(const wxString& wildCard);
   virtual void SetFilterIndex(int filterIndex);

   virtual int ShowModal();
   virtual bool Show( bool show = true );

   //private:
   bool m_destroyed_by_delete;

   // override this from wxTLW since the native
   // form doesn't have any m_wxwindow
   virtual void DoSetSize(int x, int y,
                          int width, int height,
                          int sizeFlags = wxSIZE_AUTO);

   virtual void EnableButton(wxString label, fdCallback cb, void *cbdata);
   virtual void ClickButton(int index);

private:
   DECLARE_DYNAMIC_CLASS(FileDialog)
   DECLARE_EVENT_TABLE()
   void OnFakeOk( wxCommandEvent &event );

   wxString m_buttonlabel;
   fdCallback m_callback;
   void *m_cbdata;
};

#endif


text:
- 2.1.0 (TBD)
  Features:
  - Added `-tok spm` for multilingual SPM tokenization
    (thanks to Naman Goyal and James Cross at Facebook)

  Fixes:
  - Handle potential memory usage issues due to LRU caching in tokenizers (#167)
  - Bugfix: BLEU.corpus_score() now using max_ngram_order (#173)

- 2.0.0 (2021-07-18)
  - Build: Add Windows and OS X testing to Travis CI.
  - Improve documentation and type annotations.
  - Drop `Python < 3.6` support and migrate to f-strings.
  - Relax `portalocker` version pinning, add `regex, tabulate, numpy` dependencies.
  - Drop input type manipulation through `isinstance` checks. If the user does not obey
    to the expected annotations, exceptions will be raised. Robustness attempts lead to
    confusions and obfuscated score errors in the past (#121)
  - Variable # references per segment is supported for all metrics by default. It is
    still only available through the API.
  - Use colored strings in tabular outputs (multi-system evaluation mode) through
    the help of `colorama` package.
  - tokenizers: Add caching to tokenizers which seem to speed up things a bit.
  - `intl` tokenizer: Use `regex` module. Speed goes from ~4 seconds to ~0.6 seconds
    for a particular test set evaluation. (#46)
  - Signature: Formatting changed (mostly to remove '+' separator as it was
    interfering with chrF++). The field separator is now '|' and key values
    are separated with ':' rather than '.'.
  - Signature: Boolean true / false values are shortened to yes / no.
  - Signature: Number of references is `var` if variable number of references is used.
  - Signature: Add effective order (yes/no) to BLEU and chrF signatures.
  - Metrics: Scale all metrics into the [0, 100] range (#140)
  - Metrics API: Use explicit argument names and defaults for the metrics instead of
    passing obscure `argparse.Namespace` objects.
  - Metrics API: A base abstract `Metric` class is introduced to guide further
    metric development. This class defines the methods that should be implemented
    in the derived classes and offers boilerplate methods for the common functionality.
    A new metric implemented this way will automatically support significance testing.
  - Metrics API: All metrics now receive an optional `references` argument at
    initialization time to process and cache the references. Further evaluations
    of different systems against the same references becomes faster this way
    for example when using significance testing.
  - BLEU: In case of no n-gram matches at all, skip smoothing and return 0.0 BLEU (#141).
  - CHRF: Added multi-reference support, verified the scores against chrF++.py, added test case.
  - CHRF: Added chrF+ support through `word_order` argument. Added test cases against chrF++.py.
    Exposed it through the CLI (--chrf-word-order) (#124)
  - CHRF: Add possibility to disable effective order smoothing (pass --chrf-eps-smoothing).
    This way, the scores obtained are exactly the same as chrF++, Moses and NLTK implementations.
    We keep the effective ordering as the default for compatibility, since this only
    affects sentence-level scoring with very short sentences. (#144)
  - CLI: `--input/-i` can now ingest multiple systems. For this reason, the positional
    `references` should always preceed the `-i` flag.
  - CLI: Allow modifying TER arguments through CLI. We still keep the TERCOM defaults.
  - CLI: Prefix metric-specific arguments with --chrf and --ter. To maintain compatibility,
    BLEU argument names are kept the same.
  - CLI: Separate metric-specific arguments for clarity when `--help` is printed.
  - CLI: Added `--format/-f` flag. The single-system output mode is now `json` by default.
    If you want to keep the old text format persistently, you can export `SACREBLEU_FORMAT=text` into your
    shell.
  - CLI: For multi-system mode, `json` falls back to plain text. `latex` output can only
    be generated for multi-system mode.
  - CLI: sacreBLEU now supports evaluating multiple systems for a given test set
    in an efficient way. Through the use of `tabulate` package, the results are
    nicely rendered into a plain text table, LaTeX, HTML or RST (cf. --format/-f argument).
    The systems can be either given as a list of plain text files to `-i/--input` or
    as a tab-separated single stream redirected into `STDIN`. In the former case,
    the basenames of the files will be automatically used as system names.
  - Statistical tests: sacreBLEU now supports confidence interval estimation
    through bootstrap resampling for single-system evaluation (`--confidence` flag)
    as well as paired bootstrap resampling (`--paired-bs`) and paired approximate
    randomization tests (`--paired-ar`) when evaluating multiple systems (#40 and #78).

- 1.5.1 (2021-03-05)
  - Fix extraction error for WMT18 extra test sets (test-ts) (#142)
  - Validation and test datasets are added for multilingual TEDx

- 1.5.0 (2021-01-15)
  - Fix an assertion error in chrF (#121)
  - Add missing `__repr__()` methods for BLEU and TER
  - TER: Fix exception when `--short` is used (#131)
  - Pin Mecab version to 1.0.3 for Python 3.5 support
  - [API Change]: Default value for `floor` smoothing is now 0.1 instead of 0.
  - [API Change]: `sacrebleu.sentence_bleu()` now uses the `exp` smoothing method,
    exactly the same as the CLI's --sentence-level behavior. This was mainly done
    to make two methods behave the same.
  - Add smoothing value to BLEU signature (#98)
  - dataset: Fix IWSLT links (#128)
  - Allow variable number of references for BLEU (only via API) (#130).
    Thanks to Ondrej Dusek (@tuetschek)

- 1.4.14 (2020-09-13)
  - Added character-based tokenization (`-tok char`).
    Thanks to Christian Federmann.
  - Added TER (`-m ter`). Thanks to Ales Tamchyna! (fixes #90)
  - Allow calling the script as a standalone utility (fixes #86)
  - Fix type annotation issues (fixes #100) and mark sacrebleu as supporting mypy
  - Added WMT20 robustness test sets:
    - wmt20/robust/set1 (en-ja, en-de)
    - wmt20/robust/set2 (en-ja, ja-en)
    - wmt20/robust/set3 (de-en)

- 1.4.13 (2020-07-30)
  - Added WMT20 newstest test sets (#103)
  - Make mecab3-python an extra dependency, adapt code to new mecab3-python
    This fixes the recent Windows installation issues as well (#104)
    Japanese support should now be explicitly installed through sacrebleu[ja] package.
  - Fix return type annotation of corpus_bleu()
  - Improve sentence_score's documentation, do not allow single ref string (#98)

- 1.4.12 (2020-07-03)
  - Fix a deployment bug (#96)

- 1.4.11 (2020-07-03)
  - Added Multi30k multimodal MT test set metadata
  - Refactored all tokenizers into respective classes (fixes #85)
  - Refactored all metrics into respective classes
  - Moved utility functions into `utils.py`
  - Implemented signatures using `BLEUSignature` and `CHRFSignature` classes
  - Simplified checking of Chinese characters (fixes #5)
  - Unified common regexp tokenization codes for tokenizers (fixes #27)
  - Fixed --detail failing when no test sets are provided
  - Fixed multi-reference BLEU failing when tab-delimited reference stream is used
  - Removed lowercase option for ChrF which was not functional (#85)
  - Simplified ChrF and used the same I/O logic as BLEU to allow for future
    multi-reference reading
  - Added score regression tests for chrF using reference chrF++ implementation
  - Added multi-reference & tokenizer & signature tests

- 1.4.10 (2020-05-30)
  - Fixed bug in signature with mecab tokenizer
  - Cleaned up deprecation warnings (thanks to Karthikeyan Singaravelan @tirkarthi)
  - Now only lists the external [typing](https://pypi.org/project/typing/)
    module as a dependency for Python `<= 3.4`, as it was integrated in the standard
    library in Python 3.5 (thanks to Erwan de Lépinau @ErwanDL).
  - Added LICENSE to pypi (thanks to Mark Harfouche @hmaarrfk)

- 1.4.9 (2020-04-30)
  - Changed `get_available_testsets()` to return a list
  - Remove Japanese MeCab tokenizer from requirements.
    (Must be installed manually to avoid Windows incompatibility).
    Many thanks to Makoto Morishita (@MorinoseiMorizo).

- 1.4.8 (2020-04-26)
  - Added to API:
    - get_source_file()
    - get_reference_files()
    - get_available_testsets()
    - get_langpairs_for_testset()
  - Some internal refactoring
  - Fixed descriptions of some WMT19/google test sets
  - Added API test case (test/test_apy.py)

- 1.4.7 (2020-04-19)
  - Added Google's extra wmt19/en-de refs (-t wmt19/google/{ar,arp,hqall,hqp,hqr,wmtp})
    (Freitag, Grangier, & Caswell
     BLEU might be Guilty but References are not Innocent
     https://arxiv.org/abs/2004.06063)
  - Restored SACREBLEU_DIR and smart_open to exports (thanks to Thomas Liao @tholiao)

- 1.4.6 (2020-03-28)
  - Large internal reorganization as a module (thanks to Thamme Gowda @thammegowda)

- 1.4.5 (2020-03-28)
  - Added Japanese MeCab tokenizer (`-tok ja-mecab`) (thanks to Makoto Morishita @MorinoseiMorizo)
  - Added wmt20/dev test sets (thanks to Martin Popel @martinpopel)

- 1.4.4 (2020-03-10)
  - Smoothing changes (Sebastian Nickels @sn1c)
    - Fixed bug that only applied smoothing to n-grams for n > 2
    - Added default smoothing values for methods "floor" (0) and "add-k" (1)
  - `--list` now returns a list of all language pairs for a task when combined with `-t`
    (e.g., `sacrebleu -t wmt19 --list`)
  - added missing languages for IWSLT17
  - Minor code improvements (Thomas Liao @tholiao)

- 1.4.3 (2019-12-02)
  - Bugfix: handling of result object for CHRF
  - Improved API example

- 1.4.2 (2019-10-11)
  - Tokenization variant omitted from the chrF signature; it is relevant only for BLEU (thanks to Martin Popel)
  - Bugfix: call to sentence_bleu (thanks to Rachel Bawden)
  - Documentation example for Python API (thanks to Vlad Lyalin)
  - Calls to corpus_chrf and sentence_chrf now return a an object instead of a float (use result.score)

- 1.4.1 (2019-09-11)
   - Added sentence-level scoring via -sl (--sentence-level)

- 1.4.0 (2019-09-10)
   - Many thanks to Martin Popel for all the changes below!
   - Added evaluation on concatenated test sets (e.g., `-t wmt17,wmt18`).
     Works as long as they all have the same language pair.
   - Added `sacrebleu --origlang` (both for evaluation on a subset and for `--echo`).
     Note that while echoing prints just the subset, evaluation expects the complete
     test set (and just skips the irrelevant parts).
   - Added `sacrebleu --detail` for breakdown by domain-specific subsets of the test sets.
     (Available for WMT19).
   - Minor changes
     - Improved display of `sacrebleu -h`
     - Added `sacrebleu --list`
     - Code refactoring
     - Documentation and tests updates
     - Fixed a race condition bug (`os.makedirs(outdir, exist_ok=True)` instead of `if os.path.exists`)

- 1.3.7 (2019-07-12)
   - Lazy loading of regexes cuts import time from ~1s to nearly nothing (thanks, @louismartin!)
   - Added a simple (non-atomic) lock on downloading
   - Can now read multiple refs from a single tab-delimited file.
     You need to pass `--num-refs N` to tell it to run the split.
     Only works with a single reference file passed from the command line.

- 1.3.6 (2019-06-10)
   - Removed another f-string for Python 3.5 compatibility

- 1.3.5 (2019-06-07)
   - Restored Python 3.5 compatibility

- 1.3.4 (2019-05-28)
   - Added MTNT 2019 test sets
   - Added a BLEU object

- 1.3.3 (2019-05-08)
   - Added WMT'19 test sets

- 1.3.2 (2018-04-24)
   - Bugfix in test case (thanks to Adam Roberts, @adarob)
   - Passing smoothing method through `sentence_bleu`

- 1.3.1 (2019-03-20)
   - Added another smoothing approach (add-k) and a command-line option for choosing the smoothing method
     (`--smooth exp|floor|add-n|none`) and the associated value (`--smooth-value`), when relevant.
   - Changed interface to some functions (backwards incompatible)
     - 'smooth' is now 'smooth_method'
     - 'smooth_floor' is now 'smooth_value'

- 1.2.21 (19 March 2019)
   - Ctrl-M characters are now treated as normal characters, previously treated as newline.

- 1.2.20 (28 February 2018)
   - Tokenization now defaults to "zh" when language pair is known

- 1.2.19 (19 February 2019)
   - Updated checksum for wmt19/dev (seems to have changed)

- 1.2.18 (19 February 2019)
   - Fixed checksum for wmt17/dev (copy-paste error)

- 1.2.17 (6 February 2019)
   - Added kk-en and en-kk to wmt19/dev

- 1.2.16 (4 February 2019)
   - Added gu-en and en-gu to wmt19/dev

- 1.2.15 (30 January 2019)
   - Added MD5 checksumming of downloaded files for all datasets.

- 1.2.14 (22 January 2019)
   - Added mtnt1.1/train mtnt1.1/valid mtnt1.1/test data from [MTNT](http://www.cs.cmu.edu/~pmichel1/mtnt/)

- 1.2.13 (22 January 2019)
   - Added 'wmt19/dev' task for 'lt-en' and 'en-lt' (development data for new tasks).
   - Added MD5 checksum for downloaded tarballs.

- 1.2.12 (8 November 2018)
   - Now outputs only only digit after the decimal

- 1.2.11 (29 August 2018)
   - Added a function for sentence-level, smoothed BLEU

- 1.2.10 (23 May 2018)
   - Added wmt18 test set (with references)

- 1.2.9 (15 May 2018)
   - Added zh-en, en-zh, tr-en, and en-tr datasets for wmt18/test-ts

- 1.2.8 (14 May 2018)
   - Added wmt18/test-ts, the test sources (only) for [WMT18](http://statmt.org/wmt18/translation-task.html)
   - Moved README out of `sacrebleu.py` and the CHANGELOG into a separate file

- 1.2.7 (10 April 2018)
   - fixed another locale issue (with --echo)
   - grudgingly enabled `-tok none` from the command line

- 1.2.6 (22 March 2018)
   - added wmt17/ms (Microsoft's [additional ZH-EN references](https://github.com/MicrosoftTranslator/Translator-HumanParityData)).
     Try `sacrebleu -t wmt17/ms --cite`.
   - `--echo ref` now pastes together all references, if there is more than one

- 1.2.5 (13 March 2018)
   - added wmt18/dev datasets (en-et and et-en)
   - fixed logic with --force
   - locale-independent installation
   - added "--echo both" (tab-delimited)

- 1.2.3 (28 January 2018)
   - metrics (`-m`) are now printed in the order requested
   - chrF now prints a version string (including the beta parameter, importantly)
   - attempt to remove dependence on locale setting

- 1.2 (17 January 2018)
   - added the chrF metric (`-m chrf` or `-m bleu chrf` for both)
     See 'CHRF: character n-gram F-score for automatic MT evaluation' by Maja Popovic (WMT 2015)
     [http://www.statmt.org/wmt15/pdf/WMT49.pdf]
   - added IWSLT 2017 test and tuning sets for DE, FR, and ZH
     (Thanks to Mauro Cettolo and Marcello Federico).
   - added `--cite` to produce the citation for easy inclusion in papers
   - added `--input` (`-i`) to set input to a file instead of STDIN
   - removed accent mark after objection from UN official

- 1.1.7 (27 November 2017)
   - corpus_bleu() now raises an exception if input streams are different lengths
   - thanks to Martin Popel for:
      - small bugfix in tokenization_13a (not affecting WMT references)
      - adding `--tok intl` (international tokenization)
   - added wmt17/dev and wmt17/dev sets (for languages intro'd those years)

- 1.1.6 (15 November 2017)
   - bugfix for tokenization warning

- 1.1.5 (12 November 2017)
   - added -b option (only output the BLEU score)
   - removed fi-en from list of WMT16/17 systems with more than one reference
   - added WMT16/tworefs and WMT17/tworefs for scoring with both en-fi references

- 1.1.4 (10 November 2017)
   - added effective order for sentence-level BLEU computation
   - added unit tests from sockeye

- 1.1.3 (8 November 2017).
   - Factored code a bit to facilitate API:
      - compute_bleu: works from raw stats
      - corpus_bleu for use from the command line
      - raw_corpus_bleu: turns off tokenization, command-line sanity checks, floor smoothing
   - Smoothing (type 'exp', now the default) fixed to produce mteval-v13a.pl results
   - Added 'floor' smoothing (adds 0.01 to 0 counts, more versatile via API), 'none' smoothing (via API)
   - Small bugfixes, windows compatibility (H/T Christian Federmann)

- 1.0.3 (4 November 2017).
   - Contributions from Christian Federmann:
      - Added explicit support for encoding
      - Fixed Windows support
      - Bugfix in handling reference length with multiple refs

- version 1.0.1 (1 November 2017).
   - Small bugfix affecting some versions of Python.
   - Code reformatting due to Ozan Çağlayan.

- version 1.0 (23 October 2017).
   - Support for WMT 2008--2017.
   - Single tokenization (v13a) with lowercase fix (proper lower() instead of just A-Z).
   - Chinese tokenization.
   - Tested to match all WMT17 scores on all arcs.


text:
(function() {
  var kHistory = 2;
  var kRepeats = 100;
  var history = new Uint32Array(kHistory);

  function random() {
    return (Math.random() * Math.pow(2, 32)) >>> 0;
  }

  function ChiSquared(m, n) {
    var ys_minus_np1 = (m - n / 2.0);
    var chi_squared_1 = ys_minus_np1 * ys_minus_np1 * 2.0 / n;
    var ys_minus_np2 = ((n - m) - n / 2.0);
    var chi_squared_2 = ys_minus_np2 * ys_minus_np2 * 2.0 / n;
    return chi_squared_1 + chi_squared_2;
  }
  for (var predictor_bit = -2; predictor_bit < 32; predictor_bit++) {
    // The predicted bit is one of the bits from the PRNG.
    for (var random_bit = 0; random_bit < 32; random_bit++) {
      for (var ago = 0; ago < kHistory; ago++) {
        // We don't want to check whether each bit predicts itself.
        if (ago == 0 && predictor_bit == random_bit) continue;
        // Enter the new random value into the history
        for (var i = ago; i >= 0; i--) {
          history[i] = random();
        }
        // Find out how many of the bits are the same as the prediction bit.
        var m = 0;
        for (var i = 0; i < kRepeats; i++) {
          for (var j = ago - 1; j >= 0; j--) history[j + 1] = history[j];
          history[0] = random();
          var predicted;
          if (predictor_bit >= 0) {
            predicted = (history[ago] >> predictor_bit) & 1;
          } else {
            predicted = predictor_bit == -2 ? 0 : 1;
          }
          var bit = (history[0] >> random_bit) & 1;
          if (bit == predicted) m++;
        }
        // Chi squared analysis for k = 2 (2, states: same/not-same) and one
        // degree of freedom (k - 1).
        var chi_squared = ChiSquared(m, kRepeats);
        if (chi_squared > 24) {
          var percent = Math.floor(m * 100.0 / kRepeats);
          if (predictor_bit < 0) {
            var bit_value = predictor_bit == -2 ? 0 : 1;
            print(`Bit ${random_bit} is ${bit_value} ${percent}% of the time`);
          } else {
            print(`Bit ${random_bit} is the same as bit ${predictor_bit} ` +
              `${ago} ago ${percent}% of the time`);
          }
        }
        // For 1 degree of freedom this corresponds to 1 in a million.  We are
        // running ~8000 tests, so that would be surprising.
        assertTrue(chi_squared <= 24);
        // If the predictor bit is a fixed 0 or 1 then it makes no sense to
        // repeat the test with a different age.
        if (predictor_bit < 0) break;
      }
    }
  }
})();


text:
package org.springframework.jmx.export.annotation;

import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanOperationInfo;

import org.junit.Test;

import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.export.assembler.AbstractMetadataAssemblerTests;
import org.springframework.jmx.export.metadata.JmxAttributeSource;

import static org.junit.Assert.*;

/**
 * @author Rob Harrop
 * @author Chris Beams
 */
public class AnnotationMetadataAssemblerTests extends AbstractMetadataAssemblerTests {

	private static final String OBJECT_NAME = "bean:name=testBean4";

	@Test
	public void testAttributeFromInterface() throws Exception {
		ModelMBeanInfo inf = getMBeanInfoFromAssembler();
		ModelMBeanAttributeInfo attr = inf.getAttribute("Colour");
		assertTrue("The name attribute should be writable", attr.isWritable());
		assertTrue("The name attribute should be readable", attr.isReadable());
	}

	@Test
	public void testOperationFromInterface() throws Exception {
		ModelMBeanInfo inf = getMBeanInfoFromAssembler();
		ModelMBeanOperationInfo op = inf.getOperation("fromInterface");
		assertNotNull(op);
	}

	@Test
	public void testOperationOnGetter() throws Exception {
		ModelMBeanInfo inf = getMBeanInfoFromAssembler();
		ModelMBeanOperationInfo op = inf.getOperation("getExpensiveToCalculate");
		assertNotNull(op);
	}

	@Test
	public void testRegistrationOnInterface() throws Exception {
		Object bean = getContext().getBean("testInterfaceBean");
		ModelMBeanInfo inf = getAssembler().getMBeanInfo(bean, "bean:name=interfaceTestBean");
		assertNotNull(inf);
		assertEquals("My Managed Bean", inf.getDescription());

		ModelMBeanOperationInfo op = inf.getOperation("foo");
		assertNotNull("foo operation not exposed", op);
		assertEquals("invoke foo", op.getDescription());

		assertNull("doNotExpose operation should not be exposed", inf.getOperation("doNotExpose"));

		ModelMBeanAttributeInfo attr = inf.getAttribute("Bar");
		assertNotNull("bar attribute not exposed", attr);
		assertEquals("Bar description", attr.getDescription());

		ModelMBeanAttributeInfo attr2 = inf.getAttribute("CacheEntries");
		assertNotNull("cacheEntries attribute not exposed", attr2);
		assertEquals("Metric Type should be COUNTER", "COUNTER",
				attr2.getDescriptor().getFieldValue("metricType"));
	}

	@Override
	protected JmxAttributeSource getAttributeSource() {
		return new AnnotationJmxAttributeSource();
	}

	@Override
	protected String getObjectName() {
		return OBJECT_NAME;
	}

	@Override
	protected IJmxTestBean createJmxTestBean() {
		return new AnnotationTestSubBean();
	}

	@Override
	protected String getApplicationContextPath() {
		return "org/springframework/jmx/export/annotation/annotations.xml";
	}

	@Override
	protected int getExpectedAttributeCount() {
		return super.getExpectedAttributeCount() + 1;
	}

	@Override
	protected int getExpectedOperationCount() {
		return super.getExpectedOperationCount() + 4;
	}
}


text:
using System.Threading.Tasks;
using Xunit;

namespace System.Globalization.Tests
{
    public class CultureInfoAsync
    {
        [Fact]
        // async current cultures feature is supported on 4.6.1 and up on Windows desktop framework
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
        [ActiveIssue("https://github.com/dotnet/corert/issues/3747 - Port async-aware CultureInfo property from CoreCLR", TargetFrameworkMonikers.UapAot)]
        public void TestCurrentCulturesAsync()
        {
            CultureInfo currentCulture = CultureInfo.CurrentCulture;
            CultureInfo currentUICulture = CultureInfo.CurrentUICulture;

            CultureInfo newCurrentCulture = new CultureInfo(currentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
            CultureInfo newCurrentUICulture = new CultureInfo(currentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");

            CultureInfo.CurrentCulture = newCurrentCulture;
            CultureInfo.CurrentUICulture = newCurrentUICulture;

            try
            {
                Task t = Task.Run(() => {
                    Assert.Equal(CultureInfo.CurrentCulture, newCurrentCulture);
                    Assert.Equal(CultureInfo.CurrentUICulture, newCurrentUICulture);
                });

                ((IAsyncResult)t).AsyncWaitHandle.WaitOne();
                t.Wait();
            }
            finally
            {
                CultureInfo.CurrentCulture = currentCulture;
                CultureInfo.CurrentUICulture = currentUICulture;
            }
        }

        [Fact]
        // async current cultures feature is supported on 4.6.1 and up on Windows desktop framework
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
        [ActiveIssue("https://github.com/dotnet/corert/issues/3747 - Port async-aware CultureInfo property from CoreCLR", TargetFrameworkMonikers.UapAot)]
        public void TestCurrentCulturesWithAwait()
        {
            CultureInfo currentCulture = CultureInfo.CurrentCulture;
            CultureInfo currentUICulture = CultureInfo.CurrentUICulture;

            CultureInfo newCurrentCulture = new CultureInfo(currentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
            CultureInfo newCurrentUICulture = new CultureInfo(currentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");

            CultureInfo.CurrentCulture = newCurrentCulture;
            CultureInfo.CurrentUICulture = newCurrentUICulture;

            Func<Task> mainAsync = async delegate
            {
                await Task.Delay(1).ConfigureAwait(false);

                Assert.Equal(CultureInfo.CurrentCulture, newCurrentCulture);
                Assert.Equal(CultureInfo.CurrentUICulture, newCurrentUICulture);
            };

            try
            {
                mainAsync().Wait();
            }
            finally
            {
                CultureInfo.CurrentCulture = currentCulture;
                CultureInfo.CurrentUICulture = currentUICulture;
            }
        }
    }
}


text:
![Redui-jm screenshot](https://raw.githubusercontent.com/juanmnl/redui-jm-theme/master/logo.png)

# Redui-jm Syntax Theme :coffee:

Your coffee is ready!!

A nice aromatic coffee infused syntax theme for Atom and the ONE DARK UI theme
:coffee: From the highlands of the Andes to your Atom editor :coffee:

## Screen

-- *Font: Fira Code* --

JSX/ES6 (babel)
![Redui-jm screenshot](https://raw.githubusercontent.com/juanmnl/redui-jm-theme/master/jsx.png)

Scss
![Redui-jm screenshot](https://raw.githubusercontent.com/juanmnl/redui-jm-theme/master/scss.png)

Html
![Redui-jm screenshot](https://raw.githubusercontent.com/juanmnl/redui-jm-theme/master/html.png)

Open Atom Preferences > Install > Search *themes*: `redui-jm-syntax`,
then Install.

*You may need to reload Atom `Cmd+R` in between these steps.*
Activate the theme by selecting the Themes section of Preferences.


text:
package com.google.common.collect;

import java.util.Set;

public class CompactLinkedHashSetFloodingTest extends AbstractHashFloodingTest<Set<Object>> {
  public CompactLinkedHashSetFloodingTest() {
    super(
        ImmutableList.of(Construction.setFromElements(CompactLinkedHashSet::create)),
        n -> n * Math.log(n),
        ImmutableList.of(QueryOp.SET_CONTAINS));
  }
}


text:
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution(object):
    def buildTree(self, preorder, inorder):
        #使用字典很关键
        lookup = {}
        for i, num in enumerate(inorder):
            lookup[num] = i
        return self.Recur(lookup, preorder, inorder, 0, 0, len(preorder))

    def Recur(self, lookup, preorder, inorder, pre_start, in_start, in_end):
        if in_start == in_end:
            return None
        node = TreeNode(preorder[pre_start])
        i = lookup[preorder[pre_start]]
        # 递归发现不难,难的是如何表达,使用pre_start来标记每个node,更新in_start, in_end来进行确定是否是叶子节点,并且也能便于确定递归后的范围
        node.left = self.Recur(lookup, preorder, inorder, pre_start + 1, in_start, i)
        # 更新的pre_start就是(pre_start + (i - in_start) + 1)
        node.right = self.Recur(lookup, preorder, inorder, pre_start + 1 + i - in_start, i + 1, in_end)
        return node

if __name__ ==  "__main__":
    inorder = [2, 1, 3]
    preorder = [1, 2, 3]
    result = Solution().buildTree(preorder, inorder)
    print result.val
    print result.left.val
    print result.right.val


text:
#ifndef MONICA_H
#define MONICA_H

#define MONICA_MQTT_ADDR        "fd17:cafe:cafe:3::1"
#define MONICA_MQTT_PORT        (1885U)
#define MONICA_MQTT_SIZE        (64U)
#define MONICA_MQTT_STACKSIZE   (3*THREAD_STACKSIZE_DEFAULT)

int sensor_get_temperature(void);
int sensor_get_humidity(void);
size_t node_get_info(char *buf);

typedef struct monica_pub {
    char *topic;
    char *message;
} monica_pub_t;

#endif /* MONICA_H */


text:
// ***********************************************************************
// Assembly         : MusicPickerDeviceApp
// Author           : Pierre
// Created          : 06-20-2015
//
// Last Modified By : Pierre
// Last Modified On : 06-20-2015
// ***********************************************************************
// <copyright file="Device.cs" company="Hutopi">
//     Copyright ©  2015 Hugo Caille, Pierre Defache & Thomas Fossati.
//     Music Picker is released upon the terms of the Apache 2.0 License.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;

/// <summary>
/// The App namespace.
/// </summary>
namespace MusicPickerDeviceApp.App
{
    /// <summary>
    /// Class that represents a device.
    /// </summary>
    public class Device
    {
        /// <summary>
        /// Gets or sets the identifier of the device.
        /// </summary>
        /// <value>The identifier.</value>
        public int Id { get; set; }
        /// <summary>
        /// Gets or sets the registration date of the device.
        /// </summary>
        /// <value>The registration date.</value>
        public DateTime RegistrationDate { get; set; }
        /// <summary>
        /// Gets or sets the access date of the device.
        /// </summary>
        /// <value>The access date.</value>
        public DateTime AccessDate { get; set; }
        /// <summary>
        /// Gets or sets the name of the device.
        /// </summary>
        /// <value>The name.</value>
        public string Name { get; set; }
    }
}


text:
"""Auto-generated file, do not edit by hand. KE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_KE = PhoneMetadata(id='KE', country_code=None, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,3}', possible_number_pattern='\\d{3,4}'),
    fixed_line=PhoneNumberDesc(national_number_pattern='1\\d{2,3}', possible_number_pattern='\\d{3,4}'),
    mobile=PhoneNumberDesc(national_number_pattern='1\\d{2,3}', possible_number_pattern='\\d{3,4}'),
    toll_free=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    emergency=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    short_code=PhoneNumberDesc(national_number_pattern='1(?:0[09]|1(?:[06]|9[0-2579])|2[13]|3[01])', possible_number_pattern='\\d{3,4}', example_number='116'),
    standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    short_data=True)


text:
@implementation UIFont (Homenaje)

+ (instancetype)homenajeRegularFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"Homenaje-Regular"
                   fromBundle:@"Homenaje"
                    onceToken:&onceToken];
  return [self fontWithName:@"Homenaje-Regular" size:size];
}

@end


text:
package com.example.weatherforecast.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by misaki on 2016/7/1.
 */
public class WeatherForecastOpenHelper extends SQLiteOpenHelper {
    public static final String CREATE_PROVINCE="create table Province(id integer primary key autoincrement,province_name text,province_code text)";
    public static final String CREATE_CITY="create table City(id integer primary key autoincrement,city_name text,city_code text,province_id integer)";
    public static final String CREATE_COUNTRY="create table Country(id integer primary key autoincrement,country_name text,country_code text,city_id integer)";
    public WeatherForecastOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_PROVINCE);
        db.execSQL(CREATE_CITY);
        db.execSQL(CREATE_COUNTRY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


text:
export interface Things<P, T> {
    p: P;
    t: T;
}
export function make<P, CTor>(x: { new (): CTor & {props: P} }): Things<P, CTor> {
    return null as any;
}

export interface Props {
}

export default class MyComponent {
    props: Props;
    static create = make(MyComponent);
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import TableCell from '@material-ui/core/TableCell';
import { makeStyles } from '@material-ui/core/styles';
import Chip from '@material-ui/core/Chip';
import { checkBlue, inProgressYellow } from '../../../styles/js/shared';

const useStyles = makeStyles({
  tableCell: {
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },
  chip: {
    color: 'white',
    fontSize: 12,
  },
  noFactCheck: {
    background: inProgressYellow,
  },
  more: {
    background: checkBlue,
  },
});

export default function ValueListCell({
  values,
  noValueLabel,
  onClick,
  randomizeOrder,
  renderNoValueAsChip,
}) {
  const classes = useStyles();
  const [showMore, setShowMore] = React.useState(false);

  function handleMoreChipClick(e) {
    e.stopPropagation();
    setShowMore(true);
  }

  const handleClick = (e) => {
    e.stopPropagation();
    if (onClick) onClick();
  };

  let content = renderNoValueAsChip ? (
    <Chip
      size="small"
      className={[classes.chip, classes.noFactCheck].join(' ')}
      label={noValueLabel}
    />
  ) : noValueLabel;
  if (values && values.length > 0) {
    const labels = [];
    let more = 0;
    if (randomizeOrder) {
      values.sort(() => Math.random() - 0.5);
    }
    values.forEach((name, i) => {
      if (showMore || i < 2) {
        labels.push(
{name}
);
      } else {
        more += 1;
      }
    });
    if (!showMore && more > 0) {
      labels.push(
        <Chip
          size="small"
          className={[classes.chip, classes.more].join(' ')}
          onClick={handleMoreChipClick}
          label={
            <FormattedMessage
              id="valueListCell.more"
              defaultMessage="+{number} more"
              values={{ number: more }}
              description="Button to maximize list display (tags, urls, checked options) with all values within a table cell"
            />
          }
        />,
      );
    }
    content = labels;
  }

  return <TableCell onClick={handleClick} className={classes.tableCell}>{content}</TableCell>;
}

ValueListCell.defaultProps = {
  renderNoValueAsChip: false,
  noValueLabel: '-',
};
ValueListCell.propTypes = {
  values: PropTypes.arrayOf(PropTypes.node.isRequired).isRequired,
  noValueLabel: PropTypes.node,
  renderNoValueAsChip: PropTypes.bool,
};


text:
import { ExcelXMLTemplate } from '@ag-grid-community/core';
declare const interior: ExcelXMLTemplate;
export default interior;


text:
<!DOCTYPE html>
<!--[if lt IE 7]>      <html lang="en" ng-app="tryangular" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html lang="en" ng-app="tryangular" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html lang="en" ng-app="tryangular" class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en" ng-app="tryangular" class="no-js"> <!--<![endif]-->
<head>
  <base href="/">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-resource.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>

  <script src="js/dirPagination.js"></script>

  <script src="app.module.js"></script>
  <script src="app.config.js"></script>

  <script src="core/post/post.module.js"></script>
  <script src="core/post/post.service.js"></script>

  <script src="blog-detail/blog-detail.module.js"></script>
  <script src="blog-detail/blog-detail.component.js"></script>
  <script src="blog-list/blog-list.module.js"></script>
  <script src="blog-list/blog-list.component.js"></script>

  <script src="utils/confirm-click/confirm-click.module.js"></script>
  <script src="utils/confirm-click/confirm-click.directive.js"></script>

  <script src="utils/try-nav/try-nav-module.js"></script>
  <script src="utils/try-nav/try-nav.directive.js"></script>

</head>
<body>
    <div class="container">
      <try-nav></try-nav>

      <div ng-view>

      </div>
    </div>

</body>
</html>


text:
package com.example.activity;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.FrameLayout.LayoutParams;

import com.BeeFramework.BeeFrameworkApp;
import com.BeeFramework.example.R;
import com.BeeFramework.model.BeeQuery;

public class HomeTabActivity extends TabActivity {

    private TabHost tabHost;

    private ImageView image;
	private TranslateAnimation mTranslateAnimation;
	private int width;
	int start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_tab);

        if(BeeQuery.environment() == BeeQuery.ENVIROMENT_DEVELOPMENT) {
            BeeFrameworkApp.getInstance().showBug(this);
        }

        width = getWindowManager().getDefaultDisplay().getWidth()/3;

		image = (ImageView) findViewById(R.id.home_tab_image);
		LayoutParams params = (LayoutParams) image.getLayoutParams();
		params.width = width;
		image.setLayoutParams(params);

        tabHost = getTabHost();
        TabHost.TabSpec spec_tab1 = tabHost.newTabSpec("spec_tab1").setIndicator("spec_tab1")
                .setContent(new Intent(HomeTabActivity.this,ShotListActivity.class));
        tabHost.addTab(spec_tab1);

        TabHost.TabSpec spec_tab2 = tabHost.newTabSpec("spec_tab2").setIndicator("spec_tab2")
                .setContent(new Intent(HomeTabActivity.this,GalleryImageActivity.class));
        tabHost.addTab(spec_tab2);

        TabHost.TabSpec spec_tab3 = tabHost.newTabSpec("spec_tab3").setIndicator("spec_tab3")
                .setContent(new Intent(HomeTabActivity.this,TeamIntroduction.class));
        tabHost.addTab(spec_tab3);

        RadioGroup group = (RadioGroup) this.findViewById(R.id.tab_group);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId) {
                    case R.id.tab_one:
                        tabHost.setCurrentTabByTag("spec_tab1");
                        mTranslateAnimation = new TranslateAnimation(start, 0,0, 0);
    					mTranslateAnimation.setDuration(200);
    					mTranslateAnimation.setFillEnabled(true);
    					mTranslateAnimation.setFillAfter(true);
    					image.startAnimation(mTranslateAnimation);
    					start = 0;
                        break;
                    case R.id.tab_two:
                        tabHost.setCurrentTabByTag("spec_tab2");
                        mTranslateAnimation = new TranslateAnimation(start, width,0, 0);
    					mTranslateAnimation.setDuration(200);
    					mTranslateAnimation.setFillEnabled(true);
    					mTranslateAnimation.setFillAfter(true);
    					image.startAnimation(mTranslateAnimation);
    					start = width;
                        break;
                    case R.id.tab_three:
                        tabHost.setCurrentTabByTag("spec_tab3");
                        mTranslateAnimation = new TranslateAnimation(start, width*2,0, 0);
    					mTranslateAnimation.setDuration(200);
    					mTranslateAnimation.setFillEnabled(true);
    					mTranslateAnimation.setFillAfter(true);
    					image.startAnimation(mTranslateAnimation);
    					start = width*2;
                        break;
                }
            }
        });
    }
}


text:
using System.Windows;
using System.Windows.Media;
using Wox.Plugin;
using Wox.Core.Resource;
using Wox.Image;

namespace Wox.ViewModel
{
    public class PluginViewModel : BaseModel
    {
        public PluginPair PluginPair { get; set; }

        private readonly Internationalization _translator = InternationalizationManager.Instance;

        public ImageSource Image => ImageLoader.Load(PluginPair.Metadata.IcoPath);
        public Visibility ActionKeywordsVisibility => PluginPair.Metadata.ActionKeywords.Count > 1 ? Visibility.Collapsed : Visibility.Visible;
        public string InitilizaTime => string.Format(_translator.GetTranslation("plugin_init_time"), PluginPair.Metadata.InitTime);
        public string QueryTime => string.Format(_translator.GetTranslation("plugin_query_time"), PluginPair.Metadata.AvgQueryTime);
        public string ActionKeywordsText => string.Join(Query.ActionKeywordSeperater, PluginPair.Metadata.ActionKeywords);
    }
}


text:
"""
Responsible for reading in configuration files, validating the proper
format and providing sane defaults for parts that don't have any.

"""
import json
import logging
import logging.config
import os
from os import path
import sys
try:
    from urllib import parse
except ImportError:  # Python 2.7 support
    import urlparse as parse

import flatdict
import yaml

LOGGER = logging.getLogger(__name__)

APPLICATION = {'wake_interval': 60}

DAEMON = {'user': None,
          'group': None,
          'pidfile': None,
          'prevent_core': True}

LOGGING_FORMAT = ('%(levelname) -10s %(asctime)s %(process)-6d '
                  '%(processName) -20s %(threadName)-12s %(name) -30s '
                  '%(funcName) -25s L%(lineno)-6d: %(message)s')

LOGGING = {
    'disable_existing_loggers': True,
    'filters': {},
    'formatters': {
        'verbose': {
            'datefmt': '%Y-%m-%d %H:%M:%S',
            'format': LOGGING_FORMAT
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'root': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
            'level': logging.CRITICAL
        }
    },
    'incremental': False,
    'loggers': {},
    'root': {
        'handlers': ['root']
    },
    'version': 1}

class Config(object):
    """The Config object holds the current state of the configuration for an
    application. If no configuration file is provided, it will used a set of
    defaults with very basic behavior for logging and daemonization.

    """
    def __init__(self, file_path=None):
        """Create a new instance of the configuration object, passing in the
        path to the configuration file.

        :param str file_path: The path to the configuration file
        :raises: ValueError

        """
        self._values = self._default_configuration()
        self._file_path = self._normalize_file_path(file_path)
        if self._file_path:
            self._values.update(self._load_config_file())

    def get(self, name, default=None):
        """Return the value for key if key is in the configuration, else default.

        :param str name: The key name to return
        :param mixed default: The default value for the key
        :return: mixed

        """
        return self._values.get(name, default)

    @property
    def application(self):
        return self._values['Application'].as_dict()

    @property
    def daemon(self):
        return self._values['Daemon'].as_dict()

    @property
    def logging(self):
        return self._values['Logging'].as_dict()

    def reload(self):
        """Reload the configuration from disk returning True if the
        configuration has changed from the previous values.

        """
        config = self._default_configuration()
        if self._file_path:
            config.update(self._load_config_file())
        if config != self._values:
            self._values = config
            return True
        return False

    @staticmethod
    def _default_configuration():
        """Return the default configuration for Helper

        :rtype: dict

        """
        return flatdict.FlatDict({
            'Application': APPLICATION,
            'Daemon': DAEMON,
            'Logging': LOGGING
        })

    def _load_config_file(self):
        """Load the configuration file into memory, returning the content.

        """
        LOGGER.info('Loading configuration from %s', self._file_path)
        if self._file_path.endswith('json'):
            config = self._load_json_config()
        else:
            config = self._load_yaml_config()
        for key, value in [(k, v) for k, v in config.items()]:
            if key.title() != key:
                config[key.title()] = value
                del config[key]
        return flatdict.FlatDict(config)

    def _load_json_config(self):
        """Load the configuration file in JSON format

        :rtype: dict

        """
        try:
            return json.loads(self._read_config())
        except ValueError as error:
            raise ValueError(
                'Could not read configuration file: {}'.format(error))

    def _load_yaml_config(self):
        """Loads the configuration file from a .yaml or .yml file

        :type: dict

        """
        try:
            config = self._read_config()
        except OSError as error:
            raise ValueError('Could not read configuration file: %s' % error)
        try:
            return yaml.safe_load(config)
        except yaml.YAMLError as error:
            message = '\n'.join(['    > %s' % line
                                 for line in str(error).split('\n')])
            sys.stderr.write('\n\n  Error in the configuration file:\n\n'
                             '{}\n\n'.format(message))
            sys.stderr.write('  Configuration should be a valid YAML file.\n')
            sys.stderr.write('  YAML format validation available at '
                             'http://yamllint.com\n')
            raise ValueError(error)

    @staticmethod
    def _normalize_file_path(file_path):
        """Normalize the file path value.

        :param str file_path: The file path as passed in
        :rtype: str

        """
        if not file_path:
            return None
        elif file_path.startswith('s3://') or \
                file_path.startswith('http://') or \
                file_path.startswith('https://'):
            return file_path
        return path.abspath(file_path)

    def _read_config(self):
        """Read the configuration from the various places it may be read from.

        :rtype: str
        :raises: ValueError

        """
        if not self._file_path:
            return None
        elif self._file_path.startswith('s3://'):
            return self._read_s3_config()
        elif self._file_path.startswith('http://') or \
                self._file_path.startswith('https://'):
            return self._read_remote_config()
        elif not path.exists(self._file_path):
            raise ValueError(
                'Configuration file not found: {}'.format(self._file_path))

        with open(self._file_path, 'r') as handle:
            return handle.read()

    def _read_remote_config(self):
        """Read a remote config via URL.

        :rtype: str
        :raises: ValueError

        """
        try:
            import requests
        except ImportError:
            requests = None
        if not requests:
            raise ValueError(
                'Remote config URL specified but requests not installed')
        result = requests.get(self._file_path)
        if not result.ok:
            raise ValueError(
                'Failed to retrieve remote config: {}'.format(
                    result.status_code))
        return result.text

    def _read_s3_config(self):
        """Read in the value of the configuration file in Amazon S3.

        :rtype: str
        :raises: ValueError

        """
        try:
            import boto3
            import botocore.exceptions
        except ImportError:
            boto3, botocore = None, None

        if not boto3:
            raise ValueError(
                's3 URL specified for configuration but boto3 not installed')
        parsed = parse.urlparse(self._file_path)
        try:
            response = boto3.client(
                's3', endpoint_url=os.environ.get('S3_ENDPOINT')).get_object(
                    Bucket=parsed.netloc, Key=parsed.path.lstrip('/'))
        except botocore.exceptions.ClientError as e:
            raise ValueError(
                'Failed to download configuration from S3: {}'.format(e))
        return response['Body'].read().decode('utf-8')

class LoggingConfig(object):
    """The Logging class is used for abstracting away dictConfig logging
    semantics and can be used by sub-processes to ensure consistent logging
    rule application.

    """
    DEBUG_ONLY = 'debug_only'
    HANDLERS = 'handlers'
    LOGGERS = 'loggers'

    def __init__(self, configuration, debug=None):
        """Create a new instance of the Logging object passing in the
        DictConfig syntax logging configuration and a debug flag.

        :param dict configuration: The logging configuration
        :param bool debug: Toggles use of debug_only loggers

        """
        # Force a NullLogger for some libraries that require it
        root_logger = logging.getLogger()
        root_logger.addHandler(logging.NullHandler())

        self.config = dict(configuration)
        self.debug = debug
        self.configure()

    def update(self, configuration, debug=None):
        """Update the internal configuration values, removing debug_only
        handlers if debug is False. Returns True if the configuration has
        changed from previous configuration values.

        :param dict configuration: The logging configuration
        :param bool debug: Toggles use of debug_only loggers
        :rtype: bool

        """
        if self.config != dict(configuration) and debug != self.debug:
            self.config = dict(configuration)
            self.debug = debug
            self.configure()
            return True
        return False

    def configure(self):
        """Configure the Python stdlib logger"""
        if self.debug is not None and not self.debug:
            self._remove_debug_handlers()
        self._remove_debug_only()
        logging.config.dictConfig(self.config)
        try:
            logging.captureWarnings(True)
        except AttributeError:
            pass

    def _remove_debug_handlers(self):
        """Remove any handlers with an attribute of debug_only that is True and
        remove the references to said handlers from any loggers that are
        referencing them.

        """
        remove = list()
        for handler in self.config[self.HANDLERS]:
            if self.config[self.HANDLERS][handler].get('debug_only'):
                remove.append(handler)
        for handler in remove:
            del self.config[self.HANDLERS][handler]
            for logger in self.config[self.LOGGERS].keys():
                logger = self.config[self.LOGGERS][logger]
                if handler in logger[self.HANDLERS]:
                    logger[self.HANDLERS].remove(handler)
        self._remove_debug_only()

    def _remove_debug_only(self):
        """Iterate through each handler removing the invalid dictConfig key of
        debug_only.

        """
        LOGGER.debug('Removing debug only from handlers')
        for handler in self.config[self.HANDLERS]:
            if self.DEBUG_ONLY in self.config[self.HANDLERS][handler]:
                del self.config[self.HANDLERS][handler][self.DEBUG_ONLY]


text:
;
; Final Fantasy III-like Intro Screen Demo
;
; Copyright (c) 2014, Tim Hentenaar
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are
; met:
;
; 1. Redistributions of source code must retain the above copyright
;    notice, this list of conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright
;    notice, this list of conditions and the following disclaimer in the
;    documentation and/or other materials provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;

.segment "HEADER"

; iNES Header
.byte "NES", $1a
.byte $01          ; 1x 16k bank of PRG-ROM
.byte $00          ; 0x 8k  bank of CHR-ROM (1x 8k bank of CHR-RAM)
.byte $01          ; Vertical Mirroring / Mapper Lo: 0
.byte $00          ; Mapper Hi: 0 (NROM)

.zeropage
	textptr:      .res 2 ; Pointer to the current pos. in the text
	lineptr:      .res 2 ; Pointer to the current pos. in the nametable
	line_offset:  .res 1 ; Position within the current line of text
	num_lines:    .res 1 ; Number of lines rendered for the current page
	is_attr_addr: .res 1 ; Current attribute table address
	is_attr_byte: .res 1 ; Current attribute byte
	is_color:     .res 1 ; Current color
	frame_ctr:    .res 1 ; Frame counter for the fade effect

.code

.include "../ppu.inc"

.import enable_ppu, disable_ppu, reset_ppu_scroll, nmi_spin
.import clear_nametables
.export patterns, palettes

; Text markers
.define text_eol $aa ; End of Line
.define text_eop $ac ; End of Page
.define text_eot $ae ; End of Text

; Delay by the time it would take the effect to
; be done over this number of lines before going
; to the next page (for readability.)
.define ln_delay 2

; Memory Map for utilized RAM
.define ram_palettes $0200

init:
	; Prepare palettes and patterns
	jsr copy_palettes_to_ram

	; Initialize our pointer to the page text
	lda #<intro_pages
	sta textptr
	lda #>intro_pages
	sta textptr+1

;
; Main loop
;
.proc main
	; Disable the PPU
	jsr disable_ppu

	; Clear the screen
	jsr clear_nametables

	; Render the next page
	jsr render_page
	pha

	; Enable the PPU
	jsr enable_ppu

	; Do the fade-in effect
	jsr fade_in

	; Did we finish the last page?
	pla
	cmp #text_eot
	bne main

	; If so, we're done
	jmp ($fffc)
.endproc

;
; Do the fade-in effect
;
; It's really simple, actually. We're simply rotating
; colors in the palette we're using to give the
; impression that the text is fading-in. We then
; use the PPU attribute table to effect changes
; in palette.
;
; Keep in mind that each attribute byte affects
; a 16x16 area on the screen. Each two bits
; contains the palette number used for one tile.
;
; The bits are assigned in the following order:
;
;  -------------
; |  0   |  1   |
; | ---- | ---- |
; |  2   |  3   |
;  -------------
;
; So, the value %11100100 is used like:
;
;  -------------
; |  00  |  01  |
; | ---- | ---- |
; |  10  |  11  |
;  -------------
;
; What does this have to do with our lines of text?
;
; Simply put, we drew the text on odd-numbered rows.
; Thus, only the lower half of the attribute row is
; used for our line of text.
;
.proc fade_in
	; Set our attribute table address to point to the
	; beginning of the attribute table.
	lda #$c0
	sta is_attr_addr

	; Palette #1 / #2
@loop:
	lda #%01011010
	sta is_attr_byte
	jsr rotate_color

	; Are we at the last row of text?
	dec num_lines
	bmi :+

	; Palette #2 / #3
	lda #%10101111
	sta is_attr_byte
	jsr rotate_color

	; Finally, use palette #3
:	lda #%11111111
	sta is_attr_byte
	jsr render_intro_screen

	; Go to the next attribute table row
	lda is_attr_addr
	clc
	adc #8
	sta is_attr_addr

	; Loop until we've completed the last row
	dec num_lines
	bpl @loop
	rts
.endproc

;
; Rotate color #3 of palette #2
;
; This is where the real magic happens.
;
; Keep in mind that the NES palette goes from $00 - $3f,
; with 16 basic color entries. Thus, adding $10 lightens
; the color by one shade, while subtracting $10 makes it
; one shade darker.
;
.proc rotate_color
	; Start with the darkest grey
	lda #0
	sta is_color
@loop:
	lda is_color
	sta ram_palettes+$0b

@render:
	; Update the PPU and increment our frame counter
	jsr render_intro_screen
	inc frame_ctr
	lda frame_ctr
	and #$0f
	bne @darken

	; Make the color one shade lighter (each 16th frame)
	lda is_color
	clc
	adc #$10
	sta is_color

	; When we finally reach $40, we're done.
	cmp #$40
	bcc @loop
	rts

	; For frames 2 - 15, we make the color darker
	; for each odd-numbered frame.
@darken:
	lsr
	bcc @loop

	; Make the color one shade darker
	lda ram_palettes+$0b
	sec
	sbc #$10
	bpl :+

	; If our subtraction went negative, reset
	; our color to one shade above the darkest
	; grey.
	lda #1

	; Store the new color and loop
:	sta ram_palettes+$0b
	jmp @render
.endproc

;
; Here's where we finally send our updated
; palette and attribute data to the PPU.
;
.proc render_intro_screen
	jsr nmi_spin
	jsr copy_ram_palettes_to_ppu

	; Reset PPU address/scroll latches to avoid
	; possibly generating multiple NMIs.
	lda PPUSTAT

	; Set PPUADDR to point to the current row's attributes
	lda #$23
	sta PPUADDR
	lda is_attr_addr
	sta PPUADDR

	; Write one full row of attribute info
	ldx #8
	lda is_attr_byte
:	sta PPUDATA
	dex
	bne :-

	; Reset the PPU scrolling registers
	jmp reset_ppu_scroll
.endproc

;
; Layout a page of text on the screen
;
; Text is rendered every 2 rows from (2, 3) to (29, 27)
;
; Output:
;
;   A - Contains the text marker byte, if a End-of-Page or
;       End-of-Text marker are found.
;
; Clobbers:
;
;   Y
;
.proc render_page
	; Initalize the line pointer
	lda #$62
	sta lineptr
	lda #$20
	sta lineptr+1

	; Zero the line offset
	lda #0
	sta line_offset
	tay

	; Initialize the line counter
	lda #ln_delay
	sta num_lines

@next_byte:
	; Load the next byte and update our pointer
	lda (textptr),y
	inc textptr
	bne :+
	inc textptr+1

	; Check for space
:	cmp #$00
	beq @next_cell

	; Check for text markers
	cmp #text_eol
	beq @skip_eol
	cmp #text_eop
	beq @return
	cmp #text_eot
	beq @return

	; Set the PPU Address
	tay
	lda lineptr+1
	sta PPUADDR
	lda lineptr
	clc
	adc line_offset
	sta PPUADDR

	; Draw the char
	tya
	ldy #0
	sta PPUDATA

@next_cell:
	; Advance to the next cell
	inc line_offset
	lda line_offset
	cmp #28 ; Chars per line
	bcc @next_byte

@skip_eol:
	; Skip any leading newlines
	lda #62
	cmp lineptr
	beq @next_byte

	; Advance to the next line
	sty line_offset
	lda num_lines
	cmp #12 + ln_delay ; Lines per page
	bcs @return
	inc num_lines
	lda lineptr
	clc
	adc #$40
	sta lineptr
	bcc @next_byte

	; Are we at the end of the screen?
	inc lineptr+1
	lda lineptr+1
	cmp #28 ; Rows per page
	bne @next_byte

@return:
	rts
.endproc

;
; Copy palettes to RAM (so we can manipulate them)
;
.proc copy_palettes_to_ram
	ldx #0
:	lda palettes,x
	sta ram_palettes,x
	inx
	cpx #16
	bmi :-
	rts
.endproc

;
; Copy our palettes from RAM to the PPU
;
.proc copy_ram_palettes_to_ppu
	lda #$3f
	sta PPUADDR
	lda #$00
	sta PPUADDR
	tax
:	lda ram_palettes,x
	sta PPUDATA
	inx
	cpx #16
	bmi :-
	rts
.endproc

palettes:
	.byte $02, $02, $02, $02 ; Background Palette 0
	.byte $02, $02, $02, $02 ; Background Palette 1
	.byte $0f, $0f, $02, $02 ; Background Palette 2
	.byte $0f, $00, $02, $10 ; Background Palette 3
	.byte data_end

patterns:
	; Transparent tile
	.byte $00, $00, $00, $00, $00, $00, $00, $00
	.byte $00, $00, $00, $00, $00, $00, $00, $00
	.include "font.asm"

intro_pages:
	.incbin "text.bin"
	.byte text_eot

; vi:set ft=ca65:


text:
import { Context } from '../../src/core';
import { assert } from 'chai';
import { suite, test } from 'mocha-typescript';

@suite
class ContextImplTest {
    private static DEFAULT_PORT: number = 20202;

    @test
    instanceCreation() {
        const context: Context = new Context();

        assert.isOk(context);
    }

    @test
    testDefaultPort() {
        const context: Context = new Context();

        assert.equal(context.getPort(), ContextImplTest.DEFAULT_PORT);
    }
}


text:
using content::BrowserThread;

namespace printing {

namespace {

#if defined(OS_ANDROID)
content::WebContents* GetWebContentsForRenderView(int render_process_id,
                                                  int render_view_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  content::RenderViewHost* view = content::RenderViewHost::FromID(
      render_process_id, render_view_id);
  return view ? content::WebContents::FromRenderViewHost(view) : nullptr;
}

PrintViewManagerBasic* GetPrintManager(int render_process_id,
                                       int render_view_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  content::WebContents* web_contents =
      GetWebContentsForRenderView(render_process_id, render_view_id);
  return web_contents ? PrintViewManagerBasic::FromWebContents(web_contents)
                      : nullptr;
}
#endif

}  // namespace

PrintingMessageFilter::PrintingMessageFilter(int render_process_id,
                                             Profile* profile)
    : BrowserMessageFilter(PrintMsgStart),
      is_printing_enabled_(new BooleanPrefMember),
      render_process_id_(render_process_id),
      queue_(g_browser_process->print_job_manager()->queue()) {
  DCHECK(queue_.get());
  is_printing_enabled_->Init(prefs::kPrintingEnabled, profile->GetPrefs());
  is_printing_enabled_->MoveToThread(
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
}

PrintingMessageFilter::~PrintingMessageFilter() {
}

void PrintingMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_ANDROID)
  if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID ||
      message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) {
    *thread = BrowserThread::UI;
  }
#endif
}

bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrintingMessageFilter, message)
#if defined(OS_WIN)
    IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_ANDROID)
    IPC_MESSAGE_HANDLER(PrintHostMsg_AllocateTempFileForPrinting,
                        OnAllocateTempFileForPrinting)
    IPC_MESSAGE_HANDLER(PrintHostMsg_TempFileForPrintingWritten,
                        OnTempFileForPrintingWritten)
#endif
    IPC_MESSAGE_HANDLER(PrintHostMsg_IsPrintingEnabled, OnIsPrintingEnabled)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings,
                                    OnGetDefaultPrintSettings)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_UpdatePrintSettings,
                                    OnUpdatePrintSettings)
#if defined(ENABLE_PRINT_PREVIEW)
    IPC_MESSAGE_HANDLER(PrintHostMsg_CheckForCancel, OnCheckForCancel)
#endif
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
    base::SharedMemoryHandle renderer_handle,
    base::SharedMemoryHandle* browser_handle) {
  // Duplicate the handle in this process right now so the memory is kept alive
  // (even if it is not mapped)
  base::SharedMemory shared_buf(renderer_handle, true, PeerHandle());
  shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif

#if defined(OS_ANDROID)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
    int render_view_id,
    base::FileDescriptor* temp_file_fd,
    int* sequence_number) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  PrintViewManagerBasic* print_view_manager =
      GetPrintManager(render_process_id_, render_view_id);
  if (!print_view_manager)
    return;
  // The file descriptor is originally created in & passed from the Android
  // side, and it will handle the closing.
  temp_file_fd->fd = print_view_manager->file_descriptor().fd;
  temp_file_fd->auto_close = false;
}

void PrintingMessageFilter::OnTempFileForPrintingWritten(int render_view_id,
                                                         int sequence_number) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  PrintViewManagerBasic* print_view_manager =
      GetPrintManager(render_process_id_, render_view_id);
  if (print_view_manager)
    print_view_manager->PdfWritingDone(true);
}
#endif  // defined(OS_ANDROID)

void PrintingMessageFilter::OnIsPrintingEnabled(bool* is_enabled) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  *is_enabled = is_printing_enabled_->GetValue();
}

void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  scoped_refptr<PrinterQuery> printer_query;
  if (!is_printing_enabled_->GetValue()) {
    // Reply with NULL query.
    OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
    return;
  }
  printer_query = queue_->PopPrinterQuery(0);
  if (!printer_query.get()) {
    printer_query =
        queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
  }

  // Loads default settings. This is asynchronous, only the IPC message sender
  // will hang until the settings are retrieved.
  printer_query->GetSettings(
      PrinterQuery::GetSettingsAskParam::DEFAULTS,
      0,
      false,
      DEFAULT_MARGINS,
      false,
      base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
                 this,
                 printer_query,
                 reply_msg));
}

void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
    scoped_refptr<PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  PrintMsg_Print_Params params;
  if (!printer_query.get() ||
      printer_query->last_status() != PrintingContext::OK) {
    params.Reset();
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params);
    params.document_cookie = printer_query->cookie();
  }
  PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If printing was enabled.
  if (printer_query.get()) {
    // If user hasn't cancelled.
    if (printer_query->cookie() && printer_query->settings().dpi()) {
      queue_->QueuePrinterQuery(printer_query.get());
    } else {
      printer_query->StopWorker();
    }
  }
}

void PrintingMessageFilter::OnScriptedPrint(
    const PrintHostMsg_ScriptedPrint_Params& params,
    IPC::Message* reply_msg) {
  scoped_refptr<PrinterQuery> printer_query =
      queue_->PopPrinterQuery(params.cookie);
  if (!printer_query.get()) {
    printer_query =
        queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
  }
  printer_query->GetSettings(
      PrinterQuery::GetSettingsAskParam::ASK_USER,
      params.expected_pages_count,
      params.has_selection,
      params.margin_type,
      params.is_scripted,
      base::Bind(&PrintingMessageFilter::OnScriptedPrintReply,
                 this,
                 printer_query,
                 reply_msg));
}

void PrintingMessageFilter::OnScriptedPrintReply(
    scoped_refptr<PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  PrintMsg_PrintPages_Params params;
#if defined(OS_ANDROID)
  // We need to save the routing ID here because Send method below deletes the
  // |reply_msg| before we can get the routing ID for the Android code.
  int routing_id = reply_msg->routing_id();
#endif
  if (printer_query->last_status() != PrintingContext::OK ||
      !printer_query->settings().dpi()) {
    params.Reset();
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
    params.params.document_cookie = printer_query->cookie();
    params.pages = PageRange::GetPages(printer_query->settings().ranges());
  }
  PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  if (params.params.dpi && params.params.document_cookie) {
#if defined(OS_ANDROID)
    int file_descriptor;
    const base::string16& device_name = printer_query->settings().device_name();
    if (base::StringToInt(device_name, &file_descriptor)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          base::Bind(&PrintingMessageFilter::UpdateFileDescriptor, this,
                     routing_id, file_descriptor));
    }
#endif
    queue_->QueuePrinterQuery(printer_query.get());
  } else {
    printer_query->StopWorker();
  }
}

#if defined(OS_ANDROID)
void PrintingMessageFilter::UpdateFileDescriptor(int render_view_id, int fd) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  PrintViewManagerBasic* print_view_manager =
      GetPrintManager(render_process_id_, render_view_id);
  if (print_view_manager)
    print_view_manager->set_file_descriptor(base::FileDescriptor(fd, false));
}
#endif

void PrintingMessageFilter::OnUpdatePrintSettings(
    int document_cookie, const base::DictionaryValue& job_settings,
    IPC::Message* reply_msg) {
  scoped_ptr<base::DictionaryValue> new_settings(job_settings.DeepCopy());

  scoped_refptr<PrinterQuery> printer_query;
  if (!is_printing_enabled_->GetValue()) {
    // Reply with NULL query.
    OnUpdatePrintSettingsReply(printer_query, reply_msg);
    return;
  }
  printer_query = queue_->PopPrinterQuery(document_cookie);
  if (!printer_query.get()) {
    int host_id = render_process_id_;
    int routing_id = reply_msg->routing_id();
    if (!new_settings->GetInteger(printing::kPreviewInitiatorHostId,
                                  &host_id) ||
        !new_settings->GetInteger(printing::kPreviewInitiatorRoutingId,
                                  &routing_id)) {
      host_id = content::ChildProcessHost::kInvalidUniqueID;
      routing_id = content::ChildProcessHost::kInvalidUniqueID;
    }
    printer_query = queue_->CreatePrinterQuery(host_id, routing_id);
  }
  printer_query->SetSettings(
      std::move(new_settings),
      base::Bind(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this,
                 printer_query, reply_msg));
}

void PrintingMessageFilter::OnUpdatePrintSettingsReply(
    scoped_refptr<PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  PrintMsg_PrintPages_Params params;
  if (!printer_query.get() ||
      printer_query->last_status() != PrintingContext::OK) {
    params.Reset();
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
    params.params.document_cookie = printer_query->cookie();
    params.pages = PageRange::GetPages(printer_query->settings().ranges());
  }
  PrintHostMsg_UpdatePrintSettings::WriteReplyParams(
      reply_msg,
      params,
      printer_query.get() &&
          (printer_query->last_status() == printing::PrintingContext::CANCEL));
  Send(reply_msg);
  // If user hasn't cancelled.
  if (printer_query.get()) {
    if (printer_query->cookie() && printer_query->settings().dpi()) {
      queue_->QueuePrinterQuery(printer_query.get());
    } else {
      printer_query->StopWorker();
    }
  }
}

#if defined(ENABLE_PRINT_PREVIEW)
void PrintingMessageFilter::OnCheckForCancel(int32_t preview_ui_id,
                                             int preview_request_id,
                                             bool* cancel) {
  PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_id,
                                               preview_request_id,
                                               cancel);
}
#endif

}  // namespace printing


text:
<?php
/**
 * Created by PhpStorm.
 * User: au1ge
 * Date: 2017/6/21
 * Time: 下午5:34
 */

class Article_model extends CI_Model{
    public function __construct()
    {
        parent::__construct();
        $this -> load -> database();
    }

    public function get_articles($num){
        $this -> db -> order_by('id', 'DESC');
        $this -> db -> limit(15, $num);
        $query = $this -> db -> get('articles');
        return $query -> result();
    }

    public function add_article($post){
        $query = $this -> db -> insert('articles', $post);
    }

    public function get_category(){
        $query = $this -> db -> query('SELECT DISTINCT category FROM articles;');
        return $query -> result();
    }

    public function all_articles()
    {
        $query = $this -> db -> get('articles');
        return $query -> result();
    }

    public function all_articles_rss()
    {
        $this -> db -> order_by('id', 'desc');
        $this -> db -> limit(15, 0);
        $query = $this -> db -> get('articles');
        return $query -> result();
    }

    public function get_nums(){
        return $this -> db -> count_all_results('articles');
    }

    public function get_search($key, $num){
        $this -> db -> order_by('id', 'DESC');
        $this -> db -> or_like('title', $key);
        $this -> db -> or_like('introduction', $key);
        $this -> db -> or_like('category', $key);
        $this -> db -> or_like('url', $key);
        $this -> db -> limit(15, $num);
        $query = $this -> db -> get('articles');
        return $query -> result();
    }

    public function search_page($key){
        $this -> db -> or_like('title', $key);
        $this -> db -> or_like('introduction', $key);
        $this -> db -> or_like('category', $key);
        $this -> db -> or_like('url', $key);
        return $this -> db -> count_all_results('articles');
    }

    public function update_article($data){
        $this -> db -> where('title', $data['title']);
        $this -> db -> update('articles', $data);
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;

class CreateContinentTable extends Migration
{

    public function up ()
    {
        Schema::create('Currency', function (Blueprint $table)
        {
            $table->increments('id')->unsigned();
            $table->string('name', 100)->unique();
            $table->string('symbol', 3)->unique();

            // Boilerplate
            $table->integer('statusId')->unsigned()->index()->default(1);
            $table->datetime('createdAt')->default(DB::raw('CURRENT_TIMESTAMP'))->index();
            $table->datetime('expiresAt')->default('2038-01-01 01:01:01')->index();
        });
        DB::statement("ALTER TABLE Currency COMMENT = 'Based on ISO 4217   http://www.iso.org/iso/home/standards/currency_codes.htm'");
    }

    public function down ()
    {
        Schema::drop('Currency');
    }
}


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

import {ArcAccountPickerAppElement} from 'chrome://chrome-signin/arc_account_picker/arc_account_picker_app.js';
import {Account, ArcAccountPickerBrowserProxyImpl} from 'chrome://chrome-signin/arc_account_picker/arc_account_picker_browser_proxy.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from '../../chai_assert.js';

import {getFakeAccountsNotAvailableInArcList, TestArcAccountPickerBrowserProxy} from './test_util.js';

window.arc_account_picker_test = {};
const arc_account_picker_test = window.arc_account_picker_test;
arc_account_picker_test.suiteName = 'ArcAccountPickerTest';

/** @enum {string} */
arc_account_picker_test.TestNames = {
  EmptyAccountList: 'EmptyAccountList',
  AccountList: 'AccountList',
  AddAccount: 'AddAccount',
  MakeAvailableInArc: 'MakeAvailableInArc',
  LinkClick: 'LinkClick',
};

suite(arc_account_picker_test.suiteName, () => {
  /** @type {ArcAccountPickerAppElement} */
  let arcAccountPickerComponent;
  /** @type {TestArcAccountPickerBrowserProxy} */
  let testBrowserProxy;

  /**
   * @param {!Array<Account>} accountsNotAvailableInArc
   */
  function testSetup(accountsNotAvailableInArc) {
    document.body.innerHTML = '';
    testBrowserProxy = new TestArcAccountPickerBrowserProxy();
    if (accountsNotAvailableInArc) {
      testBrowserProxy.setAccountsNotAvailableInArc(accountsNotAvailableInArc);
    }
    ArcAccountPickerBrowserProxyImpl.setInstance(testBrowserProxy);

    arcAccountPickerComponent = /** @type {!ArcAccountPickerAppElement} */ (
        document.createElement('arc-account-picker-app'));
    document.body.appendChild(arcAccountPickerComponent);
    flush();
  }

  test(assert(arc_account_picker_test.TestNames.EmptyAccountList), async () => {
    testSetup([]);

    const accountsFound = await arcAccountPickerComponent.loadAccounts();
    assertFalse(accountsFound);
    flush();
    const uiAccounts = [
      ...arcAccountPickerComponent.shadowRoot.querySelectorAll('.account-item'),
    ].filter(item => item.id !== 'addAccountButton');
    assertEquals(0, uiAccounts.length);
  });

  test(assert(arc_account_picker_test.TestNames.AccountList), async () => {
    const fakeAccounts = getFakeAccountsNotAvailableInArcList();
    testSetup(fakeAccounts);

    const accountsFound = await arcAccountPickerComponent.loadAccounts();
    assertTrue(accountsFound);
    flush();
    const uiAccounts = [
      ...arcAccountPickerComponent.shadowRoot.querySelectorAll('.account-item'),
    ].filter(item => item.id !== 'addAccountButton');
    assertEquals(fakeAccounts.length, uiAccounts.length);
  });

  test(assert(arc_account_picker_test.TestNames.AddAccount), async () => {
    testSetup(getFakeAccountsNotAvailableInArcList());
    await arcAccountPickerComponent.loadAccounts();
    flush();

    const addAccountPromise = new Promise(
        resolve => arcAccountPickerComponent.addEventListener(
            'add-account', () => resolve()));
    arcAccountPickerComponent.shadowRoot.querySelector('#addAccountButton')
        .click();
    await addAccountPromise;
  });

  test(
      assert(arc_account_picker_test.TestNames.MakeAvailableInArc),
      async () => {
        const fakeAccounts = getFakeAccountsNotAvailableInArcList();
        testSetup(fakeAccounts);
        await arcAccountPickerComponent.loadAccounts();
        flush();

        const expectedAccount = fakeAccounts[1];
        arcAccountPickerComponent.shadowRoot
            .querySelectorAll('.account-item')[1]
            .click();
        const account = await testBrowserProxy.whenCalled('makeAvailableInArc');
        assertDeepEquals(expectedAccount, account);
      });

  test(assert(arc_account_picker_test.TestNames.LinkClick), async () => {
    testSetup(getFakeAccountsNotAvailableInArcList());
    await arcAccountPickerComponent.loadAccounts();
    flush();

    const newWindowPromise = new Promise(
        resolve => arcAccountPickerComponent.addEventListener(
            'opened-new-window', () => resolve()));
    arcAccountPickerComponent.shadowRoot.querySelector('#osSettingsLink')
        .click();
    await newWindowPromise;
  });
});


text:
package com.almasb.fxgl.entity.action;

/**
 * Default action.
 *
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
public final class IdleAction extends InstantAction {

    public IdleAction() {
        // idle action is always complete
        setComplete();
    }

    @Override
    protected void performOnce(double tpf) {
        // no-op idle
    }
}


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

namespace OpenCV.Net
{
    /// <summary>
    /// Represents a structure that contains the bounding box and confidence level for a detected object.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct ObjectDetection
    {
        /// <summary>
        /// The bounding box for the detected object.
        /// </summary>
        public Rect Rect;

        /// <summary>
        /// The detection confidence level.
        /// </summary>
        public float Score;
    }
}