text:
import os
from unittest import mock, TestCase

import numpy

import crunch

def mock_read(path, args):
    return numpy.asarray([1, 3, 3, 7]), path, 10

class TestMain(TestCase):
    def setUp(self):
        self.ap = crunch._arg_parse()
        self.def_ap = self.ap.parse_args(args=[])
        self.val_ap = self.ap.parse_args(args=["-f", "samp/", "-p", "20", "50", "60", "-o", "pca.json", "-r",
                                               "fing.npy", "-m", "-100", "-x", "100", "-t", "pca.png", "-c",
                                               "samp/data.csv", "-d", "4000", "-u", "unfilterable", "-n",
                                               "test_data_set", "-s", "sound_info.json", "-a", "1000", "-b",
                                               "pronunciation", "-k", "pca", "-g", "fft", "-e", "input.npy", "--td",
                                               "--colorby", "phoneme", "--parallel"])

    def _file_data_comp(self, data, index, x_coord, y_coord, z_coord, file_name, tags):
        self.assertEqual(data[0], index, "Unexpected index. Expected {}, Got{}".format(index, data[0]))
        self.assertEqual(data[1], x_coord, "Unexpected x coordinate. Expected {}, Got{}".format(x_coord, data[1]))
        self.assertEqual(data[2], y_coord, "Unexpected y coordinate. Expected {}, Got{}".format(y_coord, data[2]))
        self.assertEqual(data[3], z_coord, "Unexpected z coordinate. Expected {}, Got{}".format(z_coord, data[3]))
        self.assertEqual(data[4], file_name, "Unexpected file name. Expected {}, Got{}".format(file_name, data[4]))
        self.assertEqual(data[5], tags, "Unexpected tag list. Expected {}, Got{}".format(tags, data[5]))

    def test_arg_parse_defaults(self):
        args = self.def_ap
        self.assertEqual(args.input_folder, os.getcwd(), "Unexpected input folder")
        self.assertSequenceEqual(args.perplexity, [30], "Unexpected perplexity list")
        self.assertEqual(args.output_file, os.path.join(os.getcwd(), "t_sne_.json"), "Unexpected output directory")
        self.assertIsNone(args.fingerprint_output, "Unexpected fingerprint output")
        self.assertEqual(args.value_minimum, 0, "Unexpected minimum value")
        self.assertEqual(args.value_maximum, 600, "Unexpected maximum value")
        self.assertIsNone(args.plot_output, "Unexpected plot output")
        self.assertIsNone(args.collect_metadata, "Unexpected metadata path")
        self.assertEqual(args.duration, 0, "Unexpected maximum duration")
        self.assertSequenceEqual(args.unfilterables, [], "Unexpected unfilterable argument")
        self.assertEqual(args.data_set, "dataset", "Unexpected dataset value")
        self.assertIsNone(args.sound_info, "Unexpected sound_info value")
        self.assertEqual(args.max_to_load, 0, "Unexpected max_to_load value")
        self.assertSequenceEqual(args.tags_to_ignore, ["waveform", "name", "filename", "file name"],
                                 "Unexpected values in tags_to_ignore.")
        self.assertEqual(args.reduction_method, "tsne", "Unexpected value for reduction_method.")
        self.assertEqual(args.fingerprint_method, "ms", "Unexpected value for fingerprint_mathod.")
        self.assertIsNone(args.fingerprint_input, "Unexpected value for fingerprint input.")
        self.assertFalse(args.td, "Unexpected value for --td")
        self.assertIsNone(args.colorby, "Unexpected colorby value")
        self.assertFalse(args.parallel, "Unexpected value for parallel.")

    def test_arg_parse_values(self):
        args = self.val_ap
        self.assertEqual(args.input_folder, "samp/", "Unexpected input folder")
        self.assertSequenceEqual(args.perplexity, [20, 50, 60], "Unexpected perplexity list")
        self.assertEqual(args.output_file, "pca.json", "Unexpected output directory")
        self.assertEqual(args.fingerprint_output, "fing.npy", "Unexpected fingerprint output")
        self.assertEqual(args.value_minimum, -100, "Unexpected minimum value")
        self.assertEqual(args.value_maximum, 100, "Unexpected maximum value")
        self.assertEqual(args.plot_output, "pca.png", "Unexpected plot output")
        self.assertEqual(args.collect_metadata, "samp/data.csv", "Unexpected metadata path")
        self.assertEqual(args.duration, 4000, "Unexpected maximum duration")
        self.assertSequenceEqual(args.unfilterables, ["unfilterable"], "Unexpected value for unfilterable.")
        self.assertEqual(args.data_set, "test_data_set", "Unexpected value for data_set.")
        self.assertEqual(args.sound_info, "sound_info.json", "Unexpected value for sound_info.")
        self.assertEqual(args.max_to_load, 1000, "Unexpected value for max_to_load")
        self.assertSequenceEqual(args.tags_to_ignore, ["pronunciation"], "Unexpected tags_to_ignore value.")
        self.assertEqual(args.reduction_method, "pca", "Unexpected reduction method value.")
        self.assertEqual(args.fingerprint_method, "fft", "Unexpected fingerprint_method.")
        self.assertEqual(args.fingerprint_input, "input.npy", "Unexpected value for fingerprint input.")
        self.assertTrue(args.td, "Unexpected value for --td")
        self.assertEqual(args.colorby, "phoneme", "Unexpected colorby value")
        self.assertTrue(args.parallel, "Unexpected value for parallel.")

    @mock.patch("crunch.add_color")
    @mock.patch("crunch.plot_results")
    @mock.patch("crunch.normalize")
    @mock.patch("crunch.output")
    def test_finalize(self, mock_output, mock_normalize, mock_plot, mock_color):
        norm_data = mock.MagicMock
        mock_normalize.return_value = norm_data
        arr = numpy.asarray([[1, 2, 3], [2, 3, 4]]), "30"
        data = mock.MagicMock()
        metadata = mock.MagicMock()
        crunch._finalize(arr, self.def_ap, data, metadata)
        mock_color.assert_called_with(metadata, arr[0])
        self.assertFalse(mock_plot.called)
        mock_normalize.assert_called_with(arr[0], self.def_ap.value_minimum, self.def_ap.value_maximum)
        file_path = os.path.join(os.getcwd(), "t_sne_30.json")
        mock_output.assert_called_with(file_path, data, norm_data, self.def_ap, metadata, arr[1])

    @mock.patch("crunch.add_color")
    @mock.patch("crunch.plot_results")
    @mock.patch("crunch.normalize")
    @mock.patch("crunch.output")
    def test_finalize_output(self, mock_output, mock_normalize, mock_plot, mock_color):
        norm_data = mock.MagicMock
        mock_normalize.return_value = norm_data
        arr = numpy.asarray([[1, 2, 3], [2, 3, 4]]), "30"
        data = mock.MagicMock()
        metadata = mock.MagicMock()
        crunch._finalize(arr, self.val_ap, data, metadata)
        mock_color.assert_called_with(metadata, arr[0])
        mock_plot.assert_called_with(arr[0], "pca30.png", metadata, "phoneme")
        mock_normalize.assert_called_with(arr[0], self.val_ap.value_minimum, self.val_ap.value_maximum)
        file_path = "pca30.json"
        mock_output.assert_called_with(file_path, data, norm_data, self.val_ap, metadata, arr[1])

    @mock.patch("crunch.load_sample")
    def test_read_and_fingerprint(self, mock_load):
        mock_fingerprint = mock.MagicMock()
        crunch.ProcessFunctions.fingerprint_dict["ms"] = mock_fingerprint
        file_path = "mock_path"
        file_data = mock.MagicMock()
        arr = numpy.asarray([1, 3, 3, 7])
        mock_load.return_value = (file_path, file_data, 10, 16000)
        mock_fingerprint.return_value = arr
        ret = crunch._read_and_fingerprint(file_path, self.def_ap)
        mock_load.assert_called_with(file_path, 0)
        mock_fingerprint.assert_called_with(file_data, 16000, 10)
        numpy.testing.assert_array_equal(ret[0], arr)
        self.assertEqual(ret[1], file_path)
        self.assertEqual(ret[2], 10)

    @mock.patch("crunch.all_files")
    @mock.patch("crunch._read_and_fingerprint", mock_read)
    def test_read_data_to_fingerprints(self, mock_all_files):
        file_name = "mock_file.wav"
        mock_all_files.return_value = [file_name]
        arr = numpy.asarray([1, 3, 3, 7])
        res = crunch._read_data_to_fingerprints(self.def_ap)
        mock_all_files.assert_called_with(os.getcwd(), [".wav"])
        numpy.testing.assert_array_equal(res[0][0], arr)
        self.assertEqual(res[1][0], file_name)

    def test_run_dimensionality_reduction(self):
        rf = mock.MagicMock()
        crunch.ProcessFunctions.dimensionality_reduction_dict["tsne"] = rf
        rf.return_value = "mock_result"
        arr = numpy.asarray([1, 3, 3, 7])
        res = crunch._run_dimensionality_reduction([arr], self.def_ap, "mock_data", "mock_dict")
        self.assertEqual(res, "mock_result")
        numpy.testing.assert_array_equal(rf.call_args[0][0][0], arr)
        self.assertEqual(rf.call_args[0][1], 3)
        self.assertEqual(rf.call_args[0][2], self.def_ap)
        self.assertEqual(rf.call_args[1]["a_func"], crunch._finalize)
        self.assertSequenceEqual(rf.call_args[1]["a_params"], (self.def_ap, "mock_data", "mock_dict"))

    @mock.patch("crunch._read_data_to_fingerprints")
    @mock.patch("numpy.save")
    def test_generate_fingerprints(self, mock_save, mock_read_fingerprints):
        mock_read_fingerprints.return_value = [numpy.asarray([[1, 3], [3, 7]]), numpy.asarray([[7, 3], [3, 1]])], \
                                              ["file1", "file2"]
        res = crunch.generate_fingerprints(self.def_ap)
        mock_read_fingerprints.assert_called_with(self.def_ap)
        self.assertFalse(mock_save.called)
        numpy.testing.assert_array_equal(res[0], numpy.asarray([[1, 3, 3, 7], [7, 3, 3, 1]]).astype(numpy.float64))
        self.assertSequenceEqual(res[1], ["file1", "file2"])

    @mock.patch("crunch._read_data_to_fingerprints")
    @mock.patch("numpy.save")
    def test_generate_fingerprints_save(self, mock_save, mock_read_fingerprints):
        mock_read_fingerprints.return_value = [numpy.asarray([[1, 3], [3, 7]]), numpy.asarray([[7, 3], [3, 1]])], \
                                              ["file1", "file2"]
        res = crunch.generate_fingerprints(self.val_ap)
        mock_read_fingerprints.assert_called_with(self.val_ap)
        self.assertEqual(mock_save.call_args[0][0], "fing.npy")
        self.assertEqual(mock_save.call_args[0][1][0][0], "file1")
        numpy.testing.assert_array_equal(mock_save.call_args[0][1][0][1],
                                         numpy.asarray([1, 3, 3, 7]).astype(numpy.float64))
        self.assertEqual(mock_save.call_args[0][1][1][0], "file2")
        numpy.testing.assert_array_equal(mock_save.call_args[0][1][1][1],
                                         numpy.asarray([7, 3, 3, 1]).astype(numpy.float64))
        numpy.testing.assert_array_equal(res[0], numpy.asarray([[1, 3, 3, 7], [7, 3, 3, 1]]).astype(numpy.float64))
        self.assertSequenceEqual(res[1], ["file1", "file2"])


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<!--
     Copyright (C) 2012-2013 Andrew Neal
     Copyright (C) 2012-2014 The CyanogenMod Project

     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.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="app_name">Nhạc</string>
  <!-- Page titles -->
  <string name="page_recent">Gần đây</string>
  <string name="page_artists">Nghệ sĩ</string>
  <string name="page_albums">Album</string>
  <string name="page_songs">Bài hát</string>
  <string name="page_playlists">Danh sách phát</string>
  <string name="page_genres">Thể loại</string>
  <string name="page_now_playing">Đang phát</string>
  <string name="page_play_queue">Phát danh sách chờ</string>
  <!-- Section Headers -->
  <string name="header_albums">Album</string>
  <string name="header_top_songs">Bài hát thường nghe</string>
  <string name="header_all_songs">Tất cả bài hát</string>
  <!-- Option menu items -->
  <string name="menu_settings">Cài đặt</string>
  <string name="menu_search">Tìm kiếm</string>
  <string name="menu_shuffle_item">Phát ngẫu nhiên</string>
  <string name="menu_shuffle_all">Phát ngẫu nhiên tất cả</string>
  <string name="menu_shuffle_playlist">Phát ngẫu nhiên danh sách phát</string>
  <string name="menu_shuffle_album">Phát album ngẫu nhiên</string>
  <string name="menu_shuffle_artist">Phát theo nghệ sĩ ngẫu nhiên</string>
  <string name="menu_shuffle_top_tracks">Phát ngẫu nhiên bài hát thường nghe</string>
  <string name="menu_shuffle_recent">Phát ngẫu nhiên những bài hát nghe gần đây</string>
  <string name="menu_shuffle_last_added">Phát ngẫu nhiên những bài hát vừa thêm</string>
  <string name="menu_play_all">Phát tất cả</string>
  <string name="menu_sort_by">Xếp theo</string>
  <string name="menu_clear_list">Xoá danh sách</string>
  <string name="menu_clear_recents">Xoá danh sách nghe gần đây</string>
  <string name="menu_clear_queue">Xoá danh sách chờ</string>
  <string name="menu_save_queue">Lưu hàng chờ vào danh sách phát</string>
  <string name="menu_equalizer">Bộ chỉnh âm</string>
  <!-- Playlist items -->
  <string name="add_to_playlist">Thêm vào danh sách phát</string>
  <string name="add_to_queue">Thêm vào danh sách chờ</string>
  <string name="remove_from_recent">Xoá khỏi danh sách nghe gần đây</string>
  <string name="remove_from_queue">Xoá khỏi danh sách chờ</string>
  <!-- Sort orders -->
  <string name="sort_order_entry_az">A-Z</string>
  <string name="sort_order_entry_za">Z-A</string>
  <string name="sort_order_entry_artist">Nghệ sĩ</string>
  <string name="sort_order_entry_album">Album</string>
  <string name="sort_order_entry_year">Năm</string>
  <string name="sort_order_entry_duration">Thời lượng</string>
  <string name="sort_order_entry_date_added">Ngày thêm</string>
  <string name="sort_order_entry_track_list">Danh sách bài hát</string>
  <string name="sort_order_entry_number_of_songs">Số của bài hát</string>
  <string name="sort_order_entry_number_of_albums">Số của album</string>
  <string name="sort_order_entry_filename">Tên tập tin</string>
  <!-- Default playlist names -->
  <string name="playlist_last_added">Vừa thêm</string>
  <string name="playlist_recently_played">Đã phát gần đây</string>
  <string name="playlist_top_tracks">Bài hát thường nghe của tôi</string>
  <!-- AlertDialog items -->
  <string name="new_playlist">Danh sách phát mới</string>
  <string name="save">Lưu</string>
  <string name="cancel">Huỷ</string>
  <string name="overwrite">Ghi đè</string>
  <string name="clear">Xoá</string>
  <string name="new_playlist_name_template">Danh sách phát <xliff:g id="number">%d</xliff:g></string>
  <string name="create_playlist_prompt">Tên danh sách phát</string>
  <string name="delete_dialog_title">Xoá <xliff:g id="item" example="album">%s</xliff:g>?</string>
  <string name="clear_top_tracks_title">Xoá những bài hát thường nghe?</string>
  <string name="clear_recent_title">Xoá danh sách nghe gần đây?</string>
  <string name="clear_last_added">Xoá danh sách vừa thêm?</string>
  <string name="cannot_be_undone">Không thể hoàn tác điều này</string>
  <string name="delete_warning">Điều này sẽ xoá vĩnh viễn các mục nhập ảnh đã lưu trong bộ nhớ đệm</string>
  <string name="new_photo">Chọn ảnh từ Bộ sưu tập</string>
  <string name="google_search">Tìm bằng Google</string>
  <string name="use_default">Dùng ảnh mặc định</string>
  <string name="old_photo">Dùng ảnh cũ</string>
  <!-- Context menu items -->
  <string name="context_menu_play_selection">Phát</string>
  <string name="context_menu_play_next">Phát tiếp theo</string>
  <string name="context_menu_play_album">Phát album</string>
  <string name="context_menu_more_by_artist">Thêm mục của nghệ sĩ</string>
  <string name="context_menu_rename_playlist">Đổi tên</string>
  <string name="context_menu_delete">Xoá</string>
  <string name="context_menu_fetch_album_art">Tải ảnh bìa album</string>
  <string name="context_menu_fetch_artist_image">Tải ảnh nghệ sĩ</string>
  <string name="context_menu_remove_from_recent">Xoá khỏi danh sách nghe gần đây</string>
  <string name="context_menu_use_as_ringtone">Dùng làm nhạc chuông</string>
  <string name="context_menu_remove_from_playlist">Xoá khỏi danh sách phát</string>
  <string name="context_menu_change_image">Đổi ảnh</string>
  <!-- Content descriptions -->
  <string name="accessibility_play">Phát</string>
  <string name="accessibility_pause">Tạm dừng</string>
  <string name="accessibility_next">Bài tiếp theo</string>
  <string name="accessibility_prev">Bài trước đó</string>
  <string name="accessibility_shuffle">Phát ngẫu nhiên</string>
  <string name="accessibility_shuffle_all">Phát ngẫu nhiên tất cả</string>
  <string name="accessibility_repeat">Lặp lại</string>
  <string name="accessibility_repeat_all">Lặp lại tất cả</string>
  <string name="accessibility_repeat_one">Lặp lại một bài hát</string>
  <string name="accessibility_queue">Mở danh sách chờ</string>
  <string name="accessibility_browse">Duyệt nhạc</string>
  <!-- Toast messages -->
  <string name="set_as_ringtone">\'<xliff:g id="name" example="Alarm Bell">%s</xliff:g>\' được đặt làm nhạc chuông</string>
  <string name="playlist_renamed">Đã đổi tên danh sách phát</string>
  <!-- Settings -->
  <string name="settings_ui_category">Giao diện</string>
  <string name="settings_storage_category">Lưu trữ</string>
  <string name="settings_data_category">Dữ liệu</string>
  <string name="settings_delete_cache_title">Xoá bộ nhớ đệm</string>
  <string name="settings_delete_cache_summary">Xoá tất cả ảnh đã có trong bộ nhớ đệm</string>
  <string name="settings_download_only_on_wifi_title">Chỉ tải xuống qua WiFi</string>
  <string name="settings_download_only_on_wifi_summary">Để giảm cước, đừng tải qua mạng di động</string>
  <string name="settings_download_missing_artwork_title">Tải xuống ảnh bìa album còn thiếu</string>
  <string name="settings_download_artist_images_title">Tải xuống ảnh nghệ sỹ còn thiếu</string>
  <string name="settings_general_category">Tổng quát</string>
  <string name="settings_show_music_visualization_title">Hiện trực quan hoá nhạc</string>
  <string name="settings_show_lyrics_title">Hiện lời bài hát</string>
  <string name="settings_show_lyrics_summary">Đối với bài hát có tập tin srt</string>
  <string name="settings_shake_to_play">Lắc để phát</string>
  <string name="settings_shake_to_play_summary">Lắc thiết bị để phát bài hát kế tiếp</string>
  <string name="settings_lockscreen_album_art">Ảnh bìa album màn hình khoá</string>
  <string name="settings_lockscreen_album_art_summary">Thay thế nền màn hình khoá bằng ảnh bìa album</string>
  <!-- App widget -->
  <string name="app_widget_small">Nghe nhạc: 4 \u00d7 1</string>
  <string name="app_widget_large">Nghe nhạc: 4 \u00d7 2</string>
  <string name="app_widget_large_alt">Nghe nhạc: 4 \u00d7 2 (kiểu khác)</string>
  <string name="app_widget_recent">Nghe nhạc: đã nghe gần đây</string>
  <!-- Empty list / error messages -->
  <string name="no_effects_for_you">Không thể mở bộ chỉnh âm.</string>
  <string name="empty_music">Để chép nhạc từ máy tính sang thiết bị, hãy dùng cáp USB.</string>
  <string name="empty_search">Không tìm thấy kết quả tìm kiếm</string>
  <string name="empty_search_check">Hãy kiểm tra xem bạn đã nhập đúng chính tả chưa hoặc thử từ khoá khác.</string>
  <string name="empty_favorite">Bài hát bạn đã đánh dấu là yêu thích sẽ hiện tại đây.</string>
  <string name="empty_recent_main">Không có bài hát nào nghe gần đây</string>
  <string name="empty_recent">Bài hát bạn đã nghe gần đây sẽ hiện tại đây.</string>
  <string name="empty_playlist_main">Không có bài hát nào trong danh sách phát</string>
  <string name="empty_playlist_secondary">Để thêm bài hát vào danh sách phát này, chạm menu tuỳ chọn của bài hát, album hoặc nghệ sĩ và chọn \"Thêm vào danh sách phát\".</string>
  <string name="empty_top_tracks_main">Không có bài hát thường nghe</string>
  <string name="empty_top_tracks_secondary">Bài hát bạn thường nghe sẽ được thêm vào danh sách này.</string>
  <string name="empty_last_added_main">Không có bài hát được thêm gần đây</string>
  <string name="empty_last_added">Bài hát bạn thêm trong vòng một tháng gần đây sẽ hiện tại đây.</string>
  <string name="empty_generic_main">Không tìm thấy nhạc</string>
  <string name="empty_generic_secondary">Để chép nhạc từ máy tính sang thiết bị, hãy dùng cáp USB.</string>
  <string name="empty_queue_main">Không có bài hát trong danh sách chờ phát</string>
  <string name="empty_queue_secondary">Để thêm bài hát vào Danh sách chờ phát, chạm menu tuỳ chọn của bài hát, album hoặc nghệ sĩ và chọn \"Thêm vào danh sách chờ\".</string>
  <string name="error_playing_track">Không thể phát bài hát %1$s</string>
  <!-- Section Headers -->
  <string name="header_unknown_year">Năm chưa rõ</string>
  <string name="header_less_than_30s">Ngắn hơn 30 giây</string>
  <string name="header_30_to_60_seconds">30 - 60 giây</string>
  <string name="header_1_to_2_minutes">1 - 2 phút</string>
  <string name="header_2_to_3_minutes">2 - 3 phút</string>
  <string name="header_3_to_4_minutes">3 - 4 phút</string>
  <string name="header_4_to_5_minutes">4 - 5 phút</string>
  <string name="header_5_to_10_minutes">5 - 10 phút</string>
  <string name="header_10_to_30_minutes">10 - 30 phút</string>
  <string name="header_30_to_60_minutes">30 - 60 phút</string>
  <string name="header_greater_than_60_minutes">Lâu hơn 60 phút</string>
  <string name="header_1_song">1 bài hát</string>
  <string name="header_2_to_4_songs">2 - 4 bài hát</string>
  <string name="header_5_to_9_songs">5 - 9 bài hát</string>
  <string name="header_10_plus_songs">10 bài hát trở lên</string>
  <string name="header_5_plus_albums">5 album trở lên</string>
  <string name="header_other">"Khác"</string>
  <string name="footer_search_artists">Hiện tất cả nghệ sĩ</string>
  <string name="footer_search_albums">Hiện tất cả album</string>
  <string name="footer_search_songs">Hiện tất cả bài hát</string>
  <string name="footer_search_playlists">Hiện tất cả danh sách phát</string>
  <string name="searchHint">Tìm bài hát</string>
  <string name="search_title_artists">Tất cả về nghệ sĩ \"%s\"</string>
  <string name="search_title_albums">Tất cả về album \"%s\"</string>
  <string name="search_title_songs">Tất cả về bài hát \"%s\"</string>
  <string name="search_title_playlists">Tất cả về danh sách phát \"%s\"</string>
  <string name="duration_format"><xliff:g id="hours">%1$s</xliff:g> <xliff:g id="minutes">%2$s</xliff:g></string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Require Auth_OpenID::arrayGet().
 */
import('core.lib.openid.auth.OpenID');

class Auth_OpenID_Parse {

    /**
     * Specify some flags for use with regex matching.
     */
    var $_re_flags = "si";

    /**
     * Stuff to remove before we start looking for tags
     */
    var $_removed_re =
           "<!--.*?-->|<!\[CDATA\[.*?\]\]>|<script\b(?!:)[^>]*>.*?<\/script>";

    /**
     * Starts with the tag name at a word boundary, where the tag name
     * is not a namespace
     */
    var $_tag_expr = "<%s\b(?!:)([^>]*?)(?:\/>|>(.*?)(?:<\/?%s\s*>|\Z))";

    var $_attr_find = '\b(\w+)=("[^"]*"|\'[^\']*\'|[^\'"\s\/<>]+)';

    var $_open_tag_expr = "<%s\b";
    var $_close_tag_expr = "<((\/%s\b)|(%s[^>\/]*\/))>";

    function Auth_OpenID_Parse()
    {
        $this->_link_find = sprintf("/<link\b(?!:)([^>]*)(?!<)>/%s",
                                    $this->_re_flags);

        $this->_entity_replacements = array(
                                            'amp' => '&',
                                            'lt' => '<',
                                            'gt' => '>',
                                            'quot' => '"'
                                            );

        $this->_attr_find = sprintf("/%s/%s",
                                    $this->_attr_find,
                                    $this->_re_flags);

        $this->_removed_re = sprintf("/%s/%s",
                                     $this->_removed_re,
                                     $this->_re_flags);

        $this->_ent_replace =
            sprintf("&(%s);", implode("|",
                                      $this->_entity_replacements));
    }

    /**
     * Returns a regular expression that will match a given tag in an
     * SGML string.
     */
    function tagMatcher($tag_name, $close_tags = null)
    {
        $expr = $this->_tag_expr;

        if ($close_tags) {
            $options = implode("|", array_merge(array($tag_name), $close_tags));
            $closer = sprintf("(?:%s)", $options);
        } else {
            $closer = $tag_name;
        }

        $expr = sprintf($expr, $tag_name, $closer);
        return sprintf("/%s/%s", $expr, $this->_re_flags);
    }

    function openTag($tag_name)
    {
        $expr = sprintf($this->_open_tag_expr, $tag_name);
        return sprintf("/%s/%s", $expr, $this->_re_flags);
    }

    function closeTag($tag_name)
    {
        $expr = sprintf($this->_close_tag_expr, $tag_name, $tag_name);
        return sprintf("/%s/%s", $expr, $this->_re_flags);
    }

    function htmlBegin($s)
    {
        $matches = array();
        $result = preg_match($this->openTag('html'), $s,
                             $matches, PREG_OFFSET_CAPTURE);
        if ($result === false || !$matches) {
            return false;
        }
        // Return the offset of the first match.
        return $matches[0][1];
    }

    function htmlEnd($s)
    {
        $matches = array();
        $result = preg_match($this->closeTag('html'), $s,
                             $matches, PREG_OFFSET_CAPTURE);
        if ($result === false || !$matches) {
            return false;
        }
        // Return the offset of the first match.
        return $matches[count($matches) - 1][1];
    }

    function headFind()
    {
        return $this->tagMatcher('head', array('body', 'html'));
    }

    function replaceEntities($str)
    {
        foreach ($this->_entity_replacements as $old => $new) {
            $str = preg_replace(sprintf("/&%s;/", $old), $new, $str);
        }
        return $str;
    }

    function removeQuotes($str)
    {
        $matches = array();
        $double = '/^"(.*)"$/';
        $single = "/^\'(.*)\'$/";

        if (preg_match($double, $str, $matches)) {
            return $matches[1];
        } else if (preg_match($single, $str, $matches)) {
            return $matches[1];
        } else {
            return $str;
        }
    }

    /**
     * Find all link tags in a string representing a HTML document and
     * return a list of their attributes.
     *
     * @param string $html The text to parse
     * @return array $list An array of arrays of attributes, one for each
     * link tag
     */
    function parseLinkAttrs($html)
    {
        $stripped = preg_replace($this->_removed_re,
                                 "",
                                 $html);

        $html_begin = $this->htmlBegin($stripped);
        $html_end = $this->htmlEnd($stripped);

        if ($html_begin === false) {
            return array();
        }

        if ($html_end === false) {
            $html_end = strlen($stripped);
        }

        $stripped = substr($stripped, $html_begin,
                           $html_end - $html_begin);

        // Try to find the <HEAD> tag.
        $head_re = $this->headFind();
        $head_matches = array();
        if (!preg_match($head_re, $stripped, $head_matches)) {
            return array();
        }

        $link_data = array();
        $link_matches = array();

        if (!preg_match_all($this->_link_find, $head_matches[0],
                            $link_matches)) {
            return array();
        }

        foreach ($link_matches[0] as $link) {
            $attr_matches = array();
            preg_match_all($this->_attr_find, $link, $attr_matches);
            $link_attrs = array();
            foreach ($attr_matches[0] as $index => $full_match) {
                $name = $attr_matches[1][$index];
                $value = $this->replaceEntities(
                              $this->removeQuotes($attr_matches[2][$index]));

                $link_attrs[strtolower($name)] = $value;
            }
            $link_data[] = $link_attrs;
        }

        return $link_data;
    }

    function relMatches($rel_attr, $target_rel)
    {
        // Does this target_rel appear in the rel_str?
        // XXX: TESTME
        $rels = preg_split("/\s+/", trim($rel_attr));
        foreach ($rels as $rel) {
            $rel = strtolower($rel);
            if ($rel == $target_rel) {
                return 1;
            }
        }

        return 0;
    }

    function linkHasRel($link_attrs, $target_rel)
    {
        // Does this link have target_rel as a relationship?
        // XXX: TESTME
        $rel_attr = Auth_OpeniD::arrayGet($link_attrs, 'rel', null);
        return ($rel_attr && $this->relMatches($rel_attr,
                                               $target_rel));
    }

    function findLinksRel($link_attrs_list, $target_rel)
    {
        // Filter the list of link attributes on whether it has
        // target_rel as a relationship.
        // XXX: TESTME
        $result = array();
        foreach ($link_attrs_list as $attr) {
            if ($this->linkHasRel($attr, $target_rel)) {
                $result[] = $attr;
            }
        }

        return $result;
    }

    function findFirstHref($link_attrs_list, $target_rel)
    {
        // Return the value of the href attribute for the first link
        // tag in the list that has target_rel as a relationship.
        // XXX: TESTME
        $matches = $this->findLinksRel($link_attrs_list,
                                       $target_rel);
        if (!$matches) {
            return null;
        }
        $first = $matches[0];
        return Auth_OpenID::arrayGet($first, 'href', null);
    }
}

function Auth_OpenID_legacy_discover($html_text, $server_rel,
                                     $delegate_rel)
{
    $p = new Auth_OpenID_Parse();

    $link_attrs = $p->parseLinkAttrs($html_text);

    $server_url = $p->findFirstHref($link_attrs,
                                    $server_rel);

    if ($server_url === null) {
        return false;
    } else {
        $delegate_url = $p->findFirstHref($link_attrs,
                                          $delegate_rel);
        return array($delegate_url, $server_url);
    }
}

?>


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Take Picture"
            android:id="@+id/button"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="14dp"
            />

    <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:layout_below="@+id/button"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:layout_above="@+id/button2"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tweet this!"
            android:id="@+id/tweet"
            android:onClick="prepareTweet"
            android:layout_alignParentBottom="true"
            android:layout_alignRight="@+id/button"
            android:layout_marginRight="18dp"/>

</RelativeLayout>


text:
<?php

declare(strict_types=1);

namespace Phan\Library;

/**
 * An object representing a conversion specifier of a format string, such as "%1$d".
 * @phan-pure
 */
class ConversionSpec
{
    /** @var string Original text of the directive */
    public $directive;
    /** @var ?int Which argument this refers to, starting from 1 */
    public $position;
    /** @var string Character used for padding (commonly confused with $position) */
    public $padding_char;
    /** @var string indicates which side is used for alignment */
    public $alignment;
    /** @var string minimum width of output */
    public $width;
    /** @var string precision of output */
    public $precision;
    /** @var string Type to print (s,d,f,etc.) */
    public $arg_type;

    /**
     * Create a conversion specifier from a match.
     * @param array{0:string,1:string,2:string,3:string,4:string,5:string,6:string} $match groups in a match.
     */
    protected function __construct(array $match)
    {
        [$this->directive, $position_str, $this->padding_char, $this->alignment, $this->width, $this->precision, $this->arg_type] = $match;
        if ($position_str !== "") {
            $this->position = \intval(\substr($position_str, 0, -1));
        }
    }

    // A padding string regex may be a space or 0.
    // Alternate padding specifiers may be specified by prefixing it with a single quote.
    public const PADDING_STRING_REGEX_PART = '[0 ]?|\'.';

    /**
     * Based on https://secure.php.net/manual/en/function.sprintf.php
     */
    public const FORMAT_STRING_INNER_REGEX_PART =
        '%'  // Every format string begins with a percent
        . '(\d+\$)?'  // Optional n$ position specifier must go immediately after percent
        . '(' . self::PADDING_STRING_REGEX_PART . ')'  // optional padding specifier
        . '([+-]?)' // optional alignment specifier
        . '(\d*)'  // optional width specifier
        . '(\.\d*)?'   // Optional precision specifier in the form of a period followed by an optional decimal digit string
        . '(?:l)?' // Optional length specifier (ignored)
        . '([bcdeEfFgGosuxX])';  // A type specifier

    public const FORMAT_STRING_REGEX = '/%%|' . self::FORMAT_STRING_INNER_REGEX_PART . '/';

    /**
     * Compute the number of additional arguments expected when sprintf is called
     * with a format string of $fmt_str.
     * @param string $fmt_str
     */
    public static function computeExpectedArgumentCount(string $fmt_str): int
    {
        $result = 0;
        foreach (self::extractAll($fmt_str) as $i => $_) {
            $result = \max($result, $i);
        }
        return $result;
    }

    /**
     * Extract a list of directives from a format string.
     * @param string $fmt_str a format string to extract directives from.
     * @return associative-array<int,non-empty-list<ConversionSpec>> array(int position => array of ConversionSpec referring to arg at that position)
     */
    public static function extractAll(string $fmt_str): array
    {
        // echo "format is $fmt_str\n";
        $directives = [];
        \preg_match_all(self::FORMAT_STRING_REGEX, $fmt_str, $matches, \PREG_SET_ORDER);
        $unnamed_count = 0;
        foreach ($matches as $match) {
            if ($match[0] === '%%') {
                continue;
            }
            $directive = new self($match);
            if (!isset($directive->position)) {
                // @phan-suppress-next-line PhanAccessReadOnlyProperty
                $directive->position = ++$unnamed_count;
            }
            $directives[$directive->position][] = $directive;
        }
        \ksort($directives);
        return $directives;
    }

    /**
     * @return string an unambiguous way of referring to this conversion spec.
     */
    public function toCanonicalString(): string
    {
        if ($this->width !== '') {
            $padding_char = $this->padding_char;
            $alignment = $this->alignment;
        } else {
            $padding_char = '';
            $alignment = '';
        }
        return '%' . $this->position . '$' . $padding_char . $alignment . $this->width . $this->precision . $this->arg_type;
    }

    /**
     * @return string the conversion spec if the width was used as a position instead.
     */
    public function toCanonicalStringWithWidthAsPosition(): string
    {
        return '%' . $this->width . '$' . $this->padding_char . $this->alignment . $this->precision . $this->arg_type;
    }
    public const ARG_TYPE_LOOKUP = [
        'b' => 'int',
        'c' => 'int',
        'd' => 'int',
        'e' => 'float',
        'E' => 'float',
        'f' => 'float',
        'F' => 'float',
        'g' => 'float',
        'G' => 'float',
        'o' => 'int',
        's' => 'string',
        'u' => 'int',
        'x' => 'int',
        'X' => 'int',
    ];

    /**
     * @return string the name of the union type expected for the arg for this conversion spec
     */
    public function getExpectedUnionTypeName(): string
    {
        return self::ARG_TYPE_LOOKUP[$this->arg_type] ?? 'string';
    }
}


text:
function toggleAsteroids() {
  if (document.getElementById('Asteroids').childNodes[3] != undefined) {
    //Remove Asteroids
    resetAsteroids();
    document.getElementById('asteroidToggle').className -= ' checked';
  } else{
    generateAsteroids();
    document.getElementById('asteroidToggle').className += ' checked';
  };
}

function toggleStars() {
  if (document.getElementById('starsContainer').childNodes[1] != undefined) {
    //Remove Stars
    resetStars();
    document.getElementById('starToggle').className -= ' checked';
  } else{
    generateStars();
    document.getElementById('starToggle').className += ' checked';
  };
}

function resetAsteroids() {
  document.getElementById('Asteroids').innerHTML = document.getElementById('Asteroids').childNodes[1].outerHTML;
}

function resetStars() {
  document.getElementById('starsContainer').innerHTML = document.getElementById('starsContainer').childNodes[1].outerHTML;
}

function generateAsteroids(){
  var a = document.getElementById('Asteroids');
  var b = a.childNodes[0];

  for(var i = 0;i < 180; i+=.25){
    var c = b.cloneNode();
    var d = Math.cos(i/90*Math.PI);
    var e = Math.sin(i/90*Math.PI);
    var f = Math.floor(Math.random()*20);
    c.style.left = (d)*(185-f)+190;
    c.style.top = (e)*(185-f)+190;
    a.appendChild(c);
  }
}

function generateStars(container){
  var a = document.getElementById('starsContainer');
  var b = a.childNodes[0];
  for(var i = 0;i < 720; i++){
    var c = b.cloneNode();
    var d = Math.random()*100;
    var e = Math.random()*100;
    c.style.left = ''+d+'%';
    c.style.top =  ''+e+'%';
    a.appendChild(c);
  }
}


text:
package org.apache.synapse.endpoints;

import org.apache.synapse.MessageContext;
import org.apache.synapse.SynapseConstants;

/**
 * This class represents an endpoint with the EPR as the 'To' header of the message. It is
 * responsible for sending the message to this EPR, performing retries etc on failure and
 * using any QOS etc as specified
 */
public class DefaultEndpoint extends AbstractEndpoint {
    public void onFault(MessageContext synCtx) {

        // is this really a fault or a timeout/connection close etc?
        if (isTimeout(synCtx)) {
            getContext().onTimeout();
        } else if (isSuspendFault(synCtx)) {
            getContext().onFault();
        }

        // this should be an ignored error if we get here
        setErrorOnMessage(synCtx, null, null);
        super.onFault(synCtx);
    }

    public void onSuccess() {
        if (getContext() != null) {
            getContext().onSuccess();
        }
    }

    public void send(MessageContext synCtx) {
        if (getParentEndpoint() == null && !readyToSend()) {
            // if the this leaf endpoint is too a root endpoint and is in inactive
            informFailure(synCtx, SynapseConstants.ENDPOINT_ADDRESS_NONE_READY,
                    "Currently , Default endpoint : " + getContext());
        } else {
            super.send(synCtx);
        }
    }
}


text:
feature_name: Basic Service Worker
chrome_version: 40
feature_id: 6561526227927040
local_css_files: ['styles.css']
---

Background

  This sample demonstrates a basic service worker that could be used as-is, or
  as a starting point for further customization.

What It Does

    Precaches the HTML, JavaScript, and CSS files needed to display this page offline.
    (Try it out by reloading the page without a network connection!)

Cleans up the previously precached entries when the cache name is updated.

Intercepts network requests, returning a cached response when available.

    If there's no cached response, fetches the response from the network and
    adds it to the cache for future use.

  You can confirm the service worker's behavior using the
  Application panel
  of Chrome's DevTools.

What It Doesn't Do

    Automatically version any of the precached resources.

      You must manually update the CACHES.PRECACHE name to pick up
      new versions after updating anything!

    Cache-bust the precaching requests.

      The cache.addAll() call may be fulfilled with responses from
      the HTTP cache, depending on the HTTP caching headers you use. If you
      are using
      HTTP caching
      and unversioned resources, it can be safer to
      cache-bust
      your precaching requests.

    Refresh the entries in the runtime cache.

      Once an entry is added to the runtime cache, it's used indefinitely,
      without consulting the network to check for updates. If your runtime cache
      is used for resources that might be updated, a different strategy, like
      stale-while-revalidate
      could be more appropriate.

    Clean out the runtime cache.

      The runtime cache will grow as new resource URLs are requested. In this
      example, there are only 5 different images that might be loaded, so the
      cache size isn't a concern. If your web app might request an arbitrary
      number of unique resource URLs, then using a library like
      sw-toolbox
      which provides
      cache-expiration
      is recommended.

Live Demo

  The following demo illustrates the service worker's runtime caching by loading
  images in response to clicking the button below.

  The first time a given image is requested, the service worker will be load it
  from the network, but each subsequent time, it will be retrieved from the cache.

Icons:
<select id="icons">
  <option value="icons/ic_create_new_folder_black_48dp.png">New Folder</option>
  <option value="icons/ic_file_upload_black_48dp.png">File Upload</option>
  <option value="icons/ic_folder_black_48dp.png">Closed Folder</option>
  <option value="icons/ic_folder_open_black_48dp.png">Open Folder</option>
  <option value="icons/ic_folder_shared_black_48dp.png">Shared Folder</option>
</select>
<button id="show">Show Icon</button>

{% include js_snippet.html filename='demo.js' %}
{% include js_snippet.html filename='service-worker.js' displayonly=true title="Service Worker's JavaScript" %}


text:
//
//  MGSettingViewController.m
//  MGZhiHu
//
//  Created by 穆良 on 16/7/24.
//  Copyright © 2016年 穆良. All rights reserved.
//

#import "MGSettingViewController.h"
#import "MGSettingCell.h"

@interface MGSettingViewController ()
{
    NSArray *_cellTitleArray;
}
@end

@implementation MGSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置数据
    _cellTitleArray = @[@[@"我的资料"],
                        @[@"自动离线下载"],
                        @[@"移动网络不下载图片",@"大字号"],
                        @[@"消息推送",@"点评分享到微博"],
                        @[@"去好评",@"去吐槽"],
                        @[@"清除缓存"] ];

    [self setupNavBar];
}

#pragma mark - 初始化导航控制栏
- (void)setupNavBar
{
    // 导航栏颜色
    self.navigationController.navigationBar.barTintColor = MGNavBarColor;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];

    // 添加手势
    SWRevealViewController *revealVc = self.revealViewController;
    [self.view addGestureRecognizer:revealVc.panGestureRecognizer];
    [self.view addGestureRecognizer:revealVc.tapGestureRecognizer];

    // item都是白色的
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Dark_News_Arrow"] style:UIBarButtonItemStylePlain target:revealVc action:@selector(revealToggle:)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _cellTitleArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [_cellTitleArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0 || indexPath.section == 4 || indexPath.section == 5) {

        // 1.创建cell
        static NSString *ID = @"tableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        }
        // 2.设置cell的数据
        cell.textLabel.text = _cellTitleArray[indexPath.section][indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        // 3.返回cell
        return cell;

    } else {
        MGSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"settingCell"];

        // 2.设置cell的数据
        cell.cellTitleLabel.text = _cellTitleArray[indexPath.section][indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.cellSwitch.on = YES;

        // 3.返回cell
        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return section == 1 ? @"仅 WI-FI 下可用,自动下载最新内容" : @"";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        [self performSegueWithIdentifier:@"toLogin" sender:nil];
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
import nodeMap from '../util/node-map';

const propToAttrMap = {
  className: 'class'
};

export default function (src, tar, data) {
  const { name } = data;
  const node = nodeMap[src.__id];
  const prop = tar.properties[name];
  const mapped = propToAttrMap[name];

  if (mapped) {
    if (prop == null) {
      node.removeAttribute(mapped);
    } else {
      node.className = prop;
    }
  } else if (name === 'style') {
    const { style } = node;
    // Clear so we don't have to diff.
    style.cssText = '';

    // Handle both strings and objects.
    if (typeof prop === 'string') {
      style.cssText = prop;
    } else {
      for (let name in prop) {
        if (prop.hasOwnProperty(name)) {
          style[name] = prop[name];
        }
      }
    }
  } else {
    node[name] = prop;
  }
}


text:
package org.mozilla.javascript.tests;

import org.junit.Assert;
import org.junit.Test;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextAction;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.ScriptableObject;

/**
 * Unit tests for bug 549604.
 * This tests verify the properties of a JS exception and ensures that they don't change with different optimization levels.
 *
 * @author Marc Guillemot
 */
public class ErrorPropertiesTest {
    final static String LS = System.getProperty("line.separator");

    private void testScriptStackTrace(final String script, final String expectedStackTrace) {
        testScriptStackTrace(script, expectedStackTrace, -1);
        testScriptStackTrace(script, expectedStackTrace, 0);
        testScriptStackTrace(script, expectedStackTrace, 1);
    }

    private void testScriptStackTrace(final String script, final String expectedStackTrace,
                                      final int optimizationLevel) {
        try {
            Utils.executeScript(script, optimizationLevel);
        }
        catch (final RhinoException e) {
            Assert.assertEquals(expectedStackTrace, e.getScriptStackTrace());
        }
    }

    @Test
    public void fileName() {
        testIt("try { null.method() } catch (e) { e.fileName }", "myScript.js");
        testIt("try { null.property } catch (e) { e.fileName }", "myScript.js");
    }

    @Test
    public void lineNumber() {
        testIt("try { null.method() } catch (e) { e.lineNumber }", 1);
        testIt("try {\n null.method() \n} catch (e) { e.lineNumber }", 2);
        testIt("\ntry \n{\n null.method() \n} catch (e) { e.lineNumber }", 4);

        testIt("function f() {\n null.method(); \n}\n try { f() } catch (e) { e.lineNumber }", 2);
    }

    @Test
    public void defaultStack() {
        RhinoException.useMozillaStackStyle(false);
        testScriptStackTrace("null.method()", "\tat myScript.js:1" + LS);
        final String script = "function f() \n{\n  null.method();\n}\nf();\n";
        testScriptStackTrace(script, "\tat myScript.js:3 (f)" + LS + "\tat myScript.js:5" + LS);
        testIt("try { null.method() } catch (e) { e.stack }", "\tat myScript.js:1" + LS);
        final String expectedStack = "\tat myScript.js:2 (f)" + LS + "\tat myScript.js:4" + LS;
        testIt("function f() {\n null.method(); \n}\n try { f() } catch (e) { e.stack }", expectedStack);
    }

    @Test
    public void mozillaStack() {
        RhinoException.useMozillaStackStyle(true);
        testScriptStackTrace("null.method()", "@myScript.js:1" + LS);
        final String script = "function f() \n{\n  null.method();\n}\nf();\n";
        testScriptStackTrace(script, "f()@myScript.js:3" + LS + "@myScript.js:5" + LS);
        testIt("try { null.method() } catch (e) { e.stack }", "@myScript.js:1" + LS);
        final String expectedStack = "f()@myScript.js:2" + LS + "@myScript.js:4" + LS;
        testIt("function f() {\n null.method(); \n}\n try { f() } catch (e) { e.stack }", expectedStack);
    }

    private void testIt(final String script, final Object expected) {
        final ContextAction action = new ContextAction() {
            public Object run(final Context cx) {
                try {
                    final ScriptableObject scope = cx.initStandardObjects();
                    final Object o = cx.evaluateString(scope, script,
                            "myScript.js", 1, null);
                    Assert.assertEquals(expected, o);
                    return o;
                }
                catch (final RuntimeException e) {
                    throw e;
                }
                catch (final Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };

        Utils.runWithAllOptimizationLevels(action);
    }
}


text:
#ifndef __ZMQ_H_INCLUDED__
#define __ZMQ_H_INCLUDED__

#ifdef __cplusplus
extern "C" {
#endif

#if !defined WINCE
#include <errno.h>
#endif
#include <stddef.h>
#include <stdio.h>
#if defined _WIN32
#include <winsock2.h>
#endif

/*  Handle DSO symbol visibility                                             */
#if defined _WIN32
#   if defined DLL_EXPORT
#       define ZMQ_EXPORT __declspec(dllexport)
#   else
#       define ZMQ_EXPORT __declspec(dllimport)
#   endif
#else
#   if defined __SUNPRO_C  || defined __SUNPRO_CC
#       define ZMQ_EXPORT __global
#   elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER
#       define ZMQ_EXPORT __attribute__ ((visibility("default")))
#   else
#       define ZMQ_EXPORT
#   endif
#endif

/******************************************************************************/
/*  0MQ versioning support.                                                   */
/******************************************************************************/

/*  Version macros for compile-time API version detection                     */
#define ZMQ_VERSION_MAJOR 3
#define ZMQ_VERSION_MINOR 2
#define ZMQ_VERSION_PATCH 2

#define ZMQ_MAKE_VERSION(major, minor, patch) \
    ((major) * 10000 + (minor) * 100 + (patch))
#define ZMQ_VERSION \
    ZMQ_MAKE_VERSION(ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH)

/*  Run-time API version detection                                            */
ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch);

/******************************************************************************/
/*  0MQ errors.                                                               */
/******************************************************************************/

/*  A number random enough not to collide with different errno ranges on      */
/*  different OSes. The assumption is that error_t is at least 32-bit type.   */
#define ZMQ_HAUSNUMERO 156384712

/*  On Windows platform some of the standard POSIX errnos are not defined.    */
#ifndef ENOTSUP
#define ENOTSUP (ZMQ_HAUSNUMERO + 1)
#endif
#ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT (ZMQ_HAUSNUMERO + 2)
#endif
#ifndef ENOBUFS
#define ENOBUFS (ZMQ_HAUSNUMERO + 3)
#endif
#ifndef ENETDOWN
#define ENETDOWN (ZMQ_HAUSNUMERO + 4)
#endif
#ifndef EADDRINUSE
#define EADDRINUSE (ZMQ_HAUSNUMERO + 5)
#endif
#ifndef EADDRNOTAVAIL
#define EADDRNOTAVAIL (ZMQ_HAUSNUMERO + 6)
#endif
#ifndef ECONNREFUSED
#define ECONNREFUSED (ZMQ_HAUSNUMERO + 7)
#endif
#ifndef EINPROGRESS
#define EINPROGRESS (ZMQ_HAUSNUMERO + 8)
#endif
#ifndef ENOTSOCK
#define ENOTSOCK (ZMQ_HAUSNUMERO + 9)
#endif
#ifndef EMSGSIZE
#define EMSGSIZE (ZMQ_HAUSNUMERO + 10)
#endif
#ifndef EAFNOSUPPORT
#define EAFNOSUPPORT (ZMQ_HAUSNUMERO + 11)
#endif
#ifndef ENETUNREACH
#define ENETUNREACH (ZMQ_HAUSNUMERO + 12)
#endif
#ifndef ECONNABORTED
#define ECONNABORTED (ZMQ_HAUSNUMERO + 13)
#endif
#ifndef ECONNRESET
#define ECONNRESET (ZMQ_HAUSNUMERO + 14)
#endif
#ifndef ENOTCONN
#define ENOTCONN (ZMQ_HAUSNUMERO + 15)
#endif
#ifndef ETIMEDOUT
#define ETIMEDOUT (ZMQ_HAUSNUMERO + 16)
#endif
#ifndef EHOSTUNREACH
#define EHOSTUNREACH (ZMQ_HAUSNUMERO + 17)
#endif
#ifndef ENETRESET
#define ENETRESET (ZMQ_HAUSNUMERO + 18)
#endif

/*  Native 0MQ error codes.                                                   */
#define EFSM (ZMQ_HAUSNUMERO + 51)
#define ENOCOMPATPROTO (ZMQ_HAUSNUMERO + 52)
#define ETERM (ZMQ_HAUSNUMERO + 53)
#define EMTHREAD (ZMQ_HAUSNUMERO + 54)

/*  This function retrieves the errno as it is known to 0MQ library. The goal */
/*  of this function is to make the code 100% portable, including where 0MQ   */
/*  compiled with certain CRT library (on Windows) is linked to an            */
/*  application that uses different CRT library.                              */
ZMQ_EXPORT int zmq_errno (void);

/*  Resolves system errors and 0MQ errors to human-readable string.           */
ZMQ_EXPORT const char *zmq_strerror (int errnum);

/******************************************************************************/
/*  0MQ infrastructure (a.k.a. context) initialisation & termination.         */
/******************************************************************************/

/*  New API                                                                   */
/*  Context options                                                           */
#define ZMQ_IO_THREADS  1
#define ZMQ_MAX_SOCKETS 2

/*  Default for new contexts                                                  */
#define ZMQ_IO_THREADS_DFLT  1
#define ZMQ_MAX_SOCKETS_DFLT 1024

ZMQ_EXPORT void *zmq_ctx_new (void);
ZMQ_EXPORT int zmq_ctx_destroy (void *context);
ZMQ_EXPORT int zmq_ctx_set (void *context, int option, int optval);
ZMQ_EXPORT int zmq_ctx_get (void *context, int option);

/*  Old (legacy) API                                                          */
ZMQ_EXPORT void *zmq_init (int io_threads);
ZMQ_EXPORT int zmq_term (void *context);

/******************************************************************************/
/*  0MQ message definition.                                                   */
/******************************************************************************/

typedef struct zmq_msg_t {unsigned char _ [32];} zmq_msg_t;

typedef void (zmq_free_fn) (void *data, void *hint);

ZMQ_EXPORT int zmq_msg_init (zmq_msg_t *msg);
ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size);
ZMQ_EXPORT int zmq_msg_init_data (zmq_msg_t *msg, void *data,
    size_t size, zmq_free_fn *ffn, void *hint);
ZMQ_EXPORT int zmq_msg_send (zmq_msg_t *msg, void *s, int flags);
ZMQ_EXPORT int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags);
ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg);
ZMQ_EXPORT int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src);
ZMQ_EXPORT int zmq_msg_copy (zmq_msg_t *dest, zmq_msg_t *src);
ZMQ_EXPORT void *zmq_msg_data (zmq_msg_t *msg);
ZMQ_EXPORT size_t zmq_msg_size (zmq_msg_t *msg);
ZMQ_EXPORT int zmq_msg_more (zmq_msg_t *msg);
ZMQ_EXPORT int zmq_msg_get (zmq_msg_t *msg, int option);
ZMQ_EXPORT int zmq_msg_set (zmq_msg_t *msg, int option, int optval);

/******************************************************************************/
/*  0MQ socket definition.                                                    */
/******************************************************************************/

/*  Socket types.                                                             */
#define ZMQ_PAIR 0
#define ZMQ_PUB 1
#define ZMQ_SUB 2
#define ZMQ_REQ 3
#define ZMQ_REP 4
#define ZMQ_DEALER 5
#define ZMQ_ROUTER 6
#define ZMQ_PULL 7
#define ZMQ_PUSH 8
#define ZMQ_XPUB 9
#define ZMQ_XSUB 10

/*  Deprecated aliases                                                        */
#define ZMQ_XREQ ZMQ_DEALER
#define ZMQ_XREP ZMQ_ROUTER

/*  Socket options.                                                           */
#define ZMQ_AFFINITY 4
#define ZMQ_IDENTITY 5
#define ZMQ_SUBSCRIBE 6
#define ZMQ_UNSUBSCRIBE 7
#define ZMQ_RATE 8
#define ZMQ_RECOVERY_IVL 9
#define ZMQ_SNDBUF 11
#define ZMQ_RCVBUF 12
#define ZMQ_RCVMORE 13
#define ZMQ_FD 14
#define ZMQ_EVENTS 15
#define ZMQ_TYPE 16
#define ZMQ_LINGER 17
#define ZMQ_RECONNECT_IVL 18
#define ZMQ_BACKLOG 19
#define ZMQ_RECONNECT_IVL_MAX 21
#define ZMQ_MAXMSGSIZE 22
#define ZMQ_SNDHWM 23
#define ZMQ_RCVHWM 24
#define ZMQ_MULTICAST_HOPS 25
#define ZMQ_RCVTIMEO 27
#define ZMQ_SNDTIMEO 28
#define ZMQ_IPV4ONLY 31
#define ZMQ_LAST_ENDPOINT 32
#define ZMQ_ROUTER_MANDATORY 33
#define ZMQ_TCP_KEEPALIVE 34
#define ZMQ_TCP_KEEPALIVE_CNT 35
#define ZMQ_TCP_KEEPALIVE_IDLE 36
#define ZMQ_TCP_KEEPALIVE_INTVL 37
#define ZMQ_TCP_ACCEPT_FILTER 38
#define ZMQ_DELAY_ATTACH_ON_CONNECT 39
#define ZMQ_XPUB_VERBOSE 40

/*  Message options                                                           */
#define ZMQ_MORE 1

/*  Send/recv options.                                                        */
#define ZMQ_DONTWAIT 1
#define ZMQ_SNDMORE 2

/*  Deprecated aliases                                                        */
#define ZMQ_NOBLOCK ZMQ_DONTWAIT
#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY
#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY

/******************************************************************************/
/*  0MQ socket events and monitoring                                          */
/******************************************************************************/

/*  Socket transport events (tcp and ipc only)                                */
#define ZMQ_EVENT_CONNECTED 1
#define ZMQ_EVENT_CONNECT_DELAYED 2
#define ZMQ_EVENT_CONNECT_RETRIED 4

#define ZMQ_EVENT_LISTENING 8
#define ZMQ_EVENT_BIND_FAILED 16

#define ZMQ_EVENT_ACCEPTED 32
#define ZMQ_EVENT_ACCEPT_FAILED 64

#define ZMQ_EVENT_CLOSED 128
#define ZMQ_EVENT_CLOSE_FAILED 256
#define ZMQ_EVENT_DISCONNECTED 512

#define ZMQ_EVENT_ALL ( ZMQ_EVENT_CONNECTED | ZMQ_EVENT_CONNECT_DELAYED | \
                        ZMQ_EVENT_CONNECT_RETRIED | ZMQ_EVENT_LISTENING | \
                        ZMQ_EVENT_BIND_FAILED | ZMQ_EVENT_ACCEPTED | \
                        ZMQ_EVENT_ACCEPT_FAILED | ZMQ_EVENT_CLOSED | \
                        ZMQ_EVENT_CLOSE_FAILED | ZMQ_EVENT_DISCONNECTED )

/*  Socket event data (union member per event)                                */
typedef struct {
    int event;
    union {
    struct {
        char *addr;
        int fd;
    } connected;
    struct {
        char *addr;
        int err;
    } connect_delayed;
    struct {
        char *addr;
        int interval;
    } connect_retried;
    struct {
        char *addr;
        int fd;
    } listening;
    struct {
        char *addr;
        int err;
    } bind_failed;
    struct {
        char *addr;
        int fd;
    } accepted;
    struct {
        char *addr;
        int err;
    } accept_failed;
    struct {
        char *addr;
        int fd;
    } closed;
    struct {
        char *addr;
        int err;
    } close_failed;
    struct {
        char *addr;
        int fd;
    } disconnected;
    } data;
} zmq_event_t;

ZMQ_EXPORT void *zmq_socket (void *, int type);
ZMQ_EXPORT int zmq_close (void *s);
ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval,
    size_t optvallen);
ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval,
    size_t *optvallen);
ZMQ_EXPORT int zmq_bind (void *s, const char *addr);
ZMQ_EXPORT int zmq_connect (void *s, const char *addr);
ZMQ_EXPORT int zmq_unbind (void *s, const char *addr);
ZMQ_EXPORT int zmq_disconnect (void *s, const char *addr);
ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags);
ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags);
ZMQ_EXPORT int zmq_socket_monitor (void *s, const char *addr, int events);

ZMQ_EXPORT int zmq_sendmsg (void *s, zmq_msg_t *msg, int flags);
ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags);

/*  Experimental                                                              */
struct iovec;

ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags);
ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags);

/******************************************************************************/
/*  I/O multiplexing.                                                         */
/******************************************************************************/

#define ZMQ_POLLIN 1
#define ZMQ_POLLOUT 2
#define ZMQ_POLLERR 4

typedef struct
{
    void *socket;
#if defined _WIN32
    SOCKET fd;
#else
    int fd;
#endif
    short events;
    short revents;
} zmq_pollitem_t;

ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout);

/*  Built-in message proxy (3-way) */

ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture);

/*  Deprecated aliases */
#define ZMQ_STREAMER 1
#define ZMQ_FORWARDER 2
#define ZMQ_QUEUE 3
/*  Deprecated method */
ZMQ_EXPORT int zmq_device (int type, void *frontend, void *backend);

#undef ZMQ_EXPORT

#ifdef __cplusplus
}
#endif

#endif


text:
<?php
namespace Rocks\OAuth;

use Scotch\Security\OAuth\Client as Client;

abstract class OAuthClient
{
	protected $client;

	function __construct($clientID, $clientSecret)
	{
		$this->client = new Client($clientID, $clientSecret);
	}

	abstract function getAuthorizationEndpoint();

	abstract function getAccessTokenEndpoint();

	abstract function getUserDetailsEndpoint();

	function getAuthenticationUrl($redirectUrl, $parameters = array())
	{
		return $this->client->getAuthenticationUrl($this->getAuthorizationEndPoint(),$redirectUrl,$parameters);
	}

	function getAccessToken($grantType, $parameters = array())
	{
		return $this->client->getAccessToken($this->getAccessTokenEndPoint(),$grantType, $parameters);
	}

	function getUserDetails()
	{
		return $client->fetch($this->getUserDetailsEndPoint());
	}

	abstract function authenticate($redirectUrl,$parameters);
}
?>


text: bash command for making new git repository on your git server


text:
assertThrows("function f() { break }", SyntaxError);
assertThrows("function f() { break a }", SyntaxError);
assertThrows("function f() { continue }", SyntaxError);
assertThrows("function f() { continue a }", SyntaxError);


text:
<!--
  Copyright 2016 Google Inc.

  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.
-->
<project>
  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <groupId>com.example.flexible</groupId>
  <artifactId>memcache</artifactId>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>

    <failOnMissingWebXml>false</failOnMissingWebXml> <!-- REQUIRED -->

    <appengine.maven.plugin>2.4.3</appengine.maven.plugin>
    <jetty>9.4.44.v20210927</jetty>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <type>jar</type>
      <scope>provided</scope>
    </dependency>
    <!-- [START dependencies] -->
    <dependency>
      <groupId>com.googlecode.xmemcached</groupId>
      <artifactId>xmemcached</artifactId>
      <version>2.4.7</version>
    </dependency>
    <!-- [END dependencies] -->
  </dependencies>
  <build>
    <!-- for hot reload of the web application -->
    <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.2</version>
      </plugin>

      <plugin>
        <groupId>com.google.cloud.tools</groupId>
        <artifactId>appengine-maven-plugin</artifactId>
        <version>${appengine.maven.plugin}</version>
        <configuration>
          <projectId>GCLOUD_CONFIG</projectId>
          <version>GCLOUD_CONFIG</version>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>${jetty}</version>
      </plugin>
    </plugins>
  </build>
</project>


text:
sudo apt-get install --only-upgrade accountsservice=0.6.15-2ubuntu9.6.1 -y
sudo apt-get install --only-upgrade libaccountsservice0=0.6.15-2ubuntu9.6.1 -y
sudo apt-get install --only-upgrade libaccountsservice0=0.6.15-2ubuntu9.6.1 -y


text:
package org.apache.ws.secpolicy12.builders;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.builders.AssertionBuilder;
import org.apache.ws.secpolicy.SPConstants;
import org.apache.ws.secpolicy.SP12Constants;
import org.apache.ws.secpolicy.model.RecipientToken;
import org.apache.ws.secpolicy.model.Token;

public class RecipientTokenBuilder implements AssertionBuilder {

    public Assertion build(OMElement element, AssertionBuilderFactory factory)
            throws IllegalArgumentException {
        RecipientToken recipientToken = new RecipientToken(SPConstants.SP_V12);

        Policy policy = PolicyEngine.getPolicy(element.getFirstElement());
        policy = (Policy) policy.normalize(false);

        for (Iterator iterator = policy.getAlternatives(); iterator.hasNext();) {
            processAlternative((List) iterator.next(), recipientToken);

            /*
             * for the moment we will pick the first token specified in the policy
             */
            break;
        }

        return recipientToken;
    }

    private void processAlternative(List assertions, RecipientToken parent) {

        Assertion assertion;

        for (Iterator iterator = assertions.iterator(); iterator.hasNext();) {
            assertion = (Assertion) iterator.next();

            if (assertion instanceof Token) {
                parent.setToken((Token) assertion);
            }
        }
    }

    public QName[] getKnownElements() {
        return new QName[] {SP12Constants.RECIPIENT_TOKEN};
    }

}


text:
import { NotifierAnimationPreset, NotifierAnimationPresetKeyframes } from '../models/notifier-animation.model';

/**
 * Fade animation preset
 */
export const fade: NotifierAnimationPreset = {
  hide: (): NotifierAnimationPresetKeyframes => {
    return {
      from: {
        opacity: '1',
      },
      to: {
        opacity: '0',
      },
    };
  },
  show: (): NotifierAnimationPresetKeyframes => {
    return {
      from: {
        opacity: '0',
      },
      to: {
        opacity: '1',
      },
    };
  },
};


text:
package org.formbuilder.mapping.typemapper.impl;

import org.formbuilder.TypeMapper;
import org.formbuilder.mapping.change.ChangeHandler;
import org.formbuilder.validation.BackgroundMarker;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;

/**
 * Maps properties of type {@link String} to subclasses of {@link JTextComponent}
 *
 * @author eav Date: Aug 2, 2010 Time: 11:54:19 PM
 * @param <C> editor component type
 */
@NotThreadSafe
public abstract class StringMapper<C extends JTextComponent>
        implements TypeMapper<C, String>
{
    public void handleChanges( @Nonnull final C editorComponent,
                               @Nonnull final ChangeHandler changeHandler )
    {
        editorComponent.getDocument().addDocumentListener( new DocumentListener()
        {
            public void changedUpdate( final DocumentEvent e )
            {
                changeHandler.onChange( BackgroundMarker.INSTANCE );
            }

            public void insertUpdate( final DocumentEvent e )
            {
                changeHandler.onChange( BackgroundMarker.INSTANCE );
            }

            public void removeUpdate( final DocumentEvent e )
            {
                changeHandler.onChange( BackgroundMarker.INSTANCE );
            }
        } );
    }

    public String getValue( @Nonnull final C editorComponent )
    {
        final String text = editorComponent.getText();
        return "".equals( text ) ? null : text;
    }

    public Class<String> getValueClass()
    {
        return String.class;
    }

    public void setValue( @Nonnull final C editorComponent,
                          @Nullable final String value )
    {
        editorComponent.setText( value );
    }
}


text:
package org.neo4j.graphdb.traversal;

import java.util.LinkedList;
import java.util.Queue;

import org.neo4j.graphdb.PathExpander;

/**
 * Selects {@link TraversalBranch}s according to breadth first
 * pattern, the most natural ordering in a breadth first search, see
 * http://en.wikipedia.org/wiki/Breadth-first_search
 */
class PreorderBreadthFirstSelector implements BranchSelector
{
    private final Queue<TraversalBranch> queue = new LinkedList<TraversalBranch>();
    private TraversalBranch current;
    private final PathExpander expander;

    public PreorderBreadthFirstSelector( TraversalBranch startSource, PathExpander expander )
    {
        this.current = startSource;
        this.expander = expander;
    }

    public TraversalBranch next( TraversalContext metadata )
    {
        TraversalBranch result = null;
        while ( result == null )
        {
            TraversalBranch next = current.next( expander, metadata );
            if ( next != null )
            {
                queue.add( next );
                result = next;
            }
            else
            {
                current = queue.poll();
                if ( current == null )
                {
                    return null;
                }
            }
        }
        return result;
    }
}


text:
UPDATE ModifierArguments
	SET Value = 1
	WHERE ModifierId = "MINOR_CIV_KUMASI_CULTURE_TRADE_ROUTE_YIELD_BONUS" AND Name = "Amount";

--Reduce Nan Madol's culture bonus to coastal districts
UPDATE ModifierArguments
	SET Value = 1
	WHERE ModifierId = "MINOR_CIV_NAN_MADOL_DISTRICTS_CULTURE_BONUS" AND Name = "Amount";


text:
import { values, set } from 'lodash';

export const classes = {};

export default function install(db, {
  Cast,
  ControlledMovieCast,
  HotSpot,
  MovieCast,
  MovieSpecialCast,
  PanoAnim,
  PanoCast,
  PreloadCast,
  SoundCast,
  GameState,
  Scene,
}) {
  function apply(name, Class) {
    const model = db.model(name, new Class());
    set(classes, name, model);
    return model;
  }
  function discriminate(Parent, name, Class) {
    const model = Parent.discriminator(name, new Class());
    set(classes, name, model);
    return model;
  }

  const cast = apply('Cast', Cast);
  discriminate(cast, 'ControlledMovieCast', ControlledMovieCast);
  discriminate(cast, 'HotSpot', HotSpot);
  discriminate(cast, 'MovieCast', MovieCast);
  discriminate(cast, 'MovieSpecialCast', MovieSpecialCast);
  discriminate(cast, 'PanoAnim', PanoAnim);
  discriminate(cast, 'PanoCast', PanoCast);
  discriminate(cast, 'PreloadCast', PreloadCast);
  discriminate(cast, 'SoundCast', SoundCast);

  apply('GameState', GameState);
  apply('Scene', Scene);
}

export function get(className) {
  if (typeof className === 'undefined') {
    return values(classes);
  }

  return classes[className];
}


text:
package org.apache.pulsar.zookeeper;

import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.bookkeeper.test.PortManager;
import org.apache.pulsar.zookeeper.ZooKeeperClientFactory.SessionType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

@Test
public class ZookeeperClientFactoryImplTest {

    private ZookeeperServerTest localZkS;
    private ZooKeeper localZkc;
    private final int LOCAL_ZOOKEEPER_PORT = PortManager.nextFreePort();
    private final long ZOOKEEPER_SESSION_TIMEOUT_MILLIS = 5000;

    @BeforeMethod
    void setup() throws Exception {
        localZkS = new ZookeeperServerTest(LOCAL_ZOOKEEPER_PORT);
        localZkS.start();
    }

    @AfterMethod
    void teardown() throws Exception {
        localZkS.close();
    }

    @Test
    void testZKCreationRW() throws Exception {
        ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + LOCAL_ZOOKEEPER_PORT, SessionType.ReadWrite,
                (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertTrue(localZkc.getState().isConnected());
        assertNotEquals(localZkc.getState(), States.CONNECTEDREADONLY);
        localZkc.close();
    }

    @Test
    void testZKCreationRO() throws Exception {
        ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + LOCAL_ZOOKEEPER_PORT,
                SessionType.AllowReadOnly, (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertTrue(localZkc.getState().isConnected());
        localZkc.close();
    }

    @Test
    void testZKCreationFailure() throws Exception {
        ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("invalid", SessionType.ReadWrite,
                (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);

        try {
            zkFuture.get(3, TimeUnit.SECONDS);
            fail("Should have thrown exception");
        } catch (TimeoutException e) {
            // Expected
        }
    }
}