text:
import requests

class Musixmatch(object):
    def __init__(self, apikey: str) -> None:
        """Define objects of type Musixmatch.

        Args:
            apikey ([str]): For get your apikey access: https://developer.musixmatch.com
        """
        self.__apikey = apikey
        self.__url = "http://api.musixmatch.com/ws/1.1/"

    def _get_url(self, url: str) -> str:
        """Get the url for the request.

        Args:
            url (str): The url for the request.

        Returns:
            str: The url for the request.
        """
        return f"{self.__url}{url}&apikey={self.__apikey}"

    @property
    def _apikey(self) -> str:
        """Get the apikey.

        Returns:
            str: The apikey.
        """
        return self.__apikey

    def _request(self, url: str) -> dict:
        """Get the request.

        Args:
            url (str): The url for the request.

        Returns:
            dict: The request.
        """
        request = requests.get(url)
        return request.json()

    def _set_page_size(self, page_size: int) -> int:
        """Set the page size.

        Args:
            page_size (int): The page size.

        Returns:
            int: The page size.
        """
        if page_size > 100:
            page_size = 100
        elif page_size < 1:
            page_size = 1
        return page_size

    def chart_artists(self, page, page_size, country="us", _format="json"):
        """This api provides you the list
        of the top artists of a given country.

        Parameters:

        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results (range 1 - 100).
        country - A valid country code (default US).
        format - Decide the output type json or xml (default json).
        """
        request = self._request(
            self._get_url(
                f"chart.artists.get?page={page}&page_size={self._set_page_size(page_size)}&country={country}&format={_format}",
            ),
        )
        return request

    def chart_tracks_get(
        self,
        page,
        page_size,
        f_has_lyrics,
        country="us",
        _format="json",
    ):
        """This api provides you the list
        of the top songs of a given country.

        Parameters:

        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results (range 1 - 100).
        f_has_lyrics - When set, filter only contents with lyrics.
        country - A valid country code (default US).
        format - Decide the output type json or xml (default json).
        """
        request = self._request(
            self._get_url(
                f"chart.tracks.get?page={page}&page_size={self._set_page_size(page_size)}&country={country}&format={_format}&f_has_lyrics={f_has_lyrics}",
            ),
        )
        return request

    def track_search(
        self,
        q_track,
        q_artist,
        page_size,
        page,
        s_track_rating,
        _format="json",
    ):
        """Search for track in our database.

        Parameters:

        q_track - The song title.
        q_artist - The song artist.
        q_lyrics - Any word in the lyrics.
        f_artist_id - When set, filter by this artist id.
        f_music_genre_id - When set, filter by this music category id.
        f_lyrics_language - Filter by the lyrics language (en,it,..).
        f_has_lyrics - When set, filter only contents with lyrics.
        f_track_release_group_first_release_date_min - When set, filter
        the tracks with release date newer than value, format is YYYYMMDD.
        f_track_release_group_first_release_date_max - When set, filter
        the tracks with release date older than value, format is YYYYMMDD.
        s_artist_rating - Sort by our popularity index for artists (asc|desc).
        s_track_rating - Sort by our popularity index for tracks (asc|desc).
        quorum_factor - Search only a part of the given query string.
        Allowed range is (0.1 – 0.9).
        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results.
        Range is 1 to 100.
        callback - jsonp callback.
        format - Decide the output type json or xml (default json).

        Note: This method requires a commercial plan.
        """
        data = self._request(
            self._get_url(
                "track.search?"
                "q_track={}&q_artist={}"
                "&page_size={}"
                "&page={}"
                "&s_track_rating={}&format={}".format(
                    q_track,
                    q_artist,
                    _set_page_size(page_size),
                    page,
                    s_track_rating,
                    _format,
                ),
            ),
        )
        return data

    def track_get(
        self,
        track_id,
        commontrack_id=None,
        track_isrc=None,
        track_mbid=None,
        _format="json",
    ):
        """Get a track info from our database:
        title, artist, instrumental flag and cover art.

        Parameters:

        track_id - The musiXmatch track id.
        commontrack_id - The musiXmatch commontrack id.
        track_isrc - A valid ISRC identifier.
        track_mbid - The musicbrainz recording id.
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "track.get?"
                "track_id={}&commontrack_id={}"
                "&track_isrc={}&track_mbid={}"
                "&format={}".format(
                    track_id,
                    commontrack_id,
                    track_isrc,
                    track_mbid,
                    _format,
                ),
            ),
        )
        return data

    def track_lyrics_get(self, track_id, commontrack_id=None, _format="json"):
        """Get the lyrics of a track.

        Parameters:

        track_id - The musiXmatch track id.
        track_mbid - The musicbrainz track id.
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                f"track.lyrics.get?track_id={track_id}&commontrack_id={commontrack_id}&format={_format}",
            ),
        )
        return data

    def track_snippet_get(self, track_id, _format="json"):
        """Get the snippet for a given track.

        A lyrics snippet is a very short representation of a song lyrics.
        It's usually twenty to a hundred characters long and it's calculated
        extracting a sequence of words from the lyrics.

        Parameters:

        track_id - The musiXmatch track id.
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(f"track.snippet.get?track_id={track_id}&format={_format}"),
        )
        return data

    def track_subtitle_get(
        self,
        track_id,
        track_mbid=None,
        subtitle_format=None,
        f_subtitle_length=None,
        f_subtitle_length_max_deviation=None,
        _format="json",
    ):
        """Retreive the subtitle of a track.

        Return the subtitle of a track in LRC or DFXP format.
        Refer to Wikipedia LRC format page or DFXP format on W3c
        for format specifications.

        Parameters:

        track_id - The musiXmatch track id.
        track_mbid - The musicbrainz track id.
        subtitle_format - The format of the subtitle (lrc,dfxp,stledu).
        Default to lrc.
        f_subtitle_length - The desired length of the subtitle (seconds).
        f_subtitle_length_max_deviation - The maximum deviation allowed.
        from the f_subtitle_length (seconds).
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "track.subtitle.get?"
                "track_id={}&track_mbid={}"
                "&subtitle_format={}"
                "&f_subtitle_length={}"
                "&f_subtitle_length_max_deviation={}"
                "&format={}".format(
                    track_id,
                    track_mbid,
                    subtitle_format,
                    f_subtitle_length,
                    f_subtitle_length_max_deviation,
                    _format,
                ),
            ),
        )
        return data

    def track_richsync_get(
        self,
        track_id,
        f_sync_length=None,
        f_sync_length_max_deviation=None,
        _format="json",
    ):
        """Get the Rich sync for a track.

        A rich sync is an enhanced version of the
        standard sync which allows:

        - position offset by single characther.
        - endless formatting options at single char level.
        - multiple concurrent voices.
        - multiple scrolling direction.

        Parameters:

        track_id - The musiXmatch track id.
        f_sync_length - The desired length of the sync (seconds).
        f_sync_length_max_deviation - The maximum deviation allowed.
        from the f_sync_length (seconds).
        """
        data = self._request(
            self._get_url(
                "track.richsync.get?"
                "track_id={}&f_sync_length={}"
                "&f_sync_length_max_deviation={}"
                "&format={}".format(
                    track_id,
                    f_sync_length,
                    f_sync_length_max_deviation,
                    _format,
                ),
            ),
        )
        return data

    def track_lyrics_post(self, track_id, lyrics_body, _format="json"):
        """Submit a lyrics to our database.

        It may happen we don't have the lyrics for a song,
        you can ask your users to help us sending the missing
        lyrics. We'll validate every submission and in case, make
        it available through our api.

        Please take all the necessary precautions to avoid users
        or automatic software to use your website/app to use this
        commands, a captcha solution like http://www.google.com/recaptcha
        or an equivalent one has to be implemented in every user
        interaction that ends in a POST operation on the musixmatch api.

        Parameters:

        track_id - A valid country code (default US)
        lyrics_body - The lyrics
        formatDecide the output type json or xml (default json)
        """
        data = self._request(
            self._get_url(
                "track.lyrics.post?track_id={}"
                "&lyrics_body={}&format={}".format(track_id, lyrics_body, _format),
            ),
        )
        return data

    def track_lyrics_feedback_post(self, track_id, lyrics_id, feedback, _format="json"):
        """This API method provides you the opportunity to help
        us improving our catalogue.

        We aim to provide you with the best quality service imaginable,
        so we are especially interested in your detailed feedback to help
        us to continually improve it.

        Please take all the necessary precautions to avoid users or
        automatic software to use your website/app to use this commands,
        a captcha solution like http://www.google.com/recaptcha or an
        equivalent one has to be implemented in every user interaction that
        ends in a POST operation on the musixmatch api.

        Parameters:

        lyrics_id - The musiXmatch lyrics id.
        track_id - The musiXmatch track id.
        feedback - The feedback to be reported, possible values are:
        wrong_lyrics, wrong_attribution, bad_characters,
        lines_too_long, wrong_verses, wrong_formatting
        format - Decide the output type json or xml (default json)
        """
        data = self._request(
            self._get_url(
                "track.lyrics.feedback.post?"
                "track_id={}&lyrics_id={}"
                "&feedback={}&format={}".format(track_id, lyrics_id, feedback, _format),
            ),
        )
        return data

    def matcher_lyrics_get(self, q_track, q_artist, _format="json"):
        """Get the lyrics for track based on title and artist.

        Parameters:

        q_track - The song title
        q_artist - The song artist
        track_isrc - If you have an available isrc id in your catalogue
        you can query using this id only (optional)
        format - Decide the output type json or xml (default json)
        """
        data = self._request(
            self._get_url(
                "matcher.lyrics.get?"
                "q_track={}&q_artist={}&format={}".format(q_track, q_artist, _format),
            ),
        )
        return data

    def matcher_track_get(self, q_track, q_artist, _format="json"):
        """Match your song against our database.

        In some cases you already have some informations
        about the track title, artist name, album etc.

        A possible strategy to get the corresponding lyrics could be:
        - search our catalogue with a perfect match,
        - maybe try using the fuzzy search,
        - maybe try again using artist aliases, and so on.

        The matcher.track.get method does all the job for you in
        a single call. This way you dont't need to worry about the
        details, and you'll get instant benefits for your application
        without changing a row in your code, while we take care of
        improving the implementation behind. Cool, uh?
        """
        data = self._request(
            self._get_url(
                "matcher.track.get?"
                "q_track={}&q_artist={}"
                "&format={}".format(q_track, q_artist, _format),
            ),
        )
        return data

    def matcher_subtitle_get(
        self,
        q_track,
        q_artist,
        f_subtitle_length,
        f_subtitle_length_max_deviation,
        track_isrc=None,
        _format="json",
    ):
        """Get the subtitles for a song given his title,artist and duration.

        You can use the f_subtitle_length_max_deviation to fetch subtitles
        within a given duration range.

        Parameters:

        q_track - The song title.
        q_artist - The song artist.
        f_subtitle_length - Filter by subtitle length in seconds.
        f_subtitle_length_max_deviation - Max deviation for a subtitle
        length in seconds.
        track_isrc - If you have an available isrc id in your catalogue
        you can query using this id only (optional).
        format - Decide the output type json or xml (default json).

        Note: This method requires a commercial plan.
        """
        data = self._request(
            self._get_url(
                "matcher.subtitle.get?q_track={}"
                "&q_artist={}&f_subtitle_length={}"
                "&f_subtitle_length_max_deviation={}"
                "&track_isrc={}&format={}".format(
                    q_track,
                    q_artist,
                    f_subtitle_length,
                    f_subtitle_length_max_deviation,
                    track_isrc,
                    _format,
                ),
            ),
        )
        return data

    def artist_get(self, artist_id, artist_mbid=None, _format="json"):
        """Get the artist data from our database.

        Parameters:

        artist_id - Musixmatch artist id.
        artist_mbid - Musicbrainz artist id.
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "artist.get?artist_id={}"
                "&artist_mbid={}&format={}".format(artist_id, artist_mbid, _format),
            ),
        )
        return data

    def artist_search(
        self,
        q_artist,
        page,
        page_size,
        f_artist_id,
        f_artist_mbid,
        _format="json",
    ):
        """Search for artists in our database.

        Parameters:

        q_artist - The song artist.
        f_artist_id - When set, filter by this artist id.
        f_artist_mbid - When set, filter by this artist musicbrainz id.
        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results
        (Range is 1 to 100).
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "artist.search?q_artist={}"
                "&f_artist_id={}&f_artist_mbid={}"
                "&page={}&page_size={}&format={}".format(
                    q_artist,
                    f_artist_id,
                    f_artist_mbid,
                    page,
                    _set_page_size(page_size),
                    _format,
                ),
            ),
        )
        return data

    def artist_albums_get(
        self,
        artist_id,
        g_album_name,
        page,
        page_size,
        s_release_date,
        artist_mbid=None,
        _format="json",
    ):
        """Get the album discography of an artist.

        Parameters:

        artist_id - Musixmatch artist id.
        artist_mbid - Musicbrainz artist id.
        g_album_name - Group by Album Name.
        s_release_date - Sort by release date (asc|desc).
        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results
        (range is 1 to 100).
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "artist.albums.get?artist_id={}"
                "&artist_mbid={}&g_album_name={}"
                "&s_release_date={}&page={}"
                "&page_size={}&format={}".format(
                    artist_id,
                    artist_mbid,
                    g_album_name,
                    s_release_date,
                    page,
                    _set_page_size(page_size),
                    _format,
                ),
            ),
        )
        return data

    def artist_related_get(
        self,
        artist_id,
        page,
        page_size,
        artist_mbid=None,
        _format="json",
    ):
        """Get a list of artists somehow related to a given one.

        Parameters:

        artist_id - The musiXmatch artist id.
        artist_mbid - The musicbrainz artist id.
        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results.
        (range is 1 to 100).
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "artist.related.get?artist_id={}"
                "&artist_mbid={}&page={}"
                "&page_size={}&format={}".format(
                    artist_id,
                    artist_mbid,
                    page,
                    _set_page_size(page_size),
                    _format,
                ),
            ),
        )
        return data

    def album_get(self, album_id, _format="json"):
        """Get an album from our database:
        name, release_date, release_type, cover art.

        Parameters:

        album_id - The musiXmatch album id.
        format - Decide the output type json or xml (default json)
        """
        data = self._request(
            self._get_url("album.get?album_id={}&format={}".format(album_id, _format)),
        )
        return data

    def album_tracks_get(
        self,
        album_id,
        page,
        page_size,
        album_mbid,
        f_has_lyrics=None,
        _format="json",
    ):
        """This api provides you the list of the songs of an album.

        Parameters:

        album_id - Musixmatch album id.
        album_mbid - Musicbrainz album id.
        f_has_lyrics - When set, filter only contents with lyrics.
        page - Define the page number for paginated results.
        page_size - Define the page size for paginated results.
        (range is 1 to 100).
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "album.tracks.get?album_id={}"
                "&album_mbid={}&f_has_lyrics={}"
                "&page={}&page_size={}&format={}".format(
                    album_id,
                    album_mbid,
                    f_has_lyrics,
                    page,
                    _set_page_size(page_size),
                    _format,
                ),
            ),
        )
        return data

    def tracking_url_get(self, domain, _format="json"):
        """Get the base url for the tracking script

        With this api you'll be able to get the base
        url for the tracking script you need to insert in
        your page to legalize your existent lyrics library.
        Read more here: rights-clearance-on-your-existing-catalog

        In case you're fetching the lyrics by the musiXmatch api
        called track.lyrics.get you don't need to implement this API call.

        Parameters:

        domain - Your domain name.
        format - Decide the output type json or xml (default json).
        """
        data = self._request(
            self._get_url(
                "tracking.url.get?" "domain={}&format={}".format(domain, _format),
            ),
        )
        return data

    def catalogue_dump_get(self, url):
        """Get the list of our songs with the lyrics last updated information.

        CATALOGUE_COMMONTRACKS

        Dump of our catalogue in this format:

        {
            "track_name": "Shape of you",
            "artist_name": "Ed Sheeran",
            "commontrack_id":12075763,
            "instrumental": false,
            "has_lyrics": yes,
            "updated_time": "2013-04-08T09:28:40Z"
        }

        Note: This method requires a commercial plan.
        """
        data = self._request(self._get_url(url))
        return data

    def genres_get(self, _format="json"):
        """Get the list of the music genres of our catalogue:
        music_genre_id, music_genre_parent_id, music_genre_name, music_genre_name_extended, music_genre_vanity

        Parameters:

        format - Decide the output type json or xml (default json)
        """
        data = self._request(
            self._get_url("music.genres.get?" "format={}".format(_format)),
        )
        return data


text:
package xworker.java.awt.layout;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.LayoutManager2;

import org.xmeta.ActionContext;
import org.xmeta.Thing;

public class BorderLayoutConstraintCreator {
	public static void create(ActionContext actionContext) {
		Thing self = (Thing) actionContext.get("self");

		Component parent = (Component) actionContext.get("parent");

		String constranit = self.getString("constranit");
		if("AFTER_LAST_LINE".equals(constranit)){
			constranit = BorderLayout.AFTER_LAST_LINE;
		}else if("AFTER_LINE_ENDS".equals(constranit)){
			constranit = BorderLayout.AFTER_LINE_ENDS;
		}else if("BEFORE_FIRST_LINE".equals(constranit)){
			constranit = BorderLayout.BEFORE_FIRST_LINE;
		}else if("BEFORE_LINE_BEGINS".equals(constranit)){
			constranit = BorderLayout.BEFORE_LINE_BEGINS;
		}else if("CENTER".equals(constranit)){
			constranit = BorderLayout.CENTER;
		}else if("EAST".equals(constranit)){
			constranit = BorderLayout.EAST;
		}else if("LINE_END".equals(constranit)){
			constranit = BorderLayout.LINE_END;
		}else if("LINE_START".equals(constranit)){
			constranit = BorderLayout.LINE_START;
		}else if("NORTH".equals(constranit)){
			constranit = BorderLayout.NORTH;
		}else if("PAGE_END".equals(constranit)){
			constranit = BorderLayout.PAGE_END;
		}else if("PAGE_START".equals(constranit)){
			constranit = BorderLayout.PAGE_START;
		}else if("SOUTH".equals(constranit)){
			constranit = BorderLayout.SOUTH;
		}else if("WEST".equals(constranit)){
			constranit = BorderLayout.WEST;
		}

		LayoutManager layoutMgr = parent.getParent().getLayout();
		if (layoutMgr != null) {
			if (layoutMgr instanceof LayoutManager2) {
				((LayoutManager2) layoutMgr).addLayoutComponent(parent, constranit);
			} else if (constranit instanceof String) {
				layoutMgr.addLayoutComponent((String) constranit, parent);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package ru.job4j.collections.list;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedContainer<T> implements Iterable<T> {
    protected Node<T> head;
    protected Node<T> tail;
    private int[] modCoun = new int[]{0};

    public void add(T value) {
        Node<T> a = new Node<>(value);

        if (head == null) {
            this.head = a;
            this.tail = a;
            this.head.next = this.tail;
        } else {
            this.tail.next = a;
            a.next = this.head;
            a.previous = this.tail;
            this.head.previous = a;
        }
        this.tail = a;
        this.modCoun[0]++;
    }

    public void addToBeginning(T value) {
        Node<T> a = new Node<>(value);
        if (head == null) {
            this.head = a;
            this.tail = a;
            this.head.next = this.tail;
            this.head.previous = this.tail;
        } else {
            a.next = this.head;
            this.head.previous = a;
            a.previous = this.tail;
            this.tail.next = a;
            this.head = a;
        }
    }

    public T getHead() {
        return this.head.data;
    }

    public T getTail() {
        return this.tail.data;
    }

    public T getData(int index) {
        if (index == 0) {
            return (T) head;
        }
        Node rsl = head;
        for (int i = 1; i <= index; i++) {
            rsl = rsl.next;
        }
        return (T) rsl.data;
    }

    public void deleteByIndex(int index) {
        if (index == 0) {
            deleteHead();
        }
        Node rsl = head;
        for (int i = 1; i <= index; i++) {
            rsl = rsl.next;
        }
        rsl.previous.next = rsl.next;
        rsl.next.previous = rsl.previous;

    }

    public void deleteHead() {
        if (this.head.next == this.head) {
            this.head = null;
            return;
        }
        this.tail.next = this.head.next;
        this.head.next.previous = this.tail;
        this.head = this.head.next;
    }

    public void deleteTail() {
        this.tail.previous.next = this.head;
        this.head.previous = this.tail.previous;
        this.tail = this.tail.previous;
    }

    public T poll() throws NoSuchElementException {
        if (this.head == null) {
            throw new NoSuchElementException("Нет элементов");
        }
        Node<T> returnedNode = this.head;
        this.deleteHead();
        return (T) returnedNode.data;
    }

    @Override
    public Iterator<T> iterator() {
        return new IteratorOfLinkedContainer<T>(this.head, this.modCoun);
    }

}


text:
"""
Custom element classes related to text runs (CT_R).
"""

from ..ns import qn
from ..simpletypes import ST_BrClear, ST_BrType
from ..xmlchemy import (
    BaseOxmlElement, OptionalAttribute, ZeroOrMore, ZeroOrOne
)

class CT_Br(BaseOxmlElement):
    """
    ``<w:br>`` element, indicating a line, page, or column break in a run.
    """
    type = OptionalAttribute('w:type', ST_BrType)
    clear = OptionalAttribute('w:clear', ST_BrClear)

class CT_R(BaseOxmlElement):
    """
    ``<w:r>`` element, containing the properties and text for a run.
    """
    rPr = ZeroOrOne('w:rPr')
    t = ZeroOrMore('w:t')
    br = ZeroOrMore('w:br')
    cr = ZeroOrMore('w:cr')
    tab = ZeroOrMore('w:tab')
    drawing = ZeroOrMore('w:drawing')

    def _insert_rPr(self, rPr):
        self.insert(0, rPr)
        return rPr

    def add_t(self, text):
        """
        Return a newly added ``<w:t>`` element containing *text*.
        """
        t = self._add_t(text=text)
        if len(text.strip()) < len(text):
            t.set(qn('xml:space'), 'preserve')
        return t

    def add_drawing(self, inline_or_anchor):
        """
        Return a newly appended ``CT_Drawing`` (``<w:drawing>``) child
        element having *inline_or_anchor* as its child.
        """
        drawing = self._add_drawing()
        drawing.append(inline_or_anchor)
        return drawing

    def clear_content(self):
        """
        Remove all child elements except the ``<w:rPr>`` element if present.
        """
        content_child_elms = self[1:] if self.rPr is not None else self[:]
        for child in content_child_elms:
            self.remove(child)

    @property
    def style(self):
        """
        String contained in w:val attribute of <w:rStyle> grandchild, or
        |None| if that element is not present.
        """
        rPr = self.rPr
        if rPr is None:
            return None
        return rPr.style

    @style.setter
    def style(self, style):
        """
        Set the character style of this <w:r> element to *style*. If *style*
        is None, remove the style element.
        """
        rPr = self.get_or_add_rPr()
        rPr.style = style

    @property
    def text(self):
        """
        A string representing the textual content of this run, with content
        child elements like ``<w:tab/>`` translated to their Python
        equivalent.
        """
        text = ''
        for child in self:
            if child.tag == qn('w:t'):
                t_text = child.text
                text += t_text if t_text is not None else ''
            elif child.tag == qn('w:tab'):
                text += '\t'
            elif child.tag in (qn('w:br'), qn('w:cr')):
                text += '\n'
        return text

    @text.setter
    def text(self, text):
        self.clear_content()
        _RunContentAppender.append_to_run_from_text(self, text)

class CT_Text(BaseOxmlElement):
    """
    ``<w:t>`` element, containing a sequence of characters within a run.
    """

class _RunContentAppender(object):
    """
    Service object that knows how to translate a Python string into run
    content elements appended to a specified ``<w:r>`` element. Contiguous
    sequences of regular characters are appended in a single ``<w:t>``
    element. Each tab character ('\t') causes a ``<w:tab/>`` element to be
    appended. Likewise a newline or carriage return character ('\n', '\r')
    causes a ``<w:cr>`` element to be appended.
    """
    def __init__(self, r):
        self._r = r
        self._bfr = []

    @classmethod
    def append_to_run_from_text(cls, r, text):
        """
        Create a "one-shot" ``_RunContentAppender`` instance and use it to
        append the run content elements corresponding to *text* to the
        ``<w:r>`` element *r*.
        """
        appender = cls(r)
        appender.add_text(text)

    def add_text(self, text):
        """
        Append the run content elements corresponding to *text* to the
        ``<w:r>`` element of this instance.
        """
        for char in text:
            self.add_char(char)
        self.flush()

    def add_char(self, char):
        """
        Process the next character of input through the translation finite
        state maching (FSM). There are two possible states, buffer pending
        and not pending, but those are hidden behind the ``.flush()`` method
        which must be called at the end of text to ensure any pending
        ``<w:t>`` element is written.
        """
        if char == '\t':
            self.flush()
            self._r.add_tab()
        elif char in '\r\n':
            self.flush()
            self._r.add_br()
        else:
            self._bfr.append(char)

    def flush(self):
        text = ''.join(self._bfr)
        if text:
            self._r.add_t(text)
        del self._bfr[:]


text:
<?php

final class PonderQuestionEditor
  extends PonderEditor {

  private $answer;

  public function getEditorObjectsDescription() {
    return pht('Ponder Questions');
  }

  /**
   * This is used internally on @{method:applyInitialEffects} if a transaction
   * of type PonderQuestionTransaction::TYPE_ANSWERS is in the mix. The value
   * is set to the //last// answer in the transactions. Practically, one
   * answer is given at a time in the application, though theoretically
   * this is buggy.
   *
   * The answer is used in emails to generate proper links.
   */
  private function setAnswer(PonderAnswer $answer) {
    $this->answer = $answer;
    return $this;
  }
  private function getAnswer() {
    return $this->answer;
  }

  protected function shouldApplyInitialEffects(
    PhabricatorLiskDAO $object,
    array $xactions) {

    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
        case PonderQuestionTransaction::TYPE_ANSWERS:
          return true;
      }
    }

    return false;
  }

  protected function applyInitialEffects(
    PhabricatorLiskDAO $object,
    array $xactions) {

    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
        case PonderQuestionTransaction::TYPE_ANSWERS:
          $new_value = $xaction->getNewValue();
          $new = idx($new_value, '+', array());
          foreach ($new as $new_answer) {
            $answer = idx($new_answer, 'answer');
            if (!$answer) {
              continue;
            }
            $answer->save();
            $this->setAnswer($answer);
          }
          break;
      }
    }
  }

  public function getTransactionTypes() {
    $types = parent::getTransactionTypes();

    $types[] = PhabricatorTransactions::TYPE_COMMENT;
    $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
    $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
    $types[] = PhabricatorTransactions::TYPE_SPACE;

    $types[] = PonderQuestionTransaction::TYPE_TITLE;
    $types[] = PonderQuestionTransaction::TYPE_CONTENT;
    $types[] = PonderQuestionTransaction::TYPE_ANSWERS;
    $types[] = PonderQuestionTransaction::TYPE_STATUS;
    $types[] = PonderQuestionTransaction::TYPE_ANSWERWIKI;

    return $types;
  }

  protected function getCustomTransactionOldValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PonderQuestionTransaction::TYPE_TITLE:
        return $object->getTitle();
      case PonderQuestionTransaction::TYPE_CONTENT:
        return $object->getContent();
      case PonderQuestionTransaction::TYPE_ANSWERS:
        return mpull($object->getAnswers(), 'getPHID');
      case PonderQuestionTransaction::TYPE_STATUS:
        return $object->getStatus();
      case PonderQuestionTransaction::TYPE_ANSWERWIKI:
        return $object->getAnswerWiki();
    }
  }

  protected function getCustomTransactionNewValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PonderQuestionTransaction::TYPE_TITLE:
      case PonderQuestionTransaction::TYPE_CONTENT:
      case PonderQuestionTransaction::TYPE_STATUS:
      case PonderQuestionTransaction::TYPE_ANSWERWIKI:
        return $xaction->getNewValue();
      case PonderQuestionTransaction::TYPE_ANSWERS:
        $raw_new_value = $xaction->getNewValue();
        $new_value = array();
        foreach ($raw_new_value as $key => $answers) {
          $phids = array();
          foreach ($answers as $answer) {
            $obj = idx($answer, 'answer');
            if (!$answer) {
              continue;
            }
            $phids[] = $obj->getPHID();
          }
          $new_value[$key] = $phids;
        }
        $xaction->setNewValue($new_value);
        return $this->getPHIDTransactionNewValue($xaction);
    }
  }

  protected function applyCustomInternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PonderQuestionTransaction::TYPE_TITLE:
        $object->setTitle($xaction->getNewValue());
        break;
      case PonderQuestionTransaction::TYPE_CONTENT:
        $object->setContent($xaction->getNewValue());
        break;
      case PonderQuestionTransaction::TYPE_STATUS:
        $object->setStatus($xaction->getNewValue());
        break;
      case PonderQuestionTransaction::TYPE_ANSWERWIKI:
        $object->setAnswerWiki($xaction->getNewValue());
        break;
      case PonderQuestionTransaction::TYPE_ANSWERS:
        $old = $xaction->getOldValue();
        $new = $xaction->getNewValue();

        $add = array_diff_key($new, $old);
        $rem = array_diff_key($old, $new);

        $count = $object->getAnswerCount();
        $count += count($add);
        $count -= count($rem);

        $object->setAnswerCount($count);
        break;
    }
  }

  protected function applyCustomExternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {
    return;
  }

  protected function mergeTransactions(
    PhabricatorApplicationTransaction $u,
    PhabricatorApplicationTransaction $v) {

    $type = $u->getTransactionType();
    switch ($type) {
      case PonderQuestionTransaction::TYPE_TITLE:
      case PonderQuestionTransaction::TYPE_CONTENT:
      case PonderQuestionTransaction::TYPE_STATUS:
      case PonderQuestionTransaction::TYPE_ANSWERWIKI:
        return $v;
    }

    return parent::mergeTransactions($u, $v);
  }

  protected function supportsSearch() {
    return true;
  }

  protected function shouldImplyCC(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PonderQuestionTransaction::TYPE_ANSWERS:
        return false;
    }

    return parent::shouldImplyCC($object, $xaction);
  }

  protected function shouldSendMail(
    PhabricatorLiskDAO $object,
    array $xactions) {
      foreach ($xactions as $xaction) {
        switch ($xaction->getTransactionType()) {
          case PonderQuestionTransaction::TYPE_ANSWERS:
            return false;
        }
      }
      return true;
  }

  protected function shouldPublishFeedStory(
    PhabricatorLiskDAO $object,
    array $xactions) {
      foreach ($xactions as $xaction) {
        switch ($xaction->getTransactionType()) {
          case PonderQuestionTransaction::TYPE_ANSWERS:
            return false;
        }
      }
      return true;
  }

  public function getMailTagsMap() {
    return array(
      PonderQuestionTransaction::MAILTAG_DETAILS =>
        pht('Someone changes the questions details.'),
      PonderQuestionTransaction::MAILTAG_ANSWERS =>
        pht('Someone adds a new answer.'),
      PonderQuestionTransaction::MAILTAG_COMMENT =>
        pht('Someone comments on the question.'),
      PonderQuestionTransaction::MAILTAG_OTHER =>
        pht('Other question activity not listed above occurs.'),
    );
  }

  protected function buildReplyHandler(PhabricatorLiskDAO $object) {
    return id(new PonderQuestionReplyHandler())
      ->setMailReceiver($object);
  }

  protected function buildMailTemplate(PhabricatorLiskDAO $object) {
    $id = $object->getID();
    $title = $object->getTitle();
    $original_title = $object->getOriginalTitle();

    return id(new PhabricatorMetaMTAMail())
      ->setSubject("Q{$id}: {$title}")
      ->addHeader('Thread-Topic', "Q{$id}: {$original_title}");
  }

  protected function buildMailBody(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $body = parent::buildMailBody($object, $xactions);

    $header = pht('QUESTION DETAIL');
    $uri = '/Q'.$object->getID();
    foreach ($xactions as $xaction) {
      $type = $xaction->getTransactionType();
      $old = $xaction->getOldValue();
      $new = $xaction->getNewValue();
      // If the user just asked the question, add the question text.
      if ($type == PonderQuestionTransaction::TYPE_CONTENT) {
        if ($old === null) {
          $body->addRawSection($new);
        }
      }
    }

    $body->addLinkSection(
      $header,
      PhabricatorEnv::getProductionURI($uri));

    return $body;
  }

  protected function shouldApplyHeraldRules(
    PhabricatorLiskDAO $object,
    array $xactions) {
    return true;
  }

  protected function buildHeraldAdapter(
    PhabricatorLiskDAO $object,
    array $xactions) {

    return id(new HeraldPonderQuestionAdapter())
      ->setQuestion($object);
  }

}


text:
title: XR
layout: usermanual-page.hbs
position: 20
---

![VR View][2]

PlayCanvas lets you create Augmented Reality (AR) and Virtual Reality (VR) applications for a variety of devices based on the new WebXR API, as well as through external integrations. WebXR is an evolution of the WebVR API and is being added to modern browsers, providing access to virtual reality headsets, controllers and AR features.

## Platforms

WebXR is a new API and it is being rolled out gradually to all major platforms. Up to date support can be checked on [caniuse.com][3].

Additionally, support can be achieved with the [WebXR Polyfill][4].

On **mobile**, PlayCanvas XR works on Android and iOS devices using Cardboard-style VR headsets and other devices. AR is also available. It works on stand-alone Android based VR devices, such as the Oculus Quest™.

On **desktop**, PlayCanvas XR currently works in Chrome and Edge, and devices are linked through various native APIs, such as Windows Mixed Reality, OpenXR and others. This covers the majority of desktop-based VR devices.

## Testing WebXR without XR device

To start developing with WebXR today, a browser [extension][1] can be used in Chrome or Firefox which emulates the WebXR API. This allows developers to interact with various head-mounted displays and controllers.

## Getting started with WebXR

To start an XR session, support and availability should be checked first. Then, on user interaction XR, a session can be started:

```javascript
button.element.on('click', function () {
    // check if XR is supported and VR is available
    if (app.xr.supported && app.xr.isAvailable(pc.XRTYPE_VR)) {
        // start VR using a camera component
        entity.camera.startXr(pc.XRTYPE_VR, pc.XRSPACE_LOCALFLOOR);
    }
});
```

[1]: https://github.com/MozillaReality/WebXR-emulator-extension
[2]: /images/user-manual/xr/vr-view.png
[3]: https://caniuse.com/#feat=webxr
[4]: https://github.com/immersive-web/webxr-polyfill


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

/**
 * @fileoverview Accesses Chrome's tabs extension API and gives
 * feedback for events that happen in the "Chrome of Chrome".
 */

goog.provide('cvox.TabsApiHandler');

goog.require('TabsAutomationHandler');
goog.require('cvox.AbstractEarcons');
goog.require('cvox.AbstractTts');
goog.require('cvox.BrailleInterface');
goog.require('cvox.ChromeVox');
goog.require('cvox.NavBraille');

/**
 * Class that adds listeners and handles events from the tabs API.
 * @constructor
 */
cvox.TabsApiHandler = function() {
  /** @type {function(string, Array<string>=)} @private */
  this.msg_ = Msgs.getMsg.bind(Msgs);
  /**
   * Tracks whether the active tab has finished loading.
   * @type {boolean}
   * @private
   */
  this.lastActiveTabLoaded_ = false;

  chrome.tabs.onCreated.addListener(this.onCreated.bind(this));
  chrome.tabs.onRemoved.addListener(this.onRemoved.bind(this));
  chrome.tabs.onActivated.addListener(this.onActivated.bind(this));
  chrome.tabs.onUpdated.addListener(this.onUpdated.bind(this));
  chrome.windows.onFocusChanged.addListener(this.onFocusChanged.bind(this));
};

cvox.TabsApiHandler.prototype = {
  /**
   * Handles chrome.tabs.onCreated.
   * @param {Object} tab
   */
  onCreated: function(tab) {
    if (!cvox.ChromeVox.isActive) {
      return;
    }
    cvox.ChromeVox.tts.speak(this.msg_('chrome_tab_created'),
                             cvox.QueueMode.FLUSH,
                             cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);
    cvox.ChromeVox.braille.write(
        cvox.NavBraille.fromText(this.msg_('chrome_tab_created')));
    cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_OPEN);
    this.refreshAutomationHandler_(tab.id);
  },

  /**
   * Handles chrome.tabs.onRemoved.
   * @param {Object} tab
   */
  onRemoved: function(tab) {
    if (!cvox.ChromeVox.isActive) {
      return;
    }
    cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_CLOSE);
  },

  /**
   * Handles chrome.tabs.onActivated.
   * @param {Object} activeInfo
   */
  onActivated: function(activeInfo) {
    if (!cvox.ChromeVox.isActive) {
      return;
    }
    chrome.tabs.get(activeInfo.tabId, function(tab) {
      this.lastActiveTabLoaded_ = tab.status == 'complete';
      if (tab.status == 'loading') {
        return;
      }
      var title = tab.title ? tab.title : tab.url;
      cvox.ChromeVox.tts.speak(this.msg_('chrome_tab_selected',
                                         [title]),
                               cvox.QueueMode.FLUSH,
                               cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);
      cvox.ChromeVox.braille.write(
          cvox.NavBraille.fromText(this.msg_('chrome_tab_selected', [title])));
      cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_SELECT);
    }.bind(this));
  },

  /**
   * Handles chrome.tabs.onUpdated.
   * @param {number} tabId
   * @param {Object} selectInfo
   */
  onUpdated: function(tabId, selectInfo) {
    if (!cvox.ChromeVox.isActive) {
      return;
    }
    chrome.tabs.get(tabId, function(tab) {
      if (!tab.active) {
        return;
      }
      if (tab.status == 'loading') {
        this.lastActiveTabLoaded_ = false;
        cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.PAGE_START_LOADING);
      } else if (!this.lastActiveTabLoaded_) {
        this.lastActiveTabLoaded_ = true;
        cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.PAGE_FINISH_LOADING);
      }
      this.refreshAutomationHandler_(tabId);
    }.bind(this));
  },

  /**
   * Handles chrome.windows.onFocusChanged.
   * @param {number} windowId
   */
  onFocusChanged: function(windowId) {
    if (!cvox.ChromeVox.isActive) {
      return;
    }
    if (windowId == chrome.windows.WINDOW_ID_NONE) {
      return;
    }
    chrome.windows.get(windowId, function(window) {
      chrome.tabs.query({active: true, windowId: windowId}, function(tabs) {
        var msgId = window.incognito ? 'chrome_incognito_window_selected' :
            'chrome_normal_window_selected';
        var tab = tabs[0] || {};
        var title = tab.title ? tab.title : tab.url;
        cvox.ChromeVox.tts.speak(this.msg_(msgId, [title]),
                                 cvox.QueueMode.FLUSH,
                                 cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);
        cvox.ChromeVox.braille.write(
            cvox.NavBraille.fromText(this.msg_(msgId, [title])));
        cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_SELECT);
        this.refreshAutomationHandler_(tab.id);
      }.bind(this));
    }.bind(this));
  },

  /**
   * Installs a new automation handler for the given tab.
   * @param {number} tabId
   * @private
   */
  refreshAutomationHandler_: function(tabId) {
    if (!cvox.ChromeVox.isMac)
      return;

    chrome.automation.getTree(tabId, function(node) {
      if (this.handler_)
        this.handler_.unregister();

      this.handler_ = new TabsAutomationHandler(node);
    }.bind(this));
  }
};


text:
http://dasheyuan.com/post/openstack-dev-environment/

http://chenyingkof.iteye.com/blog/2233315

http://blog.csdn.net/wenwenxiong/article/details/52700833

http://yikun.github.io/2016/02/23/%E4%BC%98%E9%9B%85%E5%9C%B0%E8%B0%83%E8%AF%95OpenStack/

https://osxfuse.github.io/

sshfs stack@192.168.35.10:/opt/stack /Users/yuliyang/openstack/code

eventlet.monkey_patch(all=False, socket=True, time=True, thread=False)

```
proxychains git clone https://git.openstack.org/openstack-dev/devstack -b stable/newton
./tools/create-stack-user.sh

[stack@devstack devstack]$ cat ~/.pip/pip.conf
[global]
default-timeout = 60
index-url = https://pypi.python.org/simple/

[install]
index-url = https://pypi.python.org/simple/

/etc/yum.conf
keepcache=1

sudo proxychains yum install -y https://www.rdoproject.org/repos/rdo-release.rpm
sudo yum makecache
sudo proxychains yum remove mariadb-libs mariadb mariadb-common mariadb-config -y
sudo proxychains yum install python-pip gcc openssl-devel python-psycopg2 postgresql-devel screen memcached mariadb-server ebtables bridge-utils -y
sudo proxychains pip install --upgrade pip
sudo proxychains pip install -U os-testr

export http_proxy=http://192.168.153.1:7777
export https_proxy=http://192.168.153.1:7777
export no_proxy=127.0.0.1,192.168.153.159

vi local.conf
[[local|localrc]]
DEST=/opt/stack
DOWNLOAD_DEFAULT_IMAGES=False
IMAGE_URLS="http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-disk.img"
HOST_IP=192.168.153.159
SERVICE_IP_VERSION=4
FLAT_INTERFACE=ens33
FLOATING_RANGE="192.168.153.0/24"
FIXED_RANGE="10.0.0.0/24"
Q_FLOATING_ALLOCATION_POOL=start=192.168.153.102,end=192.168.153.110
#PUBLIC_INTERFACE=ens33
PUBLIC_NETWORK_GATEWAY="192.168.153.1"
LIBVIRT_TYPE = qemu

RECLONE=no
GIT_BASE=http://git.trystack.cn
NOVNC_REPO=http://git.trystack.cn/kanaka/noVNC.git
SPICE_REPO=http://git.trystack.cn/git/spice/spice-html5.git
ENABLE_IDENTITY_V2=True

#OFFLINE=True
RECLONE=no
HORIZON_BRANCH=stable/newton
KEYSTONE_BRANCH=stable/newton
NOVA_BRANCH=stable/newton
NEUTRON_BRANCH=stable/newton
GLANCE_BRANCH=stable/newton
CINDER_BRANCH=stable/newton
NOVNC_BRANCH=v0.6.2

ADMIN_PASSWORD=openstack
DATABASE_PASSWORD=openstack
RABBIT_PASSWORD=openstack
SERVICE_PASSWORD=$ADMIN_PASSWORD
LOGDIR=$DEST/logs
LOGFILE=$DEST/logs/stack.sh.log
LOGDAYS=2

ENABLED_SERVICES=rabbit,mysql,key
ENABLED_SERVICES+=,n-api,n-crt,n-obj,n-cpu,n-cond,n-sch,n-novnc,n-cauth
ENABLED_SERVICES+=,g-api,g-reg
ENABLED_SERVICES+=,horizon
ENABLED_SERVICES+=,cinder,c-api,c-vol,c-sch,c-bak

# Neutron
DISABLED_SERVICES=n-net
ENABLED_SERVICES+=,q-svc,q-agt,q-dhcp,q-l3,q-meta,q-metering,neutron
PUBLIC_INTERFACE=eth0
Q_PLUGIN=ml2
ENABLE_TENANT_VLANS=True

This is your host IP address: 192.168.153.159
This is your host IPv6 address: ::1
Horizon is now available at http://192.168.153.159/dashboard
Keystone is serving at http://192.168.153.159/identity/
The default users are: admin and demo
The password: openstack
```

## yum repos
custum.repo

```
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
gpgcheck=0

#released updates
[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/updates/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
gpgcheck=0

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/extras/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
gpgcheck=0

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/centosplus/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/centosplus/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
gpgcheck=0
enabled=0

#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/contrib/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/contrib/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
gpgcheck=0
enabled=0

[openstack]
name=openstack
baseurl=http://mirror.centos.org/centos/7/cloud/x86_64/openstack-newton/
enabled=1
gpgcheck=0
```

epel.repo
```
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=0

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch/debug
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch
failovermethod=priority
enabled=0
gpgcheck=0

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/7/SRPMS
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch
failovermethod=priority
enabled=0
gpgcheck=0
```

epel-testing.repo
```
[epel-testing]
name=Extra Packages for Enterprise Linux 7 - Testing - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/testing/7/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=testing-epel7&arch=$basearch
failovermethod=priority
enabled=0
gpgcheck=0

[epel-testing-debuginfo]
name=Extra Packages for Enterprise Linux 7 - Testing - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/testing/7/$basearch/debug
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=testing-debug-epel7&arch=$basearch
failovermethod=priority
enabled=0
gpgcheck=0

[epel-testing-source]
name=Extra Packages for Enterprise Linux 7 - Testing - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/testing/7/SRPMS
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=testing-source-epel7&arch=$basearch
failovermethod=priority
enabled=0
gpgcheck=0
```

```
This is your host IP address: 192.168.153.159
This is your host IPv6 address: ::1
Horizon is now available at http://192.168.153.159/dashboard
Keystone is serving at http://192.168.153.159/identity/
The default users are: admin and demo
The password: openstack
```

```
export OS_TENANT_NAME=admin
export OS_USERNAME=admin
export OS_PASSWORD=openstack
export OS_AUTH_URL="http://192.168.153.159:5000/v2.0"
export OS_ENDPOINT="http://192.168.153.159:35357/v2.0"
```
or
```
         project  user
. openrc  admin  admin
. openrc  admin  demo
. openrc  demo   demo
```

```
sudo iptables -I INPUT -s 0/0 -p tcp --dport 80 -j ACCEPT
sudo iptables -I INPUT -s 0/0 -p tcp --dport 6080 -j ACCEPT
http://192.168.153.159/dashboard
admin
openstack

systemctl start httpd
systemctl enable httpd
screen -c devstack/stack-screenrc
openstack security group rule create --protocol tcp --dst-port 22 default
openstack security group rule create --protocol icmp --dst-port -1 default

https://communities.cisco.com/community/developer/openstack/blog/2016/12/03/how-to-stack-devstack-newton-on-centos-7-in-virtualbox-on-mac
```
```
+-------------+----------------+--------------------------------------------------------------------------------+
| Name        | Type           | Endpoints                                                                      |
+-------------+----------------+--------------------------------------------------------------------------------+
| glance      | image          | RegionOne                                                                      |
|             |                |   publicURL: http://192.168.153.159:9292                                       |
|             |                |   internalURL: http://192.168.153.159:9292                                     |
|             |                |   adminURL: http://192.168.153.159:9292                                        |
|             |                |                                                                                |
| nova        | compute        | RegionOne                                                                      |
|             |                |   publicURL: http://192.168.153.159:8774/v2.1                                  |
|             |                |   internalURL: http://192.168.153.159:8774/v2.1                                |
|             |                |   adminURL: http://192.168.153.159:8774/v2.1                                   |
|             |                |                                                                                |
| nova_legacy | compute_legacy | RegionOne                                                                      |
|             |                |   publicURL: http://192.168.153.159:8774/v2/3824fdf4a57d436f8462cd41658ef929   |
|             |                |   internalURL: http://192.168.153.159:8774/v2/3824fdf4a57d436f8462cd41658ef929 |
|             |                |   adminURL: http://192.168.153.159:8774/v2/3824fdf4a57d436f8462cd41658ef929    |
|             |                |                                                                                |
| keystone    | identity       | RegionOne                                                                      |
|             |                |   publicURL: http://192.168.153.159/identity                                   |
|             |                |   internalURL: http://192.168.153.159/identity                                 |
|             |                |   adminURL: http://192.168.153.159/identity_v2_admin                           |
|             |                |                                                                                |
| neutron     | network        | RegionOne                                                                      |
|             |                |   publicURL: http://192.168.153.159:9696/                                      |
|             |                |   internalURL: http://192.168.153.159:9696/                                    |
|             |                |   adminURL: http://192.168.153.159:9696/                                       |
|             |                |                                                                                |
+-------------+----------------+--------------------------------------------------------------------------------+

```

![http://7o504d.com1.z0.glb.clouddn.com/tXNYvqK.png](http://7o504d.com1.z0.glb.clouddn.com/tXNYvqK.png)

pxe问题
```
#更新qemu版本
[root@ceph04 ~]# rpm -qa|grep qemu-kvm
qemu-kvm-common-ev-2.6.0-27.1.el7.x86_64
qemu-kvm-ev-2.6.0-27.1.el7.x86_64

yum install openstack-neutron-linuxbridge
```


text:
var amqp = require('amqplib');
module.exports = function(app) {
    "use strict";
    var topic = "serverRequest.*";
    var exchange = "serverRequest";
    amqp.connect('amqp://localhost').then(function(conn) {
        process.once('SIGINT', function() { conn.close(); });
        return conn.createChannel().then(function(ch) {
            var ex = "serverRequest";
            var ok = ch.assertExchange(ex, 'topic', {durable: false});

            ok = ok.then(function() {
                return ch.assertQueue('servQueue', {exclusive: true});
            });

            ok = ok.then(function(qok) {
                var queue = qok.queue;
                ch.bindQueue(queue, ex, topic);
                return queue;
            });

            ok = ok.then(function(queue) {
                return ch.consume(queue, emit, {noAck: true});
            });

            var emit = function(message) {
                var response;
                console.log(" [x] %s:'%s'",
                    message.fields.routingKey,
                    message.content.toString());
                try{
                    var json = JSON.parse(message.content.toString());
                    console.log("emit " + json.message);
                    if (app.middleware.socketConnection.socket && app.middleware.socketConnection.socket.connected) {
                        app.middleware.socketConnection.socket.emit(json.message, json.data);
                        response = {"status": "SENDED"};
                        ch.sendToQueue(message.properties.replyTo,
                            new Buffer(JSON.stringify(response)));
                    } else {
                        response = {"status": "NOT_CONNECTED"};
                        ch.sendToQueue(message.properties.replyTo,
                            new Buffer(JSON.stringify(response)));
                    }
                } catch (e) {
                    console.log("unable to parse "+message);
                }
            };
            return ok.then(function() {
                console.log(' [*] Waiting for logs. To exit press CTRL+C.');
            });

        });
    }).then(null, console.warn);
};


text:
```js
// ./resources/preprocessor.js
var babel = require('babel-core');
var PreprocessorAdapter = require('preprocessor-adapter');

module.exports = PreprocessorAdapter.create({
  extensions: ['.js', 'jsx'],
  filter: function(file) {
    // not in "node_modules"
    return !/\bnode_modules\b/.test(file);
  },
  transform: function(src, file) {
    return babel.transform({loose: 'all'});
  }
});
```

```js
// node
require('./resources/preprocessor').register();

// browserify
browserify('main.js')
  .transform(require('./resources/preprocessor'))
  .bundle()
  .pipe(fs.createWriteStream('bundle.js'));

// jest (in package.json)
{
  "jest": {
    "scriptPreprocessor": "<rootDir>/resources/preprocessor.js"
  }
}
```


text:
<!DOCTYPE html>

	<title>The PostgreSQL JDBC Interface</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="description" content="The official documentation for the PostgreSQL JDBC Driver" />
	<meta name="copyright" content="The PostgreSQL Global Development Group" />

	<link rel="stylesheet" type="text/css" href="media/css/syntax.css">

	<link rel="shortcut icon" href="media/favicon.ico" />

The PostgreSQL JDBC Interface

Table of Contents

1. Introduction

2. Setting up the JDBC Driver

Getting the Driver

Setting up the Class Path

Preparing the Database Server for <acronym class="ACRONYM">JDBC</acronym>

Creating a Database

3. Initializing the Driver

Importing <acronym class="ACRONYM">JDBC</acronym>

Loading the Driver

Connecting to the Database

Connection Parameters

4. Using <acronym class="ACRONYM">SSL</acronym>

Configuring the Server

Configuring the Client

Using SSL without Certificate Validation

Custom SSLSocketFactory

5. Issuing a Query and Processing the Result

Getting results based on a cursor

Using the Statement or PreparedStatement Interface

Using the ResultSet Interface

Performing Updates

Creating and Modifying Database Objects

Using Java 8 Date and Time classes

6. Calling Stored Functions

Obtaining a ResultSet from a stored function

From a Function Returning SETOF type

From a Function Returning a refcursor

7. Storing Binary Data

8. <acronym class="ACRONYM">JDBC</acronym> escapes

Escape for like escape character

Escape for outer joins

Date-time escapes

Escaped scalar functions

9. PostgreSQL™ Extensions to the <acronym class="ACRONYM">JDBC</acronym> <acronym class="ACRONYM">API</acronym>

Accessing the Extensions

Geometric Data Types

Large Objects

Listen / Notify

Server Prepared Statements

Physical and Logical replication API

10. Using the Driver in a Multithreaded or a Servlet Environment

11. Connection Pools and Data Sources

Overview

Application Servers: ConnectionPoolDataSource

Applications: DataSource

Tomcat setup

Data Sources and <acronym class="ACRONYM">JNDI</acronym>

12. Logging with java.util.logging

13. Further Reading

List of Tables

								8.1. Supported escaped numeric functions

								8.2. Supported escaped string functions

								8.3. Supported escaped date/time functions

								8.4. Supported escaped misc functions

								11.1. ConnectionPoolDataSource Configuration Properties

								11.2. DataSource Implementations

								11.3. DataSource Configuration Properties

								11.4. Additional Pooling DataSource Configuration Properties

List of Examples

								5.1. Processing a Simple Query in <acronym class="ACRONYM">JDBC</acronym>

								5.2. Setting fetch size to turn cursors on and off.

								5.3. Deleting Rows in <acronym class="ACRONYM">JDBC</acronym>

								5.4. Dropping a Table in <acronym class="ACRONYM">JDBC</acronym>

								6.1. Calling a built in stored function

								6.2.  Getting SETOF type values from a function

								6.3.  Getting refcursor Value From a Function

								6.4. Treating refcursor as a cursor name

								7.1. Processing Binary Data in <acronym class="ACRONYM">JDBC</acronym>

								8.1. Using jdbc escapes

								9.1. Using the CIRCLE datatype from <acronym class="ACRONYM">JDBC</acronym>

								9.2. Receiving Notifications

								9.3. Using server side prepared statements

								11.1. DataSource Code Example

								11.2. DataSource <acronym class="ACRONYM">JNDI</acronym> Code Example

      							Next

							Chapter 1. Introduction

				Privacy Policy |
				About PostgreSQL

				Copyright © 1996-2017 The PostgreSQL Global Development Group


text:
package edu.pdx.cs410J.lang;

/**
 * This class is the base class in our animal hierarchy.  Each animal
 * has a name and it makes a sound.
 */
public abstract class Animal {
  protected String name;

  /**
   * Returns the name of this animal.
   */
  public final String getName() {
    return this.name;
  }

  /**
   * Returns the sound that this animal makes.
   */
  public abstract String says();

  public String toString() {
    return getName() + " says " + says();
  }
}


text:
package java.awt;

import gnu.java.awt.java2d.AlphaCompositeContext;

import java.awt.image.ColorModel;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author Eric Blake (ebb9@email.byu.edu)
 * @see Composite
 * @see CompositeContext
 * @since 1.3
 * @status updated to 1.4 except for createContext, needs documentation
 */
public final class AlphaComposite implements Composite
{
  /** Map Long to AlphaComposites. See getInstance for details. */
  private static final LinkedHashMap cache = new LinkedHashMap(11, 0.75f, true)
  {
    /** The largest the alpha composite cache can grow. */
    private static final int MAX_CACHE_SIZE = 2048;

    /** Prune stale entries. */
    protected boolean removeEldestEntry(Map.Entry eldest)
    {
      return size() > MAX_CACHE_SIZE;
    }
  };

  public static final int CLEAR = 1;
  public static final int SRC = 2;
  public static final int DST = 9;
  public static final int SRC_OVER = 3;
  public static final int DST_OVER = 4;
  public static final int SRC_IN = 5;
  public static final int DST_IN = 6;
  public static final int SRC_OUT = 7;
  public static final int DST_OUT = 8;
  public static final int SRC_ATOP = 10;
  public static final int DST_ATOP = 11;
  public static final int XOR = 12;
  public static final AlphaComposite Clear = getInstance(CLEAR);
  public static final AlphaComposite Src = getInstance(SRC);
  public static final AlphaComposite Dst = getInstance(DST);
  public static final AlphaComposite SrcOver = getInstance(SRC_OVER);
  public static final AlphaComposite DstOver = getInstance(DST_OVER);
  public static final AlphaComposite SrcIn = getInstance(SRC_IN);
  public static final AlphaComposite DstIn = getInstance(DST_IN);
  public static final AlphaComposite SrcOut = getInstance(SRC_OUT);
  public static final AlphaComposite DstOut = getInstance(DST_OUT);
  public static final AlphaComposite SrcAtop = getInstance(SRC_ATOP);
  public static final AlphaComposite DstAtop = getInstance(DST_ATOP);
  public static final AlphaComposite Xor = getInstance(XOR);

  private final int rule;
  private final float alpha;
  private AlphaComposite(int rule, float alpha)
  {
    this.rule = rule;
    this.alpha = alpha;
  }

  /**
   * Creates an AlphaComposite object with the specified rule.
   *
   * @param rule The compositing rule.
   *
   * @exception IllegalArgumentException If rule is not one of the following:
   * CLEAR, SRC, DST, SRC_OVER, DST_OVER, SRC_IN, DST_IN, SRC_OUT, DST_OUT,
   * SRC_ATOP, DST_ATOP, or XOR.
   */
  public static AlphaComposite getInstance(int rule)
  {
    return getInstance(rule, 1);
  }

  /**
   * Creates an AlphaComposite object with the specified rule and the constant
   * alpha to multiply with the alpha of the source. The source is multiplied
   * with the specified alpha before being composited with the destination.
   *
   * @param rule The compositing rule.
   *
   * @exception IllegalArgumentException If rule is not one of the following:
   * CLEAR, SRC, DST, SRC_OVER, DST_OVER, SRC_IN, DST_IN, SRC_OUT, DST_OUT,
   * SRC_ATOP, DST_ATOP, or XOR.
   */
  public static AlphaComposite getInstance(int rule, float alpha)
  {
    if (rule < CLEAR || rule > XOR || ! (alpha >= 0 && alpha <= 1))
      throw new IllegalArgumentException();
    // This long is guaranteed unique for all valid alpha composites.
    Long l = new Long(rule + Double.doubleToLongBits(alpha));
    AlphaComposite a = (AlphaComposite) cache.get(l);
    if (a == null)
      {
        a = new AlphaComposite(rule, alpha);
        cache.put(l, a);
      }
    return a;
  }

  /**
   * Creates a {@link CompositeContext} that can be used to perform
   * compositing operations according to this AlphaComposite settings.
   *
   * @param srcColorModel the color model of the source raster
   * @param dstColorModel the color model of the destination raster
   * @param hints the rendering hints to use
   *
   * @return a {@link CompositeContext} that can be used to perform
   *         compositing operations according to this AlphaComposite settings
   */
  public CompositeContext createContext(ColorModel srcColorModel,
                                        ColorModel dstColorModel,
                                        RenderingHints hints)
  {
    return new AlphaCompositeContext(this, srcColorModel, dstColorModel);
  }

  /**
   * Return an AlphaComposite similar to this,
   * that uses the specified rule. If rule is the same as
   * this.rule, then this is returned.
   *
   * @since 1.6
   */
  public AlphaComposite derive(int rule)
  {
    if (this.rule == rule)
      return this;
    else
      return AlphaComposite.getInstance(rule, this.getAlpha());
  }

  /**
   * Return an AlphaComposite similar to this,
   * that uses the specified alpha.
   *
   * If alph is the same as this.alpha,
   * then this is returned.
   *
   * @since 1.6
   */
  public AlphaComposite derive(float alpha)
  {
      if (this.getAlpha() == alpha)
        return this;
      else
        return AlphaComposite.getInstance(this.getRule(), alpha);
  }

  public float getAlpha()
  {
    return alpha;
  }

  public int getRule()
  {
    return rule;
  }

  public int hashCode()
  {
    return 31 * Float.floatToIntBits(alpha) + rule;
  }

  public boolean equals(Object o)
  {
    if (! (o instanceof AlphaComposite))
      return false;
    AlphaComposite a = (AlphaComposite) o;
    return rule == a.rule && alpha == a.alpha;
  }
} // class AlphaComposite


text:
START_ATF_NAMESPACE
    typedef __int16 *PINT16;
END_ATF_NAMESPACE


text:
const validate = require('jsonschema').validate;

exports.authSchema = {
  id: 'auth params',
  type: "object",
  response_type: { type: 'string' },
  client_id: { type: 'string' },
  scope: { type: 'string' },
  redirect_uri: { type: 'string' },
  required: [ 'response_type', 'client_id', 'redirect_uri' ]
}

exports.configSchema = {
  id: 'configuration',
  type: 'object',
  state: {
    type: 'object',
    client: { type: 'string' },
    required: [ 'client' ] // TODO: incomplete
  },
  required: [ 'state', 'login_url' ]
}

exports.displayableValidationErrors = function(errors) {
  return errors.map(function(e) { return e.message; }).join(', ');
}

exports.validationErrors = function(what, schema) {
  var errors = validate(what, schema).errors
  if (errors.length) {
    return exports.displayableValidationErrors(errors)
  } else {
    return;
  }
}

exports.validate = validate


text:
package com.example.fishweather.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.example.fishweather.db.UserCity;
import com.example.fishweather.service.WeatherService;

import java.util.List;

/**
 * Created by Administrator on 2017/3/31 0031.
 */

public class BaseActivity extends AppCompatActivity {

    protected WeatherService weatherService;
    protected boolean isBound;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isBound = false;
    }

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

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

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WeatherService.ServiceBinder binder = (WeatherService.ServiceBinder) service;
            weatherService = (WeatherService) binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    public void bindWeatherService(){
        if(!isBound) {
            isBound = true;
            Intent intent = new Intent(this, WeatherService.class);
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }

    public void unbindWeatherService(){
        if(isBound) {
            isBound = false;
            unbindService(connection);
        }
    }
}


text:
package com.google.cloud.scheduler.v1beta1;

import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class JobName implements ResourceName {
  private static final PathTemplate PROJECT_LOCATION_JOB =
      PathTemplate.createWithoutUrlEncoding("projects/{project}/locations/{location}/jobs/{job}");
  private volatile Map<String, String> fieldValuesMap;
  private final String project;
  private final String location;
  private final String job;

  @Deprecated
  protected JobName() {
    project = null;
    location = null;
    job = null;
  }

  private JobName(Builder builder) {
    project = Preconditions.checkNotNull(builder.getProject());
    location = Preconditions.checkNotNull(builder.getLocation());
    job = Preconditions.checkNotNull(builder.getJob());
  }

  public String getProject() {
    return project;
  }

  public String getLocation() {
    return location;
  }

  public String getJob() {
    return job;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  public static JobName of(String project, String location, String job) {
    return newBuilder().setProject(project).setLocation(location).setJob(job).build();
  }

  public static String format(String project, String location, String job) {
    return newBuilder().setProject(project).setLocation(location).setJob(job).build().toString();
  }

  public static JobName parse(String formattedString) {
    if (formattedString.isEmpty()) {
      return null;
    }
    Map<String, String> matchMap =
        PROJECT_LOCATION_JOB.validatedMatch(
            formattedString, "JobName.parse: formattedString not in valid format");
    return of(matchMap.get("project"), matchMap.get("location"), matchMap.get("job"));
  }

  public static List<JobName> parseList(List<String> formattedStrings) {
    List<JobName> list = new ArrayList<>(formattedStrings.size());
    for (String formattedString : formattedStrings) {
      list.add(parse(formattedString));
    }
    return list;
  }

  public static List<String> toStringList(List<JobName> values) {
    List<String> list = new ArrayList<>(values.size());
    for (JobName value : values) {
      if (value == null) {
        list.add("");
      } else {
        list.add(value.toString());
      }
    }
    return list;
  }

  public static boolean isParsableFrom(String formattedString) {
    return PROJECT_LOCATION_JOB.matches(formattedString);
  }

  @Override
  public Map<String, String> getFieldValuesMap() {
    if (fieldValuesMap == null) {
      synchronized (this) {
        if (fieldValuesMap == null) {
          ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
          if (project != null) {
            fieldMapBuilder.put("project", project);
          }
          if (location != null) {
            fieldMapBuilder.put("location", location);
          }
          if (job != null) {
            fieldMapBuilder.put("job", job);
          }
          fieldValuesMap = fieldMapBuilder.build();
        }
      }
    }
    return fieldValuesMap;
  }

  public String getFieldValue(String fieldName) {
    return getFieldValuesMap().get(fieldName);
  }

  @Override
  public String toString() {
    return PROJECT_LOCATION_JOB.instantiate("project", project, "location", location, "job", job);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o != null || getClass() == o.getClass()) {
      JobName that = ((JobName) o);
      return Objects.equals(this.project, that.project)
          && Objects.equals(this.location, that.location)
          && Objects.equals(this.job, that.job);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= Objects.hashCode(project);
    h *= 1000003;
    h ^= Objects.hashCode(location);
    h *= 1000003;
    h ^= Objects.hashCode(job);
    return h;
  }

  /** Builder for projects/{project}/locations/{location}/jobs/{job}. */
  public static class Builder {
    private String project;
    private String location;
    private String job;

    protected Builder() {}

    public String getProject() {
      return project;
    }

    public String getLocation() {
      return location;
    }

    public String getJob() {
      return job;
    }

    public Builder setProject(String project) {
      this.project = project;
      return this;
    }

    public Builder setLocation(String location) {
      this.location = location;
      return this;
    }

    public Builder setJob(String job) {
      this.job = job;
      return this;
    }

    private Builder(JobName jobName) {
      this.project = jobName.project;
      this.location = jobName.location;
      this.job = jobName.job;
    }

    public JobName build() {
      return new JobName(this);
    }
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: leiyu
 * Date: 2017/8/8
 * Time: 15:42
 */

namespace Ylf\Api;

use Exception;
use Tobscure\JsonApi\Document;
use Tobscure\JsonApi\ErrorHandler as JsonApiErrorHandler;

class ErrorHandler
{
    /**
     * @var JsonApiErrorHandler
     */
    protected $errorHandler;

    public $debug;

    /**
     * @param JsonApiErrorHandler $errorHandler
     */
    public function __construct(JsonApiErrorHandler $errorHandler)
    {
        $this->errorHandler = $errorHandler;
    }

    /**
     * @param Exception $e
     * @return JsonApiResponse
     */
    public function handle(Exception $e)
    {
        $response = $this->errorHandler->handle($e);

        $document = new Document;
        $document->setErrors($response->getErrors());

        return new JsonApiResponse($document, $response->getStatus());
    }
}


text:
import sys
import re
import maglica.config
import maglica.cli
import maglica.cli.image
import maglica.cli.vm
import maglica.cli.log
from maglica.util import MaglicaCliException

OBJECT_TYPES = filter(
    lambda x: not re.match(r"^__", x) and x != 'dispatcher',
    dir(maglica.cli)
)

def run_command(args):
    type = args.pop(0)
    action = args.pop(0)
    cmd = eval("maglica.cli." + type + "." + action)

    if len(args) > 0:
        options = {}
        for arg in args:
            try:
                (key, value) = arg.split('=')
            except ValueError:
                key = arg
                value = True

            key = key.replace('--', '')
            options[key] = value
        try:
            cmd(options)
        except MaglicaCliException, options:
            print_options(type, action, options)

    else:
        try:
            cmd({})
        except MaglicaCliException, options:
            print_options(type, action, options)

def print_options(type, action, options):
    mandatory = " ".join(["--%s=..." % x for x in options[0]["mandatory"]])
    optional = " ".join(["--%s=..." % x for x in options[0]["optional"]])
    if optional:
        optional = "[%s]" % optional

    print "usage\n====="
    action = action.replace('_', '-')
    print "maglica %s %s %s %s" % (type, action, mandatory, optional)

def get_object_type(args):
    """
    If this is a CLI command about an object type, e.g. "maglica vm list", return the type, like "vm"
    """
    if len(args) < 1:
        return None
    elif args[0] in OBJECT_TYPES:
        return args[0]
    return None

def get_object_actions(object_type):
    excludes = ['maglica', 're', '_print', 'cprint', 'json']
    actions = filter(
        lambda x: not re.match(r"^__", x) and x not in excludes,
        eval("dir(maglica.cli." + object_type + ")")
    )
    return actions

def get_object_action(object_type, args):
    actions = get_object_actions(object_type)
    if len(args) < 2:
        return None
    elif args[1] in actions:
        return args[1]
    return None

def print_help():
    """
    Prints general-top level help, e.g. "maglica --help" or "maglica" or "maglcica command-does-not-exist"
    """
    print "usage\n====="
    print "maglica <" + ('|').join(OBJECT_TYPES) + "> ..."
    exit(1)

def print_object_help(object_type):
    actions = get_object_actions(object_type)
    print "usage"
    print "====="
    for action in actions:
        action = action.replace('_', '-')
        print "maglica %s %s" % (object_type, action)
    exit(1)

def main():
    args = sys.argv[1:]
    if len(args) > 1:
        args[1] = args[1].replace('-', '_')
    object_type = get_object_type(args)

    if len(sys.argv) < 2 or sys.argv[1] == "--help" or not object_type:
        print_help()

    object_action = get_object_action(object_type, args)
    if not object_action:
        print_object_help(object_type)

    run_command(args)


text:
"use strict";
const _1 = require('../src/');
const token = process.env.BOT_TOKEN || process.env.TEST_TOKEN; // run `. config.test.sh` for setting TEST_TOKEN
const bot = new _1.default(token, { autoUpdate: true });
bot.on('update.message.photo', (msg) => {
    console.log('new photo message recived');
    // console.log(msg);
    let photo = msg.photo.pop(); // get last item (largest photo) in array
    bot.sendPhoto({
        chat_id: msg.chat.id,
        photo: photo.file_id
    })
        .then(() => {
        console.log('Message sent');
    })
        .catch((err) => {
        console.log('Send Message Error:', err);
    });
});
bot.on('update.message.video', (msg) => {
    console.log('new vide message recived');
    // console.log(msg);
    bot.sendVideo({
        chat_id: msg.chat.id,
        video: msg.video.file_id
    })
        .then(() => {
        console.log('Message sent');
    })
        .catch((err) => {
        console.log('Send Message Error:', err);
    });
});
bot.on('update.message.document', (msg) => {
    console.log('new document message recived');
    // telegram sending gif movies as a document
    // console.log(msg);
    bot.sendDocument({
        chat_id: msg.chat.id,
        document: msg.document.file_id
    })
        .then(() => {
        console.log('Message sent');
    })
        .catch((err) => {
        console.log('Send Message Error:', err);
    });
});
console.log('Bot actived.');


text:
package com.twitter.meil_mitu.twitter4holo.data;

import android.os.Parcel;
import android.os.Parcelable;

import com.twitter.meil_mitu.twitter4holo.exception.Twitter4HoloException;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Arrays;

import static com.twitter.meil_mitu.twitter4holo.util.JsonUtils.getJSONArray;
import static com.twitter.meil_mitu.twitter4holo.util.JsonUtils.getJSONObject;

public class SuggestionUser extends Suggestion implements android.os.Parcelable{

    public final User[] Users;

    public SuggestionUser(JSONObject obj) throws Twitter4HoloException{
        super(obj);
        if(obj.isNull("users")){
            Users = new User[0];
        }else{
            JSONArray ar = getJSONArray(obj, "users");
            int size = ar.length();
            Users = new User[size];
            for(int i = 0; i < size; i++){
                Users[i] = new User(getJSONObject(ar, i));
            }
        }
    }

    public SuggestionUser(Parcel in){
        super(in);
        Parcelable[] ps = in.readParcelableArray(User.class.getClassLoader());
        if(ps == null){
            Users = new User[0];
        }else{
            Users = Arrays.copyOf(ps, ps.length, User[].class);
        }
    }

    @Override
    public void writeToParcel(Parcel dest, int flags){
        super.writeToParcel(dest, flags);
        dest.writeParcelableArray(this.Users, flags);
    }

    @Override
    public String toString(){
        return "SuggestionUser{" +
                "Users=" + Arrays.toString(Users) +
                '}';
    }

    @Override
    public boolean equals(Object o){
        if(this == o) return true;
        if(!(o instanceof SuggestionUser)) return false;
        if(!super.equals(o)) return false;

        SuggestionUser that = (SuggestionUser) o;

        if(!Arrays.equals(Users, that.Users)) return false;

        return true;
    }

    @Override
    public int hashCode(){
        int result = super.hashCode();
        result = 31 * result + Arrays.hashCode(Users);
        return result;
    }

    @Override
    public int describeContents(){
        return 0;
    }

    public static final Creator<SuggestionUser> CREATOR = new Creator<SuggestionUser>(){
        public SuggestionUser createFromParcel(Parcel source){
            return new SuggestionUser(source);
        }

        public SuggestionUser[] newArray(int size){
            return new SuggestionUser[size];
        }
    };
}


text:
package com.github.nstdio.libpgn.common;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class ArrayUtilsTest {
    @Test
    public void isEmpty() {
        assertThat(ArrayUtils.isEmptyOrNull(new byte[0])).isTrue();
        assertThat(ArrayUtils.isEmptyOrNull((byte[]) null)).isTrue();

        assertThat(ArrayUtils.isEmptyOrNull(new byte[5])).isFalse();
    }

    @Test
    public void isNotEmpty() {
        assertThat(ArrayUtils.isNotEmptyOrNull(new byte[0])).isFalse();
        assertThat(ArrayUtils.isNotEmptyOrNull(null)).isFalse();

        assertThat(ArrayUtils.isNotEmptyOrNull(new byte[5])).isTrue();
    }

    @Test
    public void concatByteArrays() {
        final byte[] first = new byte[]{1, 2};
        final byte[] second = new byte[]{3, 4};

        final byte[] expected = new byte[]{1, 2, 3, 4};

        final byte[] actual = ArrayUtils.concat(first, second);

        assertThat(actual).containsExactly(expected);
    }

    @Test
    public void concatByteArrays_FirstEmpty() {
        final byte[] first = new byte[0];
        final byte[] second = new byte[]{3, 4};

        final byte[] expected = new byte[]{3, 4};

        final byte[] actual = ArrayUtils.concat(first, second);

        assertThat(actual)
                .isSameAs(second)
                .containsExactly(expected);
    }

    @Test
    public void concatByteArrays_SecondEmpty() {
        final byte[] first = new byte[]{1, 2};
        final byte[] second = new byte[0];

        final byte[] expected = new byte[]{1, 2};

        final byte[] actual = ArrayUtils.concat(first, second);

        assertThat(actual)
                .isSameAs(first)
                .containsExactly(expected);
    }
}