text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>Citing MetPy — MetPy 1.1dev</title>

  <link href="../_static/css/theme.css" rel="stylesheet">
  <link href="../_static/css/index.ff1ffe594081f20da1ef19478df9384b.css" rel="stylesheet">

  <link rel="stylesheet"
    href="../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/css/blank.css" />
    <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
    <link rel="stylesheet" type="text/css" href="../_static/sg_gallery.css" />
    <link rel="stylesheet" type="text/css" href="../_static/sg_gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../_static/sg_gallery-dataframe.css" />
    <link rel="stylesheet" type="text/css" href="../_static/sg_gallery-rendered-html.css" />
    <link rel="stylesheet" type="text/css" href="../_static/theme-unidata.css" />

  <link rel="preload" as="script" href="../_static/js/index.be7d3bbb2ef33a8344ce.js">

    <link rel="shortcut icon" href="../_static/metpy_32x32.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Talks and Other Media" href="media.html" />
    <link rel="prev" title="Support" href="SUPPORT.html" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="None">

    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/userguide/citing.html" />

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-collapsible" aria-controls="navbar-collapsible" aria-expanded="false" aria-label="Toggle navigation">

  </button>

  User Guide

  Reference Guide

  Developer's Guide

  Example Gallery

  Support

        Release Notes

        <form class="bd-search d-flex align-items-center" action="../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

            GitHub

            Twitter

  Version 1.1dev

   Install Guide

   Getting Started with MetPy

   Tutorials

  <input class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" type="checkbox"/>

     Working With Units

     Upper Air Sounding Tutorial

     xarray with MetPy Tutorial

     MetPy Declarative Syntax Tutorial

   MetPy 1.0 Upgrade Guide

  <input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" type="checkbox"/>

     MetPy 1.0 API Changes

   GEMPAK Comparison Guide

   Support

   Citing MetPy

   Talks and Other Media

     On this page

   BibTeX entry

   AMS Journal Style

Citing MetPy¶

If MetPy played an important role in your research, then please add us to
your reference list using one of the options below.
MetPy also maintains a CITATION.cff 1 file with human- and machine-readable
metadata for generating up-to-date citations.

DOI: 10.5065/D6WW7G29

BibTeX entry¶

Example BibTeX entry:

@software{metpy,
  author = {May, Ryan M. and Arms, Sean C. and Marsh, Patrick and Bruning, Eric and Leeman,
            John R. and Goebbert, Kevin and Thielen, Jonathan E. and Bruick, Zachary S and Camron, M. Drew.},
  organization = {Unidata},
  title = {MetPy: A {Python} Package for Meteorological Data},
  year = {2021},
  version = {1.1.0},
  doi = {10.5065/D6WW7G29},
  url = {https://github.com/Unidata/MetPy},
}

AMS Journal Style¶

AMS suggested BibTeX entry:

@misc{metpy,
  author = {May, Ryan M. and Arms, Sean C. and Marsh, Patrick and Bruning, Eric and Leeman,
            John R. and Goebbert, Kevin and Thielen, Jonathan E. and Bruick, Zachary S. and Camron, M. Drew.},
  publisher = {Unidata},
  title = {MetPy: A {Python} Package for Meteorological Data},
  year = {2021},
  doi = {10.5065/D6WW7G29},
  note = {url{https://github.com/Unidata/MetPy}},
}

Example Citation:

May, R. M., Arms, S. C., Marsh, P., Bruning, E., Leeman, J. R., Goebbert, K., Thielen, J. E.,
    Bruick, Z., and Camron, M. D., 2021: MetPy: A Python Package for Meteorological Data.
    Unidata, https://github.com/Unidata/MetPy, doi:10.5065/D6WW7G29.

1

https://citation-file-format.github.io

previous

Support

next

Talks and Other Media

    © Copyright 2008–2021, MetPy Developers.Development is supported by Unidata and the National Science Foundation..

Created using Sphinx 4.3.1.


text:
package org.woehlke.twitterwall.oodm.model.transients.mapper;

import org.springframework.jdbc.core.RowMapper;
import org.woehlke.twitterwall.oodm.model.transients.HashTagCounted;

import java.sql.ResultSet;
import java.sql.SQLException;

public class CountAllUsers2HashTagsRowMapper implements RowMapper<HashTagCounted> {

    public final static String SQL_COUNT_ALL_USER_2_HASHTAG = "select count(user_id) as number_of_users,hash_tags_id,text from userprofile_hashtag,hashtag where hashtag.id = hash_tags_id group by hash_tags_id,hashtag.id order by number_of_users desc";

    @Override
    public HashTagCounted mapRow(ResultSet resultSet, int i) throws SQLException {

        long id = resultSet.getLong("hash_tags_id");
        long number = resultSet.getLong("number_of_users");
        String text = resultSet.getString("text");

        return new HashTagCounted(id, number, text);
    }
}

redpajama_set_name: RedPajamaGithub


text:
%{
  version: "0.9.2",
  title: "Mix",
  excerpt: """
  Sebelum kita belajar lebih mendalam mengenai Elixir kita perlu memahami tentang mix.  Jika anda biasa dengan Ruby, mix adalah gabungan Bundler, RubyGems dan Rake.  Ia adalah elemen penting di dalam mana-mana projek Elixir dan di dalam pelajaran ini kita akan meneroka beberapa cirinya yang hebat.  Untuk melihat apa yang dibekalkan oleh mix, jalankan `mix help`.

Sehingga tahap ini kita telah bekerja dengan `iex` yang mempunyai banyak kekangan.  Untuk membina sesuatu yang berguna kita perlu memisahkan kod kita kepada banyak fail supaya mudah untuk diuruskan, dan mix memudahkan kita menguruskan projek-projek kita
  """
}
---

## Projek Baru

Apabila kita bersedia untuk membina satu projek baru Elixir, mix memudahkannya dengan arahan `mix new`.  Ini akan menjana struktur direktori projek dan plat dandang(boilerplate) yang berkaitan.  Ianya agak mudah, jadi mari kita mulakan:

```bash
mix new example
```

Daripada paparan output kita boleh melihat yang mix telah membuat direktori kita dan beberapa fail plat dandang:

```bash
* creating README.md
* creating .gitignore
* creating .formatter.exs
* creating mix.exs
* creating lib
* creating lib/example.ex
* creating test
* creating test/test_helper.exs
* creating test/example_test.exs
```

Di dalam pelajaran ini kita akan memberi fokus kepada `mix.exs`.  Di sini kita membuat tetapan aplikasi kita, komponen sokongan, persekitaran, dan versi.  Buka fail tersebut di dalam perisian suntingan teks kegemaran anda, anda sepatutnya dapat melihat sesuatu seperti ini(komen-komen dibuang untuk memudahkan pembacaan):

```elixir
defmodule Example.Mix do
  use Mix.Project

  def project do
    [
      app: :example,
      version: "0.1.0",
      elixir: "~> 1.5",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application do
    [
      extra_applications: [:logger]
    ]
  end

  defp deps do
    []
  end
end
```

Bahagian pertama yang akan kita lihat ialah `project`.  Di sini kita tetapkan nama aplikasi kita (`app`), versi kita (`version`), versi Elixir (`elixir`), dan akhir sekali komponen sokongan (`deps`).

Bahagian `application` digunakan semasa penjanaan fail aplikasi kita yang akan kita lihat seterusnya.

## Interaktif

Ada kemungkinan di mana `iex` perlu digunakan di dalam konteks aplikasi kita.  Kita bernasib baik, mix telah memudahkan kita.  Kita boleh menjalankan satu sesi `iex` baru:

```bash
cd example
iex -S mix
```

Menjalankan `iex` dengan cara ini akan memuatkan aplikasi kita dan komponen sokongan ke dalam runtime semasa.

## Pengkompilan

Mix adalah pintar dan akan mengkompil perubahan anda apabila diperlukan, tetapi ada kemungkinan di mana kita perlu menyatakan keperluan pengkompilan secara nyata di dalam projek kita.  Di dalam bahagian ini kita akan lihat bagaimana untuk mengkompil projek dan apa yang dilakukan oleh pengkompil.

Untuk mengkompil projek, kita hanya perlu jalankan `mix compile` di dalam direktori induk:

```bash
mix compile
```

Projek kita tidak mempunyai banyak kandungan jadi paparan output tidak begitu menarik tetap ia sepatutnya berjaya dijalankan:

```bash
Compiled lib/example.ex
Generated example app
```

Apabila kita kompilkan satu projek, mix akan membuat direktori `_build`.  Jika kita melihat ke dalam `_build` kita akan nampak fail kompilan aplikasi kita: `example.app`.

## Mengurus Komponen Sokongan

Projek kita masih belum mengandungi apa-apa komponen sokongan, jadi kita akan teruskan dan lihat bagaimana untuk membuat tetapan dan memuatkan komponen sokongan.

Untuk memuatkan satu komponen sokongan baru, kita perlu masukkan ia ke dalam fail `mix.exs` di bahagian `deps`.  Senarai komponen sokongan adalah sekumpulan tuple yang mengandungi dua nilai wajib dan  satu nilai pilihan:  Nama pakej dalam bentuk atom, versi dalam bentuk string, dan nilai-nilai pilihan.

Sebagai contoh mari kita lihat satu projek yang mengandungi komponen sokongan, seperti [phoenix_slim](https://github.com/doomspork/phoenix_slim):

```elixir
def deps do
  [
    {:phoenix, "~> 1.1 or ~> 1.2"},
    {:phoenix_html, "~> 2.3"},
    {:cowboy, "~> 1.0", only: [:dev, :test]},
    {:slime, "~> 0.14"}
  ]
end
```

Sebagaimana yang dapat anda lihat dari senarai komponen sokongan di atas, komponen sokongan `cowboy` cuma diperlukan dalam persekitaran pembangunan(dev) dan pengujian(test).

Setelah membuat tetapan komponen sokongan langkah terakhir ialah memuatkan mereka.  Ini adalah sama dengan `bundle install`:

```bash
mix deps.get
```

Itu sahaja!  Kita telah membuat tetapan dan memuatkan komponen sokongan untuk projek kita.  Sekarang kita telah bersedia untuk memuatkan komponen sokongan lain apabila diperlukan.

## Persekitaran

Mix, seperti Bundler, menyokong pelbagai persekitaran(environment).  Secara lalai, mix boleh digunakan dalam tiga persekitaran:

+ `:dev` — persekitaran lalai.
+ `:test` — Digunakan oleh `mix test`.  Akan dilihat lebih lanjut dalam pelajaran seterusnya.
+ `:prod` — Digunakan apabila memasang aplikasi kita dalam persekitaran pengeluaran(production)

Nilai persekitaran semasa boleh dicapai menggunakan `Mix.env`.  ilai persekitaran juga boleh diubah menggunakan pembolehubah `MIX_ENV`:

```bash
MIX_ENV=prod mix compile
```


text:
package org.rpwf.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This is the Default Converter for Date objects. The format is dd.mm.yyyy.
 * Created by Fabian
 */
public class DefaultDateConverter implements Converter<Date> {

    @Override
    public Date convert(String input) throws CannotConvertException {
        try {
            SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
            return format.parse(input);
        } catch (ParseException p) {
            throw new CannotConvertException(p);
        }
    }

  @Override
  public Class<Date> convertType() {
      return Date.class;
  }
}


text:
package vn.vanlanguni.ponggame;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class JDialogSettings extends JDialog {
	String userName1;
	String userName2;
	String u1;
	String u2;
	public DialogR dialog;
	private static int WIDTH = 400, HEIGHT = 600;
	private JTextField txtUsername1;
	private JTextField txtUsername2;
	private JRadioButton opt1 = new JRadioButton("Ball1"), opt2 = new JRadioButton("Ball2"), opt3 = new JRadioButton("Ball3");
	private JLabel ball = new JLabel("Chose Ball"),   ball1 = new JLabel(""),ball2 = new JLabel(""),ball3 = new JLabel("");
	ButtonGroup btngr = new ButtonGroup();
	ImageIcon Ball1 = new ImageIcon("imgaes/Ball1.png");
	ImageIcon Ball2 = new ImageIcon("imgaes/Ball2.png");
	ImageIcon Ball3 = new ImageIcon("imgaes/Ball3.png");
	public JDialogSettings() {
		setTitle("Config infomation");
		setPreferredSize(new Dimension(WIDTH, HEIGHT));
		setLocation(380, 150);
		setLayout(null);
		pack();
	txtUsername1 = new JTextField(10);
	txtUsername2 = new JTextField(10);
	getContentPane().add(txtUsername1);
	getContentPane().add(txtUsername2);
	txtUsername1.setBounds(90, 26, 100, 20);
	txtUsername2.setBounds(90, 66, 100, 20);

	JLabel lblUser_1 = new JLabel("Player one 1");
	lblUser_1.setBounds(10, 29, 71, 14);
	getContentPane().add(lblUser_1);

	JLabel lblUser_2 = new JLabel("Player two 2");
	lblUser_2.setBounds(10, 69, 71, 14);
	getContentPane().add(lblUser_2);

	add(ball);
	ball.setBounds(10, 90, 200, 25);
	ball.setFont(new Font(Font.DIALOG, Font.BOLD, 20));
	add(opt1);
	opt1.setBounds(10, 130, 100, 25);
	add(opt2);
	opt2.setBounds(110, 130, 100, 25);
	add(opt3);
	opt3.setBounds(210, 130, 100, 25);
	btngr.add(opt1);
	btngr.add(opt2);
	btngr.add(opt3);

	JButton btnSave = new JButton("Save");
	btnSave.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			dialog = DialogR.YES;
			setVisible(false);
		}
	});
	btnSave.setBounds(44, 300, 89, 23);
	getContentPane().add(btnSave);

	JButton btnCancel = new JButton("Cancel");
	btnCancel.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			dialog = DialogR.CANCEL;
			setVisible(false);
		}
	});
	btnCancel.setBounds(154, 300, 89, 23);
	getContentPane().add(btnCancel);
	setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
	pack();

	addWindowListener(new WindowAdapter() {

		@Override
		public void windowClosing(WindowEvent arg0) {
			int result = JOptionPane.showConfirmDialog(JDialogSettings.this, "Exit?");
			if(result == JOptionPane.YES_OPTION){
				setVisible(false);
			}
		}
	});
}
	public Setting getSetings() {
		Setting st = new Setting();
		st.setUserName1(txtUsername1.getText());
		st.setUserName2(txtUsername2.getText());
		if (opt1.isSelected()) {
			st.setBallNumber(1);
		} else if (opt2.isSelected()) {
			st.setBallNumber(2);
		}else if(opt3.isSelected()){
			st.setBallNumber(3);
		}
		return st;
	}
}


text:
package test.types;

import javax.annotation.PostConstruct;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

//property = "osgi.jaxrs.resource.base=/test-addon",
public class TestAddon {

	@GET
	@Path("/{name}")
	public String sayHello(@PathParam("name") String name) {
		return "Hello " + name;
	}

	@PostConstruct
	public void init() {
		System.out.println("URIINFO: " + _uriInfo);
	}

	@Context
	UriInfo _uriInfo;

}


text:
#include "stdafx.h"
#include "GameoverScene.h"

GameoverScene::GameoverScene(E_GAME_STATE* State)
{
    SyncGameState(State);
    LoadImageResources();
    Setup();
}

GameoverScene::~GameoverScene()
{
}

void GameoverScene::Update()
{
}

void GameoverScene::Render(HDC hdc)
{
}

void GameoverScene::Setup()
{
}

void GameoverScene::LoadImageResources()
{
}

void GameoverScene::DeleteScene()
{
}


text:
package org.odk.collect.android.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.utilities.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * ListMultiWidget handles multiple selection fields using check boxes. The check boxes are aligned
 * horizontally. They are typically meant to be used in a field list, where multiple questions with
 * the same multiple choice answers can sit on top of each other and make a grid of buttons that is
 * easy to navigate quickly. Optionally, you can turn off the labels. This would be done if a label
 * widget was at the top of your field list to provide the labels. If audio or video are specified
 * in the select answers they are ignored. This class is almost identical to ListWidget, except it
 * uses checkboxes. It also did not require a custom clickListener class.
 *
 * @author Jeff Beorse (jeff@beorse.net)
 */
public class ListMultiWidget extends QuestionWidget {
    private static final String t = "ListMultiWidget";

    // Holds the entire question and answers. It is a horizontally aligned linear layout
    // needed because it is created in the super() constructor via addQuestionText() call.
    LinearLayout questionLayout;

    private boolean mCheckboxInit = true;

    private List<SelectChoice> mItems; // may take a while to compute...

    private ArrayList<CheckBox> mCheckboxes;
    private View center;

    @SuppressWarnings("unchecked")
    public ListMultiWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
        super(context, prompt);

        // SurveyCTO-added support for dynamic select content (from .csv files)
        XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(
                prompt.getAppearanceHint());
        if (xPathFuncExpr != null) {
            mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
        } else {
            mItems = prompt.getSelectChoices();
        }
        mCheckboxes = new ArrayList<CheckBox>();
        mPrompt = prompt;

        // Layout holds the horizontal list of buttons
        LinearLayout buttonLayout = new LinearLayout(context);

        List<Selection> ve = new ArrayList<Selection>();
        if (prompt.getAnswerValue() != null) {
            ve = (List<Selection>) prompt.getAnswerValue().getValue();
        }

        if (mItems != null) {
            for (int i = 0; i < mItems.size(); i++) {
                CheckBox c = new CheckBox(getContext());
                c.setTag(Integer.valueOf(i));
                c.setId(QuestionWidget.newUniqueId());
                c.setFocusable(!prompt.isReadOnly());
                c.setEnabled(!prompt.isReadOnly());
                for (int vi = 0; vi < ve.size(); vi++) {
                    // match based on value, not key
                    if (mItems.get(i).getValue().equals(ve.get(vi).getValue())) {
                        c.setChecked(true);
                        break;
                    }

                }
                mCheckboxes.add(c);

                // when clicked, check for readonly before toggling
                c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (!mCheckboxInit && mPrompt.isReadOnly()) {
                            if (buttonView.isChecked()) {
                                buttonView.setChecked(false);
                                Collect.getInstance().getActivityLogger().logInstanceAction(this,
                                        "onItemClick.deselect",
                                        mItems.get((Integer) buttonView.getTag()).getValue(),
                                        mPrompt.getIndex());
                            } else {
                                buttonView.setChecked(true);
                                Collect.getInstance().getActivityLogger().logInstanceAction(this,
                                        "onItemClick.select",
                                        mItems.get((Integer) buttonView.getTag()).getValue(),
                                        mPrompt.getIndex());
                            }
                        }
                    }
                });

                String imageURI;
                if (mItems.get(i) instanceof ExternalSelectChoice) {
                    imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
                } else {
                    imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
                            FormEntryCaption.TEXT_FORM_IMAGE);
                }

                // build image view (if an image is provided)
                ImageView mImageView = null;
                TextView mMissingImage = null;

                final int labelId = QuestionWidget.newUniqueId();

                // Now set up the image view
                String errorMsg = null;
                if (imageURI != null) {
                    try {
                        String imageFilename =
                                ReferenceManager._().DeriveReference(imageURI).getLocalURI();
                        final File imageFile = new File(imageFilename);
                        if (imageFile.exists()) {
                            Bitmap b = null;
                            try {
                                Display display =
                                        ((WindowManager) getContext().getSystemService(
                                                Context.WINDOW_SERVICE)).getDefaultDisplay();
                                int screenWidth = display.getWidth();
                                int screenHeight = display.getHeight();
                                b =
                                        FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
                                                screenWidth);
                            } catch (OutOfMemoryError e) {
                                errorMsg = "ERROR: " + e.getMessage();
                            }

                            if (b != null) {
                                mImageView = new ImageView(getContext());
                                mImageView.setPadding(2, 2, 2, 2);
                                mImageView.setAdjustViewBounds(true);
                                mImageView.setImageBitmap(b);
                                mImageView.setId(labelId);
                            } else if (errorMsg == null) {
                                // An error hasn't been logged and loading the image failed, so it's
                                // likely
                                // a bad file.
                                errorMsg = getContext().getString(R.string.file_invalid, imageFile);

                            }
                        } else if (errorMsg == null) {
                            // An error hasn't been logged. We should have an image, but the file
                            // doesn't
                            // exist.
                            errorMsg = getContext().getString(R.string.file_missing, imageFile);
                        }

                        if (errorMsg != null) {
                            // errorMsg is only set when an error has occured
                            Log.e(t, errorMsg);
                            mMissingImage = new TextView(getContext());
                            mMissingImage.setText(errorMsg);

                            mMissingImage.setPadding(2, 2, 2, 2);
                            mMissingImage.setId(labelId);
                        }
                    } catch (InvalidReferenceException e) {
                        Log.e(t, "image invalid reference exception");
                        e.printStackTrace();
                    }
                } else {
                    // There's no imageURI listed, so just ignore it.
                }

                // build text label. Don't assign the text to the built in label to he
                // button because it aligns horizontally, and we want the label on top
                TextView label = new TextView(getContext());
                label.setText(prompt.getSelectChoiceText(mItems.get(i)));
                label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
                label.setGravity(Gravity.CENTER_HORIZONTAL);
                if (!displayLabel) {
                    label.setVisibility(View.GONE);
                }

                // answer layout holds the label text/image on top and the radio button on bottom
                RelativeLayout answer = new RelativeLayout(getContext());
                RelativeLayout.LayoutParams headerParams =
                        new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT);
                headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

                RelativeLayout.LayoutParams buttonParams =
                        new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT);
                buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

                if (mImageView != null) {
                    mImageView.setScaleType(ScaleType.CENTER);
                    if (!displayLabel) {
                        mImageView.setVisibility(View.GONE);
                    }
                    answer.addView(mImageView, headerParams);
                } else if (mMissingImage != null) {
                    answer.addView(mMissingImage, headerParams);
                } else {
                    if (displayLabel) {
                        label.setId(labelId);
                        answer.addView(label, headerParams);
                    }

                }
                if (displayLabel) {
                    buttonParams.addRule(RelativeLayout.BELOW, labelId);
                }
                answer.addView(c, buttonParams);
                answer.setPadding(4, 0, 4, 0);

                // /Each button gets equal weight
                LinearLayout.LayoutParams answerParams =
                        new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                                LayoutParams.MATCH_PARENT);
                answerParams.weight = 1;

                buttonLayout.addView(answer, answerParams);
            }
        }

        // Align the buttons so that they appear horizonally and are right justified
        buttonLayout.setOrientation(LinearLayout.HORIZONTAL);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.RIGHT_OF, center.getId());
        addView(buttonLayout, params);

    }

    @Override
    public void clearAnswer() {
        for (int i = 0; i < mCheckboxes.size(); i++) {
            CheckBox c = mCheckboxes.get(i);
            if (c.isChecked()) {
                c.setChecked(false);
            }
        }
    }

    @Override
    public IAnswerData getAnswer() {
        List<Selection> vc = new ArrayList<Selection>();
        for (int i = 0; i < mCheckboxes.size(); i++) {
            CheckBox c = mCheckboxes.get(i);
            if (c.isChecked()) {
                vc.add(new Selection(mItems.get(i)));
            }
        }

        if (vc.size() == 0) {
            return null;
        } else {
            return new SelectMultiData(vc);
        }

    }

    @Override
    public void setFocus(Context context) {
        // Hide the soft keyboard if it's showing.
        InputMethodManager inputManager =
                (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
    }

    // Override QuestionWidget's add question text. Build it the same
    // but add it to the questionLayout
    protected void addQuestionText(FormEntryPrompt p) {

        // Add the text view. Textview always exists, regardless of whether there's text.
        TextView questionText = new TextView(getContext());
        questionText.setText(p.getLongText());
        questionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
        questionText.setTypeface(null, Typeface.BOLD);
        questionText.setPadding(0, 0, 0, 7);
        questionText.setId(QuestionWidget.newUniqueId()); // assign random id

        // Wrap to the size of the parent view
        questionText.setHorizontallyScrolling(false);

        if (p.getLongText() == null) {
            questionText.setVisibility(GONE);
        }

        // Put the question text on the left half of the screen
        LinearLayout.LayoutParams labelParams =
                new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        labelParams.weight = 1;
    }

    @Override
    public void setOnLongClickListener(OnLongClickListener l) {
        for (CheckBox c : mCheckboxes) {
            c.setOnLongClickListener(l);
        }
    }

    @Override
    public void cancelLongPress() {
        super.cancelLongPress();
        for (CheckBox c : mCheckboxes) {
            c.cancelLongPress();
        }
    }

    @Override
    protected void addQuestionMediaLayout(View v) {
        center = new View(getContext());
        RelativeLayout.LayoutParams centerParams = new RelativeLayout.LayoutParams(0, 0);
        centerParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        center.setId(QuestionWidget.newUniqueId());
        addView(center, centerParams);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.LEFT_OF, center.getId());
        addView(v, params);
    }
}


text:
package com.ibatis.sqlmap.engine.cache.lru;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.ibatis.sqlmap.engine.cache.CacheController;
import com.ibatis.sqlmap.engine.cache.CacheModel;

/**
 * LRU (least recently used) cache controller implementation
 */
public class LruCacheController implements CacheController {

    private int cacheSize;
    private Map cache;
    private List keyList;

    /**
     * Default constructor
     */
    public LruCacheController() {
        this.cacheSize = 100;
        this.cache = Collections.synchronizedMap(new HashMap());
        this.keyList = Collections.synchronizedList(new LinkedList());
    }

    public int getCacheSize() {
        return cacheSize;
    }

    public void setCacheSize(int cacheSize) {
        this.cacheSize = cacheSize;
    }

    /**
     * Configures the cache
     *
     * @param props Optionally can contain properties [reference-type=WEAK|SOFT|STRONG]
     */
    public void setProperties(Properties props) {
        String size = props.getProperty("cache-size");
        if (size == null) {
            size = props.getProperty("size");
        }
        if (size != null) {
            cacheSize = Integer.parseInt(size);
        }
    }

    /**
     * Add an object to the cache
     *
     * @param cacheModel The cacheModel
     * @param key        The key of the object to be cached
     * @param value      The object to be cached
     */
    public void putObject(CacheModel cacheModel, Object key, Object value) {
        cache.put(key, value);
        keyList.add(key);
        if (keyList.size() > cacheSize) {
            try {
                Object oldestKey = keyList.remove(0);
                cache.remove(oldestKey);
            } catch (IndexOutOfBoundsException e) {
                //ignore
            }
        }
    }

    /**
     * Get an object out of the cache.
     *
     * @param cacheModel The cache model
     * @param key        The key of the object to be returned
     * @return The cached object (or null)
     */
    //��ͷ�����������ʹ�õģ�������getObject�󣬵�ǰʹ�õ���key���ǻ�ŵ����
    public Object getObject(CacheModel cacheModel, Object key) {
        Object result = cache.get(key);
        keyList.remove(key);
        if (result != null) {
            keyList.add(key);
        }
        return result;
    }

    public Object removeObject(CacheModel cacheModel, Object key) {
        keyList.remove(key);
        return cache.remove(key);
    }

    /**
     * Flushes the cache.
     *
     * @param cacheModel The cache model
     */
    public void flush(CacheModel cacheModel) {
        cache.clear();
        keyList.clear();
    }

}


text:
@extends('cms-frontend::layout.master')

@section('content')

Pages Directory

        @foreach($pages as $page)

                url) !!}">{{ $page->title }}

        @endforeach

@endsection

@section('cms')
    @edit('pages')
@endsection


text:
var expect = require('chai').expect;

var Drac = require('../');

describe('not in rules', function() {
  var testFunc = Drac.define({
    params: {
      name: { notIn: ['hello', 3, false] }
    }
  }, function(name) { return 'name: ' + name; });

  it('should give correct result', function() {
    var result = testFunc(true);
    expect(result).to.equal('name: true');
  });

  it('should throw error on missing parameters', function () {
    expect(function() {
      testFunc();
    }).to.throw(Error);
  });

  it('should throw error on extra parameters', function () {
    expect(function() {
      testFunc(3, 'hello');
    }).to.throw(Error);
  });

  it('should throw error on invalid parameters', function () {
    expect(function() {
      testFunc(3);
    }).to.throw(Error);
  });
});


text:
require 'money'

module Wechselkurse
  class Currencylayer < Base
    base_uri 'http://apilayer.net/api'

    DATE_REGEX = /\d{4}-\d{2}-\d{2}/.freeze

    def initialize
      @auth = { access_key: ENV["CURRENCYLAYER_ACCESS_KEY"]}
    end

    def exchange_rates(source:, currencies:, date: Date.today)
      validate_params(source, currencies, date)
      options = {
        query: {
          source: source,
          currencies: currencies.join(','),
          date: date
        }
      }
      options[:query].merge!(@auth)
      exchange_rates = raw_exchange_rates(options)
      Wechselkurse::Broadcaster.send_message exchange_rates
      exchange_rates
    end

    def exchange_rate(source:, currencies:, value:, date: Date.today)
      exchange_rates = exchange_rates(
        source: source,
        currencies: currencies,
        date: date
      )
      exchange_rate = exchange_rates[:quotes].map do |quote|
        { quote.key.to_sym => value * quote.value}
      end
      Wechselkurse::Broadcaster.send_message exchange_rate
      exchange_rate
    end

    def highest_exchange_rate(source:, target:)
      last_exchange_rates = last_seven_days.flat_map do |date|
        exchange_rates(source: source, currencies: target.to_a, date: date).last
      end
      highest_exchange_rate = last_exchange_rates.max_by{|code, value| value}
      Wechselkurse::Broadcaster.send_message highest_exchange_rate
      highest_exchange_rate
    end

    private

    def last_seven_days
      (Date.today-7..Date.today)
    end

    def validate_params(source, currencies, date)
      validate_currencies!(currencies.push(source))
      validate_date!(date)
    end

    def validate_currencies! currencies
      unless (currencies - valid_currencies).empty?
        raise Wechselkurse::Error::UnknownCurrency
      end
    end

    def validate_date! date
      return unless date
      unless date.to_s =~ DATE_REGEX && Date.parse(date.to_s)
        raise Wechselkurse::Error::InvalidDate
      end
    end

    def valid_currencies
      @valid_currencies ||= ::Money::Currency.table.keys.map do |code|
        code.to_s.upcase
      end
    end

    def raw_exchange_rates options
      response = make_request('/historical', options)
      {quotes: response['quotes']}
    end
  end
end


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

namespace GSF.TimeSeries.Adapters
{
    /// <summary>
    /// An interface to provide a custom implementation of the routing functionality of the <see cref="RoutingTables"/>
    /// </summary>
    public interface IRouteMappingTables
    {
        /// <summary>
        /// Gets the number of routes in this routing table.
        /// </summary>
        int RouteCount { get; }

        /// <summary>
        /// Assigns the status messaging callbacks.
        /// </summary>
        /// <param name="onStatusMessage">Raise status messages on this callback</param>
        /// <param name="onProcessException">Raise exceptions on this callback</param>
        void Initialize(Action<string> onStatusMessage, Action<Exception> onProcessException);

        /// <summary>
        /// Patches the existing routing table with the supplied adapters.
        /// </summary>
        /// <param name="producerAdapters">all of the producers</param>
        /// <param name="consumerAdapters">all of the consumers</param>
        void PatchRoutingTable(RoutingTablesAdaptersList producerAdapters, RoutingTablesAdaptersList consumerAdapters);

        /// <summary>
        /// This method will directly inject measurements into the routing table and use a shared local input adapter. For
        /// contention reasons, it is not recommended this be its default use case, but it is necessary at times.
        /// </summary>
        /// <param name="sender">the sender object</param>
        /// <param name="measurements">the event arguments</param>
        void InjectMeasurements(object sender, EventArgs<ICollection<IMeasurement>> measurements);

    }
}


text:
<project
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
		http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>clinic.programming</groupId>
  <artifactId>maven-starter-pro</artifactId>
  <version>1.0</version>

  <dependencies>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.6</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/core';

@Component({
  selector: 'formly-field-ns-input',
  template: `
    <TextField class="input"
      [formlyAttributes]="field"
      [formControl]="formControl"

      [autocorrect]="to.autocorrect"
      [secure]="to.secure"
      [hint]="to.hint"
      [keyboardType]="to.keyboardType">
    </TextField>
  `,
})
export class FormlyFieldText extends FieldType {}


text:
package de.uni_jena.min.in0043.nine_mens_morris.test;

import de.uni_jena.min.in0043.nine_mens_morris.core.GameClient;
import de.uni_jena.min.in0043.nine_mens_morris.gui.Head;
import de.uni_jena.min.in0043.nine_mens_morris.net.Client;

public class ClientTest {

	//static Client client = new Client("gw.kjerkreit.org");
	static Client client = new Client("gw.kjerkreit.org");
	static GameClient display = new Head(client);

	public static void main(String[] args) {
		System.out.println("firing up Client");
		client.start();
		client.addDisplay(display);
		((Head)display).init();

	}
}


text:
package patdroid.core;

import patdroid.util.Log;

import java.util.HashMap;

/**
 * The base ClassDetail loader. Itself does nothing but throwing an exception.
 * Any loader extending it should do some work.
 */
public class ClassDetailLoader {
    private static final ClassNotFoundException x_x =
            new ClassNotFoundException("the bare ClassDetail loader does not load anything");
    public void load(ClassInfo ci) throws ClassNotFoundException,
            ExceptionInInitializerError, NoClassDefFoundError
    { throw x_x; }

    protected static ClassDetail createDetail(ClassInfo superClass, ClassInfo[] interfaces,
                int accessFlags, MethodInfo[] methods,
                HashMap<String, ClassInfo> fields,
                HashMap<String, ClassInfo> staticFields, boolean isFrameworkClass) {
        return new ClassDetail(superClass, interfaces, accessFlags, methods, fields, staticFields, isFrameworkClass);
    }

    /**
     * Set the details of the class, usually used only by class loader
     *

     * Note: this might start class loading if the class is not loaded yet
     * @param details the detailed info about the class
     */
    protected static void setDetails(ClassInfo ci, ClassDetail details) {
        Log.warnwarn(ci.details == null, "class is already loaded" + ci);
        ci.details = details;
        details.updateDerivedClasses(ci);
    }
}


text:
/**
 *
Provides functionality for Exceptions.

 *
Contains the concept of an exception with context i.e. such an exception will contain a map with keys and values.
 * This provides an easy way to pass valuable state information at exception time in useful form to a calling process.

 *
Lastly, {@link org.apache.commons.lang3.exception.ExceptionUtils} also contains Throwable manipulation
 * and examination routines.

 *
 * @since 1.0
 * @version $Id: package-info.java 1558546 2014-01-15 19:38:15Z britter $
 */
package org.apache.commons.lang3.exception;


text:
var mobile_found = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

var libsToLoad = [
    'jquery',
    'menu',
    'play',
    'levels/level2',
    'levels/level2_menu',
    'Bird',
    'phaser'
];

var game = {},
    app  = {};

if (mobile_found) {
    console.log('MOBILE');
    // add cordova when using a mobile device
    libsToLoad.push('../cordova');
} else {
    console.log('NOT MOBILE');
    libsToLoad.push('//localhost:35729/livereload.js');
}

require(libsToLoad, function(
    $
    // ,Phaser
){

    app.score = 0;
    app.dims = {
        maxWidth: 400,
        maxHeight: 490
    }

    getWindowSizes = function() {
      var windowHeight = 0, windowWidth = 0;
      if (typeof (window.innerWidth) == 'number') {
          windowHeight = window.innerHeight;
          windowWidth = window.innerWidth;

      } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
          windowHeight = document.documentElement.clientHeight;
          windowWidth = document.documentElement.clientWidth;

      } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
         windowHeight = document.body.clientHeight;
         windowWidth = document.body.clientWidth;
      }
      return [windowWidth, windowHeight];
    }

    if (mobile_found) {
        // $(window).bind('resize', function () {
        var a = getWindowSizes();
        app.width = a[0];
        app.height = a[1];
        // }).trigger('resize');
    } else {
        app.width = $(window).width() > app.dims.maxWidth ? app.dims.maxWidth : $(window).width();
        app.height = $(window).height() > app.dims.maxHeight ? app.dims.maxHeight : $(window).height();
    }

    // Initialize Phaser, and creates a 400x490px game
    game = new Phaser.Game(app.width, app.height, Phaser.AUTO, 'game_div');

    var load_state = {
        preload: function() {
            game.stage.backgroundColor = '#71c5cf';
            game.load.image('bird', 'img/bird.png');
            game.load.image('pipe', 'img/rack_tile.png');
            // game.load.audio('jump', 'assets/jump.wav');
        },
        create: function() {
            // When all assets are loaded, go to the 'menu' state
            game.state.start('menu');
        }
    };

    game.state.add('load', load_state);
    game.state.add('menu', menu_state);
    game.state.add('play', play_state);
    game.state.add('level2_menu', level2_menu);
    game.state.add('level2', level2_state);

    if (mobile_found) {
        document.addEventListener('deviceready', function() {
            game.state.start('load');
        }, false);
    } else {
        $(function() {
            game.state.start('load');
        });
    }

});


text:
using System.Collections.Generic;

namespace SignalR.Hubs
{
    public class HubRequest
    {
        public string Hub { get; set; }
        public string Method { get; set; }
        public IJsonValue[] ParameterValues { get; set; }
        public IDictionary<string, object> State { get; set; }
        public string Id { get; set; }
    }
}


text:
import * as React from 'react';

import { Api } from 'poet-js';
import { WorkNameWithLinkById } from '../../../components/atoms/Work';
import { ProfileNameWithLink } from '../../../components/atoms/Profile';
import EventType = Api.Events.EventType

export const renderEventMessage = (event: Api.Events.Resource) => {
  switch (event.type) {
    case EventType.WORK_CREATED:
      return Creative work registered by <ProfileNameWithLink profileId={event.actorId} >{event.actorDisplayName}</ProfileNameWithLink>;
    case EventType.PROFILE_CREATED:
      return <ProfileNameWithLink profileId={event.actorId} >{event.actorDisplayName}</ProfileNameWithLink> created a public profile;
    case EventType.TITLE_ASSIGNED:
      return Title for <WorkNameWithLinkById workId={event.workId} >{event.workDisplayName}</WorkNameWithLinkById> assigned to <ProfileNameWithLink profileId={event.actorId} >{event.actorDisplayName}</ProfileNameWithLink>;
    case EventType.LICENSE_OFFERED:
      return License offered for <WorkNameWithLinkById workId={event.workId} >{event.workDisplayName}</WorkNameWithLinkById> by <ProfileNameWithLink profileId={event.actorId} >{event.actorDisplayName}</ProfileNameWithLink>;
    case EventType.LICENSE_BOUGHT:
      return License bought for <WorkNameWithLinkById workId={event.workId} >{event.workDisplayName}</WorkNameWithLinkById> by <ProfileNameWithLink profileId={event.actorId} >{event.actorDisplayName}</ProfileNameWithLink>;
    case EventType.WORK_MODIFIED:
      return Work <WorkNameWithLinkById workId={event.workId} /> modified by <ProfileNameWithLink profileId={event.actorId} />;
    default:
      return null
  }
};


text:
#ifndef __LUCENE_INDEX_DOCUMENT_WRITER__
#define __LUCENE_INDEX_DOCUMENT_WRITER__

#import  <Foundation/Foundation.h>
#import  "LCDirectory.h"
#import  "LCAnalyzer.h"
#import  "LCSimilarity.h"
#import  "LCDocument.h"
#import  "LCIndexWriter.h"

@class LCFieldInfos;

@interface LCDocumentWriter: NSObject
{
	LCAnalyzer *analyzer;
	id <LCDirectory> directory;
	LCSimilarity *similarity;
	int maxFieldLength;
	int termIndexInterval;

	/*** Private ***/
	// Keys are Terms, values are Postings.
	// Used to buffer a document before it is written to the index.
	LCFieldInfos *fieldInfos;
	NSMutableDictionary *postingTable;
	float *fieldBoosts;
	long long *fieldLengths;
	long long *fieldPositions;
	long long *fieldOffsets;
}

- (id) initWithDirectory: (id <LCDirectory>) directory
				analyzer: (LCAnalyzer *) analyzer
			  similarity: (LCSimilarity *) similarity
		  maxFieldLength: (int) maxFieldLength;
- (id) initWithDirectory: (id <LCDirectory>) directory
				analyzer: (LCAnalyzer *) analyzer
			 indexWriter: (LCIndexWriter *) indexWriter;
- (void) addDocument: (NSString *) segment
			document: (LCDocument *) doc;

@end

#endif /* __LUCENE_INDEX_DOCUMENT_WRITER__ */


text:
package apfe.tc1.generated;

import java.util.List;
import java.util.LinkedList;

import apfe.runtime.*;
import apfe.tc1.*;

public class nt2 extends Acceptor implements ITokenCodes {

    public nt2() {
    }

    @Override
    protected boolean accepti() {
        Acceptor matcher = new Sequence(new Terminal(IDENT),
                new Repetition(new Sequence(new Terminal(COMMA),
                                new Terminal(IDENT)), Repetition.ERepeat.eZeroOrMore));
        Acceptor accepted = match(matcher);
        boolean match = (null != accepted);

        if (match && (null != getListeners())) {
            for (Listener cb : getListeners()) {
                cb.onAccept(accepted);
            }
        }

        return match;
    }

    @Override
    public nt2 create() {
        return new nt2();
    }

    //Begin memoize
    @Override
    protected void memoize(Marker mark, Marker endMark) {
        stMemo.add(mark, this, endMark);
    }

    @Override
    protected Memoize.Data hasMemoized(Marker mark) {
        return stMemo.memoized(mark);
    }
    /**
     * Memoize for all instances of nt2.
     */
    private static final Memoize stMemo = new Memoize();
	//End memoize

    //Begin Listener
    static //@Override
    public void addListener(final Listener listener) {
        if (null == stListeners) {
            stListeners = new LinkedList<>();
        }
        stListeners.add(listener);
    }

    @Override
    protected Iterable<Listener> getListeners() {
        return stListeners;
    }

    private static List<Listener> stListeners;
    //End Listener

}


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "CType#isdigit" do
  it "returns true if self is between 0..9" do
    a = []
    "0a1b2C3;4:5d6=7+8p9".each_byte do |b|
      a << Rubinius::CType.isdigit(b)
    end

    a.should == [ true, false, true, false, true, false, true, false, true, false, true,
        false, true, false, true, false, true, false, true]
  end
end


text:
export * from "./ability_ranks.js";
export * from "./messages.js";
export * from "./races.js";


text:
<Type Name="MessageEventArgs" FullName="MailKit.MessageEventArgs">
  <TypeSignature Language="C#" Value="public class MessageEventArgs : EventArgs" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit MessageEventArgs extends System.EventArgs" />
  <AssemblyInfo>
    <AssemblyName>MailKit</AssemblyName>
    <AssemblyVersion>1.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.EventArgs</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    <summary>
            Event args used when the state of a message changes.
            </summary>
    <remarks>
            Event args used when the state of a message changes.
            </remarks>
  </Docs>
  <Members>
    <Member MemberName="Index">
      <MemberSignature Language="C#" Value="public int Index { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance int32 Index" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Int32</ReturnType>
      </ReturnValue>
      <Docs>
        <summary>
            Gets the index of the message that changed.
            </summary>
        <value>The index of the message.</value>
        <remarks>
            Gets the index of the message that changed.
            </remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
<?php

namespace Zwig\NodeHandler;

use Twig_Node;
use Zwig\Compiler;
use Zwig\Exception\NotImplementedException;
use Zwig\Exception\UnknownStructureException;
use Zwig\Sequence\Segment;

/**
 * Compiles a node that checks if two conditions are both true.
 * @see http://twig.sensiolabs.org/doc/templates.html#math
 */
class ExpressionBinaryAndHandler extends AbstractExpressionBinaryHandler
{
    const TWIG_NODE_CLASS_NAME = 'Twig_Node_Expression_Binary_And';

    /**
     * @param Compiler $compiler
     * @param Twig_Node $node
     * @return Segment
     * @throws NotImplementedException
     * @throws UnknownStructureException
     */
    public function compile(Compiler $compiler, Twig_Node $node)
    {
        return $this->compileBinary($compiler, $node, '&&');
    }
}


text:
<?php

namespace ZendServiceTest\SlideShare;

use Zend\Http\Client as HttpClient;
use ZendService\SlideShare;
use ZendService\SlideShare\SlideShare as SlideShareService;
use Zend\Cache\StorageFactory as CacheFactory;
use Zend\Cache\Storage\Adapter\AdapterInterface as CacheAdapter;

/**
 * @category   Zend
 * @package    Zend_Service_SlideShare
 * @subpackage UnitTests
 * @group      Zend_Service
 * @group      Zend_Service_SlideShare
 */
class SlideShareTest extends \PHPUnit_Framework_TestCase
{
    /**
     * The Slide share object instance
     *
     * @var \ZendService\SlideShare
     */
    protected static $_ss;

    /**
     * Enter description here...
     *
     * @return \ZendService\SlideShare\SlideShare
     */
    protected function _getSSObject()
    {
        $ss = new SlideShareService(TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY,
                                    TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET,
                                    TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME,
                                    TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD,
                                    new HttpClient(null, array(
                                        'maxredirects'  => 2,
                                        'timeout'       => 5,
                                        'sslverifypeer' => false
                                    )));

        $cache = CacheFactory::adapterFactory('memory', array('memory_limit' => 0));
        $ss->setCacheObject($cache);

        return $ss;
    }

    public function setUp()
    {
        if(!defined("TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY") ||
           !defined("TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET") ||
           !defined("TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME") ||
           !defined("TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD") ||
           (TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY == "") ||
           (TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET == "") ||
           (TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME == "") ||
           (TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD == "")) {

               $this->markTestSkipped("You must configure an account for slideshare to run these tests");
        }
    }

    public function tearDown()
    {
    }

    public function testGetSlideShow()
    {
        if(!defined("TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID") ||
           (TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID <= 0)) {
               $this->markTestSkipped("You must provide a Slideshow ID to retrieve to perform this test");
        }

        $ss = $this->_getSSObject();
        try {
            $result = $ss->getSlideShow(TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID);
        } catch(Exception $e) {
            $this->fail("Exception Caught retrieving Slideshow");
        }

        $this->assertTrue($result instanceof SlideShare\SlideShow);

    }

    public function testGetSlideShowByTag()
    {
        $ss = $this->_getSSObject();

        try {
            $results = $ss->getSlideShowsByTag('zend', 0, 1);
        } catch(Exception $e) {
            $this->fail("Exception Caught retrieving Slideshow List (tag)");
        }

        $this->assertTrue(is_array($results));
        $this->assertTrue(count($results) == 1);
        $this->assertTrue($results[0] instanceof SlideShare\SlideShow);

    }

    public function testGetSlideShowByTags()
    {
        $ss = $this->_getSSObject();

        try {
            $results = $ss->getSlideShowsByTag(array('zend', 'php'), 0, 1);
        } catch(Exception $e) {
            $this->fail("Exception Caught retrieving Slideshow List (tag)");
        }

        $this->assertTrue(is_array($results));

        if(!empty($results)) {
            $this->assertTrue(count($results) == 1);
            $this->assertTrue($results[0] instanceof SlideShare\SlideShow);
        }
    }

    public function testGetSlideShowByUsername()
    {
        $ss = $this->_getSSObject();

        try {
            $results = $ss->getSlideShowsByUsername(TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME, 0, 1);
        } catch(Exception $e) {
            $this->fail("Exception Caught retrieving Slideshow List (tag)");
        }

        $this->assertTrue(is_array($results));
        $this->assertTrue(count($results) == 1);
        $this->assertTrue($results[0] instanceof SlideShare\SlideShow);

    }

    public function testUploadSlideShowInvalidFileException()
    {
        $this->setExpectedException('\ZendService\SlideShare\Exception\InvalidArgumentException',
                    'Specified Slideshow for upload not found or unreadable');

        $ss = $this->_getSSObject();
        $show = new SlideShare\SlideShow();
        $show->setFilename('invalid_filename');
        $show->setDescription('Unit Test');
        $show->setTitle('title');
        $show->setTags(array('unittest'));
        $show->setID(0);

        $result = $ss->uploadSlideShow($show, false);
    }

    public function testUploadSlideShow()
    {
        $ss = $this->_getSSObject();

        $title = "Unit Test for ZF SlideShare Component";
        $ppt_file = __DIR__."/_files/demo.ppt";

        $show = new SlideShare\SlideShow();
        $show->setFilename($ppt_file);
        $show->setDescription("Unit Test");
        $show->setTitle($title);
        $show->setTags(array('unittest'));
        $show->setID(0);

        try {
            $result = $ss->uploadSlideShow($show, false);
        } catch(Exception $e) {

            if($e->getCode() == SlideShareService::SERVICE_ERROR_NOT_SOURCEOBJ) {
                // We ignore this exception, the web service sometimes throws this
                // error code because it seems to be buggy. Unfortunately it seems
                // to be sparatic so we can't code around it and have to call this
                // test a success
                return;
            } else {
                $this->fail("Exception Caught uploading slideshow");
            }
        }

        $this->assertTrue($result instanceof SlideShare\SlideShow);
        $this->assertTrue($result->getId() > 0);
        $this->assertTrue($result->getTitle() === $title);

    }

    public function testSlideShowObj()
    {
        $ss = new SlideShare\SlideShow();

        $ss->setDescription("Foo");
        $ss->setEmbedCode("Bar");
        $ss->setFilename("Baz");
        $ss->setId(123);
        $ss->setLocation("Somewhere");
        $ss->setNumViews(4432);
        $ss->setPermaLink("nowhere");
        $ss->setStatus(124);
        $ss->setStatusDescription("Boo");
        $ss->setTags(array('bar', 'baz'));
        $ss->addTag('fon');
        $ss->setThumbnailUrl('asdf');
        $ss->setTitle('title');

        $this->assertEquals($ss->getDescription(), "Foo");
        $this->assertEquals($ss->getEmbedCode(), "Bar");
        $this->assertEquals($ss->getFilename(), "Baz");
        $this->assertEquals($ss->getId(), 123);
        $this->assertEquals($ss->getLocation(), "Somewhere");
        $this->assertEquals($ss->getNumViews(), 4432);
        $this->assertEquals($ss->getPermaLink(), "nowhere");
        $this->assertEquals($ss->getStatus(), 124);
        $this->assertEquals($ss->getStatusDescription(), "Boo");
        $this->assertEquals($ss->getTags(), array('bar', 'baz', 'fon'));
        $this->assertEquals($ss->getThumbnailUrl(), "asdf");
        $this->assertEquals($ss->getTitle(), "title");

    }

    /**
     * @group   ZF-3247
     */
    public function testSlideShareObjectHandlesUnicodeCharactersWell()
    {
        $slideShow = new SlideShare\SlideShow();

        $slideShow->setTitle('Unicode test: ஸ்றீனிவாஸ ராமானுஜன் ஐயங்கார்');

        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('Extension "mbstring" not loaded');
        }
        $this->assertEquals('UTF-8', mb_detect_encoding($slideShow->getTitle()));
    }
}


text:
package org.mousephenotype.dcc.crawler;

import java.io.FileOutputStream;
import org.apache.commons.io.output.CountingOutputStream;
import org.mousephenotype.dcc.crawler.entities.ZipDownload;

/**
 * The download tracker regularly updates the number of bytes that have
 * been downloaded so far. This may be used by the tracker web services to
 * check the latest file download status.
 *
 * @author Gagarine Yaikhom <g.yaikhom@har.mrc.ac.uk>
 */
public class DownloadTracker extends CountingOutputStream {

    private static final long MEGABYTES_TO_BYTES = 1048576L;
    private long sizeInBytes; // total size of the file in bytes
    private long doneInMegabytes; // already downloaded size in megabytes
    private ZipDownload zipDownload;
    private static final double PERCENTAGE = 100.0;

    DownloadTracker(ZipDownload zipDownload, FileOutputStream fos, long sizeInBytes) {
        super(fos);
        this.sizeInBytes = sizeInBytes;
        this.doneInMegabytes = 0L;
        this.zipDownload = zipDownload;
    }

    @Override
    protected void beforeWrite(int n) {
        super.beforeWrite(n);

        // only update download progress into the database for every megabyte,
        // or when the download is complete
        long byteCount = getByteCount();
        if (byteCount == sizeInBytes
                || (byteCount / MEGABYTES_TO_BYTES) > doneInMegabytes) {
            ++doneInMegabytes;
            DatabaseAccessor da = DatabaseAccessor.getInstance();
            da.setDownloadProgress(zipDownload, getByteCount());
        }
    }

    public long getFileSize() {
        return sizeInBytes;
    }

    public float getDownloadPercentage() {
        return (float) ((getByteCount() * PERCENTAGE) / sizeInBytes);
    }
}


text:
'use strict';

angular.module('core').controller('HomeController', ['$scope', 'Authentication', 'Cars',
  function ($scope, Authentication, Cars) {
    // This provides Authentication context.
    $scope.authentication = Authentication;

    $scope.find = function () {
      $scope.cars = Cars.query();

    };
  }

]);


text:
/**
 * created by Maxim Orlov on 18 Nov 2014
 */
package string1;

public class NTwice {
	public String nTwice(String str, int n) {
		return str.substring(0, n) + str.substring(str.length() - n);
	}
}


text:
package armedgeorderpartner_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/edgeorderpartner/armedgeorderpartner"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/edgeorderpartner/resource-manager/Microsoft.EdgeOrderPartner/preview/2020-12-01-preview/examples/ListOperationsPartner.json
func ExampleAPISClient_NewListOperationsPartnerPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armedgeorderpartner.NewAPISClient("<subscription-id>", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListOperationsPartnerPager(nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/edgeorderpartner/resource-manager/Microsoft.EdgeOrderPartner/preview/2020-12-01-preview/examples/ManageInventoryMetadata.json
func ExampleAPISClient_BeginManageInventoryMetadata() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armedgeorderpartner.NewAPISClient("b783ea86-c85c-4175-b76d-3992656af50d", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginManageInventoryMetadata(ctx,
		"AzureStackEdge",
		"westus",
		"SerialNumber1",
		armedgeorderpartner.ManageInventoryMetadataRequest{
			ConfigurationOnDevice: &armedgeorderpartner.ConfigurationOnDevice{
				ConfigurationIdentifier: to.Ptr("EdgeP_High"),
			},
			InventoryMetadata: to.Ptr("InventoryMetadata"),
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	_, err = poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/edgeorderpartner/resource-manager/Microsoft.EdgeOrderPartner/preview/2020-12-01-preview/examples/ManageLink.json
func ExampleAPISClient_ManageLink() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armedgeorderpartner.NewAPISClient("b783ea86-c85c-4175-b76d-3992656af50d", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	_, err = client.ManageLink(ctx,
		"AzureStackEdge",
		"westus",
		"SerialNumber1",
		armedgeorderpartner.ManageLinkRequest{
			ManagementResourceArmID: to.Ptr("/subscriptions/c783ea86-c85c-4175-b76d-3992656af50d/resourceGroups/EdgeTestRG/providers/Microsoft.DataBoxEdge/DataBoxEdgeDevices/TestEdgeDeviceName1"),
			Operation:               to.Ptr(armedgeorderpartner.ManageLinkOperationLink),
			TenantID:                to.Ptr("a783ea86-c85c-4175-b76d-3992656af50d"),
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/edgeorderpartner/resource-manager/Microsoft.EdgeOrderPartner/preview/2020-12-01-preview/examples/SearchInventories.json
func ExampleAPISClient_NewSearchInventoriesPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armedgeorderpartner.NewAPISClient("b783ea86-c85c-4175-b76d-3992656af50d", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewSearchInventoriesPager(armedgeorderpartner.SearchInventoriesRequest{
		FamilyIdentifier: to.Ptr("AzureStackEdge"),
		SerialNumber:     to.Ptr("SerialNumber1"),
	},
		nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}


text:
package org.lwjgl.fmod;

import javax.annotation.*;

import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;

/**
 *
Type

 *
 *

 * void * (*{@link #invoke}) (
 *     unsigned int size,
 *     FMOD_MEMORY_TYPE type,
 *     char const *sourcestr
 * )

 */
public abstract class FMOD_DSP_ALLOC_FUNC extends Callback implements FMOD_DSP_ALLOC_FUNCI {

    /**
     * Creates a {@code FMOD_DSP_ALLOC_FUNC} instance from the specified function pointer.
     *
     * @return the new {@code FMOD_DSP_ALLOC_FUNC}
     */
    public static FMOD_DSP_ALLOC_FUNC create(long functionPointer) {
        FMOD_DSP_ALLOC_FUNCI instance = Callback.get(functionPointer);
        return instance instanceof FMOD_DSP_ALLOC_FUNC
            ? (FMOD_DSP_ALLOC_FUNC)instance
            : new Container(functionPointer, instance);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code functionPointer} is {@code NULL}. */
    @Nullable
    public static FMOD_DSP_ALLOC_FUNC createSafe(long functionPointer) {
        return functionPointer == NULL ? null : create(functionPointer);
    }

    /** Creates a {@code FMOD_DSP_ALLOC_FUNC} instance that delegates to the specified {@code FMOD_DSP_ALLOC_FUNCI} instance. */
    public static FMOD_DSP_ALLOC_FUNC create(FMOD_DSP_ALLOC_FUNCI instance) {
        return instance instanceof FMOD_DSP_ALLOC_FUNC
            ? (FMOD_DSP_ALLOC_FUNC)instance
            : new Container(instance.address(), instance);
    }

    protected FMOD_DSP_ALLOC_FUNC() {
        super(CIF);
    }

    FMOD_DSP_ALLOC_FUNC(long functionPointer) {
        super(functionPointer);
    }

    private static final class Container extends FMOD_DSP_ALLOC_FUNC {

        private final FMOD_DSP_ALLOC_FUNCI delegate;

        Container(long functionPointer, FMOD_DSP_ALLOC_FUNCI delegate) {
            super(functionPointer);
            this.delegate = delegate;
        }

        @Override
        public long invoke(int size, int type, long sourcestr) {
            return delegate.invoke(size, type, sourcestr);
        }

    }

}


text:
package org.locationtech.geowave.core.store.data;

import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;

/**
 * This is a basic mapping of field ID to native field type. "Native" in this sense can be to either
 * the data adapter or the common index, depending on whether it is in the common index or is an
 * extended field.
 *
 * @param <T> The most specific generalization for the type for all of the values in this dataset.
 */
public class SingleFieldPersistentDataset<T> implements PersistentDataset<T> {
  private String fieldName;
  private T value;

  public SingleFieldPersistentDataset() {}

  public SingleFieldPersistentDataset(final String fieldName, final T value) {
    this();
    this.fieldName = fieldName;
    this.value = value;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.locationtech.geowave.core.store.data.PersistentDataSet#addValue(java.lang.String, T)
   */
  @Override
  public void addValue(final String fieldName, final T value) {
    this.fieldName = fieldName;
    this.value = value;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.locationtech.geowave.core.store.data.PersistentDataSet#addValues(java.util.Map)
   */
  @Override
  public void addValues(final Map<String, T> values) {
    if (!values.isEmpty()) {
      final Entry<String, T> e = values.entrySet().iterator().next();
      fieldName = e.getKey();
      value = e.getValue();
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see org.locationtech.geowave.core.store.data.PersistentDataSet#getValue(java.lang.String)
   */
  @Override
  public T getValue(final String fieldName) {
    if ((this.fieldName == null) && (fieldName == null)) {
      return value;
    }
    if ((this.fieldName != null) && this.fieldName.equals(fieldName)) {
      return value;
    }
    return null;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.locationtech.geowave.core.store.data.PersistentDataSet#getValues()
   */
  @Override
  public Map<String, T> getValues() {
    return Collections.singletonMap(fieldName, value);
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static unsafe partial class mincore
    {
        [DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
        internal extern static unsafe int LCMapStringEx(
                    string lpLocaleName,
                    uint dwMapFlags,
                    char* lpSrcStr,
                    int cchSrc,
                    void* lpDestStr,
                    int cchDest,
                    void* lpVersionInformation,
                    void* lpReserved,
                    IntPtr sortHandle);

        [DllImport("api-ms-win-core-localization-l1-2-0.dll", EntryPoint = "FindNLSStringEx")]
        internal extern static unsafe int FindNLSStringEx(
                    char* lpLocaleName,
                    uint dwFindNLSStringFlags,
                    char* lpStringSource,
                    int cchSource,
                    char* lpStringValue,
                    int cchValue,
                    int* pcchFound,
                    void* lpVersionInformation,
                    void* lpReserved,
                    IntPtr sortHandle);

        [DllImport("api-ms-win-core-string-l1-1-0.dll", EntryPoint = "CompareStringEx")]
        internal extern static unsafe int CompareStringEx(
                    char* lpLocaleName,
                    uint dwCmpFlags,
                    char* lpString1,
                    int cchCount1,
                    char* lpString2,
                    int cchCount2,
                    void* lpVersionInformation,
                    void* lpReserved,
                    IntPtr lParam);

        [DllImport("api-ms-win-core-string-l1-1-0.dll", EntryPoint = "CompareStringOrdinal")]
        internal extern static unsafe int CompareStringOrdinal(
                    char* lpString1,
                    int cchCount1,
                    char* lpString2,
                    int cchCount2,
                    bool bIgnoreCase);

        [DllImport("api-ms-win-core-libraryloader-l1-1-0.dll", EntryPoint = "FindStringOrdinal")]
        internal extern static unsafe int FindStringOrdinal(
                    uint dwFindStringOrdinalFlags,
                    char* lpStringSource,
                    int cchSource,
                    char* lpStringValue,
                    int cchValue,
                    int bIgnoreCase);

        [DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
        internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, IntPtr lpLCData, int cchData);

        [DllImport("api-ms-win-core-localization-l1-2-1.dll")]
        internal extern static bool EnumSystemLocalesEx(IntPtr lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr lpReserved);

        [DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
        internal extern static int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName);

        // Wrappers around the GetLocaleInfoEx APIs which handle marshalling the returned
        // data as either and Int or String.
        internal static unsafe String GetLocaleInfoEx(String localeName, uint field)
        {
            // REVIEW: Determine the maximum size for the buffer
            const int BUFFER_SIZE = 530;

            char* pBuffer = stackalloc char[BUFFER_SIZE];
            int resultCode = Interop.mincore.GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE);
            if (resultCode > 0)
            {
                return new String(pBuffer);
            }

            return "";
        }

        internal static unsafe int GetLocaleInfoExInt(String localeName, uint field)
        {
            const uint LOCALE_RETURN_NUMBER = 0x20000000;
            const int BUFFER_SIZE = 2; // sizeof(int) / sizeof(char)

            field |= LOCALE_RETURN_NUMBER;

            char* pBuffer = stackalloc char[BUFFER_SIZE];
            Interop.mincore.GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE);

            return *(int*)pBuffer;
        }

        internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, char* lpLCData, int cchData)
        {
            return GetLocaleInfoEx(lpLocaleName, lcType, (IntPtr)lpLCData, cchData);
        }

        [DllImport("api-ms-win-core-localization-l2-1-0.dll", CharSet = CharSet.Unicode)]
        internal extern static int EnumTimeFormatsEx(IntPtr lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);

        [DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
        internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue);

        [DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
        internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue);

        [DllImport("api-ms-win-core-localization-l2-1-0.dll", CharSet = CharSet.Unicode)]
        internal extern static int EnumCalendarInfoExEx(IntPtr pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
    }
}


text:
	{% for item in site.data.[include.src] %}
	    {% include post.html postcount=forloop.index placeholder="Leave a comment…" %}
	{% endfor %}


text:
module PCPEasy
  class PMAPI
    class PmUnits

      # Decodes a 32bit integer into the correct fields of pmUnits.
      # This implementation assumes little-endian encoding

      def initialize(pm_units)
        @pm_units = pm_units
      end

      def dim_space
        signed_4_bit(@pm_units >> 28)
      end

      def dim_time
        signed_4_bit(@pm_units >> 24)
      end

      def dim_count
        signed_4_bit(@pm_units >> 20)
      end

      def scale_space
        unsigned_4_bit(@pm_units >> 16)
      end

      def scale_time
        unsigned_4_bit(@pm_units >> 12)
      end

      def scale_count
        signed_4_bit(@pm_units >> 8)
      end

      def inspect
        "<#{self.class.to_s}:#{object_id} @pm_units=#{@pm_units} {#{dim_space},#{dim_time},#{dim_count},#{scale_space},#{scale_time},#{scale_count}}>"
      end

      def ==(other)
        self.class == other.class && \
        dim_space == other.dim_space && \
        dim_time == other.dim_time && \
        dim_count == other.dim_count && \
        scale_space == other.scale_space && \
        scale_time == other.scale_time && \
        scale_count == other.scale_count
      end

      private

      def signed_4_bit(lowest_4_bits)
        lowest_4_bits & 0x8 == 0 ? lowest_4_bits & 0xf : -((~lowest_4_bits & 0xf) + 1)
      end

      def unsigned_4_bit(lowest_4_bits)
        lowest_4_bits & 0xf
      end

    end
  end
end


text:
:orphan:

charliecloud man page
+++++++++++++++++++++

.. include:: ../README.rst
.. include:: ./bugs.rst

See also
--------

ch-checkns(1),
ch-convert(1),
ch-fromhost(1),
ch-image(1),
ch-run(1),
ch-run-oci(1),
ch-ssh(1),
ch-test(1),

Full documentation at: https://hpc.github.io/charliecloud

Note
----

These man pages are for Charliecloud version |release| (Git commit |version|).


text:
package java.nio;

/**
 * CharArrayBuffer implements char[]-based CharBuffers.
 */
final class CharArrayBuffer extends CharBuffer {

  private final char[] backingArray;

  private final int arrayOffset;

  private final boolean isReadOnly;

  CharArrayBuffer(char[] array) {
    this(array.length, array, 0, false);
  }

  private CharArrayBuffer(int capacity, char[] backingArray, int arrayOffset, boolean isReadOnly) {
    super(capacity, 0);
    this.backingArray = backingArray;
    this.arrayOffset = arrayOffset;
    this.isReadOnly = isReadOnly;
  }

  private static CharArrayBuffer copy(CharArrayBuffer other, int markOfOther, boolean isReadOnly) {
    CharArrayBuffer buf = new CharArrayBuffer(other.capacity(), other.backingArray, other.arrayOffset, isReadOnly);
    buf.limit = other.limit;
    buf.position = other.position();
    buf.mark = markOfOther;
    return buf;
  }

  @Override public CharBuffer asReadOnlyBuffer() {
    return copy(this, mark, true);
  }

  @Override public CharBuffer compact() {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    System.arraycopy(backingArray, position + arrayOffset, backingArray, arrayOffset, remaining());
    position = limit - position;
    limit = capacity;
    mark = UNSET_MARK;
    return this;
  }

  @Override public CharBuffer duplicate() {
    return copy(this, mark, isReadOnly);
  }

  @Override public CharBuffer slice() {
    return new CharArrayBuffer(remaining(), backingArray, arrayOffset + position, isReadOnly);
  }

  @Override public boolean isReadOnly() {
    return isReadOnly;
  }

  @Override char[] protectedArray() {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    return backingArray;
  }

  @Override int protectedArrayOffset() {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    return arrayOffset;
  }

  @Override boolean protectedHasArray() {
    if (isReadOnly) {
      return false;
    }
    return true;
  }

  @Override public final char get() {
    if (position == limit) {
      throw new BufferUnderflowException();
    }
    return backingArray[arrayOffset + position++];
  }

  @Override public final char get(int index) {
    checkIndex(index);
    return backingArray[arrayOffset + index];
  }

  @Override public final CharBuffer get(char[] dst, int srcOffset, int charCount) {
    if (charCount > remaining()) {
      throw new BufferUnderflowException();
    }
    System.arraycopy(backingArray, arrayOffset + position, dst, srcOffset, charCount);
    position += charCount;
    return this;
  }

  @Override public final boolean isDirect() {
    return false;
  }

  @Override public final ByteOrder order() {
    return ByteOrder.nativeOrder();
  }

  @Override public final CharBuffer subSequence(int start, int end) {
    checkStartEndRemaining(start, end);
    CharBuffer result = duplicate();
    result.limit(position + end);
    result.position(position + start);
    return result;
  }

  @Override public CharBuffer put(char c) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    if (position == limit) {
      throw new BufferOverflowException();
    }
    backingArray[arrayOffset + position++] = c;
    return this;
  }

  @Override public CharBuffer put(int index, char c) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkIndex(index);
    backingArray[arrayOffset + index] = c;
    return this;
  }

  @Override public CharBuffer put(char[] src, int srcOffset, int charCount) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    if (charCount > remaining()) {
      throw new BufferOverflowException();
    }
    System.arraycopy(src, srcOffset, backingArray, arrayOffset + position, charCount);
    position += charCount;
    return this;
  }

  @Override public final String toString() {
    return String.copyValueOf(backingArray, arrayOffset + position, remaining());
  }
}


text:
import time
import logging

log=logging.getLogger("RMDocker.Parameter")

class Parameter:

    retried = 10

    def __init__(self,name,path,configure):
        self.name=name
        self.path=path
        self.changed = False
        self.value   = ""
        self.configure=configure
        self.subParameter=[]
        if self.configure.get(self.name) is None:
            return
        if type(self.configure.get(self.name)) is list:
            self.subParameter.extend(self.configure.get(self.name))
        else:
            self.subParameter.append(self.configure.get(self.name))

    def read(self):
        try:
            file=open(self.path)
            self.value=""
            for line in file.readlines():
                if len(line.split()) == 1:
                    self.value=line.strip()
                    break
                elif line.split()[0].strip() in self.subParameter:
                    self.value=self.value+line.split()[0].strip()+":"+line.split()[1].strip()+" "
                else:
                    continue
        except Exception as error:
            log.error("read error %s",error)

    def update(self,value):
        self.changed=True
        self.value=value

    def sync(self):
        isSuccess = False
        if self.changed is False:
            return True
        count = self.retried
        file=None
        log.info("key %s",self.path)
        log.info("value %s",self.value)
        while count > 0:
            try:
                file=open(self.path,"w")
                file.write(str(self.value))
                file.close()
            except Exception as error:
                count = count - 1
                log.error("write value to file with error %s count %d",error,10-count)
                ##time.sleep(1)
                continue
            isSuccess = True
            break
        if isSuccess:
            self.changed = False
        else:
            log.error("write value error")
        return isSuccess

    def get(self):
        return self.value


text:
package org.medipi.concentrator.services;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import ma.glasnost.orika.MapperFacade;
import org.medipi.concentrator.dao.AllHardwareDownloadableDAOImpl;
import org.medipi.concentrator.dao.AllHardwareDownloadedDAOImpl;
import org.medipi.concentrator.dao.HardwareDAOImpl;
import org.medipi.concentrator.dao.HardwareDownloadableDAOImpl;
import org.medipi.concentrator.entities.AllHardwareDownloadable;
import org.medipi.concentrator.entities.AllHardwareDownloaded;
import org.medipi.concentrator.entities.HardwareDownloadable;
import org.medipi.concentrator.exception.InternalServerError500Exception;
import org.medipi.concentrator.exception.NotFound404Exception;
import org.medipi.concentrator.logging.MediPiLogger;
import org.medipi.concentrator.model.DownloadableDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service class to expose interfaces for the HATEOAS links sent by the
 * DownloadableListService responses.
 *
 *
 * The methods allow downloading of the files defined in the
 * DownloadableListService response and the acknowledgement of their receipt by
 * the MediPi Patient Device.
 *
 * The "all hardware" updates are global updates intended for all the MediPi
 * Patient devices connected to the concentrator
 *
 * @author rick@robinsonhq.com
 */
@Service
public class HardwareDownloadableService {

    @Autowired
    private MediPiLogger logger;

    @Autowired
    private HardwareDownloadableDAOImpl hardwareDownloadableDAOImpl;

    @Autowired
    private AllHardwareDownloadableDAOImpl allHardwareDownloadableDAOImpl;

    @Autowired
    private AllHardwareDownloadedDAOImpl allHardwareDownloadedDAOImpl;

    @Autowired
    private HardwareDAOImpl hardwareDAOImpl;

    @Autowired
    private MapperFacade mapperFacade;

    /**
     * Method to enable download of hardware update file from Concentrator
     *
     * @param downloadable_uuid of the download file item
     * @return File System Resource Response
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseEntity<FileSystemResource> getDownload(String downloadable_uuid) {
        String fileName = null;
        try {
            HardwareDownloadable hd = hardwareDownloadableDAOImpl.getHardwareDownload(downloadable_uuid);
            fileName = hd.getScriptLocation();
        } catch (EmptyResultDataAccessException e) {
            throw new NotFound404Exception("Cannot find the requested hardware downloadable record UUID: " + downloadable_uuid);
        } catch (Exception e) {
            throw new InternalServerError500Exception("Internal Server Error");
        }
        try {

            ResponseEntity<FileSystemResource> response = retreiveDownloadableBinary(fileName, downloadable_uuid);
            return response;
        } catch (Exception e) {
            throw new NotFound404Exception("Cannot find the resource quested download");
        }
    }

    /**
     * Method to enable download of "all hardware" global update files from
     * Concentrator
     *
     * @param downloadable_uuid of the download file item
     * @param hardwareName
     * @return File System Resource Response
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseEntity<FileSystemResource> getAllDownload(String downloadable_uuid, String hardwareName) {
        String fileName = null;
        try {
            AllHardwareDownloadable ahd = allHardwareDownloadableDAOImpl.getHardwareDownload(downloadable_uuid);
            fileName = ahd.getScriptLocation();
        } catch (EmptyResultDataAccessException e) {
            throw new NotFound404Exception("Cannot find the requested all hardware downloadable record UUID: "+downloadable_uuid);
        } catch (Exception e) {
            throw new InternalServerError500Exception("Internal Server Error " + e.getLocalizedMessage());
        }
        try {

            ResponseEntity<FileSystemResource> response = retreiveDownloadableBinary(fileName, downloadable_uuid);
            return response;
        } catch (IOException | NotFound404Exception e) {
            throw new NotFound404Exception("Cannot find the requested download " + e.getLocalizedMessage());
        }
    }

    private ResponseEntity<FileSystemResource> retreiveDownloadableBinary(String fileName, String downloadable_uuid) throws IOException, NotFound404Exception {
        if (fileName == null || fileName.isEmpty()) {
            throw new NotFound404Exception("Cannot find the downloadable resource which has been requested");
        }
        File f = new File(fileName);
        FileSystemResource fsr = new FileSystemResource(fileName);
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        header.set("Content-Disposition",
                "attachment; filename=" + fileName.replace(" ", "_"));
        header.setContentLength(fsr.contentLength());
        logger.log(HardwareDownloadableService.class.getName(), new Date().toString() + " Hardware Downloadable item: " + downloadable_uuid + " downloaded");
        ResponseEntity<FileSystemResource> response = new ResponseEntity<>(fsr, header, HttpStatus.OK);
        return response;
    }

    /**
     * Method to enable acknowledgement of the hardware update files from
     * Concentrator
     *
     * @param downloadable_uuid of the download file item
     * @return updated DownloadableDO Response
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseEntity<DownloadableDO> acknowledgeDownload(String downloadable_uuid) {
        HardwareDownloadable hd = null;
        try {
            //retreive the hardwareDownloadable element to update
            hd = hardwareDownloadableDAOImpl.getHardwareDownload(downloadable_uuid);
        } catch (EmptyResultDataAccessException e) {
            throw new NotFound404Exception("Cannot find the requested downloadable record");
        } catch (Exception e) {
            throw new InternalServerError500Exception("Internal Server Error "+ e.getLocalizedMessage());
        }
        if (hd != null) {
            try {
                if (hd.getDownloadedDate() != null) {
                    throw new InternalServerError500Exception("Internal Server Error");
                }
                hd.setDownloadedDate(new Date());
                hardwareDownloadableDAOImpl.update(hd);
                DownloadableDO d = this.mapperFacade.map(hd, DownloadableDO.class);

                logger.log(HardwareDownloadableService.class.getName(), new Date().toString() + " Patient Downloadable item: " + downloadable_uuid + " acknowledged");
                return new ResponseEntity<>(d, HttpStatus.OK);
            } catch (Exception e) {
                throw new InternalServerError500Exception("Internal Server Error");
            }
        } else {
            throw new InternalServerError500Exception("Internal Server Error");
        }
    }

    /**
     * Method to enable acknowledgement of the all hardware global update files
     * from Concentrator
     *
     * @param downloadable_uuid of the download file item
     * @param hardwareName
     * @return updated DownloadableDO Response
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseEntity<DownloadableDO> acknowledgeAllDownload(String downloadable_uuid, String hardwareName) {
        try {
            // check to see that the download hasnt already beend acked
            AllHardwareDownloaded ahdd = allHardwareDownloadedDAOImpl.hasBeenDownloaded(downloadable_uuid, hardwareName);
            if (ahdd != null) {
                // The download has an entry already so must have been acked previously
                throw new InternalServerError500Exception("Internal Server Error");
            }
        } catch (EmptyResultDataAccessException e) {
            // Expected outcome
        } catch (Exception e) {
            throw new InternalServerError500Exception("Internal Server Error"+ e.getLocalizedMessage());
        }
        try {
            AllHardwareDownloaded ahd = new AllHardwareDownloaded();
            AllHardwareDownloadable ahde = allHardwareDownloadableDAOImpl.findByPrimaryKey(downloadable_uuid);
            ahd.setDownloadableUuid(ahde);
            ahd.setHardwareName(hardwareDAOImpl.findByPrimaryKey(hardwareName));
            ahd.setDownloadedDate(new Date());
            allHardwareDownloadedDAOImpl.save(ahd);
            DownloadableDO d = this.mapperFacade.map(ahde, DownloadableDO.class);
            d.setDownloadedDate(ahd.getDownloadedDate());
            logger.log(HardwareDownloadableService.class.getName(), new Date().toString() + " Patient Downloadable item: " + downloadable_uuid + " acknowledged");
            return new ResponseEntity<>(d, HttpStatus.OK);
        } catch (Exception e) {
            throw new InternalServerError500Exception("Internal Server Error" + e.getLocalizedMessage());
        }

    }

}


text:
{% extends 'base.html' %}
{% block content %}

this is about page

{% endblock %}


text:
require File.expand_path('../test_helper', __FILE__)

# Mock controller used for testing session handling.
class HttpTokenController < ApplicationController
  authenticates_using_http_token

  def show
    if current_user
      render text: "User: #{current_user.id}"
    else
      render text: "No user"
    end
  end

  def bouncer
    bounce_to_http_token
  end
end

class HttpTokenControllerTest < ActionController::TestCase
  setup do
    @user = users(:john)
  end

  test "no user_id in session cookie or header" do
    get :show
    assert_response :success
    assert_nil assigns(:current_user)
    assert_equal 'No user', response.body
  end

  test "valid user_id in session cookie" do
    set_session_current_user @user
    get :show
    assert_response :success
    assert_nil assigns(:current_user)
    assert_equal 'No user', response.body
  end

  test "valid user credentials in header" do
    set_http_token_user @user
    get :show
    assert_equal @user, assigns(:current_user)
    assert_equal nil, session_current_user,
        'Token authentication should not update the session'

    john_id = ActiveRecord::FixtureSet.identify :john
    assert_equal "User: #{john_id}", response.body
  end

  test "invalid token in header" do
    set_http_token_user @user
    Tokens::Api.where(user_id: @user.id).destroy_all
    get :show
    assert_nil assigns(:current_user)
    assert_equal 'No user', response.body
  end

  test "uses Tokens::Api.authenticate" do
    Tokens::Api.expects(:authenticate).at_least_once.with('ap1-c0d3').
        returns @user
    set_http_token_user @user, 'ap1-c0d3'
    get :show
    assert_equal @user, assigns(:current_user)
    assert_equal nil, session_current_user,
        'Token authentication should not update the session'

    john_id = ActiveRecord::FixtureSet.identify :john
    assert_equal "User: #{john_id}", response.body
  end

  test "reset user credentials in header" do
    set_http_token_user @user
    set_http_token_user nil
    get :show
    assert_nil assigns(:current_user)
    assert_equal 'No user', response.body
  end

  test "newly created API token in header" do
    user = users(:jane)
    set_http_token_user user
    get :show
    assert_equal user, assigns(:current_user)
    assert_equal nil, session_current_user,
        'Token authentication should not update the session'

    jane_id = ActiveRecord::FixtureSet.identify :jane
    assert_equal "User: #{jane_id}", response.body
  end

  test "invalid authpwn_suid in session" do
    get :show, {}, authpwn_suid: 'random@user.com'
    assert_response :success
    assert_nil assigns(:current_user)
  end

  test "valid user bounced to http authentication" do
    set_http_token_user @user
    get :bouncer
    assert_response :forbidden
    assert_template 'session/forbidden'
    assert_select 'a[href="/session"][data-method="delete"]', 'sign out'
  end

  test "valid user bounced in json" do
    set_http_token_user @user
    get :bouncer, format: 'json'
    assert_response :ok
    data = ActiveSupport::JSON.decode response.body
    assert_match(/not allowed/i, data['error'])
  end

  test "no user_id bounced to http authentication" do
    get :bouncer
    assert_response :unauthorized
    assert_equal 'Token realm="Application"',
                 response.headers['WWW-Authenticate']
  end

  test "no user_id bounced in json" do
    get :bouncer, format: 'json'
    assert_response :unauthorized
    assert_equal 'Token realm="Application"',
                 response.headers['WWW-Authenticate']
  end
end