text:
package org.apache.polygene.migration;

import java.util.Map;

/**
 * Implement this as a service to receive events from the Migration process.
 */
public interface MigrationEvents
{
    void propertyAdded( String entity, String name, Object value );

    void propertyRemoved( String entity, String name );

    void propertyRenamed( String entity, String from, String to );

    void associationAdded( String entity, String name, String defaultReference );

    void associationRemoved( String entity, String name );

    void associationRenamed( String entity, String from, String to );

    void manyAssociationAdded( String entity, String name, String... defaultReferences );

    void manyAssociationRemoved( String entity, String name );

    void manyAssociationRenamed( String entity, String from, String to );

    void namedAssociationAdded( String entity, String name, Map<String, String> defaultReferences );

    void namedAssociationRemoved( String entity, String name );

    void namedAssociationRenamed( String entity, String from, String to );

    void entityTypeChanged( String entity, String newEntityType );
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Namespace Bifrost.FluentValidation.Commands
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Namespace Bifrost.FluentValidation.Commands
   ">
    <meta name="generator" content="docfx 2.9.3.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Namespace Bifrost.FluentValidation.Commands

Classes

CommandBusinessValidator<T>

Base class to inherit from for basic business-rule validation of a command.

CommandInputValidator<T>

Base class to inherit from for basic input validation of a command.

CommandPredicateRule<T>

Represents the rule for a predicate in the form of a Func that will be called for validation

CommandValidator

Represents a ICommandValidator

CommandValidatorFactory

Represents an implementation of FluentValidation.IValidatorFactory for dealing with validation for commands

CommandValidatorProvider

Represents an instance of an ICommandValidatorProvider

ComposedCommandBusinessValidator<T>

Represents a command business validator that is constructed from discovered rules.

ComposedCommandInputValidator<T>

Represents a command input validator that is constructed from discovered rules.

ComposedCommandRuleBuilder<TProperty>

Represents an implementation of IComposedCommandRuleBuilder.

NullCommandBusinessValidator<T>

Represent a null or non-existant validator.

NullCommandInputValidator<T>

Represent a null or non-existant validator.

Interfaces

ICommandBusinessValidator

Marker interface for business validators.

ICommandInputValidator

Defines a marker interface for input level validator for a ICommand

ICommandValidatorProvider

Defines a provider that returns command-specific input and business rule validators

IComposedCommandRuleBuilder

Defines an interface to add composed child validators to a parent validator.

                    Improve this Doc

              Back to top

            Copyright © 2008-2017 Dolittle

redpajama_set_name: RedPajamaGithub


text:
This is my first repository to practice Git and GitHub on the command line.

## Information
- Name: Rudd Stevens
- Profession: Software Engineer
- Summer Activity: Fishing


text:
'use strict';

var Type = require('../type');

module.exports = new Type('tag:yaml.org,2002:str', {
  loadKind: 'scalar'
});


text:
namespace autofill_assistant {
namespace {

void RunCallbackWithoutData(
    base::OnceCallback<void(bool)> callback,
    const ClientStatus& status,
    const std::vector<std::string>& ignored_payloads,
    const std::vector<std::string>& ignored_tags,
    const base::flat_map<std::string, DomObjectFrameStack>& ignored_elements) {
  std::move(callback).Run(status.ok());
}

}  // namespace

// Static
std::unique_ptr<ScriptPrecondition> ScriptPrecondition::FromProto(
    const std::string& script_path,
    const ScriptPreconditionProto& script_precondition_proto) {
  std::vector<std::unique_ptr<re2::RE2>> path_pattern;
  for (const auto& pattern : script_precondition_proto.path_pattern()) {
    auto re = std::make_unique<re2::RE2>(pattern);
    if (re->error_code() != re2::RE2::NoError) {
#ifdef NDEBUG
      DVLOG(1) << "Invalid regexp in script precondition";
#else
      DVLOG(1) << "Invalid regexp in script precondition '" << pattern
               << "' for script path: " << script_path << ".";
#endif

      return nullptr;
    }
    path_pattern.emplace_back(std::move(re));
  }

  // TODO(crbug.com/806868): Detect unknown or unsupported conditions and
  // reject them.
  return std::make_unique<ScriptPrecondition>(
      script_precondition_proto.domain(), std::move(path_pattern),
      script_precondition_proto.script_parameter_match(),
      script_precondition_proto.element_condition());
}

ScriptPrecondition::~ScriptPrecondition() {}

void ScriptPrecondition::Check(
    const GURL& url,
    BatchElementChecker* batch_checks,
    const TriggerContext& context,
    base::OnceCallback<void(bool)> callback) {
  if (!MatchDomain(url) || !MatchPath(url) || !MatchParameters(context)) {
    std::move(callback).Run(false);
    return;
  }
  batch_checks->AddElementConditionCheck(
      element_precondition_,
      base::BindOnce(&RunCallbackWithoutData, std::move(callback)));
}

ScriptPrecondition::ScriptPrecondition(
    const google::protobuf::RepeatedPtrField<std::string>& domain_match,
    std::vector<std::unique_ptr<re2::RE2>> path_pattern,
    const google::protobuf::RepeatedPtrField<ScriptParameterMatchProto>&
        parameter_match,
    const ElementConditionProto& element_condition)
    : domain_match_(domain_match.begin(), domain_match.end()),
      path_pattern_(std::move(path_pattern)),
      parameter_match_(parameter_match.begin(), parameter_match.end()),
      element_precondition_(element_condition) {}

bool ScriptPrecondition::MatchDomain(const GURL& url) const {
  if (domain_match_.empty())
    return true;

  // We require the scheme and host parts to match.
  // TODO(crbug.com/806868): Consider using Origin::IsSameOriginWith here.
  std::string scheme_domain = base::StrCat({url.scheme(), "://", url.host()});
  return domain_match_.find(scheme_domain) != domain_match_.end();
}

bool ScriptPrecondition::MatchPath(const GURL& url) const {
  if (path_pattern_.empty()) {
    return true;
  }

  std::string path = url.has_ref()
                         ? base::StrCat({url.PathForRequest(), "#", url.ref()})
                         : url.PathForRequest();
  for (auto& regexp : path_pattern_) {
    if (regexp->Match(path, 0, path.size(), re2::RE2::ANCHOR_BOTH, NULL, 0)) {
      return true;
    }
  }
  return false;
}

bool ScriptPrecondition::MatchParameters(const TriggerContext& context) const {
  for (const auto& match : parameter_match_) {
    if (!context.GetScriptParameters().Matches(match)) {
      return false;
    }
  }
  return true;
}

}  // namespace autofill_assistant


text: Najat Vallaud-Belkacem, votre députée candidate de la gauche à Villeurbanne, les 11 et 18 juin prochain.


text:
package com.jayway.maven.plugins.android.phase11preintegrationtest;

import com.jayway.maven.plugins.android.AbstractInstrumentationMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
 * Internal. Do not use.

 * Called automatically when the lifecycle reaches phase pre-integration-test. Figures out whether to
 * call goals in this phase; and if so, calls android:deploy-dependencies and android:deploy.
 *
 * @author hugo.josefson@jayway.com
 * @goal internal-pre-integration-test
 * @phase pre-integration-test
 */
public class InternalPreIntegrationTestMojo extends AbstractInstrumentationMojo {

    public void execute() throws MojoExecutionException, MojoFailureException {
        if (isEnableIntegrationTest()) {
            deployDependencies();
            deployBuiltApk();
        }
    }

}


text:
make_module() {
  # Reset OPTIND so that getopts invocations don't conflict
  unset OPTIND
  # Set fallback values
  module_prefix="/no/prefix/given"
  output_file="/dev/stdout"
  variables_to_import=""
  variables_to_append=""
  variables_to_prepend=""
  module_whatis="This is a module with no description string."
  module_conflicts=""
  module_prereqs=""
  send_help_and_quit="n"

  #Get command line arguments
  while getopts  "hp:o:n:v:a:e:w:c:r:d" flag
  do
    case "$flag" in
      "p")
        module_prefix="$OPTARG"
        ;;
      "o")
        output_file="$OPTARG"
        ;;
      "d")
        omit_normal_block="y"
        ;;
      "v")
        printf -v variables_to_import "%s\nsetenv %s" "$variables_to_import" "${OPTARG/=/ }"
        ;;
      "a")
        printf -v variables_to_append "%s\nappend-path %s" "$variables_to_append" "${OPTARG/:/ }"
        ;;
      "e")
        printf -v variables_to_prepend "%s\nprepend-path %s" "$variables_to_prepend" "${OPTARG/:/ }"
        ;;
      "w")
        module_whatis="$OPTARG"
        ;;
      "c")
        printf -v module_conflicts "%s\nconflict %s" "$module_conflicts" "$OPTARG"
        ;;
      "r")
        printf -v module_prereqs "%s\nprereq %s" "$module_prereqs" "$OPTARG"
        ;;
      "h")
        send_help_and_quit="y"
        ;;
      *)
        echo "Module maker: Invalid argument specified: $flag" >&2
        exit 5
        ;;
    esac
  done

  module_maker_help_file="module_maker_inc.sh: makes modules

  In shell, so as to not add extra dependencies.

  Options:
    -p   prefix dir: allows quick configuration of all \$prefix/bin, \$prefix/lib paths
    -o   where to write modulefile -- directories will be created if necessary
    -d   omit normal prefix block
    -v   variables to set, as \"variable=value\". Use multiple times if nec.
    -a   variables to append, as \"variable:value\". Ditto.
    -e   variables to prepend, as \"variable:value\". Ditto.
    -w   module whatis information. A brief description.
    -c   modules this module conflicts with. Space separate, quote.
    -r   modules this module depends on. Space separate, quote.
    -h   print this.
  "

  #Send the help message and exit if -h was specified.
  if [[ "$send_help_and_quit" == "y" ]]; then
    echo -e "$module_maker_help_file"
    exit
  fi

  #Extra output variables
  user=$(whoami)
  date=$(date +"%Y-%m-%d %H:%M:%S %z")

  #Create dir for module if necessary
  mkdir -p "$(dirname "$output_file")"

  cat >"$output_file" <<EOF
#%Module -*- tcl -*-
##
## generated by $user on $date
## using cmd line:
##  "$@"

proc ModulesHelp { } {

  puts stderr {${module_whatis}}

}

module-whatis {${module_whatis}}
${module_prereqs}
${module_conflicts}

set              prefix               $module_prefix
${variables_to_import}${variables_to_prepend}${variables_to_append}
EOF

if [ -z "${omit_normal_block:-}" ]; then
cat >>"$output_file" <<EOF

prepend-path        CMAKE_PREFIX_PATH    \$prefix

if { [file isdirectory \$prefix/bin] } then {
  prepend-path      PATH                 \$prefix/bin
}

if { [file isdirectory \$prefix/man] } then {
  prepend-path      MANPATH              \$prefix/man
}

if { [file isdirectory \$prefix/share/man] } then {
  prepend-path      MANPATH              \$prefix/share/man
}

if { [file isdirectory \$prefix/lib] } then {
  prepend-path      LIBRARY_PATH         \$prefix/lib
  prepend-path      LD_RUN_PATH          \$prefix/lib
  prepend-path      LD_LIBRARY_PATH      \$prefix/lib
}

if { [file isdirectory \$prefix/lib64] } then {
  prepend-path      LIBRARY_PATH         \$prefix/lib64
  prepend-path      LD_RUN_PATH          \$prefix/lib64
  prepend-path      LD_LIBRARY_PATH      \$prefix/lib64
}

if { [file isdirectory \$prefix/lib/pkgconfig] } then {
  prepend-path      PKG_CONFIG_PATH      \$prefix/lib/pkgconfig
}

if { [file isdirectory \$prefix/include] } then {
  prepend-path      CPATH                \$prefix/include
  prepend-path      INCLUDE_PATH         \$prefix/include
}

EOF
fi

}

if [ "$(basename -- "$0")" == "module_maker_inc.sh" ]; then
  make_module "$@"
fi


text:
<?php

namespace ProjetK\PretBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Transaction
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="ProjetK\PretBundle\Entity\TransactionRepository")
 */
class Transaction
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date_pret", type="date")
     */
    private $datePret;

    /**
     * @ORM\ManyToOne(targetEntity="ProjetK\UserBundle\Entity\User", cascade={"persist"})
	 * @ORM\JoinColumn(nullable=true)
     */
    private $emprunteur;

    /**
     * @ORM\OneToOne(targetEntity="ProjetK\PretBundle\Entity\Objet", cascade={"persist"})
	 * @ORM\JoinColumn(nullable=true)
     */
    private $objet;

    // /**
     // * @ORM\OneToOne(targetEntity="ProjetK\UserBundle\Entity\User", cascade={"persist"})
	 // * @ORM\JoinColumn(nullable=false)
     // */
    // private $preteur;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set datePret
     *
     * @param \DateTime $datePret
     * @return Transaction
     */
    public function setDatePret($datePret)
    {
        $this->datePret = $datePret;

        return $this;
    }

    /**
     * Get datePret
     *
     * @return \DateTime
     */
    public function getDatePret()
    {
        return $this->datePret;
    }

    /**
     * Set emprunteur
     *
     * @param ProjetK\UserBundle\Entity\User $emprunteur
     * @return Transaction
     */
    public function setEmprunteur(\ProjetK\UserBundle\Entity\User $emprunteur)
    {
        $this->emprunteur = $emprunteur;

        return $this;
    }

    /**
     * Get emprunteur
     *
     * @return ProjetK\UserBundle\Entity\User
     */
    public function getEmprunteur()
    {
        return $this->emprunteur;
    }

	    // /**
     // * Set preteur
     // *
     // * @param ProjetK\UserBundle\Entity\User $preteur
     // * @return Transaction
     // */
    // public function setPreteur(\ProjetK\UserBundle\Entity\User $preteur)
    // {
        // $this->preteur = $preteur;
//
        // return $this;
    // }

    // /**
     // * Get preteur
     // *
     // * @return ProjetK\UserBundle\Entity\User
     // */
    // public function getPreteur()
    // {
        // return $this->preteur;
    // }

    /**
     * Set objet
     *
     * @param ProjetK\PretBundle\Entity\Objet $objet
     * @return Transaction
     */
    public function setObjet(\ProjetK\PretBundle\Entity\Objet $objet = null)
    {
        $this->objet = $objet;

        return $this;
    }

    /**
     * Get objet
     *
     * @return ProjetK\PretBundle\Entity\Objet
     */
    public function getObjet()
    {
        return $this->objet;
    }
}


text:
package KinoSearch::Index::Lexicon;
use KinoSearch;

1;

__END__

__BINDING__

my $synopsis = <<'END_SYNOPSIS';
    my $lex_reader = $seg_reader->obtain('KinoSearch::Index::LexiconReader');
    my $lexicon = $lex_reader->lexicon( field => 'content' );
    while ( $lexicon->next ) {
       print $lexicon->get_term . "\n";
    }
END_SYNOPSIS

Clownfish::Binding::Perl::Class->register(
    parcel            => "KinoSearch",
    class_name        => "KinoSearch::Index::Lexicon",
    bind_methods      => [qw( Seek Next Reset Get_Term Get_Field )],
    bind_constructors => ["new"],
    make_pod          => {
        synopsis => $synopsis,
        methods  => [qw( seek next get_term reset )],
    },
);

__COPYRIGHT__

Copyright 2005-2011 Marvin Humphrey

This program is free software; you can redistribute it and/or modify
under the same terms as Perl itself.


text:
package com.nightwind.contacts.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

import com.nightwind.contacts.R;
import com.nightwind.contacts.model.Contact;
import com.nightwind.contacts.model.ContactLoader;
import com.nightwind.contacts.model.Contacts;
import com.nightwind.contacts.model.GroupSummary;
import com.nightwind.contacts.model.dataitem.DataItem;
import com.nightwind.contacts.model.dataitem.EmailDataItem;
import com.nightwind.contacts.model.dataitem.PhoneDataItem;
import com.nightwind.contacts.widget.FullyLinearLayoutManager;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ContactEditorFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ContactEditorFragment extends Fragment {

    private static final String ARG_CONTACT_LOOKUP_URI = "ARG_CONTACT_LOOKUP_URI";

    private String mContactLookupUri;

    private RecyclerView recyclerView;
    private Contact contact;
    private RecyclerView.Adapter adapter;

    private final List<DataItemEntity> phoneItems = new ArrayList<>();
    private final List<DataItemEntity> emailItems = new ArrayList<>();
    private final List<DataItemEntity> groupItems = new ArrayList<>();
    private final List<GroupSpinnerEntry> groupSpinnerItems = new ArrayList<>();
    private final Set<Long> deleteDataId = new HashSet<>();

    private String originName;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param lookupUri Parameter 1.
     * @return A new instance of fragment ContactEditorFragment.
     */
    public static ContactEditorFragment newInstance(String lookupUri) {
        ContactEditorFragment fragment = new ContactEditorFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CONTACT_LOOKUP_URI, lookupUri);
        fragment.setArguments(args);
        return fragment;
    }

    public ContactEditorFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mContactLookupUri = getArguments().getString(ARG_CONTACT_LOOKUP_URI);
        }

        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mContactLookupUri == null) {
            ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.person_add);
        } else {
            ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.person_edit);
        }

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_contact_editor, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        contact = new Contact();
        contact.setData(new ArrayList<DataItem>());
        phoneItems.add(new DataItemEntity());
        emailItems.add(new DataItemEntity());

        if (mContactLookupUri != null) {
            loadContact();
        }

        adapter = new ContactEditorAdapter(getActivity(), contact);
        recyclerView.setAdapter(adapter);

        return view;
    }

    private void loadContact() {

        // get all group title
        groupSpinnerItems.clear();
        for (GroupSummary groupSummary: new Contacts(getActivity()).getGroupSummary()) {
            GroupSpinnerEntry item = new GroupSpinnerEntry();
            item.groupId = groupSummary.getId();
            item.title = groupSummary.getTitle();
            groupSpinnerItems.add(item);
        }

        getLoaderManager().initLoader(0, null, new LoaderManager.LoaderCallbacks<Contact>() {
            @Override
            public Loader<Contact> onCreateLoader(int id, Bundle args) {
                return new ContactLoader(getActivity(), mContactLookupUri);
            }

            @Override
            public void onLoadFinished(Loader<Contact> loader, Contact data) {
                List<DataItem> dataItems = contact.getData();
                dataItems.clear();
                dataItems.addAll(data.getData());
//                contact.setData(data.getData());
                contact.setId(data.getId());
                contact.setRawContactId(data.getRawContactId());
                contact.setName(data.getName());
                originName = data.getName();
                contact.setPhotoUri(data.getPhotoUri());
                ((ContactEditorAdapter)adapter).refreshData();
            }

            @Override
            public void onLoaderReset(Loader<Contact> loader) {

            }
        });
    }

    class DataItemEntity {
        public long id;
        public String data;
        public String label;
        public int labelType = 1;
        public int newLabelType = 1;
    }

    private class GroupSpinnerEntry {
        long dataId;
        long groupId;
        String title;
        boolean contain;
        boolean newContain;
    }

    private class ContactEditorAdapter extends RecyclerView.Adapter {

        private final Context context;
        private final Contact contact;

        private final int VIEW_TYPE_NAME = 0;
        private final int VIEW_TYPE_PHONE = 1;
        private final int VIEW_TYPE_EMAIL = 2;
        private final int VIEW_TYPE_GROUP = 3;

        public ContactEditorAdapter(Context context, Contact contact) {
            this.context = context;
            this.contact = contact;
            List<DataItem> dataItems = contact.getData();
            loadEntitiesFromDataItems(dataItems);
        }

        public void loadEntitiesFromDataItems(List<DataItem> dataItems) {

            phoneItems.clear();
            emailItems.clear();
            groupItems.clear();
            for (DataItem dataItem: dataItems) {
                if (dataItem.getMimeType().equals(Phone.CONTENT_ITEM_TYPE)) {
//                    phoneItems.add(dataItem);
                    DataItemEntity item = new DataItemEntity();
                    item.id = dataItem.getId();
                    item.data = ((PhoneDataItem)dataItem).getNumber();
                    item.label = ((PhoneDataItem)dataItem).getLabel();
                    item.labelType = ((PhoneDataItem)dataItem).getType();
                    phoneItems.add(item);
                } else if (dataItem.getMimeType().equals(Email.CONTENT_ITEM_TYPE)) {
//                    emailItems.add(dataItem);
                    DataItemEntity item = new DataItemEntity();
                    item.id = dataItem.getId();
                    item.data = ((EmailDataItem)dataItem).getAddress();
                    item.label = ((EmailDataItem)dataItem).getLabel();
                    item.labelType = ((EmailDataItem)dataItem).getType();
                    emailItems.add(item);
                } else if (dataItem.getMimeType().equals(ContactsContract.Groups.CONTENT_ITEM_TYPE)) {
                    DataItemEntity item = new DataItemEntity();
                    item.id = dataItem.getId();
                    item.data = dataItem.getData();
                    groupItems.add(item);

                    long dataId = dataItem.getId();
                    long groupId = Long.valueOf(dataItem.getData());
                    for (GroupSpinnerEntry spinnerEntry: groupSpinnerItems) {
                        if (groupId == spinnerEntry.groupId) {
                            spinnerEntry.dataId = dataId;
                            spinnerEntry.contain = true;
                            item.label = spinnerEntry.title;
                        }
                    }

                }
            }

            // add a empty entry
            phoneItems.add(new DataItemEntity());
            emailItems.add(new DataItemEntity());
            groupItems.add(new DataItemEntity());
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(context);
            RecyclerView.ViewHolder vh;
            switch (viewType) {
                case VIEW_TYPE_NAME:
                    vh = new NormalEditorViewHolder(inflater.inflate(R.layout.item_editor_name, parent, false));
                    break;
//                case VIEW_TYPE_GROUP:
//                    vh = new SpinnerDataEditorViewHolder(inflater.inflate(R.layout.item_editor_data, parent, false));
//                    break;
                default:
                    vh = new RecyclerEditorViewHolder(inflater.inflate(R.layout.recyclerview, parent, false));
                    break;
            }
            return vh;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            switch (holder.getItemViewType()) {
                case VIEW_TYPE_NAME:
                    bindNameEditor((NormalEditorViewHolder) holder);
                    break;
                case VIEW_TYPE_GROUP:
//                    bindGroupViewEditor((SpinnerDataEditorViewHolder) holder);
//                    break;
                case VIEW_TYPE_PHONE:
                case VIEW_TYPE_EMAIL:
                    bindRecyclerViewEditor((RecyclerEditorViewHolder) holder, holder.getItemViewType());
                    break;

            }
        }

        private void bindNameEditor(NormalEditorViewHolder holder) {
            holder.data.setText(contact.getName());
            holder.data.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    contact.setName(String.valueOf(s));
                }
            });
        }

        private void bindRecyclerViewEditor(RecyclerEditorViewHolder holder, int type) {
            holder.recyclerView.setLayoutManager(new FullyLinearLayoutManager(context));
            switch (type) {
                case VIEW_TYPE_PHONE:
                    holder.recyclerView.setAdapter(new recyclerEditorAdapter(context, phoneItems, type));
                    break;
                case VIEW_TYPE_EMAIL:
                    holder.recyclerView.setAdapter(new recyclerEditorAdapter(context, emailItems, type));
                    break;
                case VIEW_TYPE_GROUP:
                    holder.recyclerView.setAdapter(new GroupAdapter(context, groupSpinnerItems, type));
                    break;
            }
        }

        private void bindGroupViewEditor(SpinnerDataEditorViewHolder holder) {
            holder.data.setVisibility(View.GONE);
            holder.typeImage.setImageResource(R.drawable.ic_group);

//            ArrayAdapter<GroupSpinnerEntry> spinnerAdapter
//                    = new ArrayAdapter<GroupSpinnerEntry>(context, R.layout.item_spinner_text, groupSpinnerItems) {
//                @Override
//                public View getView(int position, View convertView, ViewGroup parent) {
//                    GroupSpinnerEntry group = getItem(position);
//                    if (convertView == null) {
//                        convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_spinner_text, parent, false);
//                    }
////                    CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.checkText);
////                    checkedTextView.setText(group.title);
////                    checkedTextView.setChecked(group.contain);
//                    ((TextView)convertView).setText(group.title);
//                    return convertView;
//                }
//            };

//            List<String> titles = new ArrayList<>();
//            for (GroupSpinnerEntry gpe: groupSpinnerItems) {
//                titles.add(gpe.title);
//            }

            SpinnerAdapter spinnerAdapter = new BaseAdapter() {

                @Override
                public int getCount() {
                    return groupSpinnerItems.size();
                }

                @Override
                public Object getItem(int position) {
                    return groupSpinnerItems.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return groupSpinnerItems.get(position).dataId;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    GroupSpinnerEntry group = groupSpinnerItems.get(position);

                    if (convertView == null) {
                        convertView = LayoutInflater.from(context).inflate(R.layout.item_spinner_group, parent, false);
                    }

                    CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.checkText);
                    checkedTextView.setText(group.title);
                    checkedTextView.setChecked(group.contain);

                    return convertView;
                }
            };

            holder.spinner.setAdapter(spinnerAdapter);
        }

        private void bindPhoneEditor(SpinnerDataEditorViewHolder holder) {
            holder.typeImage.setImageResource(R.drawable.ic_action_call);
        }

        @Override
        public int getItemCount() {
            // 现只有name,phone,email
            return 3;
        }

        public void refreshData() {

            List<DataItem> dataItems = contact.getData();
            loadEntitiesFromDataItems(dataItems);
            notifyDataSetChanged();
        }

        public boolean isEditMode() {
            return mContactLookupUri != null;
        }

        private class recyclerEditorAdapter extends RecyclerView.Adapter {

            private final int type;
            private Context context;
            private List<DataItemEntity> dataItems;

            public recyclerEditorAdapter(Context context, List<DataItemEntity> dataItems, int type) {
                this.context = context;
                this.dataItems = dataItems;
                this.type = type;
            }

            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(context).inflate(R.layout.item_editor_data, parent, false);
                return new SpinnerDataEditorViewHolder(view);
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
                final DataItemEntity item = dataItems.get(position);
                final SpinnerDataEditorViewHolder viewHolder = (SpinnerDataEditorViewHolder) holder;
                int typeImageResource = 0;
                String textHint = "";
                List<String> spinnerList = new ArrayList<>();
                if (type == VIEW_TYPE_PHONE) {
                    typeImageResource = R.drawable.ic_action_call;
                    textHint = "电话";

                    // add spinner type label
                    for (int i = 0; i <= Phone.TYPE_OTHER; i++) {
                        if (i > 0 || isEditMode() && item.labelType == Phone.TYPE_CUSTOM) {
                            CharSequence label = Phone.getTypeLabel(getResources(), i, item.label);
                            spinnerList.add(String.valueOf(label));
                        }
                    }

                    ((SpinnerDataEditorViewHolder) holder).data.setText(item.data);
                } else if (type == VIEW_TYPE_EMAIL) {
                    typeImageResource = R.drawable.ic_action_mail;
                    textHint = "邮箱";

                    // add spinner type lable
                    for (int i = 0; i <= Email.TYPE_MOBILE; i++) {
                        if (i > 0 || isEditMode() && item.labelType == Email.TYPE_CUSTOM) {
                            CharSequence label = Email.getTypeLabel(getResources(), i, item.label);
                            spinnerList.add(String.valueOf(label));
                        }
                    }

                    ((SpinnerDataEditorViewHolder) holder).data.setText(item.data);
                } else if (type == VIEW_TYPE_GROUP) {
                    typeImageResource = R.drawable.ic_group;
                    textHint = "分组";

                    // add spinner type label
                    for (GroupSpinnerEntry entry: groupSpinnerItems) {
                        spinnerList.add(entry.title);
                    }

                    // set edit text view gone
                    viewHolder.data.setVisibility(View.GONE);
                }

                // set deleteImage action and visible or not
                if (position < getItemCount() - 1) {
                    viewHolder.deleteImage.setImageResource(R.drawable.ic_close);

                } else {
                    viewHolder.deleteImage.setImageDrawable(null);
                }
                viewHolder.deleteImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = dataItems.indexOf(item);
                        dataItems.remove(position);
                        if (item.id != 0) {
                            deleteDataId.add(item.id);
                        }
                        notifyItemRemoved(position);
                        if (position == 0) {
                            notifyItemChanged(0);
                        }
                    }
                });

                // set spinner
                viewHolder.spinner.setAdapter(new ArrayAdapter<>(context, R.layout.item_spinner_text, spinnerList));
                viewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (item.labelType == ContactsContract.CommonDataKinds.BaseTypes.TYPE_CUSTOM) {
                            item.newLabelType = position;
                        } else {
                            item.newLabelType = position + 1;
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                if (item.labelType == ContactsContract.CommonDataKinds.BaseTypes.TYPE_CUSTOM) {
                    viewHolder.spinner.setSelection(item.labelType);
                } else {
                    viewHolder.spinner.setSelection(item.labelType - 1);
                }

                // set type image
                if (position > 0) {
                    viewHolder.typeImage.setImageDrawable(null);
                } else {
                    viewHolder.typeImage.setImageResource(typeImageResource);
                }

                // set data
                viewHolder.data.setHint(textHint);
                final int finalTypeImageResource = typeImageResource;
                viewHolder.data.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int position = dataItems.indexOf(item);
                        if (position == dataItems.size()-1) {
//                            dataItems.add(DataItem.EMPTY_DATA_ITEM);
                            dataItems.add(new DataItemEntity());
                            notifyItemInserted(position + 1);
                            viewHolder.deleteImage.setImageResource(R.drawable.ic_close);
                            if (position > 0) {
                                viewHolder.typeImage.setImageDrawable(null);
                            } else {
                                viewHolder.typeImage.setImageResource(finalTypeImageResource);
                            }
                        }
                        item.data = String.valueOf(s);
                    }
                });

            }

            @Override
            public int getItemCount() {
                return dataItems.size();
            }

            private class DataEditWatcher implements TextWatcher {

                private final int position;

                public DataEditWatcher(int position) {
                    this.position = position;
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (position == dataItems.size()-1) {
//                            dataItems.add(DataItem.EMPTY_DATA_ITEM);
                        dataItems.add(new DataItemEntity());
                        notifyItemInserted(position + 1);
                    }
                    dataItems.get(position).data = String.valueOf(s);
                }
            }
        }
    }

    private class NormalEditorViewHolder extends RecyclerView.ViewHolder {

        public ImageView typeImage;
        public EditText data;
        public ImageView deleteImage;

        public NormalEditorViewHolder(View itemView) {
            super(itemView);
            typeImage = (ImageView) itemView.findViewById(R.id.typeImage);
            data = (EditText) itemView.findViewById(R.id.data);
            deleteImage = (ImageView) itemView.findViewById(R.id.deleteImage);
        }
    }

    private class SpinnerDataEditorViewHolder extends NormalEditorViewHolder {

        public Spinner spinner;

        public SpinnerDataEditorViewHolder(View itemView) {
            super(itemView);
            spinner = (Spinner) itemView.findViewById(R.id.spinner);
        }
    }

    private class RecyclerEditorViewHolder extends RecyclerView.ViewHolder {

        public RecyclerView recyclerView;

        public RecyclerEditorViewHolder(View itemView) {
            super(itemView);
//            recyclerView = (RecyclerView) itemView.findViewById(R.id.recyclerView);
            recyclerView = (RecyclerView) itemView;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
//        inflater.inflate(R.menu.menu_person_add, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.action_save) {
            //检查是否为空
            if (isEmpty()) {
                Toast.makeText(getActivity(), R.string.warn_contact_can_not_empty,
                        Toast.LENGTH_SHORT).show();
                return true;
            }

            String newName = contact.getName();
            if (!newName.equals(originName) && nameIsExist(newName)) {
                Toast.makeText(getActivity(), R.string.name_is_exist,
                        Toast.LENGTH_SHORT).show();
                return true;
            }

            try {
                saveContact();
                mContactLookupUri = new Contacts(getActivity()).getLookupKey(newName);
                getActivity().setResult(Activity.RESULT_OK,
                        new Intent().putExtra("lookupKey", mContactLookupUri));
                getActivity().finish();
                Toast.makeText(getActivity(), R.string.save_success, Toast.LENGTH_SHORT).show();
            } catch (RemoteException | OperationApplicationException | IllegalArgumentException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), R.string.save_failed, Toast.LENGTH_SHORT).show();
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private boolean isEmpty() {
        return TextUtils.isEmpty(contact.getName()) || phoneItems.size() == 1 /*&& emailItems.size() == 1*/;
    }

    private boolean nameIsExist(String name) {
        return TextUtils.isEmpty(name) || new Contacts(getActivity()).nameIsExist(name);
    }

    private boolean isInsertingContact() {
        return mContactLookupUri == null;
    }

    private void saveContact() throws RemoteException, OperationApplicationException {

        // 重新生成dataItem
        List<DataItem> dataItems = new ArrayList<>();
        for (DataItemEntity item: phoneItems) {
            if (phoneItems.indexOf(item) == phoneItems.size() -1) {
                continue;
            }

            if (!TextUtils.isDigitsOnly(item.data)) {
                Toast.makeText(getActivity(), R.string.warn_number_format, Toast.LENGTH_SHORT).show();
                throw new IllegalArgumentException();
            }

            ContentValues cv = new ContentValues();
            cv.put(ContactsContract.Data._ID, item.id);
            cv.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
            cv.put(Phone.NUMBER, item.data);
            cv.put(Phone.TYPE, item.newLabelType);
            cv.put(Phone.LABEL, item.label);
            dataItems.add(DataItem.createFrom(cv));
        }

        for (DataItemEntity item: emailItems) {
            if (emailItems.indexOf(item) == emailItems.size() -1) {
                continue;
            }

            //check email format

            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(item.data);
            boolean isMatched = matcher.matches();
            if (!isMatched) {
                Toast.makeText(getActivity(), R.string.warn_email_format, Toast.LENGTH_SHORT).show();
                throw new IllegalArgumentException();
            }

            ContentValues cv = new ContentValues();
            cv.put(ContactsContract.Data._ID, item.id);
            cv.put(Email.MIMETYPE, Email.CONTENT_ITEM_TYPE);
            cv.put(Email.ADDRESS, item.data);
            cv.put(Email.TYPE, item.newLabelType);
            cv.put(Email.LABEL, item.label);
            dataItems.add(DataItem.createFrom(cv));
        }

        //delete data
        for (Long id : deleteDataId) {
            if (id > 0) {
                ContentValues cv = new ContentValues();
                cv.put(ContactsContract.Data._ID, id);
                dataItems.add(DataItem.createFrom(cv));

            }
        }

        contact.setData(dataItems);

        if (mContactLookupUri != null) {
            // update contact
            new Contacts(getActivity()).updateContact(contact);
        } else {
            // insert contact
            new Contacts(getActivity()).saveContact(contact.getName(), null, dataItems);
        }

    }

    private class GroupAdapter extends RecyclerView.Adapter {
        private final Context context;
        private final List<GroupSpinnerEntry> groupItems;
        private final int type;

        public GroupAdapter(Context context, List<GroupSpinnerEntry> groupItems, int type) {
            this.context = context;
            this.groupItems = groupItems;
            this.type = type;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        }

        @Override
        public int getItemCount() {
            return groupItems.size();
        }
    }
}


text:
package com.jameswolfeoliver.pigeon.Activities;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.jameswolfeoliver.pigeon.Presenters.BasePresenter;
import com.jameswolfeoliver.pigeon.R;
import com.jameswolfeoliver.pigeon.Services.PigeonService;
import com.jameswolfeoliver.pigeon.Utilities.NetworkStateReceiver;
import com.jameswolfeoliver.pigeon.Utilities.PigeonApplication;

public abstract class BaseActivity extends AppCompatActivity implements NetworkStateReceiver.NetworkStateReceiverListener {
    protected BasePresenter basePresenter;
    private NetworkStateReceiver networkStateReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        basePresenter = new BasePresenter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopReceiver();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.action_connect_to_pc:
                showConnectionStatus();
                return true;
            case R.id.action_view_connections:
                Intent confirmConnectionIntent = new Intent(this, ConnectionActivity.class);
                startActivity(confirmConnectionIntent);
                return true;
            default:
                return (super.onOptionsItemSelected(menuItem));
        }
    }

    @Override
    abstract public void onNetworkStateChange(boolean isAvailable);

    private void showConnectionStatus() {
        basePresenter.isServerRunning((uri, secure, status) -> {
            if (status == PigeonService.PigeonServerStatus.RUNNING) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(String.format(getString(R.string.connected_message), uri + "/inbox"))
                        .setTitle(R.string.connect_to_pc)
                        .setIcon(R.drawable.ic_phonelink_dark)
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> dialog.dismiss())
                        .setNegativeButton(R.string.disconnect, (dialog, which) -> basePresenter.tearDownServer(null));
                AlertDialog connectToPcDialog = builder.create();
                connectToPcDialog.show();
            } else {
                showServerSetupDialog();
            }
        });
    }

    private void showServerSetupDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            builder.setIcon(R.drawable.ic_phonelink_dark);
            builder.setTitle(getString(R.string.setup_connection));
            builder.setMessage(getString(R.string.setup_connection_message));

            String positiveText = getString(R.string.setup_encrypted);
            builder.setPositiveButton(positiveText, (dialog, which) -> {
                basePresenter.startServer(true, (uri, secure, status) -> {
                    if (status == PigeonService.PigeonServerStatus.RUNNING) {
                        showConnectionSuccess(uri);
                    } else {
                        Toast.makeText(getApplicationContext(), R.string.connection_failed, Toast.LENGTH_SHORT).show();
                    }
                });
            });
            String negativeText = getString(R.string.setup_normal);
            builder.setNegativeButton(negativeText, (dialog, which) -> {
                basePresenter.startServer(false, (uri, secure, status) -> {
                    if (status == PigeonService.PigeonServerStatus.RUNNING) {
                        showConnectionSuccess(uri);
                    } else {
                        Toast.makeText(getApplicationContext(), R.string.connection_failed, Toast.LENGTH_SHORT).show();
                    }
                });
            });

            final AlertDialog securityDialog = builder.create();
            securityDialog.show();
        } else {
            // Connect to wifi
            builder.setIcon(R.drawable.ic_signal_wifi_off);
            builder.setTitle(getString(R.string.setup_connection));
            builder.setMessage(getString(R.string.setup_connection_wifi_error_message));
            String positiveText = getString(android.R.string.ok);
            builder.setPositiveButton(positiveText, (dialog, which) -> startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)));
            final AlertDialog networkDialog = builder.create();
            networkDialog.show();
        }
    }

    protected void showConnectionSuccess(String loginUrl) {
        Snackbar.make(getWindow().getDecorView(), String.format(getString(R.string.connected_message), loginUrl), Snackbar.LENGTH_LONG)
                .setAction(R.string.undo, basePresenter)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_base, menu);
        return true;
    }

    public void startReceiver() {
        networkStateReceiver = new NetworkStateReceiver();
        networkStateReceiver.addListener(this);
        PigeonApplication.getAppContext().registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }

    public void stopReceiver() {
        if (networkStateReceiver != null) {
            networkStateReceiver.removeListener(this);
            PigeonApplication.getAppContext().unregisterReceiver(networkStateReceiver);
            networkStateReceiver = null;
        }
    }
}


text:
require 'conditionz/post_condition_not_met_error'

describe Conditionz::PostConditionNotMetError do

  it "should have correct message" do
    message = "some message"
    error = Conditionz::PostConditionNotMetError.new(message)

    error.message.should == message
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Kirk, Cannon, David & Stalpers, Ainsworth & Bisby's Dictionary of the Fungi (Wallingford), Edn 9 x (2001)

#### Original name
Protosteliales L.S. Olive & Stoian. ex P.M. Kirk, P.F. Cannon & J.C. David

### Remarks
null


text:
module Main (main) where

import Protolude

import Test.Tasty (defaultMain, TestTree, testGroup)

import qualified Comment
import qualified Diff
import qualified Todo

main :: IO ()
main = defaultMain tests

tests :: TestTree
tests =
  testGroup "Fixme"
  [ Comment.tests
  , Diff.tests
  , Todo.tests
  ]


text:
require 'spec_helper'

describe Poppins do
  it "should have a VERSION" do
    Poppins::VERSION.should_not be nil
  end
end


text:
"""
This script plots the reconstruction of all the spectrograms of the audio files in a directory,
given a particular model.
"""
import argparse
import audiosegment as asg
import math
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import os
import sys

# Load the stuff we need from ArtieInfant proper
sys.path.append(os.path.abspath("../../"))
sys.path.append(os.path.abspath("../../Artie"))
from experiment.thesis import phase1                    # pylint: disable=locally-disabled, import-error
from experiment.analysis.vae import plotvae             # pylint: disable=locally-disabled, import-error

def _plot(specs, title, fname, times, frequencies):
    """
    Plot an nxn grid of spectrograms.
    """
    n = math.ceil(math.sqrt(specs.shape[0]))
    if n * (n - 1) >= specs.shape[0]:
        m = n - 1
    else:
        m = n
    #fig, axs = plt.subplots(n, n)
    fig = plt.figure()
    for i in range(m):
        for j in range(n):
            # Plot a subplot if possible
            if (i * n + j) < specs.shape[0]:
                sample = specs[i * n + j, :, :]
                ax = fig.add_subplot(m, n, (i * n + j) + 1)
                ax.pcolormesh(times, frequencies, sample)
            else:
                pass

            # Remove the ticklabels from y axis if we are not on the left
            if j == 0:
                # We are on the left
                pass
            else:
                ax.yaxis.set_ticklabels([])

            # Remove the ticklabels from x axis if we are not on the bottom
            if i == m - 1:
                # We are on the bottom row
                pass
            else:
                ax.xaxis.set_ticklabels([])

    fig.suptitle(title)
    fig.text(0.5, 0.04, "Time (s)", ha='center', va='center')
    fig.text(0.03, 0.5, "Hz", ha='center', va='center', rotation='vertical')

    save = os.path.join(os.path.abspath("."), fname)
    print("Saving", save)
    plt.savefig(save)
    plt.show()
    plt.clf()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('ndims', type=int, help="The number of dimensions of the latent space for the given model of autoencoder.")
    parser.add_argument('specmode', choices=['long', 'short'], help="Long: 241x20x1 spectrograms; Short: 81x18x1")
    parser.add_argument('aemodelpath', type=str, help="Path to the Auto Encoder weights.")
    parser.add_argument('audiodir', type=str, help="Directory that contains the sound files you want to reconstruct")
    args = parser.parse_args()

    # Validate args
    if not os.path.isfile(args.aemodelpath):
        print("Not a file: {}".format(args.aemodelpath))
        exit(1)
    elif not os.path.isdir(args.audiodir):
        print("Not a directory: {}".format(args.audiodir))
        exit(2)

    # Set stuff up based on what mode we are
    if args.specmode == 'long':
        input_shape = [241, 20, 1]
        sample_rate_hz = 16000.0
        duration_s = 0.5
        window_length_s = 0.03
        ae = phase1._build_vae1(is_variational=False, input_shape=input_shape, latent_dim=args.ndims, optimizer='adadelta', loss='mse', tbdir=None, kl_loss_prop=None, recon_loss_prop=None, std_loss_prop=None)
    else:
        input_shape = [81, 18, 1]
        sample_rate_hz = 8000.0
        duration_s = 0.3
        window_length_s = 0.02
        ae = phase1._build_vae2(is_variational=False, input_shape=input_shape, latent_dim=args.ndims, optimizer='adadelta', loss='mse', tbdir=None, kl_loss_prop=None, recon_loss_prop=None, std_loss_prop=None)

    # Load the weights into the autoencoder
    ae.load_weights(args.aemodelpath)

    # Load each file in the directory if it is a wav file
    wavpaths = [os.path.join(args.audiodir, fname) for fname in os.listdir(args.audiodir) if os.path.splitext(fname)[-1].lower() == ".wav"]
    segments = [asg.from_file(w) for w in wavpaths]
    segments = [seg.resample(sample_rate_Hz=sample_rate_hz) for seg in segments]

    # Turn each segment into a spectrogram (make sure to do exactly the same preprocessing as the autoencoder expects)
    spectrograms = [seg.spectrogram(0, duration_s, window_length_s=window_length_s, overlap=0.2) for seg in segments]
    amplitudes = [spec[-1] for spec in spectrograms]
    amplitudes = [amp * 255.0 / np.max(np.abs(amp)) for amp in amplitudes]
    amplitudes = [amp / 255.0 for amp in amplitudes]
    amplitudes = [np.expand_dims(amp, -1) for amp in amplitudes]
    amplitudes = np.array(amplitudes)

    # Run each one through the autoencoder to get the result
    reconstructions = ae.encode_decode(amplitudes)
    reconstructions = np.squeeze(reconstructions)
    amplitudes = np.squeeze(amplitudes)

    times = np.linspace(0, duration_s, num=input_shape[1])
    frequencies = np.linspace(0, sample_rate_hz / 2.0, num=input_shape[0])

    # Plot everything
    dirname = os.path.basename(args.audiodir)
    _plot(amplitudes, "Spectrograms of Variations on /{}/".format(dirname), "spectrogram_variations.png", times, frequencies)
    _plot(reconstructions, "Reconstructions of Variations on /{}/".format(dirname), "spectrogram_reconstruction.png", times, frequencies)


text:
//
//  BMAvailableZone.h
//  Net
//
//  Created by ganfuchuan on 16/3/10.
//  Copyright © 2016年 ganfuchuan. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BMAvailableZone : NSObject

/** 地区ID */
@property (nonatomic, assign) NSInteger zoneID;
/** 地区代号 */
@property (nonatomic, assign) NSInteger zoneCode;
/** 地区name */
@property (nonatomic, copy) NSString *zoneName;
/** ParentZoneID */
@property (nonatomic, assign) NSInteger parentZoneID;
/** 完整编号 */
@property (nonatomic, assign) NSInteger fullCode;
/** 地区全名 */
@property (nonatomic, copy) NSString *fullName;
/** 子地区 */
@property (nonatomic, strong) NSArray *subZones;
@end

/**(自己的)
 "fullName": "福建省",
 "fullCode": "35",
 "zoneID": 1,
 "zoneName": "福建省",
 "parentZoneID": -1,
 "subZones": [],
 "zoneCode": 35
 */

/**(jdt)
 "ZoneID": 29,
 "ZoneCode": "04",
 "ZoneName": "三明市",
 "ParentZoneID": 1,
 "FullCode": "3504",
 "FullName": "福建省 三明市",
 "SubZones":
 */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

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

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

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

    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author:  Alexander V. Esin
Version: $Revision: 1.1 $
-->
<Test
  ID="signature0702"
  date-of-creation="2006-07-03"
  timeout="1"
  >
  <Author value="Alexander V. Esin"/>
  <Description>
    Checks that VM throws ClassFormatError on loading a class file which has
    Signature attribute in field info structure in which attribute_length is
    greater than 2 (equal to 4).
    Negative test.
    Covered assertions assert_class535_003
  </Description>

  <Keyword name="JVMS3ed_specific"/>

  <Source name="signature0702n.ccode"/>

  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.share.vmVerifierRun">
          <Option name="load"/>
          <Option name="org.apache.harmony.vts.test.vm.jvms.classFile.attributes.signature.signature07.signature0702.signature0702n"/>
          <Option name="java.lang.ClassFormatError"/>
    </Param>
  </Runner>
</Test>


text:
#ifndef CONDITIONVARFULLDEBUG_H
#define CONDITIONVARFULLDEBUG_H

#include "pandabase.h"
#include "pmutex.h"
#include "conditionVarImpl.h"

#ifdef DEBUG_THREADS

/**
 * A condition variable, usually used to communicate information about
 * changing state to a thread that is waiting for something to happen.  A
 * condition variable can be used to "wake up" a thread when some arbitrary
 * condition has changed.
 *
 * A condition variable is associated with a single mutex, and several
 * condition variables may share the same mutex.
 */
class EXPCL_PANDA_PIPELINE ConditionVarFullDebug {
public:
  explicit ConditionVarFullDebug(MutexDebug &mutex);
  ConditionVarFullDebug(const ConditionVarFullDebug &copy) = delete;
  virtual ~ConditionVarFullDebug();

  ConditionVarFullDebug &operator = (const ConditionVarFullDebug &copy) = delete;

PUBLISHED:
  INLINE MutexDebug &get_mutex() const;

  BLOCKING void wait();
  BLOCKING void wait(double timeout);
  void notify();
  void notify_all();
  virtual void output(std::ostream &out) const;

private:
  MutexDebug &_mutex;
  ConditionVarFullImpl _impl;
};

INLINE std::ostream &
operator << (std::ostream &out, const ConditionVarFullDebug &cv) {
  cv.output(out);
  return out;
}

#include "conditionVarFullDebug.I"

#endif  // DEBUG_THREADS

#endif


text:
package com.anttoolkit.hadoop.tasks.yarn;

import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.exceptions.*;
import org.apache.hadoop.yarn.util.*;
import org.apache.tools.ant.*;

public class KillAppTask extends GenericYarnTask
{
	private String applicationId;

	public void setApplicationId(String id)
	{
		this.applicationId = id;
	}

	@Override
	protected void doHadoopWork() throws BuildException
	{
		ApplicationReport appReport = getApplicationReport(applicationId);

		if (appReport == null)
		{
			return;
		}

		if (appReport.getYarnApplicationState() == YarnApplicationState.FINISHED
			|| appReport.getYarnApplicationState() == YarnApplicationState.KILLED
			|| appReport.getYarnApplicationState() == YarnApplicationState.FAILED)
		{
			return;
		}

		try
		{
			this.getYarnClient().killApplication(ConverterUtils.toApplicationId(applicationId));
		}
		catch (ApplicationNotFoundException e)
		{
		}
		catch (Throwable e)
		{
			throw new BuildException("Failed to kill YARN application: " + applicationId, e);
		}
	}

	@Override
	protected void hadoopValidate()
	{
		if (applicationId == null || applicationId.trim().isEmpty())
		{
			throw new BuildException("ApplicationId should be specified");
		}
	}
}


text:
<?php
abstract class Kwc_Chained_Abstract_Component extends Kwc_Abstract
{
    private $_pdfWriter;

    public static function getChainedComponentClass($masterComponentClass, $prefix)
    {
        $cmp = $masterComponentClass;
        $cmp = Kwc_Admin::getComponentClass($cmp, "{$prefix}_Component");
        if (!$cmp) $cmp = "Kwc_Chained_{$prefix}_Component";
        $cmp .= '.'.$masterComponentClass;
        return $cmp;
    }

    public static function getChainedSettings($settings, $masterComponentClass, $prefix = 'Cc', $copySettings = array(), $copyFlags = array())
    {
        $ret = $settings;
        if (!$masterComponentClass) {
            throw new Kwf_Exception("This component requires a parameter");
        }
        $ret['masterComponentClass'] = $masterComponentClass;

        $ret['alternativeComponents'] = array();
        if (Kwc_Abstract::getFlag($masterComponentClass, 'hasAlternativeComponent')) {
            $alternativeComponents = call_user_func(array($masterComponentClass, 'getAlternativeComponents'), $masterComponentClass);
            foreach ($alternativeComponents as $acKey => $alternativeComponent) {
                $ret['alternativeComponents'][$acKey] = self::getChainedComponentClass($alternativeComponent, $prefix);
            }
        }
        $ret['generators'] = Kwc_Abstract::getSetting($masterComponentClass, 'generators');
        foreach ($ret['generators'] as $k=>$g) {
            $ret['generators'][$k] = self::createChainedGenerator($masterComponentClass, $k, $prefix);
        }
        foreach ($copySettings as $i) {
            if (Kwc_Abstract::hasSetting($masterComponentClass, $i)) {
                $ret[$i] = Kwc_Abstract::getSetting($masterComponentClass, $i);
            }
        }
        foreach ($copyFlags as $f) {
            $flags = Kwc_Abstract::getSetting($masterComponentClass, 'flags', false);
            if (isset($flags[$f])) {
                $ret['flags'][$f] = $flags[$f];
            }
        }
        return $ret;
    }

    public static function createChainedGenerator($class, $key, $prefix)
    {
        $generators = Kwc_Abstract::getSetting($class, 'generators');
        $g = $generators[$key];
        if (!isset($g['class'])) throw new Kwf_Exception("generator class is not set for component '$class' generator '$key'");
        if (!is_array($g['component'])) $g['component'] = array($key => $g['component']);
        foreach ($g['component'] as &$c) {
            if (!$c) continue;
            $masterC = $c;

            if (is_instance_of($c, 'Kwc_Chained_CopyPages_Component') || is_instance_of($c, 'Kwc_Chained_CopyPages_Cc_Component')) {
                continue;
            }

            $c = self::getChainedComponentClass($c, $prefix);
            $g['masterComponentsMap'][$masterC] = $c;

            // Für jede Unterkomponente mit einer AlternativeComponent muss es auch einen Eintrag in der masterComponentsMap geben
            if (Kwc_Abstract::getFlag($masterC, 'hasAlternativeComponent')) {
                $alternativeComponents = call_user_func(array($masterC, 'getAlternativeComponents'), $masterC);
                foreach ($alternativeComponents as $alternativeComponent) {
                    $g['masterComponentsMap'][$alternativeComponent] = self::getChainedComponentClass($alternativeComponent, $prefix);
                }
            }
        }
        $g['chainedGenerator'] = $g['class'];
        $g['class'] = "Kwc_Chained_{$prefix}_Generator";
        if (isset($g['dbIdShortcut'])) unset($g['dbIdShortcut']);
        if (isset($g['plugins'])) {
            foreach ($g['plugins'] as $pKey => $plugin) {
                $pc = Kwc_Admin::getComponentClass($plugin, "{$prefix}_Component");
                if ($pc != $plugin) {
                    $g['plugins'][$pKey] = $pc;
                } else {
                    unset($g['plugins'][$pKey]); // generator-plugins in Translation only if there is an translated plugin available
                }
            }
        }
        if (isset($g['model'])) unset($g['model']);
        return $g;
    }

    public static function getAlternativeComponents($componentClass)
    {
        return Kwc_Abstract::getSetting($componentClass, 'alternativeComponents');
    }

    public function preProcessInput($postData)
    {
        $c = $this->getData()->chained->getComponent();
        if (method_exists($c, 'preProcessInput')) {
            $c->preProcessInput($postData);
        }
    }

    public function processInput($postData)
    {
        $c = $this->getData()->chained->getComponent();
        if (method_exists($c, 'processInput')) {
            $c->processInput($postData);
        }
    }

    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $data = $this->getData();
        $ret = $data->chained->getComponent()->getTemplateVars($renderer);
        $ret['data'] = $data;
        $ret['chained'] = $data->chained;
        if (!is_instance_of($data->chained->componentClass, 'Kwc_Chained_Abstract_Component')) {
            $ret['linkTemplate'] = self::getTemplateFile($data->chained->componentClass);
        }

        $ret['componentClass'] = get_class($this);

        $ret['placeholder'] = Kwc_Abstract::getSetting($data->chained->componentClass, 'placeholder');
        foreach ($ret['placeholder'] as $k => $v) {
            $ret['placeholder'][$k] = $this->getData()->trlStaticExecute($v);
        }
        return $ret;
    }

    public static function getPartialClass($componentClass)
    {
        $mc = Kwc_Abstract::getSetting($componentClass, 'masterComponentClass');
        return call_user_func(array($mc, 'getPartialClass'), $mc);
    }

    public function getPartialParams()
    {
        return $this->getData()->chained->getComponent()->getPartialParams();
    }

    public function getPartialVars($partial, $nr, $info)
    {
        $ret = $this->getData()->chained->getComponent()->getPartialVars($partial, $nr, $info);
        $ret['linkTemplate'] = self::getTemplateFile($this->getData()->chained->componentClass, 'Partial');
        return $ret;
    }

    public function getPartialCacheVars($nr)
    {
        return $this->getData()->chained->getComponent()->getPartialCacheVars($nr);
    }

    public function getContentWidth()
    {
        return $this->getData()->chained->getComponent()->getContentWidth();
    }

    public function hasContent()
    {
        return $this->getData()->chained->hasContent();
    }

    public function getPdfWriter($pdf)
    {
        if (!isset($this->_pdfWriter)) {
            $class = Kwc_Admin::getComponentFile($this->getData()->chained->componentClass, 'Pdf', 'php', true);
            $this->_pdfWriter = new $class($this, $pdf);
        }
        return $this->_pdfWriter;
    }

    public static function getChainedByMaster($masterData, $chainedData, $chainedType, $select = array())
    {
        return self::_getChainedByMaster($masterData, $chainedData, $chainedType, $select);
    }

    protected static final function _getChainedByMaster($masterData, $chainedData, $chainedType, $select = array())
    {
        if (!$masterData) return null;

        while ($chainedData) {
            if (Kwc_Abstract::getFlag($chainedData->componentClass, 'chainedType') == $chainedType) {
                break;
            }
            $chainedData = $chainedData->parent;
        }
        $c = $masterData;
        $ids = array();
        $subrootReached = false;
        while ($c) {
            $pos = max(
                strrpos($c->componentId, '-'),
                strrpos($c->componentId, '_')
            );
            $id = substr($c->componentId, $pos);
            if (Kwc_Abstract::getFlag($c->componentClass, 'chainedType') == $chainedType) {
                $subrootReached = true;
                break;
            }
            $skipParents = false;
            if ((int)$id > 0) { // nicht mit is_numeric wegen Bindestrich, das als minus interpretiert wird
                $id = '_' . $id;
                $skipParents = true;
            }
            $c = $c->parent;
            if ($c) {
                $ids[] = $id;
                //bei pages die parent ids auslassen
                if ($skipParents) {
                    while (is_numeric($c->componentId)) {
                        $c = $c->parent;
                    }
                }
            }
        }
        if (!$subrootReached) return null;
        $ret = $chainedData;
        if (is_array($select)) {
            $select = new Kwf_Component_Select($select);
        } else {
            $select = clone $select;
        }
        foreach (array_reverse($ids) as $id) {
            $select->whereId($id);
            $ret = $ret->getChildComponent($select);
            if (!$ret) return null;
        }
        return $ret;
    }

    public static function getAllChainedByMaster($master, $chainedType, $parentDataSelect = array())
    {
        $cacheId = 'hasChainedBMCls-'.Kwf_Component_Data_Root::getComponentClass();
        $classes = Kwf_Cache_SimpleStatic::fetch($cacheId);
        if ($classes === false) {
            $classes = array();
            foreach (Kwc_Abstract::getComponentClasses() as $cls) {
                if (Kwc_Abstract::getFlag($cls, 'hasAllChainedByMaster')) {
                    $classes[] = $cls;
                }
            }
            Kwf_Cache_SimpleStatic::add($cacheId, $classes);
        }
        $ret = array();
        foreach ($classes as $cls) {
            $c = strpos($cls, '.') ? substr($cls, 0, strpos($cls, '.')) : $cls;
            $ret = array_merge($ret, call_user_func(array($c, 'getAllChainedByMasterFromChainedStart'), $cls, $master, $chainedType, $parentDataSelect));
        }
        return $ret;
    }
}


text:
<?php

/**
 * @todo setDescription
 */

namespace Ovh\Xdsl;

use Ovh\Common\Exception\BadConstructorCallException;
use Ovh\Common\Exception\NotImplementedYetException;

use Ovh\Xdsl\XdslClient;

/**
 *
 */
class Xdsl
{
    /**
     * @var string
     */
    private $id;

    /**
     * @var  \Ovh\Xdsl\XdslClient;
     */
    private static $client;

    /**
     * @var
     */
    private $properties;

    /**
     *
     * @param string $id
     *
     * @throws \Ovh\Common\Exception\BadConstructorCallException;
     */
    public function __construct($id)
    {
        if (!$id)
            throw new BadConstructorCallException("$id parameter is missing.");
        $this->id = (string)$id;
    }

    /**
     * @return XdslClient
     */
    private static function getClient()
    {
        if (!self::$client instanceof XdslClient) {
            self::$client = new XdslClient();
        }
        return self::$client;
    }

    /**
     * Get Raw properties
     *
     * @return object
     */
    public function getProperties()
    {
        $this->properties = json_decode(self::getClient()->getProperties($this->id));
        return $this->properties;
    }

    /**
     * Is IPV6 Enabled
     *
     * @param bool $forceReload
     * @return bool
     */
    public function isIpv6Enabled($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->ipv6Enabled;
    }

    /**
     * Get Status
     *
     * @param bool $forceReload
     * @return string
     */
    public function getStatus($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->status;
    }

    /**
     * Return nb pairs used
     *
     * @param bool $forceReload
     * @return integer
     */
    public function getPairsNumber($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->pairsNumber;
    }

    /**
     * Get description (writtable -> setDescription)
     *
     * @param bool $forceReload
     * @return string
     */
    public function getDescription($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->description;
    }

    /**
     * Get access Type (eg adsl, sdsl,..)
     *
     * @param bool $forceReload
     * @return string
     */
    public function getAccessType($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->accessType;
    }

    /**
     *  Get capabilities
     *
     * @param bool $forceReload
     * @return object
     */
    public function getCapabilities($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->capabilities;
    }

    /**
     * Can we change DSLAM Profile  ?
     *
     * @param bool $forceReload
     * @return boolean
     */
    public function canChangeDslamProfile($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->capabilities->canChangeDslamProfile;
    }

    /**
     * Can we change DSLAM port ?
     *
     * @param bool $forceReload
     * @return boolean
     */
    public function canResetDslamPort($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->capabilities->canResetDslamPort;
    }

    /**
     * Can we change Lns ?
     *
     * @param bool $forceReload
     * @return boolean
     */
    public function canChangeLns($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->capabilities->canChangeLns;
    }

    /**
     * Get address
     *
     * @param bool $forceReload
     * @return object
     */
    public function getAddress($forceReload = false)
    {
        if (!$this->properties || $forceReload)
            $this->getProperties();
        return $this->properties->address;
    }

    /**
     * Set description
     *
     * @param $desc
     */
    public function setDescription($desc)
    {
        self::getClient()->setDescription($this->id, (string)$desc);
    }

    /**
     * Get Pending Action
     *
     * @return object
     */
    public function getPendingAction()
    {
        return json_decode(self::getClient()->getPendingAction($this->id));
    }

    /**
     * Get all tasks
     *
     * @return array
     */
    public function getTasks()
    {
        return json_decode(self::getClient()->getTasks($this->id));
    }

    /**
     * Get task info
     *
     * @param $taskId
     * @return mixed
     */
    public function getTask($taskId)
    {
        return json_decode(self::getClient()->getTask($this->id, $taskId));
    }

    /**
     * Get IP
     *
     * @return array of ips
     */
    public function getIps()
    {
        return json_decode(self::getClient()->getIps($this->id));
    }

    /**
     * Get IP properties
     *
     * @param string $ip
     * @return mixed
     */
    public function getIpProperties($ip)
    {
        return json_decode(self::getClient()->getIpProperties($this->id, $ip));
    }

    /**
     * Get IP monitoring state (enable | disable)
     *
     * @param string $ip
     * @return string enable | disable
     */
    public function ipGetMonitoringState($ip)
    {
        return self::getClient()->ipGetMonitoringState($this->id, $ip);
    }

    /**
     * Get IP version (ipv4 or ipv6)
     *
     * @param  string $ip
     * @return string ipv4 | ipv6
     */
    public function ipGetVersion($ip)
    {
        return self::getClient()->ipGetVersion($this->id, $ip);
    }

    /**
     * Get IP range
     *
     * @param string $ip
     * @return int
     */
    public function ipGetRange($ip)
    {
        return self::getClient()->ipGetRange($this->id, $ip);
    }

    /**
     * Get DNS List for IP
     *
     * @param string $ip
     * @return array of IP
     */
    public function ipGetDnsList($ip)
    {
        return self::getClient()->ipGetDnsList($this->id, $ip);
    }

    /**
     * Get IP reverse
     *
     * @param string $ip
     * @return string
     */
    public function ipGetReverse($ip)
    {
        return self::getClient()->ipGetReverse($this->id, $ip);
    }

    /**
     * Get monitoring notifications for IP
     *
     * @param string $ip
     * @return array
     */
    public function ipGetMonitoringNotifications($ip)
    {
        return json_decode(self::getClient()->ipGetMonitoringNotifications($this->id, $ip));
    }

    /**
     * Set a monitoring notification on IP
     *
     * @param string $ip
     * @param string $frequency
     * @param string $email
     * @param array $sms
     * @return object
     */
    public function ipSetMonitoringNotifications($ip, $frequency = 'once', $email = '', $sms = array())
    {
        return json_decode(self::getClient()->ipSetMonitoringNotifications($this->id, $ip, $frequency, $email, $sms));
    }

    /**
     * Get monitoring notification properties for IP
     *
     * @param  string $ip
     * @param integer $notificationId
     * @return object
     */
    public function ipGetMonitoringNotification($ip, $notificationId)
    {
        return json_decode(self::getClient()->ipGetMonitoringNotification($this->id, $ip, $notificationId));
    }

    /**
     * Update monitoring notification for IP $ip
     *
     * @param string $ip
     * @param integer $notificationId
     * @param string $frequency
     * @param string $email
     * @param string $phone
     * @param bool $enable
     */
    public function ipUpdateMonitoringNotification($ip, $notificationId, $frequency, $email, $phone, $enable)
    {
        self::getClient()->ipUpdateMonitoringNotification($this->id, $ip, $notificationId, $frequency, $email, $phone, $enable);
    }

    /**
     * Delete notification for IP $ip
     *
     * @param string $ip
     * @param string $notificationId
     */
    public function ipDeleteMonitoringNotification($ip, $notificationId)
    {
        self::getClient()->ipDeleteMonitoringNotification($this->id, $ip, $notificationId);
    }

    /**
     * Get lines
     *
     * @return array of string
     */
    public function getLines()
    {
        return json_decode(self::getClient()->getLines($this->id));
    }

    /**
     * Get line properties
     *
     * @todo : dispacth properties (eg getLineDeconsolidation, ...)
     *
     * @param string $line
     * @return object
     */
    public function getLineProperties($line)
    {
        return json_decode(self::getClient()->getLineProperties($this->id, $line));
    }

    /**
     * Reset Dslam port
     * @todo object task
     *
     * @param string $line
     * @return object Task
     */

    public function lineResetDslamPort($line)
    {
        return json_decode(self::getClient()->lineResetDslamPort($this->id, $line));
    }

    /**
     * @todo "Operator sfr not supported"
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function lineChangeDslamProfile()
    {
        throw new NotImplementedYetException;
    }

    /**
     * Get available Dslam profile for line $line
     *
     * @param $line
     * @return array of object DslamLineProfile
     */
    public function lineGetAvailableDslamProfiles($line)
    {
        return json_decode(self::getClient()->lineGetAvailableDslamProfiles($this->id, $line));
    }

    /**
     * returm modem properties
     *
     * @return object modem
     */
    public function getModemProperties()
    {
        return json_decode(self::getClient()->getModemProperties($this->id));
    }

    /**
     * Enable IPv6 routing
     *
     * @return object task
     */
    public function enableIpv6()
    {
        return json_decode(self::getClient()->enableIpv6($this->id));
    }

    /**
     * Disable IPv6 routing
     *
     * @return object task
     */
    public function disableIpv6()
    {
        return json_decode(self::getClient()->disableIpv6($this->id));
    }

    /**
     * Resquest ppp credentials (will be sent by mail)
     */
    public function getPppLoginByMail()
    {
        self::getClient()->getPppLoginByMail($this->id);
    }

    /**
     * @todo waiting for sandbox...
     *
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function requestTotalDeconsolidation()
    {
        throw new NotImplementedYetException;
    }

    /**
     * Get available Lns
     *
     * @return array of Lns Object (@todo lns object)
     */
    public function getAvailableLns()
    {
        return json_decode(self::getClient()->getAvailableLns($this->id));
    }

    /**
     * Change Lns
     *
     * @param  string $lnsName
     * @return object task
     */
    public function changeLns($lnsName)
    {
        return json_decode(self::getClient()->changeLns($this->id, $lnsName));
    }

}


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

package org.myrobotlab.service;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;

import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;

import wiiusej.WiiUseApiManager;
import wiiusej.Wiimote;
import wiiusej.wiiusejevents.physicalevents.ExpansionEvent;
import wiiusej.wiiusejevents.physicalevents.IREvent;
import wiiusej.wiiusejevents.physicalevents.MotionSensingEvent;
import wiiusej.wiiusejevents.physicalevents.WiimoteButtonsEvent;
import wiiusej.wiiusejevents.utils.WiimoteListener;
import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.DisconnectionEvent;
import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.NunchukInsertedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.NunchukRemovedEvent;
import wiiusej.wiiusejevents.wiiuseapievents.StatusEvent;

// http://diy.sickmods.net/Tutorials/Wii/Disassemble_Wiimote/
// http://procrastineering.blogspot.com/2008/09/working-with-pixart-camera-directly.html
// http://www.bot-thoughts.com/2010/12/connecting-mbed-to-wiimote-ir-camera.html

public class Wii extends Service implements WiimoteListener, SerialPortEventListener {

	public static class IRData implements Serializable {
		private static final long serialVersionUID = 1L;
		public long time;
		transient public IREvent event;

		public IRData(long t, int s) {
			this.time = t;
		}

		public IRData(long t, IREvent ir) {
			this.time = t;
			this.event = ir;
		}
	}

	private static final long serialVersionUID = 1L;

	public final static Logger log = LoggerFactory.getLogger(Wii.class);
	transient Wiimote[] wiimotes = null;
	transient Wiimote wiimote = null;
	int cnt = 0;

	boolean serialInitialized = false;

	private long bitCount = 0;

	private boolean strobeState = true;

	public static class Blah{
		public String name;
		Integer pos = 0;
		Integer x = 7;
	}

	public static void main(String[] args) {

		LoggingFactory.getInstance().configure();
		LoggingFactory.getInstance().setLevel(Level.DEBUG);
		try {

			Object object = new Object();
			Class c = Object.class;

			int loops = 1000000;

			long start = System.currentTimeMillis();
			for (int i = 0; i < loops; i++) {
				object.toString();
			}
			System.out.println(loops + " regular method calls:" + (System.currentTimeMillis() - start) + " milliseconds.");
			java.lang.reflect.Method method = c.getMethod("toString", null);
			HashMap<String, Method> mcache = new HashMap<String, Method>();
			mcache.put("toString", method);

			Blah blah = null;

			Integer xx = 7;
			Integer yy = 5;
			start = System.currentTimeMillis();
			for (int i = 0; i < loops; i++) {
				//method.invoke(object, null);
				//blah = new Blah();
				//blah.pos = i;
				xx = i;
				yy = i;
				method.invoke(mcache.get("toString"), null);
			}

			System.out.println(loops + " reflective method calls without lookup:" + (System.currentTimeMillis() - start) + " milliseconds.");
			start = System.currentTimeMillis();
			for (int i = 0; i < loops; i++) {
				//Integer x = new Integer(7);
				method = c.getMethod(String.format("%s","toString"), null);
				method.invoke(object, null);
			}
			System.out.println(loops + " reflective method calls with lookup:" + (System.currentTimeMillis() - start) + " milliseconds.");

			Wii wii = new Wii("wii");

			// add the port as a possible option for the Arduino
			/*
			 * Arduino.addPortName("wiicom", CommPortIdentifier.PORT_SERIAL,
			 * (CommDriver) new WiiDriver(wii));
			 */
			/*
			 * try { portId = CommPortIdentifier.getPortIdentifier("wiicom"); }
			 * catch (NoSuchPortException e1) { // TODO Auto-generated catch
			 * block e1.printStackTrace(); }
			 */
			Arduino arduino = new Arduino("arduino");
			arduino.startService();

			Servo servo = new Servo("servo");
			servo.startService();

			// GUIService gui = new GUIService("gui");
			// gui.startService();

			wii.getWiimotes();
			wii.initSerial();
			wii.setSensorBarAboveScreen();
			wii.activateIRTRacking();
			wii.setIrSensitivity(5); // 1-5 (highest)
			wii.activateListening();

		} catch (Exception e) {
			Logging.logError(e);
		}
	}

	public Wii(String n) {
		super(n);
	}

	public void activateIRTRacking() {
		wiimote.activateIRTRacking();
	}

	public void activateListening() {
		wiimote.addWiiMoteEventListeners(this);
	}

	// button publishing/event hooks end -------

	public void activateMotionSensing() {
		wiimote.activateMotionSensing();
	}

	@Override
	public String[] getCategories() {
		return new String[] { "sensor" };
	}

	@Override
	public String getDescription() {
		return "<html>wrapper service for wiiusej</html>";
	}

	public Wiimote[] getWiimotes() {
		wiimotes = WiiUseApiManager.getWiimotes(1, true);
		wiimote = wiimotes[0];
		return wiimotes;
	}

	public Wiimote[] getWiimotes(int n, boolean rumble) {
		return WiiUseApiManager.getWiimotes(n, rumble);
	}

	public boolean initSerial() {

		// magic 3 bytes - this is to synch the protocol
		// when the wii connects the leds are flashing
		// the arduino will disregard this garbage data
		// the wii should stop with the first led high
		// these 3 bytes should stop the arduino from
		// continuing to disregard
		// synced

		if (wiimote == null) {
			log.error("wii is not connected - can not initialize");
			log.error("please press the (1) & (2) buttons of the wii - and re-run program while lights are flashing");
			return false;
		}

		if (!serialInitialized) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logException(e);
			} // must slow down to initialize

			// force to correct state strobe state
			wiimote.setLeds(true, false, false, false);

			// break out of init
			wiimote.setLeds(false, false, true, false);
			wiimote.setLeds(true, false, false, false);
			wiimote.setLeds(false, false, false, false); // last 2 bits
															// disregarded !

			wiimote.setLeds(true, false, false, false);
			wiimote.setLeds(false, false, false, false);
			wiimote.setLeds(true, false, false, false); // last 2 bits
														// disregarded

			wiimote.setLeds(false, false, false, false);
			wiimote.setLeds(true, true, true, true);
			wiimote.setLeds(false, true, true, true);

			serialInitialized = true;
		} else {
			log.warn("wii serial already initialized");
		}

		return true;
	}

	// button publishing/event hooks begin -------
	public void onButtonDownJustPressed() {
		log.info("buttonDownJustPressed");
	}

	public void onButtonLeftJustPressed() {
		log.info("onButtonLeftJustPressed");
	}

	public void onButtonRightJustPressed() {
		log.info("onButtonRightJustPressed");
	}

	// TODO - support shutdown()
	@Override
	public void onButtonsEvent(WiimoteButtonsEvent arg0) {
		log.debug("{}", arg0);
		// if (arg0.isButtonAPressed()){
		// WiiUseApiManager.shutdown();
		// }

		if (arg0.isButtonDownJustPressed()) {
			invoke("onButtonDownJustPressed");
		}

		if (arg0.isButtonUpJustPressed()) {
			invoke("onButtonUpJustPressed");
		}

		if (arg0.isButtonLeftJustPressed()) {
			invoke("onButtonLeftJustPressed");
		}

		if (arg0.isButtonRightJustPressed()) {
			invoke("onButtonRightJustPressed");
		}
	}

	public void onButtonUpJustPressed() {
		log.info("onButtonUpJustPressed");
	}

	@Override
	public void onClassicControllerInsertedEvent(ClassicControllerInsertedEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClassicControllerRemovedEvent(ClassicControllerRemovedEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDisconnectionEvent(DisconnectionEvent arg0) {
		log.debug("disconnect event {}", arg0);
	}

	@Override
	public void onExpansionEvent(ExpansionEvent arg0) {
		log.debug("expansion event {}", arg0);
	}

	@Override
	public void onGuitarHeroInsertedEvent(GuitarHeroInsertedEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGuitarHeroRemovedEvent(GuitarHeroRemovedEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIrEvent(IREvent arg0) {
		// log.debug(arg0);
		++cnt;
		if (cnt % 100 == 0) {
			log.error("cnt {}", cnt);
		}
		IRData ir = new IRData(System.currentTimeMillis(), arg0);
		// t.add(ir);
		invoke("publishIR", ir);
	}

	@Override
	public void onMotionSensingEvent(MotionSensingEvent arg0) {
		log.debug("motion sensing event {}", arg0);
	}

	@Override
	public void onNunchukInsertedEvent(NunchukInsertedEvent arg0) {
		log.debug("NunchukInsertedEvent {}", arg0);
	}

	@Override
	public void onNunchukRemovedEvent(NunchukRemovedEvent arg0) {
		log.debug("NunchukRemovedEvent {}", arg0);
	}

	@Override
	public void onStatusEvent(StatusEvent arg0) {
		log.debug("status event {}", arg0);
	}

	public IRData publishIR(IRData ir) {
		return ir;
	}

	// NOT THREAD SAFE
	// true = 0 | false = 1 - thats how the hardware works :P
	public void sendSerial(int data) {
		if (!serialInitialized) {
			initSerial();
		}
		strobeState = (bitCount % 2 == 0);
		// 1st 3 MSB bits
		wiimote.setLeds(strobeState, (data & 128) == 0, (data & 64) == 0, (data & 32) == 0);
		++bitCount;
		// 2nd 3 bits
		wiimote.setLeds(!strobeState, (data & 16) == 0, (data & 8) == 0, (data & 4) == 0);
		++bitCount;
		// last 2 bits
		wiimote.setLeds(strobeState, (data & 2) == 0, (data & 1) == 0, false);

		++bitCount;

	}

	@Override
	public void serialEvent(SerialPortEvent arg0) {
		// TODO Auto-generated method stub
		log.info("serialEvent - YAY!");
	}

	public void setIrSensitivity(int level) {
		wiimote.setIrSensitivity(level);
	}

	public void setLeds(boolean l1, boolean l2, boolean l3, boolean l4) {
		wiimote.setLeds(l1, l2, l3, l4);
	}

	public void setSensorBarAboveScreen() {
		wiimote.setSensorBarAboveScreen();
	}

	public void setSensorBarBelowScreen() {
		wiimote.setSensorBarBelowScreen();
	}

}