text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Threading;
using System.ComponentModel;
using Microsoft.Devices;
using Microsoft.Phone.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Windows.Media.Imaging;
using System.Web;
using System.Threading;
using System.Diagnostics;

namespace Xupt_lib
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            N1.Tap += N1_Tap;
            N2.Tap += N1_Tap;
            N3.Tap += N1_Tap;
            N4.Tap += N1_Tap;
            N5.Tap += N1_Tap;
            N6.Tap += N1_Tap;
            N7.Tap += N1_Tap;
            N8.Tap += N1_Tap;
            N9.Tap += N1_Tap;
            N10.Tap += N1_Tap;
            N11.Tap += N1_Tap;
            N12.Tap += N1_Tap;
            N13.Tap += N1_Tap;
            N14.Tap += N1_Tap;
            N15.Tap += N1_Tap;
            N16.Tap += N1_Tap;
            N17.Tap += N1_Tap;
            N18.Tap += N1_Tap;
            N19.Tap += N1_Tap;
            N20.Tap += N1_Tap;
            N21.Tap += N1_Tap;
            N22.Tap += N1_Tap;
            N23.Tap += N1_Tap;

        }

        void N1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var s = (Grid)sender;
            string uri = "/NewBookResult.xaml?type=" + s.Name.ToString();
            this.NavigationService.Navigate(new Uri(uri, UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.NavigationService.BackStack.ElementAt(0).Source.ToString().Contains("Guide.xaml"))
                {
                    this.NavigationService.RemoveBackEntry();
                }
            }
            catch { }
            if (DeviceNetworkInformation.IsNetworkAvailable == false)
            {
                new App.ToastTips("网络不可用");
                return;
            }
            LoadUserInfo();
        }

        private void login_Click(object sender, EventArgs e)
        {
            doLogin();
        }
        private void doLogin()
        {
            string passwd = passwd1.Password;
            string username = textBox1.Text;
            App.ID = username;
            App.Password = passwd;
            if (passwd == "" || username == "")
            {
                new App.ToastTips("用户名或密码不能为空");
                return;
            }
            ProcUserInfo();
            load.IsIndeterminate = true;
            load.IsVisible = true;
            load.Text = "加载中...";
            if (!DeviceNetworkInformation.IsNetworkAvailable)
            {
                new App.ToastTips("网络不可用");
                load.IsVisible = false;
                return;
            }
            GetWebData(username, passwd, result =>
            {
                load.IsVisible = false;
                if (result == "shibai")
                {
                    new App.ToastTips("用户名或密码错误");
                    return;
                }
                else if (result == "null")
                {
                    new App.ToastTips("信息不完整");
                    return;
                }
                else if (result == "error")
                {
                    new App.ToastTips("服务器错误");
                    return;
                }
                else if (result == "")
                {
                    return;
                }
                else
                {
                    (App.Current as App).info = result;
                    GetUserData(username, passwd, aresult =>
                    {
                        if (aresult == "true")
                        {
                            this.NavigationService.Navigate(new Uri("/certify.xaml?user=true", UriKind.Relative));
                        }
                        else
                        {
                            if ((App.Current as App).info != null)
                                this.NavigationService.Navigate(new Uri("/certify.xaml?user=false", UriKind.Relative));
                            else
                            {
                                new App.ToastTips("网络错误");
                                return;
                            }
                        }
                    });
                }
            });
        }
        private void ProcUserInfo()
        {
            if (remember.IsChecked == true)
            {
                IsolatedStorageSettings.ApplicationSettings["UserName"] = textBox1.Text;
                IsolatedStorageSettings.ApplicationSettings["Password"] = passwd1.Password;
                IsolatedStorageSettings.ApplicationSettings["Remember"] = true;
            }
            else
            {
                try { IsolatedStorageSettings.ApplicationSettings.Remove("UserName"); }
                catch { }
                try { IsolatedStorageSettings.ApplicationSettings.Remove("Password"); }
                catch { }
                try { IsolatedStorageSettings.ApplicationSettings.Remove("Remember"); }
                catch { }
            }
        }

        private void LoadUserInfo()
        {
            if (!(IsolatedStorageSettings.ApplicationSettings.Contains("UserName") ||
                IsolatedStorageSettings.ApplicationSettings.Contains("Password") ||
                IsolatedStorageSettings.ApplicationSettings.Contains("Remember")))
            {
                textBox1.Text = "";
                passwd1.Password = "";
                remember.IsChecked = false;
            }
            else
            {
                textBox1.Text = IsolatedStorageSettings.ApplicationSettings["UserName"].ToString();
                passwd1.Password = IsolatedStorageSettings.ApplicationSettings["Password"].ToString();
                remember.IsChecked = true;
            }
        }

        private void reset_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            passwd1.Password = "";
            remember.IsChecked = false;
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (book.SelectedIndex)
            {
                case 0:
                    ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["submit"];
                    break;
                case 1:
                    ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["search"];
                    break;
                case 2:
                    ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["rank"];
                    //GetRanksInfo();
                    break;
                default:
                    ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["submit"];
                    break;
            }
        }
#region
        /*void GetRanksInfo()
        {
            Dispatcher.BeginInvoke(() =>
                {
                    string Rank1, Rank2, Rank3, Rank4;
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("Rank1"))
                    {
                        if (!string.IsNullOrEmpty(IsolatedStorageSettings.ApplicationSettings["Rank1"].ToString()))
                        {
                            Rank1 = IsolatedStorageSettings.ApplicationSettings["Rank1"].ToString();
                            JObject obj = JObject.Parse(Rank1);
                            Dispatcher.BeginInvoke(() =>
                            {
                                R1.Message = "共计:" + (string)obj["Amount"] + " 条";
                            });
                        }
                        else
                        {
                            RanksHttpRequset("01", result =>
                            {
                                Rank1 = result;
                                IsolatedStorageSettings.ApplicationSettings["Rank1"] = Rank1;
                                JObject obj = JObject.Parse(Rank1);
                                Dispatcher.BeginInvoke(() =>
                                {
                                    R1.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                            });
                        }
                    }
                    else
                    {
                        RanksHttpRequset("01", result =>
                        {
                            Rank1 = result;
                            IsolatedStorageSettings.ApplicationSettings["Rank1"] = Rank1;
                            JObject obj = JObject.Parse(Rank1);
                            Dispatcher.BeginInvoke(() =>
                                {
                                    R1.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                        });
                    }
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("Rank2"))
                    {
                        if (!string.IsNullOrEmpty(IsolatedStorageSettings.ApplicationSettings["Rank2"].ToString()))
                        {
                            Rank2 = IsolatedStorageSettings.ApplicationSettings["Rank2"].ToString();
                            JObject obj = JObject.Parse(Rank2);
                            Dispatcher.BeginInvoke(() =>
                            {
                                R1.Message = "共计:" + (string)obj["Amount"] + " 条";
                            });
                        }
                        else
                        {
                            RanksHttpRequset("02", result =>
                            {
                                Rank2 = result;
                                IsolatedStorageSettings.ApplicationSettings["Rank2"] = Rank2;
                                JObject obj = JObject.Parse(Rank2);
                                Dispatcher.BeginInvoke(() =>
                                {
                                    R2.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                            });
                        }
                    }
                    else
                    {
                        RanksHttpRequset("02", result =>
                        {
                            Rank2 = result;
                            IsolatedStorageSettings.ApplicationSettings["Rank2"] = Rank2;
                            JObject obj = JObject.Parse(Rank2);
                            Dispatcher.BeginInvoke(() =>
                                {
                                    R2.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                        });
                    }
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("Rank3"))
                    {
                        if (!string.IsNullOrEmpty(IsolatedStorageSettings.ApplicationSettings["Rank3"].ToString()))
                        {
                            Rank3 = IsolatedStorageSettings.ApplicationSettings["Rank3"].ToString();
                            JObject obj = JObject.Parse(Rank3);
                            Dispatcher.BeginInvoke(() =>
                            {
                                R1.Message = "共计:" + (string)obj["Amount"] + " 条";
                            });
                        }
                        else
                        {
                            RanksHttpRequset("03", result =>
                            {
                                Rank3 = result;
                                IsolatedStorageSettings.ApplicationSettings["Rank3"] = Rank3;
                                JObject obj = JObject.Parse(Rank3);
                                Dispatcher.BeginInvoke(() =>
                                {
                                    R3.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                            });
                        }
                    }
                    else
                    {
                        RanksHttpRequset("03", result =>
                        {
                            Rank3 = result;
                            IsolatedStorageSettings.ApplicationSettings["Rank3"] = Rank3;
                            JObject obj = JObject.Parse(Rank3);
                            Dispatcher.BeginInvoke(() =>
                                {
                                    R3.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                        });
                    }
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("Rank4"))
                    {
                        if (!string.IsNullOrEmpty(IsolatedStorageSettings.ApplicationSettings["Rank4"].ToString()))
                        {
                            Rank4 = IsolatedStorageSettings.ApplicationSettings["Rank4"].ToString();
                            JObject obj = JObject.Parse(Rank4);
                            Dispatcher.BeginInvoke(() =>
                            {
                                R1.Message = "共计:" + (string)obj["Amount"] + " 条";
                            });
                        }
                        else
                        {
                            RanksHttpRequset("05", result =>
                            {
                                Rank4 = result;
                                IsolatedStorageSettings.ApplicationSettings["Rank4"] = Rank4;
                                JObject obj = JObject.Parse(Rank4);
                                Dispatcher.BeginInvoke(() =>
                                {
                                    R4.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                            });
                        }
                    }
                    else
                    {
                        RanksHttpRequset("05", result =>
                        {
                            Rank4 = result;
                            IsolatedStorageSettings.ApplicationSettings["Rank4"] = Rank4;
                            JObject obj = JObject.Parse(Rank4);
                            Dispatcher.BeginInvoke(() =>
                                {
                                    R4.Message = "共计:" + (string)obj["Amount"] + " 条";
                                });
                        });
                    }
                });
        }*/
        void RanksHttpRequset(string type,HandleResult handle)
        {
            this.handle = handle;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://222.24.63.109/lib/rank.aspx?type=" + type);
            request.UserAgent = "XiyouLibrary_Windows_Phone_Client";
            request.BeginGetResponse(new AsyncCallback(RanksRes), request);
        }
        void RanksRes(IAsyncResult result)
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            handle(reader.ReadToEnd());
        }
#endregion
        private void about_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/about.xaml", UriKind.Relative));
        }

        private void textBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            if (textBox1.Text == "")
                return;
            textBox1.Text = textBox1.Text.ToUpper();
            //if (textBox1.Text[0].ToString().ToUpper() != "S")
            //{
            //    Regex rex = new Regex("[0-9]+");
            //    Match ma = rex.Match(textBox1.Text);
            //    if (ma.Success)
            //    {
            //        textBox1.Text = "S" + textBox1.Text;
            //    }
            //}
        }
#region
        public delegate void HandleResult(string result);
        private HandleResult handle;
        private void GetWebData(string User, string Password, HandleResult handle)
        {
            this.handle = handle;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(string.Format("http://222.24.63.101/library/login?userNumber={0}&password={1}", User, Password));
            req.UserAgent = "XiyouLibrary_Windows_Phone_Client";
            req.BeginGetResponse(new AsyncCallback(GetResponse), req);
        }
        private void GetResponse(IAsyncResult result)
        {
            string responsestring = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                Stream streamResponse = response.GetResponseStream();
                using (StreamReader streamread = new StreamReader(streamResponse))
                {
                    responsestring = streamread.ReadToEnd();
                }
                streamResponse.Close();
            }
            catch
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => { handle("error"); });
            }
            Deployment.Current.Dispatcher.BeginInvoke(() => { handle(responsestring); });
        }
        byte[] postBin;
        private void GetUserData(string User, string Password,HandleResult handle)
        {
            this.handle = handle;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://222.24.63.109/libuser/");
            req.UserAgent = "XiyouLibrary_Windows_Phone_Client";
            string param = string.Format("id={0}&password={1}", User,Password);
            postBin = Encoding.UTF8.GetBytes(param);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            req.BeginGetRequestStream(new AsyncCallback(GetRequestSt), req);
        }
        private void GetRequestSt(IAsyncResult result)
        {
            HttpWebRequest Request = (HttpWebRequest)result.AsyncState;
            using (Stream st = Request.EndGetRequestStream(result))
            {
                st.Write(postBin, 0, postBin.Length);
            }
            Request.BeginGetResponse(new AsyncCallback(UserDataResponse), Request);
            //st.Close();
        }
        private void UserDataResponse(IAsyncResult result)
        {
            string responsestring = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                Stream streamResponse = response.GetResponseStream();
                using (StreamReader streamread = new StreamReader(streamResponse))
                {
                    responsestring = streamread.ReadToEnd();
                }
                streamResponse.Close();
            }
            catch
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => { handle("error"); });
            }
            if (responsestring.Contains("Login_Failed"))
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => { handle("failed"); });
            }
            JObject data = JObject.Parse(responsestring);
            App.User = new UserInfo
            {
                ID = (string)data["ID"],
                Name = (string)data["Name"],
                Cls = (string)data["Cls"]
            };
            Deployment.Current.Dispatcher.BeginInvoke(() => { handle("true"); });
        }
#endregion

        private void PhoneApplicationPage_BackKeyPress_1(object sender, CancelEventArgs e)
        {
            if (MessageBox.Show("确定退出吗?", "西邮图书借阅查询系统", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                e.Cancel = true;
        }

        private void passwd1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                doLogin();
            }
        }

        private void SearchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (SearchBox.Text != "")
            {
                SearchBox.Tag = "";
            }
            else
            {
                SearchBox.Tag = "轻触输入关键词";
            }
        }

        private void SearchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (SearchBox.Text != "")
            {
                SearchBox.Tag = "";
            }
            else
            {
                SearchBox.Tag = "轻触输入关键词";
            }
            SearchBox.SelectAll();
        }

        private void DoSearch()
        {
            if (SearchBox.Text == "")
            {
                new App.ToastTips("关键词不能为空");
                return;
            }
            if (SearchBox.Text.Length <= 1)
            {
                new App.ToastTips("关键词长度过短");
                return;
            }
            App.SearchParam = SearchBox.Text;
            string uri = "/SearchResult.xaml";
            this.NavigationService.Navigate(new Uri(uri, UriKind.Relative));
        }

        private void search_Click(object sender, EventArgs e)
        {
            DoSearch();
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            DoSearch();
        }

        private void SearchBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DoSearch();
            }
        }

        private void MoreSearch_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/SpecificSearch.xaml", UriKind.Relative));
        }

        private void textBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox1.SelectAll();
        }

        private void passwd1_GotFocus_1(object sender, RoutedEventArgs e)
        {
            passwd1.SelectAll();
        }

        private void textBox1_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                passwd1.Focus();
        }

        private void reset_search_Click(object sender, EventArgs e)
        {
            SearchBox.Text = "";
        }

        private void scanbarcode_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/ScanPage.xaml", UriKind.Relative));

        }

        private void refresh_rank_Click(object sender, EventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings.Remove("Rank1");
            IsolatedStorageSettings.ApplicationSettings.Remove("Rank2");
            IsolatedStorageSettings.ApplicationSettings.Remove("Rank3");
            IsolatedStorageSettings.ApplicationSettings.Remove("Rank4");
        }

        private void R1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/RankDetail.xaml?kind=1",UriKind.Relative));
        }

        private void R2_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/RankDetail.xaml?kind=2", UriKind.Relative));
        }

        private void R3_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/RankDetail.xaml?kind=3", UriKind.Relative));
        }

        private void R4_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/RankDetail.xaml?kind=4", UriKind.Relative));
        }

        private void mPass_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/ModifyPassword.xaml", UriKind.Relative));
        }

        private void clearUserInfo_Click(object sender, EventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings.Remove("UserName");
            IsolatedStorageSettings.ApplicationSettings.Remove("Password");
            IsolatedStorageSettings.ApplicationSettings.Remove("Remember");
            textBox1.Text = "";
            passwd1.Password = "";
            remember.IsChecked = false;
        }

    }
}


text:
<?php

namespace Borobudur\Broadcasting;

/**
 * @author      Iqbal Maulana <iq.bluejack@gmail.com>
 * @created     9/16/15
 */
interface BroadcastEventInterface
{
    const DEFAULT_CHANNEL = 'borobudur-channel';

    /**
     * Set broadcast name.
     *
     * @param string $name
     */
    public function setBroadcastName($name);

    /**
     * Get broadcast name.
     *
     * @return string
     */
    public function getBroadcastName();

    /**
     * Set broadcast channels.
     *
     * @param array $channels
     */
    public function setBroadcastChannel(array $channels);

    /**
     * Get broadcast channels.
     *
     * @return array
     */
    public function getBroadcastChannels();

    /**
     * @return array|null
     */
    public function getBroadcastPayload();
}

redpajama_set_name: RedPajamaGithub


text:
"""The interface and txt implementation classes to do pyrering reports.

This module has an Reporter interface which defines the basic API for PyreRing
report.
Another class TxtReporter is the implementation of the interface. It is ready
to be used to generate a txt report with a fixed format. User can extend from
either the interface or the TxtReporter to generate the report format whatever
they like.
"""

__author__ = 'mwu@google.com (Mingyu Wu)'

import logging
import time
from lib import common_util
from lib import constants

logger = logging.getLogger('PyreRing')
DEBUG = common_util.DebugLog

HEAD = 1
SUMMARY = 2
PRE_BODY = 3
BODY = 4
EXTRA = 5
APPEND = 6
OVERWRITE = 7

TRUNCATE_MESSAGE = '''
...message truncated. Check the bottom for the full message.
'''

class Error(Exception):
  """Base reporter Exception."""
  pass

class ReporterError(Error):
  """General reporter exception."""
  pass

class Reporter(object):
  """The abstract base class for reporter."""

  def StartTest(self,
                unused_test_name,
                unused_host_name,
                unused_tester,
                unused_uid,
                unused_uname):
    """Called before the real test starts.

    Args:
      unused_test_name: the name of the test, normally should be just a list of
      the tests.
      unused_host_name: the machine runs the test.
      unused_tester: the user executes the test.
      unused_uid: the uid of the tester.
      unused_uname: the uname string of the machine.

    Returns:
      None.
    """
    raise NotImplementedError('Prepare to start a test')

  def EndTest(self):
    """Called after all test completed to wrap up report."""
    raise NotImplementedError('Finish up the test')

  def SuiteReport(self, unused_name, unused_result, unused_msg):
    """Report one suite result.

    Args:
      unused_name: the suite's name
      unused_result: the test result string 'PASS/FAIL'
      unused_msg: extra message to append

    Returns:
      None.
    """
    raise NotImplementedError('Report a suite result')

  def TestCaseReport(self, unused_name, unused_result, unused_msg):
    """Report one test result.

    Args:
      unused_name: the test case name
      unused_result: the result string 'PASS/FAIL/TIMEOUT'
      unused_msg: extra message to append

    Returns:
      None.
    """
    raise NotImplementedError('Report a test case result', msg='')

  def ExtraMessage(self, unused_msg):
    """Extra message needed to append to the report.

    Args:
      unused_msg: a string to append at the end of the report.

    Returns:
      None.
    """
    raise NotImplementedError('Attach extra message at the end of the test')

  def GetReportFile(self):
    """Get the report file name."""
    raise NotImplementedError('Return a file for the test result')

  def SetReportFile(self, unused_file_name):
    """Set the report file."""
    raise NotImplementedError('Set the report file')

class TxtReporter(Reporter):
  """A txt reporter reports test in txt format."""

  def __init__(self, project_name=''):
    """init the test reporter with a project name."""
    super(TxtReporter, self).__init__()
    logger.debug('enter TxtReporter.__init__')
    self.project_name = project_name
    self.report_file = ''
    self.report_pipe = ''

    self.start_time = ''
    self.end_time = 'NOT END YET'

    self.testresults = []
    self.suiteresults = []
    self.passed = 0
    self.failed = 0
    self.timeout = 0
    self.notrun = 0
    self.error = 0
    self.unknown = 0
    self.extra_message = '\nExtra Notes:\n'

    self.header = 'HEADER:\n'
    self.summary = 'SUMMARY:\n'
    self.body = 'BODY:\n'
    self.extra = 'EXTRA:\n'
    self.pre_body = 'PRE_BODY:\n'

    logger.debug('exit TxtReporter.__init__')

  def _WriteToRecord(self, location, msg, mode=APPEND):
    """Save info to record strings.

    This method will store the msg into a string for the test report.

    Args:
      location: one of the constants, HEAD, SUMMARY, BODY, EXTRA.
      msg: a string message.
      mode: one of the constants, APPEND, OVERWRITE.

    Returns:
      None.

    Raises:
      ReporterError: if the location or mode fall out of the expected values.
    """
    if location not in [HEAD, SUMMARY, PRE_BODY, BODY, EXTRA]:
      raise ReporterError('Unknown location: %d' % location)
    if mode not in [APPEND, OVERWRITE]:
      raise ReporterError('Unknown mode: %d' % mode)

    if location == HEAD and mode == APPEND:
      self.header = '%s%s\n' % (self.header, msg)
    elif location == HEAD and mode == OVERWRITE:
      self.header = 'HEADER:\n%s\n' % msg
    elif location == SUMMARY and mode == APPEND:
      self.summary = '%s%s\n' % (self.summary, msg)
    elif location == SUMMARY and mode == OVERWRITE:
      self.summary = 'SUMMARY:\n%s\n' % msg
    elif location == PRE_BODY and mode == APPEND:
      self.pre_body = '%s%s\n' % (self.pre_body, msg)
    elif location == PRE_BODY and mode == OVERWRITE:
      self.pre_body = 'PRE_BODY:\n%s\n' % msg
    elif location == BODY and mode == APPEND:
      self.body = '%s%s\n' % (self.body, msg)
    elif location == BODY and mode == OVERWRITE:
      self.body = 'BODY:\n%s\n' % msg
    elif location == EXTRA and mode == APPEND:
      self.extra = '%s%s\n' % (self.extra, msg)
    elif location == EXTRA and mode == OVERWRITE:
      self.extra = 'EXTRA:\n%s\n' % msg

  @DEBUG
  def TestCaseReport(self, name, result, msg=''):
    """Report one test case result.

    This method should be called every time a test is finished. It will log the
    result to the report body part.

    Args:
      name: the testcase name
      result: the result string 'PASS/FAIL/TIMEOUT/ERROR'
      msg: any extra messsage needed to append to the end of this test case.

    Returns:
      None.
    """
    self._WriteToRecord(BODY, 'TESTCASE: %s     %s' % (name, result))
    if msg:
      self._WriteToRecord(BODY, '    %s' % msg)
    # Collect none passed test in PRE_BODY too.
    if result != constants.PASS:
      self._WriteToRecord(PRE_BODY, 'TESTCASE: %s     %s' % (name, result))

    if result == constants.TIMEOUT:
      self.timeout += 1
    elif result == constants.FAIL:
      self.failed += 1
    elif result == constants.PASS:
      self.passed += 1
    elif result == constants.NOTRUN:
      self.notrun += 1
    elif result == constants.ERROR:
      self.error += 1
    else:
      self.unknown += 1

    self._WriteToReport()

  @DEBUG
  def SuiteReport(self, name, result, msg=''):
    """Report one suite result.

    This method should be called every time a test suite is finished. It will
    log the result to the report body part.

    Args:
      name: the suite name to report
      result: the result string 'PASS/FAIL'
      msg: any extra message you want to append to the end of this line.

    Returns:
      None.
    """
    self._WriteToRecord(BODY, '\nSUITE: %s%s%s\n%s%s' %
                        (name, ' ' * 4, result, ' ' * 8, msg))
    self._WriteToReport()

  @DEBUG
  def SetReportFile(self, file_name):
    """Update the report file name and open for writing.

    This will set the report file and open it for writing.
    If the report file failed to open, the test should be stopped. So no need
    to catch any exceptions here. Just let it raise up to the top level who
    ever calls it.

    Args:
      file_name: the full path of the report file.

    Returns:
      None.
    """
    self.report_file = file_name

  @DEBUG
  def GetReportFile(self):
    """Return the report file name."""
    return self.report_file

  @DEBUG
  def StartTest(self, test_name, host_name, tester, uid, uname):
    """Called at the start of the test.

    This method be called before the real test gets started. It will mark the
    time and write some prefix info about the test to the report file.

    Args:
      test_name: the name of this test.
      host_name: the machine the test runs on.
      tester: the user executed the test.
      uid: the uid of the tester.
      uname: the uname value of the host.

    Returns:
      None.
    """
    self.start_time = self._GetTimeString()
    self.test_name = str(test_name)

    self._PrefixReport(host_name, tester, uid, str(uname))
    self._WriteToReport()

  @DEBUG
  def EndTest(self):
    """Announce the test is finished, clean up.

    This method should record the end time and write the summary to the report
    file and close it. And it will close whatever pipe the instance is using.
    """
    self.end_time = self._GetTimeString()
    self._SummaryTestToRecord()
    self._WriteToReport()

  def _WriteToReport(self):
    """Write the result to self.report_file."""
    self.report_pipe = open(self.report_file, 'w')
    self.report_pipe.write(''.join(['-' * 40, '\n']))
    for message in [self.header, self.summary, self.pre_body,
                    self.body, self.extra]:
      self.report_pipe.write(message)
      self.report_pipe.write(''.join(['-' * 40, '\n']))
      self.report_pipe.flush()
    self.report_pipe.close()

  def _WriteTestToFile(self, output_file, testcase, msg):
    """Write test case output to a single file.

    Args:
      output_file: string, pathname of testcase output file.
      testcase: string, testcase name.
      msg: string, output from testcase.
    Returns:
      None.
    """
    self.report_pipe = open(output_file, 'w')
    self.report_pipe.write(testcase)
    self.report_pipe.write('\n\n')
    self.report_pipe.write(msg)
    self.report_pipe.flush()
    self.report_pipe.close()

  def _SummaryTestToRecord(self):
    """Construct a test summary and send to pipe.

    This is an assistant method to calculate and construct a summary info for
    the test run and send to the given pipe.

    Returns:
      None. The constructed info sent to report_pipe.
    """
    total = (self.passed + self.failed + self.timeout + self.notrun +
             self.error + self.unknown)
    if not total:
      percent = '0'
    else:
      percent = str(self.passed * 100 / total)

    self._WriteToRecord(
        SUMMARY,
        '\n'.join(['Test Summary:',
                   'Test %8s:     %d' % (constants.PASS, self.passed),
                   'Test %8s:     %d' % (constants.FAIL, self.failed),
                   'Test %8s:     %d' % (constants.TIMEOUT, self.timeout),
                   'Test %8s:     %d' % (constants.ERROR, self.error),
                   'Test %8s:     %d' % (constants.NOTRUN, self.notrun),
                   'Test Pass rate:     %s%%' % percent,
                   'Test Case Total:     %d' % total,
                   'Test Start Time:     %s' % self.start_time,
                   'Test End Time:       %s' % self.end_time,
                  ]),
        OVERWRITE)
    if self.unknown:
      self._WriteToRecord(SUMMARY, 'Test Result unknown: %d\n' % self.unknown)

  def _GetTimeString(self):
    """Generate a string represent current local time.

    TODO(mwu): I am planning to move this method to a common library sometime,
    since it is needed more than one place and it has nothing to do with any
    individual module.

    Returns:
      a string for timestamp.
    """
    return time.strftime('%Y%m%d%H%M')

  def _PrefixReport(self, host_name, tester, uid, uname):
    """Prepare the header section of a test report.

    This method will collect some test running environment and write to a pipe.
    Normally it is used to prefix a test result. Hence the name.

    Args:
      host_name: the name of the machine the test runs
      tester: the user executes the test
      uid: user id of the tester
      uname: uname of the host

    Returns:
      None.
    """
    s = ['PyreRing Test Report',
         'Project: %s' % self.project_name,
         'Suites: %s' % self.test_name,
         'Start Time: %s' % self.start_time,
         'Host Name: %s' % host_name,
         'Tester: %s' % tester,
         'UID: %s' % uid,
         'uname: %s' % str(uname),
         '=' * 80,
        ]

    self._WriteToRecord(HEAD, '\n'.join(s), OVERWRITE)

  @DEBUG
  def AttachHeader(self, msg, length=10):
    """ExtraMessage adds before the body of the report.

    The method will post max 'length' line of msg to the header part and
    reattach the message to EXTRA section if the msg is more than 'length'
    lines.

    Args:
      msg: <string> a string message add to the pre_body part.
      length: <int> the length kept in header part.

    Returns:
      None.
    """
    msg_list = msg.splitlines()
    if len(msg_list) > length:
      # The pre_body part has a limit of 10 lines, if the msg is larger than 10
      # lines, truncate it and attach to the extra part at the bottom.
      self._WriteToRecord(EXTRA, '...full message of header part\n')
      self._WriteToRecord(EXTRA, msg)
      self._WriteToRecord(HEAD, '\n'.join(msg_list[:(length - 1)]))
      self._WriteToRecord(HEAD, TRUNCATE_MESSAGE)
    else:
      self._WriteToRecord(HEAD, msg)

  @DEBUG
  def ExtraMessage(self, msg):
    """ExtraMessage adds to the bottom of the report.

    Args:
      msg: a string message add to the end of the report.

    Returns:
      None.
    """
    self._WriteToRecord(EXTRA, msg)

  @DEBUG
  def SendTestOutput(self, output_file, testcase, message):
    """Send output from one testcase to a file.

    Args:
      output_file: string, pathname of file to write testcase output.
      testcase: string, name of testcase.
      message: string, output from testcase.

    Returns:
      None.
    """
    self._WriteTestToFile(output_file, testcase, message)


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=".PinFormFragment">

    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ratingBar"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="25dp"
        android:layout_above="@+id/pick_button"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pick_photo"
        android:id="@+id/pick_button"
        android:layout_gravity="center_horizontal"
        style="?android:attr/borderlessButtonStyle"
        android:textColor="#ff0097a7"
        android:textSize="14sp"
        android:layout_above="@+id/new_pin_button"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="75dp"
        android:layout_height="36dp"
        android:text="@string/pin_it"
        android:id="@+id/new_pin_button"
        android:layout_gravity="center_horizontal"
        android:background="#ff0097a7"
        android:textColor="#ffffffff"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/radioGroup"
        android:layout_below="@+id/formDescription"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="48dp"
        android:weightSum="1"
        android:layout_toLeftOf="@+id/new_pin_button"
        android:layout_toStartOf="@+id/new_pin_button">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/search_place"
            android:id="@+id/radioButtonSearch"
            android:checked="true" />

    </RadioGroup>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/formDescription"
        android:layout_gravity="center_horizontal"
        android:hint="@string/description"
        android:layout_below="@+id/formTitle"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/formTitle"
        android:hint="@string/title"
        android:textSize="30dp"
        android:singleLine="false"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="172dp"
        android:layout_height="wrap_content"
        android:id="@+id/editTextPlace"
        android:inputType="text"
        android:layout_alignBottom="@+id/radioGroup"
        android:layout_alignLeft="@+id/new_pin_button"
        android:layout_alignStart="@+id/new_pin_button"/>

</RelativeLayout>


text:
Utilies for playing cards.

## Installation

    npm install card-utils

## Usage

```javascript
var cardUtils = require('card-utils');

var deck = cardUtils.generateDeck();
var shuffled = cardUtils.shuffle(deck);
var sorted = cardUtils.sort(shuffled);
```

## Tests

Run `npm test` in package root.


text:
import {reducerBuilder} from '../../reducers/reducer-builder';
import {loadMixedTypes, saveMixedTypes} from '../actions/mixed-actions';

// default data
const DEFAULT_DATA = {
    city: 'Libercourt'
};

// Reducer for the user entity with a state modification on load and save.
const userReducer = reducerBuilder({
    name: 'USER.ADDRESS',
    loadTypes: loadMixedTypes,
    saveTypes: saveMixedTypes,
    defaultData: DEFAULT_DATA
});

export default userReducer;


text:
#include "unwind_i.h"
#include "dwarf_i.h"

HIDDEN define_lock (aarch64_lock);
HIDDEN int tdep_init_done;

HIDDEN void
tdep_init (void)
{
  intrmask_t saved_mask;

  sigfillset (&unwi_full_mask);

  lock_acquire (&aarch64_lock, saved_mask);
  {
    if (tdep_init_done)
      /* another thread else beat us to it... */
      goto out;

    mi_init ();

    dwarf_init ();

#ifndef UNW_REMOTE_ONLY
    aarch64_local_addr_space_init ();
#endif
    tdep_init_done = 1; /* signal that we're initialized... */
  }
 out:
  lock_release (&aarch64_lock, saved_mask);
}


text:
import sys
import time
import requests
import csv

BASE_URL = "http://127.0.0.1:5000/"
POST_URL = BASE_URL + "benchmark/write"
GET_URL = BASE_URL + "benchmark/read/"
GET_QUERY = "test"
CSV_HEADER = ['type', 'server_cpu_usage', 'server_memory_usage', 'so_cpu_usage', 'so_memory_usage' , 'db_time', 'total_time', 'response_time']
SAMPLES = []

def run_experiment(test_type, requests_per_min, duration):
    start_time = time.time()
    for i in range(duration):
        if test_type == 'POST':
            run_post_experiment(requests_per_min)
        elif test_type == 'GET':
            run_get_experiment(requests_per_min)
        else:
            print (test_type +" Is an invalid experiment type")
            break
        time.sleep(60)

    save_to_csv(test_type, duration, requests_per_min)

def run_post_experiment(requests_per_min):
    global SAMPLES
    for i in range(requests_per_min):
        start_time = time.time()
        r = requests.post(POST_URL,json={"title":"test", "text":"lorem ipsum"})
        response_time = time.time() - start_time
        json = r.json()
        SAMPLES.append(['POST',
            json['server_cpu_usage'],
            json['server_memory_usage'],
            json['so_cpu_usage'],
            json['so_memory_usage'],
            json['db_time'],
            json['total_time'],
            response_time])

def run_get_experiment(requests_per_min):
    global SAMPLES
    for i in range(requests_per_min):
        start_time = time.time()
    	r = requests.get(GET_URL + GET_QUERY)
        response_time = time.time() - start_time
    	json =  r.json()
    	        SAMPLES.append(['GET',
                    json['server_cpu_usage'],
                    json['server_memory_usage'],
                    json['so_cpu_usage'],
                    json['so_memory_usage'],
                    json['db_time'],
                    json['total_time'],
                    response_time])

def save_to_csv(test_type, duration, requests_per_min):
    file_name = "{timestamp}-{test_type}_{requests}_requests_per_minute_for_{duration}_min.csv".format(timestamp=time.time(), test_type=test_type, requests=requests_per_min, duration=duration)
    with open(file_name, 'wb') as csvfile:
    	writer = csv.writer(csvfile, delimiter=',', escapechar=' ', quoting=csv.QUOTE_NONE)
    	writer.writerow(CSV_HEADER)
    	for row in zip(SAMPLES):
    		writer.writerow(row[0])

if __name__ == "__main__":
    if(len(sys.argv) < 4):
    	print "Run with: <test_type> <requests per min> <duration in min>"
    else:
        test_type = str(sys.argv[1]).upper()
        requests_per_min = int(sys.argv[2])
        duration = int(sys.argv[3])

        # Run Experiments with provided configuration
        print("Running...")
        run_experiment(test_type, requests_per_min, duration)

        # End message
        file_name = "{timestamp}-{test_type}_{requests}_requests_per_minute_for_{duration}_min.csv".format(timestamp=time.time(), test_type=test_type, requests=requests_per_min, duration=duration)
        print("\n\nFinished execution of {request} req/min for {duration} min".format(request=requests_per_min, duration=duration))
        print("saved results on file: {file_name}".format(file_name = file_name))


text:
"""Backend session management for accounts.

The actual backend sessions are provided by ``flask-kvsession``.
This module provides management functionality and populates the
:class:`invenio_accounts.models.SessionActivity` table as new sessions are
created.
"""

from __future__ import absolute_import, print_function

from flask import after_this_request, current_app, request, session
from geolite2 import geolite2
from invenio_db import db
from ua_parser import user_agent_parser
from werkzeug.local import LocalProxy

from .models import SessionActivity
from .proxies import current_accounts

_sessionstore = LocalProxy(lambda: current_app.kvsession_store)

def _ip2country(ip):
    """Get user country."""
    if ip:
        match = geolite2.reader().get(ip)
        return match.get('country', {}).get('iso_code') if match else None

def _extract_info_from_useragent(user_agent):
    """Extract extra informations from user."""
    parsed_string = user_agent_parser.Parse(user_agent)
    return {
        'os': parsed_string.get('os', {}).get('family'),
        'browser': parsed_string.get('user_agent', {}).get('family'),
        'browser_version': parsed_string.get('user_agent', {}).get('major'),
        'device': parsed_string.get('device', {}).get('family'),
    }

def add_session(session=None):
    r"""Add a session to the SessionActivity table.

    :param session: Flask Session object to add. If None, ``session``
        is used. The object is expected to have a dictionary entry named
        ``"user_id"`` and a field ``sid_s``
    """
    user_id, sid_s = session['user_id'], session.sid_s
    with db.session.begin_nested():
        session_activity = SessionActivity(
            user_id=user_id,
            sid_s=sid_s,
            ip=request.remote_addr,
            country=_ip2country(request.remote_addr),
            **_extract_info_from_useragent(
                request.headers.get('User-Agent', '')
            )
        )
        db.session.merge(session_activity)

def login_listener(app, user):
    """Connect to the user_logged_in signal for table population.

    :param app: The Flask application.
    :param user: The :class:`invenio_accounts.models.User` instance.
    """
    @after_this_request
    def add_user_session(response):
        """Regenerate current session and add to the SessionActivity table.

        .. note:: `flask.session.regenerate()` actually calls Flask-KVSession's
            `flask_kvsession.KVSession.regenerate`.
        """
        # Regenerate the session to avoid session fixation vulnerabilities.
        session.regenerate()
        # Save the session first so that the sid_s gets generated.
        app.session_interface.save_session(app, session, response)
        add_session(session)
        current_accounts.datastore.commit()
        return response

def logout_listener(app, user):
    """Connect to the user_logged_out signal.

    :param app: The Flask application.
    :param user: The :class:`invenio_accounts.models.User` instance.
    """
    @after_this_request
    def _commit(response=None):
        if hasattr(session, 'sid_s'):
            delete_session(session.sid_s)
        # Regenerate the session to avoid session fixation vulnerabilities.
        session.regenerate()
        current_accounts.datastore.commit()
        return response

def delete_session(sid_s):
    """Delete entries in the data- and kvsessionstore with the given sid_s.

    On a successful deletion, the flask-kvsession store returns 1 while the
    sqlalchemy datastore returns None.

    :param sid_s: The session ID.
    :returns: ``1`` if deletion was successful.
    """
    # Remove entries from sessionstore
    _sessionstore.delete(sid_s)
    # Find and remove the corresponding SessionActivity entry
    with db.session.begin_nested():
        SessionActivity.query.filter_by(sid_s=sid_s).delete()
    return 1

def delete_user_sessions(user):
    """Delete all active user sessions.

    :param user: User instance.
    :returns: If ``True`` then the session is successfully deleted.
    """
    with db.session.begin_nested():
        for s in user.active_sessions:
            _sessionstore.delete(s.sid_s)

        SessionActivity.query.filter_by(user=user).delete()

    return True

def default_session_store_factory(app):
    """Session store factory.

    If ``ACCOUNTS_SESSION_REDIS_URL`` is set, it returns a
    :class:`simplekv.memory.redisstore.RedisStore` otherwise
    a :class:`simplekv.memory.DictStore`.
    """
    accounts_session_redis_url = app.config.get('ACCOUNTS_SESSION_REDIS_URL')
    if accounts_session_redis_url:
        import redis
        from simplekv.memory.redisstore import RedisStore
        return RedisStore(redis.StrictRedis.from_url(
            accounts_session_redis_url))
    from simplekv.memory import DictStore
    return DictStore()


text:
Automatically clone all your GitHub and Bitbucket Cloud repositories.

[![Build Status](https://travis-ci.org/ngeor/clone-all.svg?branch=master)](https://travis-ci.org/ngeor/clone-all)
[![npm (scoped)](https://img.shields.io/npm/v/@ngeor/clone-all.svg)](https://www.npmjs.com/package/@ngeor/clone-all)
[![Coverage Status](https://coveralls.io/repos/github/ngeor/clone-all/badge.svg)](https://coveralls.io/github/ngeor/clone-all)
[![Dependencies](https://david-dm.org/ngeor/clone-all.svg)](https://david-dm.org/ngeor/clone-all)
[![devDependencies Status](https://david-dm.org/ngeor/clone-all/dev-status.svg)](https://david-dm.org/ngeor/clone-all?type=dev)
[![PayPal donate](https://img.shields.io/badge/paypal-donate-blue.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3DDPDSSHEUGBN)

## Requirements

clone-all requires [Node.js](http://nodejs.org/) version 10 or higher.

## Usage

### Cloning

You need a directory into which clone-all will clone all your repositories.

```
npx @ngeor/clone-all --provider github --username ngeor --output ./repositories/
```

This will clone all the repositories of the `ngeor` user into the `repositories`
folder.

### Listing repository information

This command prints information about repositories without cloning them.

```
npx @ngeor/clone-all -p github --username ngeor --list
```

Example output (fields are tab separated):

```
Name    Language        Size    Pushed At
android-tictactoe       Java    386     2017-08-31T08:45:56Z
archetype-quickstart-jdk8       Shell   63      2017-04-02T07:12:55Z
clone-all       JavaScript      229     2018-01-23T15:13:59Z
```

## Command Line Options

### Specifying with repositories to fetch

- -p, --provider: github or bitbucket_cloud
- --username: the user owning the repositories
- --protocol: specify the cloning protocol (https or ssh)
- --ssh-username: specify a different username for cloning over ssh (instead of
  `git@`)
- --no-forks: Do not clone forked repositories
- --no-archived: Do not clone archived repositories

Bitbucket Cloud options:

- --owner: the user owning the repositories
- --username: the username to use against Bitbucket REST API
- --password: the password to use against Bitbucket REST API. It is possible to
  specify this parameter via the `BITBUCKET_PASSWORD` environment variable. CLI
  option has precedence.

### Cloning options

- --output: the folder in which to clone the repositories

### List options

- --list: Prints information about the repositories without cloning them.

### Additional configuration options

- -v: increases verbosity
- --dry-run: don't clone anything, just show what would happen


text:
'use strict';

import dom from 'metal-dom';
import Component from 'metal-component';
import IncrementalDomChildren from '../../src/children/IncrementalDomChildren';

describe('IncrementalDomChildren', function() {
	it('should capture children calls to incremental dom', function(done) {
		var renderer = {
			buildRef: sinon.stub()
		};

		IncrementalDomChildren.capture(renderer, function(tree) {
			assert.strictEqual(1, tree.config.children.length);

			var node = tree.config.children[0];
			assert.ok(!node.text);
			assert.strictEqual('span', node.tag);
			assert.ok(node.config);
			assert.strictEqual('key', node.config.key);
			assert.deepEqual('test', node.config.class);
			assert.strictEqual('bar', node.config.foo);

			assert.strictEqual(1, node.config.children.length);
			assert.strictEqual('Hello World', node.config.children[0].text);
			done();
		});

		IncrementalDOM.elementOpen('span', 'key', ['class', 'test'], 'foo', 'bar');
		IncrementalDOM.text('Hello World');
		IncrementalDOM.elementClose('span');
		IncrementalDOM.elementClose('div');
	});

	it('should set refs of component calls according to result of "buildRef" function', function(done) {
		var counter = 0;
		var renderer = {
			buildRef: () => 'ref' + counter++
		};

		IncrementalDomChildren.capture(renderer, function(tree) {
			assert.strictEqual(1, tree.config.children.length);

			var node = tree.config.children[0];
			assert.strictEqual('span', node.tag);
			assert.ok(!node.config.ref);

			assert.strictEqual(2, node.config.children.length);
			assert.strictEqual(Component, node.config.children[0].tag);
			assert.strictEqual('ref0', node.config.children[0].config.ref);
			assert.strictEqual(Component, node.config.children[1].tag);
			assert.strictEqual('ref1', node.config.children[1].config.ref);
			done();
		});

		IncrementalDOM.elementOpen('span');
		IncrementalDOM.elementVoid(Component);
		IncrementalDOM.elementVoid(Component);
		IncrementalDOM.elementClose('span');
		IncrementalDOM.elementClose('div');
	});

	it('should store args for text nodes when they contain more than just the text', function(done) {
		var renderer = {
			buildRef: sinon.stub()
		};

		IncrementalDomChildren.capture(renderer, function(tree) {
			var node = tree.config.children[0];
			assert.strictEqual('No args', node.text);
			assert.ok(!node.args);

			node = tree.config.children[1];
			assert.strictEqual('With args', node.text);
			assert.deepEqual([
				node.text,
				formatFn
			], node.args);
			done();
		});

		var formatFn = val => val;
		IncrementalDOM.text('No args');
		IncrementalDOM.text('With args', formatFn);
		IncrementalDOM.elementClose('div');
	});

	it('should render captured children via incremental dom', function() {
		var element = document.createElement('div');

		IncrementalDOM.patch(element, () => {
			IncrementalDomChildren.render({
				tag: 'span',
				config: {
					children: [
						{
							args: ['Hello World'],
							text: 'Hello World'
						}
					],
					class: 'test',
					foo: 'bar',
					key: 'key'
				}
			});
		});

		assert.strictEqual(1, element.childNodes.length);

		var spanElement = element.childNodes[0];
		assert.strictEqual('SPAN', spanElement.tagName);
		assert.ok(dom.hasClass(spanElement, 'test'));
		assert.strictEqual('bar', spanElement.getAttribute('foo'));
		assert.strictEqual(1, spanElement.childNodes.length);
		assert.strictEqual('Hello World', spanElement.childNodes[0].textContent);
	});

	it('should skip rendering children node when skipNode function returns true', function() {
		var element = document.createElement('div');

		function skipNode(node) {
			if (node.config && node.config.id === 'skip') {
				return true;
			}
		}
		IncrementalDOM.patch(element, () => {
			IncrementalDomChildren.render({
				tag: 'span',
				config: {
					children: [
						{
							tag: 'span',
							config: {
								id: 'beforeSkip'
							}
						},
						{
							tag: 'span',
							config: {
								id: 'skip'
							}
						},
						{
							tag: 'span',
							config: {
								id: 'afterSkip'
							}
						}
					],
					id: 'parent'
				}
			}, skipNode);
		});

		assert.strictEqual(1, element.childNodes.length);

		var child = element.childNodes[0];
		assert.strictEqual(2, child.childNodes.length);
		assert.strictEqual('beforeSkip', child.childNodes[0].id);
		assert.strictEqual('afterSkip', child.childNodes[1].id);
	});

	it('should render text nodes that have been changed after capture', function(done) {
		var renderer = {
			buildRef: sinon.stub()
		};

		IncrementalDomChildren.capture(renderer, function(tree) {
			var element = document.createElement('div');
			tree.config.children[0].text = 'New Text';
			IncrementalDOM.patch(element, () => {
				IncrementalDomChildren.render(tree.config.children[0]);
			});

			assert.strictEqual(1, element.childNodes.length);
			assert.strictEqual('New Text Formatted', element.childNodes[0].textContent);
			done();
		});

		IncrementalDOM.text('Hello World', val => val + ' Formatted');
		IncrementalDOM.elementClose('div');
	});

	it('should keep original renderer for children that have been recaptured by another1', function(done) {
		var renderer1 = {
			buildRef: sinon.stub()
		};
		var renderer2 = {
			buildRef: sinon.stub()
		};

		IncrementalDomChildren.capture(renderer2, function(tree) {
			var element = tree.config.children[0];
			assert.strictEqual('div', element.tag);
			assert.strictEqual(renderer2, element[IncrementalDomChildren.CHILD_OWNER]);
			assert.strictEqual(1, element.config.children.length);

			element = element.config.children[0];
			assert.strictEqual('span', element.tag);
			assert.strictEqual(renderer1, element[IncrementalDomChildren.CHILD_OWNER]);
			assert.strictEqual(1, element.config.children.length);

			element = element.config.children[0];
			assert.strictEqual('Hello World', element.text);
			assert.strictEqual(renderer1, element[IncrementalDomChildren.CHILD_OWNER]);
			done();
		});

		IncrementalDOM.elementOpen('div');
		IncrementalDomChildren.render({
			tag: 'span',
			config: {
				children: [
					{
						text: 'Hello World',
						[IncrementalDomChildren.CHILD_OWNER]: renderer1
					},
				]
			},
			[IncrementalDomChildren.CHILD_OWNER]: renderer1
		});
		IncrementalDOM.elementClose('div');
		IncrementalDOM.elementClose('div');
	});
});


text:
#pragma once
#include <aws/iot/IoT_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoT
{
namespace Model
{

  /**
   *
 The target of a mitigation action task.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOT_API DetectMitigationActionsTaskTarget
  {
  public:
    DetectMitigationActionsTaskTarget();
    DetectMitigationActionsTaskTarget(Aws::Utils::Json::JsonView jsonValue);
    DetectMitigationActionsTaskTarget& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The unique identifiers of the violations.

     */
    inline const Aws::Vector<Aws::String>& GetViolationIds() const{ return m_violationIds; }

    /**
     *
 The unique identifiers of the violations.

     */
    inline bool ViolationIdsHasBeenSet() const { return m_violationIdsHasBeenSet; }

    /**
     *
 The unique identifiers of the violations.

     */
    inline void SetViolationIds(const Aws::Vector<Aws::String>& value) { m_violationIdsHasBeenSet = true; m_violationIds = value; }

    /**
     *
 The unique identifiers of the violations.

     */
    inline void SetViolationIds(Aws::Vector<Aws::String>&& value) { m_violationIdsHasBeenSet = true; m_violationIds = std::move(value); }

    /**
     *
 The unique identifiers of the violations.

     */
    inline DetectMitigationActionsTaskTarget& WithViolationIds(const Aws::Vector<Aws::String>& value) { SetViolationIds(value); return *this;}

    /**
     *
 The unique identifiers of the violations.

     */
    inline DetectMitigationActionsTaskTarget& WithViolationIds(Aws::Vector<Aws::String>&& value) { SetViolationIds(std::move(value)); return *this;}

    /**
     *
 The unique identifiers of the violations.

     */
    inline DetectMitigationActionsTaskTarget& AddViolationIds(const Aws::String& value) { m_violationIdsHasBeenSet = true; m_violationIds.push_back(value); return *this; }

    /**
     *
 The unique identifiers of the violations.

     */
    inline DetectMitigationActionsTaskTarget& AddViolationIds(Aws::String&& value) { m_violationIdsHasBeenSet = true; m_violationIds.push_back(std::move(value)); return *this; }

    /**
     *
 The unique identifiers of the violations.

     */
    inline DetectMitigationActionsTaskTarget& AddViolationIds(const char* value) { m_violationIdsHasBeenSet = true; m_violationIds.push_back(value); return *this; }

    /**
     *
 The name of the security profile.

     */
    inline const Aws::String& GetSecurityProfileName() const{ return m_securityProfileName; }

    /**
     *
 The name of the security profile.

     */
    inline bool SecurityProfileNameHasBeenSet() const { return m_securityProfileNameHasBeenSet; }

    /**
     *
 The name of the security profile.

     */
    inline void SetSecurityProfileName(const Aws::String& value) { m_securityProfileNameHasBeenSet = true; m_securityProfileName = value; }

    /**
     *
 The name of the security profile.

     */
    inline void SetSecurityProfileName(Aws::String&& value) { m_securityProfileNameHasBeenSet = true; m_securityProfileName = std::move(value); }

    /**
     *
 The name of the security profile.

     */
    inline void SetSecurityProfileName(const char* value) { m_securityProfileNameHasBeenSet = true; m_securityProfileName.assign(value); }

    /**
     *
 The name of the security profile.

     */
    inline DetectMitigationActionsTaskTarget& WithSecurityProfileName(const Aws::String& value) { SetSecurityProfileName(value); return *this;}

    /**
     *
 The name of the security profile.

     */
    inline DetectMitigationActionsTaskTarget& WithSecurityProfileName(Aws::String&& value) { SetSecurityProfileName(std::move(value)); return *this;}

    /**
     *
 The name of the security profile.

     */
    inline DetectMitigationActionsTaskTarget& WithSecurityProfileName(const char* value) { SetSecurityProfileName(value); return *this;}

    /**
     *
 The name of the behavior.

     */
    inline const Aws::String& GetBehaviorName() const{ return m_behaviorName; }

    /**
     *
 The name of the behavior.

     */
    inline bool BehaviorNameHasBeenSet() const { return m_behaviorNameHasBeenSet; }

    /**
     *
 The name of the behavior.

     */
    inline void SetBehaviorName(const Aws::String& value) { m_behaviorNameHasBeenSet = true; m_behaviorName = value; }

    /**
     *
 The name of the behavior.

     */
    inline void SetBehaviorName(Aws::String&& value) { m_behaviorNameHasBeenSet = true; m_behaviorName = std::move(value); }

    /**
     *
 The name of the behavior.

     */
    inline void SetBehaviorName(const char* value) { m_behaviorNameHasBeenSet = true; m_behaviorName.assign(value); }

    /**
     *
 The name of the behavior.

     */
    inline DetectMitigationActionsTaskTarget& WithBehaviorName(const Aws::String& value) { SetBehaviorName(value); return *this;}

    /**
     *
 The name of the behavior.

     */
    inline DetectMitigationActionsTaskTarget& WithBehaviorName(Aws::String&& value) { SetBehaviorName(std::move(value)); return *this;}

    /**
     *
 The name of the behavior.

     */
    inline DetectMitigationActionsTaskTarget& WithBehaviorName(const char* value) { SetBehaviorName(value); return *this;}

  private:

    Aws::Vector<Aws::String> m_violationIds;
    bool m_violationIdsHasBeenSet;

    Aws::String m_securityProfileName;
    bool m_securityProfileNameHasBeenSet;

    Aws::String m_behaviorName;
    bool m_behaviorNameHasBeenSet;
  };

} // namespace Model
} // namespace IoT
} // namespace Aws


text:
#include <aws/inspector/model/StartAssessmentRunResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Inspector::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

StartAssessmentRunResult::StartAssessmentRunResult()
{
}

StartAssessmentRunResult::StartAssessmentRunResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

StartAssessmentRunResult& StartAssessmentRunResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("assessmentRunArn"))
  {
    m_assessmentRunArn = jsonValue.GetString("assessmentRunArn");

  }

  return *this;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/widget_icon_root"
    android:layout_width="match_parent"
    android:layout_height="@dimen/one_row_widget_height_higher"
    android:gravity="center"
    android:background="?android:attr/colorBackground"
    android:theme="@style/Theme.Material3.DynamicColors.DayNight"
    tools:ignore="Overdraw" >

    <ImageView
        android:id="@+id/widget_icon_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:scaleType="fitXY"
        android:src="@drawable/rounded_widget_background_5"
        android:tint="?android:attr/colorBackground"
        android:visibility="gone"
        tools:ignore="ContentDescription,UseAppTint" />

    <RelativeLayout
        android:id="@+id/icon_widget_relLa1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:clickable="true"
        android:focusable="true"
        android:background="@drawable/widget_ripple_background" >

        <ImageView
            android:id="@+id/icon_widget_icon"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_profile_default"
            android:contentDescription="@string/profile_preferences_profileIcon"/>

    </RelativeLayout>

    <ImageView
        android:id="@+id/widget_icon_not_rounded_border"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:scaleType="fitXY"
        android:src="@drawable/not_rounded_widget_border"
        android:visibility="gone"
        tools:ignore="ContentDescription" />

    <ImageView
        android:id="@+id/widget_icon_rounded_border"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:scaleType="fitXY"
        android:src="@drawable/rounded_widget_border_5"
        android:tint="?android:attr/textColorSecondary"
        android:visibility="gone"
        tools:ignore="ContentDescription,UseAppTint" />

</FrameLayout>


text:
package nam.ui;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aries.Assert;
import org.aries.RuntimeContext;
import org.aries.jaxb.JAXBSessionCache;
import org.aries.launcher.Bootstrap;
import org.aries.runtime.BeanContext;
import org.aries.util.ExceptionUtil;
import org.aries.util.FileUtil;

public class ServletListenerOLD implements ServletContextListener, HttpSessionListener {

	private static final Log log = LogFactory.getLog(ServletListenerOLD.class);

	public String getDomain() {
		return "nam";
	}

	public String getModule() {
		return "nam-view";
	}

	public void contextInitialized(ServletContextEvent event) {
		ServletContext servletContext = event.getServletContext();
		RuntimeContext.getInstance().setServletContext(servletContext);
		String propertyName = getDomain() + ".application_runtime_home";

		try {
			String runtimeHome = System.getProperty(propertyName);
			Assert.notNull(runtimeHome, "External property not found: "+propertyName);
			Bootstrap bootstrapper = new Bootstrap();
			bootstrapper.setDomainName(getDomain());
			bootstrapper.setModuleName(getModule());
			BeanContext.set(getDomain() + ".bootstrapper", bootstrapper);
			bootstrapper.initialize(runtimeHome);
			runtimeHome = FileUtil.normalizePath(runtimeHome);

			JAXBSessionCache jaxbSessionCache = BeanContext.get(getDomain() + ".jaxbSessionCache");

			// Add schema for: http://www.aries.org/common
			String schemaFileName2 = "file://" + runtimeHome + "/model/common/aries-common-1.0.xsd";
			jaxbSessionCache.addSchema(schemaFileName2, org.aries.common.ObjectFactory.class);

			// Add schema for: http://nam/model
			String schemaFileName3 = "file://" + runtimeHome + "/model/nam/nam-1.0.xsd";
			jaxbSessionCache.addSchema(schemaFileName3, nam.model.ObjectFactory.class);

		} catch (Exception e) {
			Throwable rootCause = ExceptionUtil.getRootCause(e);
			log.error("Error:", e);
			log.error("Caused by:", rootCause);
			throw new RuntimeException(rootCause);
		}
	}

	public void contextDestroyed(ServletContextEvent event) {
		//nothing for now
	}

	public void sessionCreated(HttpSessionEvent event) {
		//nothing for now
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		//nothing for now
	}

}


text:
module Elasticsearch
  module Autocomplete
    module Filters
      module ClassMethods
        def analysis
          {
            analysis: {
              analyzer: {
                simple: {
                  type: "custom",
                  tokenizer: "keyword",
                  filter: [ "asciifolding", "lowercase" ]
                },
                autocomplete: {
                  type: "custom",
                  tokenizer: "standard",
                  filter: [ 'asciifolding', "lowercase", "ngram_beginning" ]
                },
                fuzzy: {
                  type: "custom",
                  tokenizer: "standard",
                  filter: [ 'asciifolding', "lowercase", "ngram_short" ]
                },
                beginning: {
                  type: "custom",
                  tokenizer: "keyword",
                  filter: [ "asciifolding", 'lowercase', 'ngram_beginning' ]
                }
              },
              filter: {
                ngram_beginning: {
                  type: "edgeNGram",
                  min_gram: 1,
                  max_gram: 45
                },
                ngram_short: {
                  type: "ngram",
                  min_gram: 1,
                  max_gram: 15
                }
              }
            }
          }
        end

        def build_config(field, add_options_to_fields={})
          {
            :type => :multi_field,
            :fields => {
              field.to_sym => { type: 'string' }.merge(add_options_to_fields),
              :"#{field}.exact" => { type: 'string', index_analyzer: 'simple' }.merge(add_options_to_fields),
              :"#{field}.beginning" => { type: 'string', index_analyzer: 'beginning'}.merge(add_options_to_fields),
              :"#{field}.autocomplete" => { type: 'string', index_analyzer: 'autocomplete'}.merge(add_options_to_fields),
              :"#{field}.fuzzy" => { type: 'string', index_analyzer: 'fuzzy'}.merge(add_options_to_fields)
            }
          }
        end

        alias_method :config, :build_config
      end
      extend ClassMethods
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Guriu</logradouro><bairro>Jurubatuba</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>04696060</cep></feed>


text:
from django.contrib import admin
from cameras.models import Camera
# Register your models here.

admin.site.register(Camera)


text:
/**
 * @member module:Falcor.Path
 * @see {@link https://github.com/Netflix/falcor-path-utils}
 */
require('lodash/collection/reduce')([
    require('./path/relative'),
    require('./path/resolve')
], require('protean/utility/merge-exports'), exports);

/**
 * @typedef Key
 * @type {String|null}
 * @see {@link http://netflix.github.io/falcor/doc/global.html#Key}
 */

/**
 * @typedef KeySet
 * @type {Key|Range|Array<Key|Range>}
 * @see {@link http://netflix.github.io/falcor/doc/global.html#KeySet}
 */

/**
 * @typedef Path
 * @type {Key[]}
 * @see {@link http://netflix.github.io/falcor/doc/global.html#Path}
 */

/**
 * @typedef PathSet
 * @type {Array<KeySet>}
 * @see {@link http://netflix.github.io/falcor/doc/global.html#PathSet}
 */

/**
 * @typedef PathValue
 * @type {Object}
 * @see {@link http://netflix.github.io/falcor/doc/global.html#PathValue}
 * @property {Path} path
 * @property {*} value
 */

/**
 * @typedef Range
 * @type {Object}
 * @see {@link http://netflix.github.io/falcor/doc/global.html#Range}
 * @property {Integer} [from]
 * @property {Integer} to
 * @property {Integer} [length]
 */


text:
SYNONYM

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

#### Published in
Flora 66:549. 1883

#### Original name
null

### Remarks
null


text:
class List {
public:
	List();
	virtual ~List();
	unsigned int size() const;
protected:
	unsigned int length;
};

#endif


text:
<?php
namespace Agnostic\Entity;

use Aura\Marshal\Entity\BuilderInterface;
use Agnostic\Manager;

class Builder implements BuilderInterface
{
    protected $class = 'Agnostic\Entity\Entity';

    public function __construct($class = null)
    {
        if ($class) {
            $this->setClass($class);
        }
    }

    public function setClass($class)
    {
        $this->class = $class;
    }

    public function newInstance(array $data)
    {
        $class = $this->class;
        $entity = new $class;

        foreach ($data as $field => $value) {
            $entity->offsetSet($field, $value);
        }

        return $entity;
    }
}


text:
<?php $id = $row['serviceId'] ?>
<div id="<?php echo $id; ?>" class="modform">
    <label for="modUsername<?php echo $id; ?>">User:
    <input type="text" id="modUsername<?php echo $id; ?>" value="<?php echo sanitizeHtmlString($row['username']);?>" />

    <label for="modPassword<?php echo $id; ?>">Pass:
    <input type="text" id="modPassword<?php echo $id; ?>" value="<?php echo sanitizeHtmlString($row['password']);?>" />

    <button class="modSubmit" onclick="submitPasswordChange(<?php echo $id; ?>,$('#modUsername<?php echo $id; ?>').val(),$('#modPassword<?php echo $id; ?>').val())">Change</button>
    <a class="modHide" href="#" onclick="hideModForm(<?php echo $id; ?>);">Hide


text:
{{+partials.standard_extensions_article
    article:articles.manifest/externally_connectable
    data:apis.extensions.extensionsManifestTypes.byName.ExternallyConnectable/}}


text:
package com.squareup.javapoet;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.util.Types;

import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static com.squareup.javapoet.Util.checkState;

/** A generated constructor or method declaration. */
public final class MethodSpec {
  static final String CONSTRUCTOR = "<init>";
  static final ClassName OVERRIDE = ClassName.get(Override.class);

  public final String name;
  public final CodeBlock javadoc;
  public final List<AnnotationSpec> annotations;
  public final Set<Modifier> modifiers;
  public final List<TypeVariableName> typeVariables;
  public final TypeName returnType;
  public final List<ParameterSpec> parameters;
  public final boolean varargs;
  public final List<TypeName> exceptions;
  public final CodeBlock code;
  public final CodeBlock defaultValue;

  private MethodSpec(Builder builder) {
    CodeBlock code = builder.code.build();
    checkArgument(code.isEmpty() || !builder.modifiers.contains(Modifier.ABSTRACT),
        "abstract method %s cannot have code", builder.name);
    checkArgument(!builder.varargs || lastParameterIsArray(builder.parameters),
        "last parameter of varargs method %s must be an array", builder.name);

    this.name = checkNotNull(builder.name, "name == null");
    this.javadoc = builder.javadoc.build();
    this.annotations = Util.immutableList(builder.annotations);
    this.modifiers = Util.immutableSet(builder.modifiers);
    this.typeVariables = Util.immutableList(builder.typeVariables);
    this.returnType = builder.returnType;
    this.parameters = Util.immutableList(builder.parameters);
    this.varargs = builder.varargs;
    this.exceptions = Util.immutableList(builder.exceptions);
    this.defaultValue = builder.defaultValue;
    this.code = code;
  }

  private boolean lastParameterIsArray(List<ParameterSpec> parameters) {
    return !parameters.isEmpty()
        && TypeName.arrayComponent(parameters.get(parameters.size() - 1).type) != null;
  }

  void emit(CodeWriter codeWriter, String enclosingName, Set<Modifier> implicitModifiers)
      throws IOException {
    codeWriter.emitJavadoc(javadoc);
    codeWriter.emitAnnotations(annotations, false);
    codeWriter.emitModifiers(modifiers, implicitModifiers);

    if (!typeVariables.isEmpty()) {
      codeWriter.emitTypeVariables(typeVariables);
      codeWriter.emit(" ");
    }

    if (isConstructor()) {
      codeWriter.emit("$L(", enclosingName);
    } else {
      codeWriter.emit("$T $L(", returnType, name);
    }

    boolean firstParameter = true;
    for (Iterator<ParameterSpec> i = parameters.iterator(); i.hasNext(); ) {
      ParameterSpec parameter = i.next();
      if (!firstParameter) codeWriter.emit(", ");
      parameter.emit(codeWriter, !i.hasNext() && varargs);
      firstParameter = false;
    }

    codeWriter.emit(")");

    if (defaultValue != null && !defaultValue.isEmpty()) {
      codeWriter.emit(" default ");
      codeWriter.emit(defaultValue);
    }

    if (!exceptions.isEmpty()) {
      codeWriter.emit(" throws");
      boolean firstException = true;
      for (TypeName exception : exceptions) {
        if (!firstException) codeWriter.emit(",");
        codeWriter.emit(" $T", exception);
        firstException = false;
      }
    }

    if (hasModifier(Modifier.ABSTRACT)) {
      codeWriter.emit(";\n");
    } else if (hasModifier(Modifier.NATIVE)) {
      // Code is allowed to support stuff like GWT JSNI.
      codeWriter.emit(code);
      codeWriter.emit(";\n");
    } else {
      codeWriter.emit(" {\n");

      codeWriter.indent();
      codeWriter.emit(code);
      codeWriter.unindent();

      codeWriter.emit("}\n");
    }
  }

  public boolean hasModifier(Modifier modifier) {
    return modifiers.contains(modifier);
  }

  public boolean isConstructor() {
    return name.equals(CONSTRUCTOR);
  }

  @Override public String toString() {
    StringWriter out = new StringWriter();
    try {
      CodeWriter codeWriter = new CodeWriter(out);
      emit(codeWriter, "Constructor", Collections.<Modifier>emptySet());
      return out.toString();
    } catch (IOException e) {
      throw new AssertionError();
    }
  }

  public static Builder methodBuilder(String name) {
    return new Builder(name);
  }

  public static Builder constructorBuilder() {
    return new Builder(CONSTRUCTOR);
  }

  /**
   * Returns a new method spec builder that overrides {@code method}.
   *
   *
This will copy its visibility modifiers, type parameters, return type, name, parameters, and
   * throws declarations. An {@link Override} annotation will be added.
   */
  public static Builder overriding(ExecutableElement method) {
    checkNotNull(method, "method == null");

    Set<Modifier> modifiers = method.getModifiers();
    if (modifiers.contains(Modifier.PRIVATE)
        || modifiers.contains(Modifier.FINAL)
        || modifiers.contains(Modifier.STATIC)) {
      throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers);
    }

    String methodName = method.getSimpleName().toString();
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName);

    methodBuilder.addAnnotation(OVERRIDE);
    for (AnnotationMirror mirror : method.getAnnotationMirrors()) {
      AnnotationSpec annotationSpec = AnnotationSpec.get(mirror);
      if (annotationSpec.type.equals(OVERRIDE)) continue;
      methodBuilder.addAnnotation(annotationSpec);
    }

    modifiers = new LinkedHashSet<>(modifiers);
    modifiers.remove(Modifier.ABSTRACT);
    methodBuilder.addModifiers(modifiers);

    for (TypeParameterElement typeParameterElement : method.getTypeParameters()) {
      TypeVariable var = (TypeVariable) typeParameterElement.asType();
      methodBuilder.addTypeVariable(TypeVariableName.get(var));
    }

    methodBuilder.returns(TypeName.get(method.getReturnType()));

    List<? extends VariableElement> parameters = method.getParameters();
    for (VariableElement parameter : parameters) {
      TypeName type = TypeName.get(parameter.asType());
      String name = parameter.getSimpleName().toString();
      Set<Modifier> parameterModifiers = parameter.getModifiers();
      ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(type, name)
          .addModifiers(parameterModifiers.toArray(new Modifier[parameterModifiers.size()]));
      for (AnnotationMirror mirror : parameter.getAnnotationMirrors()) {
        parameterBuilder.addAnnotation(AnnotationSpec.get(mirror));
      }
      methodBuilder.addParameter(parameterBuilder.build());
    }
    methodBuilder.varargs(method.isVarArgs());

    for (TypeMirror thrownType : method.getThrownTypes()) {
      methodBuilder.addException(TypeName.get(thrownType));
    }

    return methodBuilder;
  }

  /**
   * Returns a new method spec builder that overrides {@code method} as a member of {@code
   * enclosing}. This will resolve type parameters: for example overriding {@link
   * Comparable#compareTo} in a type that implements {@code Comparable<Movie>}, the {@code T}
   * parameter will be resolved to {@code Movie}.
   *
   *
This will copy its visibility modifiers, type parameters, return type, name, parameters, and
   * throws declarations. An {@link Override} annotation will be added.
   */
  public static Builder overriding(
      ExecutableElement method, DeclaredType enclosing, Types types) {
    ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method);
    List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
    TypeMirror resolvedReturnType = executableType.getReturnType();

    Builder builder = overriding(method);
    builder.returns(TypeName.get(resolvedReturnType));
    for (int i = 0, size = builder.parameters.size(); i < size; i++) {
      ParameterSpec parameter = builder.parameters.get(i);
      TypeName type = TypeName.get(resolvedParameterTypes.get(i));
      builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build());
    }

    return builder;
  }

  public Builder toBuilder() {
    Builder builder = new Builder(name);
    builder.javadoc.add(javadoc);
    builder.annotations.addAll(annotations);
    builder.modifiers.addAll(modifiers);
    builder.typeVariables.addAll(typeVariables);
    builder.returnType = returnType;
    builder.parameters.addAll(parameters);
    builder.exceptions.addAll(exceptions);
    builder.code.add(code);
    builder.varargs = varargs;
    builder.defaultValue = defaultValue;
    return builder;
  }

  public static final class Builder {
    private final String name;

    private final CodeBlock.Builder javadoc = CodeBlock.builder();
    private final List<AnnotationSpec> annotations = new ArrayList<>();
    private final List<Modifier> modifiers = new ArrayList<>();
    private List<TypeVariableName> typeVariables = new ArrayList<>();
    private TypeName returnType;
    private final List<ParameterSpec> parameters = new ArrayList<>();
    private final List<TypeName> exceptions = new ArrayList<>();
    private final CodeBlock.Builder code = CodeBlock.builder();
    private boolean varargs;
    private CodeBlock defaultValue;

    private Builder(String name) {
      checkArgument(name.equals(CONSTRUCTOR) || SourceVersion.isName(name),
          "not a valid name: %s", name);
      this.name = name;
      this.returnType = name.equals(CONSTRUCTOR) ? null : TypeName.VOID;
    }

    public Builder addJavadoc(String format, Object... args) {
      javadoc.add(format, args);
      return this;
    }

    public Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs) {
      checkArgument(annotationSpecs != null, "annotationSpecs == null");
      for (AnnotationSpec annotationSpec : annotationSpecs) {
        this.annotations.add(annotationSpec);
      }
      return this;
    }

    public Builder addAnnotation(AnnotationSpec annotationSpec) {
      this.annotations.add(annotationSpec);
      return this;
    }

    public Builder addAnnotation(ClassName annotation) {
      this.annotations.add(AnnotationSpec.builder(annotation).build());
      return this;
    }

    public Builder addAnnotation(Class<?> annotation) {
      return addAnnotation(ClassName.get(annotation));
    }

    public Builder addModifiers(Modifier... modifiers) {
      Collections.addAll(this.modifiers, modifiers);
      return this;
    }

    public Builder addModifiers(Iterable<Modifier> modifiers) {
      checkNotNull(modifiers, "modifiers == null");
      for (Modifier modifier : modifiers) {
        this.modifiers.add(modifier);
      }
      return this;
    }

    public Builder addTypeVariables(Iterable<TypeVariableName> typeVariables) {
      checkArgument(typeVariables != null, "typeVariables == null");
      for (TypeVariableName typeVariable : typeVariables) {
        this.typeVariables.add(typeVariable);
      }
      return this;
    }

    public Builder addTypeVariable(TypeVariableName typeVariable) {
      typeVariables.add(typeVariable);
      return this;
    }

    public Builder returns(TypeName returnType) {
      checkState(!name.equals(CONSTRUCTOR), "constructor cannot have return type.");
      this.returnType = returnType;
      return this;
    }

    public Builder returns(Type returnType) {
      return returns(TypeName.get(returnType));
    }

    public Builder addParameters(Iterable<ParameterSpec> parameterSpecs) {
      checkArgument(parameterSpecs != null, "parameterSpecs == null");
      for (ParameterSpec parameterSpec : parameterSpecs) {
        this.parameters.add(parameterSpec);
      }
      return this;
    }

    public Builder addParameter(ParameterSpec parameterSpec) {
      this.parameters.add(parameterSpec);
      return this;
    }

    public Builder addParameter(TypeName type, String name, Modifier... modifiers) {
      return addParameter(ParameterSpec.builder(type, name, modifiers).build());
    }

    public Builder addParameter(Type type, String name, Modifier... modifiers) {
      return addParameter(TypeName.get(type), name, modifiers);
    }

    public Builder varargs() {
      return varargs(true);
    }

    public Builder varargs(boolean varargs) {
      this.varargs = varargs;
      return this;
    }

    public Builder addExceptions(Iterable<? extends TypeName> exceptions) {
      checkArgument(exceptions != null, "exceptions == null");
      for (TypeName exception : exceptions) {
        this.exceptions.add(exception);
      }
      return this;
    }

    public Builder addException(TypeName exception) {
      this.exceptions.add(exception);
      return this;
    }

    public Builder addException(Type exception) {
      return addException(TypeName.get(exception));
    }

    public Builder addCode(String format, Object... args) {
      code.add(format, args);
      return this;
    }

    public Builder addCode(CodeBlock codeBlock) {
      code.add(codeBlock);
      return this;
    }

    public Builder defaultValue(String format, Object... args) {
      return defaultValue(CodeBlock.builder().add(format, args).build());
    }

    public Builder defaultValue(CodeBlock codeBlock) {
      checkState(this.defaultValue == null, "defaultValue was already set");
      this.defaultValue = checkNotNull(codeBlock, "codeBlock == null");
      return this;
    }

    /**
     * @param controlFlow the control flow construct and its code, such as "if (foo == 5)".
     * Shouldn't contain braces or newline characters.
     */
    public Builder beginControlFlow(String controlFlow, Object... args) {
      code.beginControlFlow(controlFlow, args);
      return this;
    }

    /**
     * @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
     *     Shouldn't contain braces or newline characters.
     */
    public Builder nextControlFlow(String controlFlow, Object... args) {
      code.nextControlFlow(controlFlow, args);
      return this;
    }

    public Builder endControlFlow() {
      code.endControlFlow();
      return this;
    }

    /**
     * @param controlFlow the optional control flow construct and its code, such as
     *     "while(foo == 20)". Only used for "do/while" control flows.
     */
    public Builder endControlFlow(String controlFlow, Object... args) {
      code.endControlFlow(controlFlow, args);
      return this;
    }

    public Builder addStatement(String format, Object... args) {
      code.addStatement(format, args);
      return this;
    }

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


text:
fw_depends java maven

mvn clean package
cd target/dist
unzip *.zip

APP_ENTRY=com.techempower.act.AppEntry

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
BASE=$DIR/target/dist
if [[ $DIR == *"dist" ]]; then
  BASE=$DIR
fi
CP=$BASE/classes:$BASE/lib/*
echo
echo CLASSPATH: $CP
echo

JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -Xms1G -Xmx1G -Xss320k -XX:+UseNUMA -XX:+UseParallelGC -XX:+AggressiveOpts"

java -server $JAVA_OPTS -Dapp.mode=prod -Dapp.nodeGroup=$GROUP -Dprofile=json_plaintext -Dxio.worker_threads.max=256 -cp "$CP" $APP_ENTRY &


text:
<?php

namespace Intervention\Gif\Traits;

use Exception;

trait CanHandleFiles
{
     /**
     * Determines if input is file path
     *
     * @return boolean
     */
    private static function isFilePath($input): bool
    {
        return is_string($input) && !self::hasNullBytes($input) && @is_file($input);
    }

    /**
     * Determine if given string contains null bytes
     *
     * @param  string  $string
     * @return boolean
     */
    private static function hasNullBytes($string): bool
    {
        return strpos($string, chr(0)) !== false;
    }

    /**
     * Create file pointer from given gif image data
     *
     * @param  string $data
     * @return resource
     */
    private static function getHandleFromData($data)
    {
        $handle = fopen('php://memory', 'r+');
        fwrite($handle, $data);
        rewind($handle);

        return $handle;
    }

    /**
     * Create file pounter from given file path
     *
     * @param  string $path
     * @return resource
     */
    private static function getHandleFromFilePath(string $path)
    {
        return fopen($path, 'rb');
    }
}