text:
package jp.dip.th075altlobby.imo.Window.MainWindow;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.JCheckBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultCaret;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

import jp.dip.th075altlobby.imo.Component.JWheelableComboBox;
import jp.dip.th075altlobby.imo.Data.InstantMessageProvideManager.HTMLCS;
import jp.dip.th075altlobby.imo.Data.InstantMessageProvideManager.HTMLInstantMessageFormatter;
import jp.dip.th075altlobby.imo.Data.InstantMessageProvideManager.InstantMessageProvideManager;
import jp.dip.th075altlobby.imo.Data.InstantMessageProvideManager.PlainTextInstantMessageFormatter;
import jp.dip.th075altlobby.imo.Data.SettingManager.ClientSetting.ClientSetting;
import jp.dip.th075altlobby.imo.Data.SettingManager.ClientSetting.WindowSetting;
import jp.dip.th075altlobby.imo.Data.communication.InstantMessage;
import jp.dip.th075altlobby.imo.Resource.Resource;
import jp.dip.th075altlobby.imo.Window.EventAdapter.RunnableCallActionListener;

public class InstantMessagesPanel extends JPanel {
    /**
     * 生成シリアルバージョン(やり取りしない)
     */
    private static final long serialVersionUID = 1L;
    private final JEditorPane editorPane;
    private final ResourceBundle resource = Resource.getBundle();
    private JScrollPane console_scroll;
    private final JPopupMenu menu = new JPopupMenu();
    private final JMenuItem copySelectedMenuItem = new JMenuItem(
            resource.getString("main.InstantMessage.menu.copy"));
    private final JMenuItem selectALLMenuItem = new JMenuItem(
            resource.getString("main.InstantMessage.menu.AllSel"));
    private final JMenuItem copyALLMenuItem = new JMenuItem(
            resource.getString("main.InstantMessage.menu.AllCopy"));
    private final JMenuItem storeAllIM = new JMenuItem(
            resource.getString("main.InstantMessage.menu.store"));
    private final JMenuItem storeAllIMXHTML = new JMenuItem(
            resource.getString("main.InstantMessage.menu.storeToXML"));
    private final InstantMessageProvideManager instantMessageProvideManager = new InstantMessageProvideManager();
    private InnerBottomPanel bottomPanel;

    private final static Logger logger = Logger
            .getLogger("jp.dip.th075altlobby.imo.Application");

    public InstantMessagesPanel(StyleSheet style, ClientSetting setting) {
        GridBagLayout layout = new GridBagLayout();
        setLayout(layout);

        setPreferredSize(new Dimension(320, 380));
        setMinimumSize(new Dimension(480, 240));

        editorPane = new JEditorPane();
        console_scroll = new JScrollPane(editorPane);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0d;
        gbc.weighty = 1.0d;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(10, 10, 10, 10);
        layout.setConstraints(console_scroll, gbc);

        bottomPanel = new InnerBottomPanel();
        gbc.insets = new Insets(0, 0, 0, 0);
        gbc.weighty = 0d;
        gbc.gridy = 1;
        layout.setConstraints(bottomPanel, gbc);

        add(console_scroll);
        add(bottomPanel);

        copySelectedMenuItem.setMnemonic(KeyEvent.VK_C);
        selectALLMenuItem.setMnemonic(KeyEvent.VK_A);
        copyALLMenuItem.setMnemonic(KeyEvent.VK_V);
        storeAllIM.setMnemonic(KeyEvent.VK_S);
        storeAllIMXHTML.setMnemonic(KeyEvent.VK_X);
        copyALLMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_SPACE, InputEvent.CTRL_DOWN_MASK));

        // 初期値を設定する
        WindowSetting windowSetting = setting.getWindowSetting();
        bottomPanel.setAutoScrollCheckboxState(windowSetting.getAutoScroll());
        bottomPanel.setIMFilterSelected(windowSetting.getIM_Filter());

        // メニューに追加する
        menu.add(copySelectedMenuItem);
        menu.add(selectALLMenuItem);
        menu.add(copyALLMenuItem);
        menu.addSeparator();
        menu.add(storeAllIM);
        menu.add(storeAllIMXHTML);

        HTMLEditorKit htmlek = new HTMLEditorKit();
        for (int i = 0; i < InstantMessage.color_set.length; i++)
            style.addRule(".c-" + i + " { color: "
                    + InstantMessage.color_set[i] + ";}");

        htmlek.setStyleSheet(style);
        editorPane.setComponentPopupMenu(menu);
        editorPane.setContentType("text/html");
        editorPane.setEditable(false);
        editorPane.setEditorKit(htmlek);
        editorPane.setMinimumSize(new Dimension(320, 240));

        instantMessageProvideManager.setAutoFileOutputFlag(setting
                .getImSetting().getIMAutoLogging());
    }

    /**
     * インスタントメッセージを追加する
     *
     * @param im
     *            追加するインスタントメッセージ
     */
    public void addInstantMessage(InstantMessage im) {
        addInstantMessage(im, true);
    }

    /**
     * インスタントメッセージを追加する
     *
     * @param im
     *            追加するインスタントメッセージ
     */
    public void addInstantMessage(InstantMessage im, boolean reset) {
        instantMessageProvideManager.append(im);
        if (reset)
            resetEditorPaneText();
    }

    /**
     * IM自動保存用出力ストリームを閉じ、フラッシュします。 このメソッドは終了時に一度だけ呼び出してください。
     */
    public void close() {
        instantMessageProvideManager.setAutoFileOutputFlag(false);
    }

    /**
     *
resetEditorPaneText

     *

     * EditorPaneの文字列を再設定します。
     *

     *
スレッドセーフ

     *

     * テキストの再設定はSwingのイベントディスパッチスレッドで行われます。
     *

     *

     * このメソッドはイベントディスパッチスレッド以外でも呼び出すことができます。
     *

     */
    private void resetEditorPaneText() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                HTMLInstantMessageFormatter htmlFormatter = new HTMLInstantMessageFormatter(
                        HTMLCS.HTML32.HTMLHeader1, HTMLCS.HTML32.HTMLHeader2,
                        HTMLCS.HTML32.HTMLFooter);
                InstantMessage[] IMArray = instantMessageProvideManager
                        .getInnerIMtoArray();
                ArrayDeque<InstantMessage> IMqueue = new ArrayDeque<InstantMessage>();
                int filter = bottomPanel.getIMFilterSelected();
                for (InstantMessage im : IMArray) {
                    boolean onFlag = false;
                    if (filter == 0)
                        onFlag = true;
                    else if (filter == 1 && (im.getTo().equals("all")))
                        onFlag = true;
                    else if (filter == 2 && (!im.getTo().equals("all")))
                        onFlag = true;

                    if (onFlag)
                        IMqueue.add(im);
                }

                editorPane.setText(htmlFormatter.format(IMqueue
                        .toArray(new InstantMessage[0])));
            }
        });
    }

    /**
     * このIMProviderが保持しているIMをファイルに出力します
     *
     * @param f
     *            書き出すファイル
     * @param title
     *            テキストにつけるタイトル
     */
    private void writeOutPlainText(File f, String title) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));

            bw.write(title);
            bw.newLine();

            PlainTextInstantMessageFormatter formatter = new PlainTextInstantMessageFormatter();
            InstantMessage[] buf = instantMessageProvideManager
                    .getInnerIMtoArray();
            for (InstantMessage im : buf) {
                bw.write(formatter.format(im));
                bw.newLine();
            }

            bw.close();
        } catch (FileNotFoundException e) {
            logger.log(Level.WARNING, "保存先ファイルが見つかりません。", e);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "IO例外が発生しました。", e);
        }
    }

    /**
     * このIMProviderが保持しているIMをXHTML1.0に従ったフォーマットでファイルに出力します
     *
     * @param f
     *            書き出すファイル
     * @param title
     *            テキストにつけるタイトル
     */
    private void writeOutXHTML10(File f, String title) {
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(f), "UTF-8"));

            bw.write(HTMLCS.XHTML10S.HTMLHeader1 + title
                    + HTMLCS.XHTML10S.HTMLHeader2);

            HTMLInstantMessageFormatter xhtmlFormatter = new HTMLInstantMessageFormatter(
                    HTMLCS.XHTML10S.HTMLHeader1, HTMLCS.XHTML10S.HTMLHeader2,
                    HTMLCS.XHTML10S.HTMLFooter);
            xhtmlFormatter.setTitle(title);
            InstantMessage[] buf = instantMessageProvideManager
                    .getInnerIMtoArray();
            for (InstantMessage im : buf) {
                String escaped = xhtmlFormatter.format(im);
                bw.write("
" + escaped + "
");
                bw.newLine();
            }

            bw.write(HTMLCS.XHTML10S.HTMLFooter);
            bw.close();
        } catch (FileNotFoundException e) {
            // TODO 自動生成された catch ブロック
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自動生成された catch ブロック
            e.printStackTrace();
        }
    }

    class StoreAllIMRunnable implements Runnable {
        @Override
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    // XHTMLで保存ボタンがクリックされた時
                    JFileChooser filechooser = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter(
                            resource.getString("main.InstantMessage.chooser.store"),
                            "txt");
                    filechooser.addChoosableFileFilter(filter);
                    int selected = filechooser.showSaveDialog(null);
                    if (selected == JFileChooser.APPROVE_OPTION) {
                        SimpleDateFormat sdf = new SimpleDateFormat(
                                "yyyy/MM/dd HH:mm:ss z");
                        File file = filechooser.getSelectedFile();
                        writeOutPlainText(file,
                                "# Lobby System " + sdf.format(new Date()));
                    }
                }
            });
        }
    }

    class StoreAllIMXMLRunnable implements Runnable {
        @Override
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    // XHTMLで保存ボタンがクリックされた時
                    JFileChooser filechooser = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter(
                            resource.getString("main.InstantMessage.chooser.storeToXML"),
                            "html", "htm");
                    filechooser.addChoosableFileFilter(filter);
                    int selected = filechooser.showSaveDialog(null);
                    if (selected == JFileChooser.APPROVE_OPTION) {
                        File file = filechooser.getSelectedFile();
                        SimpleDateFormat sdf = new SimpleDateFormat(
                                "yyyy/MM/dd HH:mm:ss z");
                        writeOutXHTML10(
                                file,
                                "Lobby IM Log ("
                                        + sdf.format(new Date(System
                                                .currentTimeMillis())) + ")");
                    }
                }
            });
        }
    }

    public void registerListeners() {
        copyALLMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int start = editorPane.getSelectionStart();
                int end = editorPane.getSelectionEnd();
                editorPane.selectAll();
                editorPane.copy();
                editorPane.select(start, end);
            }
        });
        selectALLMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editorPane.selectAll();
            }
        });
        copySelectedMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editorPane.copy();
            }
        });

        storeAllIM.addActionListener(new RunnableCallActionListener(
                new StoreAllIMRunnable()));
        storeAllIMXHTML.addActionListener(new RunnableCallActionListener(
                new StoreAllIMXMLRunnable()));
    }

    public JEditorPane getEditorPane() {
        return editorPane;
    }

    /**
     *
setCaretPolicy

InstantMessageが表示されるTextPaneのキャレット移動ポリシーを変更する
     *

     *

     * InstantMessageが表示されるTextPaneのキャレット移動ポリシーを変更します。
     *

     *
スレッドセーフ

     *

     * このメソッドはSwingのイベントディスパッチスレッド以外から呼び出すことはできません。
     *

     *
     * @param flag
     *            キャレットを移動させるかどうか、trueの場合末尾移動する
     */
    public void setCaretPolicy(boolean flag) {
        // TODO 自動生成されたメソッド・スタブ
        int policy = flag ? DefaultCaret.ALWAYS_UPDATE
                : DefaultCaret.NEVER_UPDATE;

        DefaultCaret c = (DefaultCaret) editorPane.getCaret();
        c.setUpdatePolicy(policy);
        editorPane.setCaret(c);
    }

    /**
     *
isAutoScrollSelected

     *

     * 内部のCheckBoxが選択状態を取得する
     *

     *
     *
スレッドセーフ

     *

     * このメソッドはAbstractButton.isSelectedを呼び出します。
     *

     *

     * Swingのイベントディスパッチスレッド以外から呼び出すことはできません。
     *

     *
     * @return trueの場合チェック
     * @see InnerBottomPanel#isAutoScrollCheckboxState()
     * @see AbstractButton#isSelected()
     */
    public boolean isAutoScrollSelected() {
        return bottomPanel.isAutoScrollCheckboxState();
    }

    /**
     *
getIMFilterSelectedIndex

     *

     * 内部のComboBoxで選択されているインデックスを取得します
     *

     *
     *
スレッドセーフ

     *

     * このメソッドはJComboBox.getSelectedIndexを呼び出します。
     *

     *

     * Swingのイベントディスパッチスレッド以外から呼び出すことはできません。
     *

     *
     * @return 選択されている項目
     */
    public int getIMFilterSelectedIndex() {
        return bottomPanel.getIMFilterSelected();
    }

    class InnerBottomPanel extends JPanel {
        /**
         * 生成シリアルバージョン(やり取りしない)
         */
        private static final long serialVersionUID = 1L;
        private final JCheckBox autoScroll;
        private final JWheelableComboBox cIMFilter;
        private final String[] filter_string = {
                resource.getString("main.InstantMessage.filter.item1"),
                resource.getString("main.InstantMessage.filter.item2"),
                resource.getString("main.InstantMessage.filter.item3") };

        public InnerBottomPanel() {
            setPreferredSize(new Dimension(320, 30));

            GridBagLayout layout = new GridBagLayout();
            setLayout(layout);

            final Dimension d = new Dimension(100, 20);

            autoScroll = new JCheckBox(
                    resource.getString("main.InstantMessage.autoscroll"));
            autoScroll.setPreferredSize(d);

            cIMFilter = new JWheelableComboBox();
            cIMFilter.listener_init();

            cIMFilter.addItem(filter_string[0]);
            cIMFilter.addItem(filter_string[1]);
            cIMFilter.addItem(filter_string[2]);
            cIMFilter.setMinimumSize(d);
            cIMFilter.setMaximumSize(d);
            cIMFilter.setPreferredSize(d);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(0, 10, 4, 10);
            gbc.gridx = 1;
            gbc.gridy = 0;
            gbc.weightx = 0d;
            gbc.weighty = 0d;
            gbc.fill = GridBagConstraints.NONE;
            layout.setConstraints(autoScroll, gbc);

            gbc.gridx = 2;
            layout.setConstraints(cIMFilter, gbc);

            Component dummy = Box.createGlue();
            gbc.gridx = 0;
            gbc.weightx = 1.0d;
            layout.setConstraints(dummy, gbc);

            add(autoScroll);
            add(cIMFilter);

            add(dummy);
            registerListeners();
        }

        private void registerListeners() {
            cIMFilter.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    if (e.getStateChange() == ItemEvent.SELECTED)
                        resetEditorPaneText();
                }
            });

            autoScroll.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setCaretPolicy(autoScroll.isSelected());
                }
            });
        }

        /**
         *
isAutoScrollCheckboxState

         *

         * 内部のCheckBoxが選択状態を取得する
         *

         *
スレッドセーフ

         *

         * このメソッドはAbstractButton.isSelectedを呼び出します。
         *

         *

         * Swingのイベントディスパッチスレッド以外から呼び出すことはできません。
         *

         *
         * @return trueの場合チェック
         * @see AbstractButton#isSelected()
         */
        public boolean isAutoScrollCheckboxState() {
            return autoScroll.isSelected();
        }

        /**
         *
setAutoScrollCheckboxState

         *

         * 内部のCheckBoxが選択状態を設定する
         *

         *
スレッドセーフ

         *

         * このメソッドはAbstractButton.setSelectedを呼び出します。
         *

         *

         * Swingのイベントディスパッチスレッド以外から呼び出すことはできません。
         *

         *
         * @param b
         *            trueの場合チェック
         * @see AbstractButton#setSelected(boolean)
         */
        public void setAutoScrollCheckboxState(boolean b) {
            autoScroll.setSelected(b);
        }

        /**
         *
setIMFilterSelected

         *

         * インデックス anIndex にある項目を選択します。
         *

         *
スレッドセーフ

         *

         * このメソッドはJComboBox.setSelectedIndexを呼び出します。
         *

         *

         * Swingのイベントディスパッチスレッド以外から呼び出すことはできません。
         *

         *
         * @param anIndex
         *            選択するIndex, 0から始まる
         */
        public void setIMFilterSelected(int anIndex) {
            this.cIMFilter.setSelectedIndex(anIndex);
        }

        /**
         *
getIMFilterSelected

         *

         * 内部のComboBoxで選択されているインデックスを取得します
         *

         *
スレッドセーフ

         *

         * このメソッドはJComboBox.getSelectedIndexを呼び出します。
         *

         *

         * Swingのイベントディスパッチスレッド以外から呼び出すことはできません。
         *

         *
         * @return 選択されている項目
         */
        public int getIMFilterSelected() {
            return this.cIMFilter.getSelectedIndex();
        }
    }
}


text:
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_i2c.h"
#include "driverlib/i2c.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "utils/uartstdio.h"

//*****************************************************************************
//
//! \addtogroup i2c_examples_list
//!
I2C Master Loopback (i2c_master_slave_loopback)

//!
//! This example shows how to configure the I2C0 module for loopback mode.
//! This includes setting up the master and slave module.  Loopback mode
//! internally connects the master and slave data and clock lines together.
//! The address of the slave module is set in order to read data from the
//! master.  Then the data is checked to make sure the received data matches
//! the data that was transmitted.  This example uses a polling method for
//! sending and receiving data.
//!
//! This example uses the following peripherals and I/O signals.  You must
//! review these and change as needed for your own board:
//! - I2C0 peripheral
//! - GPIO Port B peripheral (for I2C0 pins)
//! - I2C0SCL - PB2
//! - I2C0SDA - PB3
//!
//! The following UART signals are configured only for displaying console
//! messages for this example.  These are not required for operation of I2C.
//! - UART0 peripheral
//! - GPIO Port A peripheral (for UART0 pins)
//! - UART0RX - PA0
//! - UART0TX - PA1
//!
//! This example uses the following interrupt handlers.  To use this example
//! in your own application you must add these interrupt handlers to your
//! vector table.
//! - None.
//!
//
//*****************************************************************************

//*****************************************************************************
//
// Number of I2C data packets to send.
//
//*****************************************************************************
#define NUM_I2C_DATA 3

//*****************************************************************************
//
// Set the address for slave module. This is a 7-bit address sent in the
// following format:
//                      [A6:A5:A4:A3:A2:A1:A0:RS]
//
// A zero in the "RS" position of the first byte means that the master
// transmits (sends) data to the selected slave, and a one in this position
// means that the master receives data from the slave.
//
//*****************************************************************************
#define SLAVE_ADDRESS 0x3C

//*****************************************************************************
//
// This function sets up UART0 to be used for a console to display information
// as the example is running.
//
//*****************************************************************************
void
InitConsole(void)
{
    //
    // Enable GPIO port A which is used for UART0 pins.
    // TODO: change this to whichever GPIO port you are using.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);

    //
    // Configure the pin muxing for UART0 functions on port A0 and A1.
    // This step is not necessary if your part does not support pin muxing.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinConfigure(GPIO_PA0_U0RX);
    GPIOPinConfigure(GPIO_PA1_U0TX);

    //
    // Select the alternate (UART) function for these pins.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Initialize the UART for console I/O.
    //
    UARTStdioInit(0);
}

//*****************************************************************************
//
// Configure the I2C0 master and slave and connect them using loopback mode.
//
//*****************************************************************************
int
main(void)
{
unsigned long ulDataTx[NUM_I2C_DATA];
unsigned long ulDataRx[NUM_I2C_DATA];
unsigned long ulindex;

    //
    // Set the clocking to run directly from the external crystal/oscillator.
    // TODO: The SYSCTL_XTAL_ value must be changed to match the value of the
    // crystal on your board.
    //
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                   SYSCTL_XTAL_16MHZ);

    //
    // The I2C0 peripheral must be enabled before use.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0);

    //
    // For this example I2C0 is used with PortB[3:2].  The actual port and
    // pins used may be different on your part, consult the data sheet for
    // more information.  GPIO port B needs to be enabled so these pins can
    // be used.
    // TODO: change this to whichever GPIO port you are using.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);

    //
    // Configure the pin muxing for I2C0 functions on port B2 and B3.
    // This step is not necessary if your part does not support pin muxing.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinConfigure(GPIO_PB2_I2C0SCL);
    GPIOPinConfigure(GPIO_PB3_I2C0SDA);

    //
    // Select the I2C function for these pins.  This function will also
    // configure the GPIO pins pins for I2C operation, setting them to
    // open-drain operation with weak pull-ups.  Consult the data sheet
    // to see which functions are allocated per pin.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinTypeI2C(GPIO_PORTB_BASE, GPIO_PIN_2 | GPIO_PIN_3);

    //
    // Enable loopback mode.  Loopback mode is a built in feature that is
    // useful for debugging I2C operations.  It internally connects the I2C
    // master and slave terminals, which effectively let's you send data as
    // a master and receive data as a slave.
    // NOTE: For external I2C operation you will need to use external pullups
    // that are stronger than the internal pullups.  Refer to the datasheet for
    // more information.
    //
    HWREG(I2C0_MASTER_BASE + I2C_O_MCR) |= 0x01;

    //
    // Enable and initialize the I2C0 master module.  Use the system clock for
    // the I2C0 module.  The last parameter sets the I2C data transfer rate.
    // If false the data rate is set to 100kbps and if true the data rate will
    // be set to 400kbps.  For this example we will use a data rate of 100kbps.
    //
    I2CMasterInitExpClk(I2C0_MASTER_BASE, SysCtlClockGet(), false);

    //
    // Enable the I2C0 slave module. This module is enabled only for testing
    // purposes.  It does not need to be enabled for proper operation of the
    // I2Cx master module.
    //
    I2CSlaveEnable(I2C0_SLAVE_BASE);

    //
    // Set the slave address to SLAVE_ADDRESS.  In loopback mode, it's an
    // arbitrary 7-bit number (set in a macro above) that is sent to the
    // I2CMasterSlaveAddrSet function.
    //
    I2CSlaveInit(I2C0_SLAVE_BASE, SLAVE_ADDRESS);

    //
    // Tell the master module what address it will place on the bus when
    // communicating with the slave.  Set the address to SLAVE_ADDRESS
    // (as set in the slave module).  The receive parameter is set to false
    // which indicates the I2C Master is initiating a writes to the slave.  If
    // true, that would indicate that the I2C Master is initiating reads from
    // the slave.
    //
    I2CMasterSlaveAddrSet(I2C0_MASTER_BASE, SLAVE_ADDRESS, false);

    //
    // Set up the serial console to use for displaying messages.  This is
    // just for this example program and is not needed for I2C operation.
    //
    InitConsole();

    //
    // Display the example setup on the console.
    //
    UARTprintf("I2C Loopback Example ->");
    UARTprintf("\n   Module = I2C0");
    UARTprintf("\n   Mode = Single Send/Receive");
    UARTprintf("\n   Rate = 100kbps\n\n");

    //
    // Initalize the data to send.
    //
    ulDataTx[0] = 'I';
    ulDataTx[1] = '2';
    ulDataTx[2] = 'C';

    //
    // Initalize the receive buffer.
    //
    for(ulindex = 0; ulindex < NUM_I2C_DATA; ulindex++)
    {
        ulDataRx[ulindex] = 0;
    }

    //
    // Indicate the direction of the data.
    //
    UARTprintf("Tranferring from: Master -> Slave\n");

    //
    // Send 3 peices of I2C data from the master to the slave.
    //
    for(ulindex = 0; ulindex < NUM_I2C_DATA; ulindex++)
    {
        //
        // Display the data that the I2C0 master is transferring.
        //
        UARTprintf("  Sending: '%c'  . . .  ", ulDataTx[ulindex]);

        //
        // Place the data to be sent in the data register
        //
        I2CMasterDataPut(I2C0_MASTER_BASE, ulDataTx[ulindex]);

        //
        // Initiate send of data from the master.  Since the loopback
        // mode is enabled, the master and slave units are connected
        // allowing us to receive the same data that we sent out.
        //
        I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_SINGLE_SEND);

        //
        // Wait until the slave has received and acknowledged the data.
        //
        while(!(I2CSlaveStatus(I2C0_SLAVE_BASE) & I2C_SCSR_RREQ))
        {
        }

        //
        // Read the data from the slave.
        //
        ulDataRx[ulindex] = I2CSlaveDataGet(I2C0_SLAVE_BASE);

        //
        // Wait until master module is done transferring.
        //
        while(I2CMasterBusy(I2C0_MASTER_BASE))
        {
        }

        //
        // Display the data that the slave has received.
        //
        UARTprintf("Received: '%c'\n", ulDataRx[ulindex]);
    }

    //
    // Reset receive buffer.
    //
    for(ulindex = 0; ulindex < NUM_I2C_DATA; ulindex++)
    {
        ulDataRx[ulindex] = 0;
    }

    //
    // Indicate the direction of the data.
    //
    UARTprintf("\n\nTranferring from: Slave -> Master\n");

    //
    // Modifiy the data direction to true, so that seeing the address will
    // indicate that the I2C Master is initiating a read from the slave.
    //
    I2CMasterSlaveAddrSet(I2C0_MASTER_BASE, SLAVE_ADDRESS, true);

    //
    // Do a dummy receive to make sure you don't get junk on the first receive.
    //
    I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_SINGLE_RECEIVE);

    //
    // Dummy acknowledge and wait for the receive request from the master.
    // This is done to clear any flags that should not be set.
    //
    while(!(I2CSlaveStatus(I2C0_SLAVE_BASE) & I2C_SLAVE_ACT_TREQ))
    {
    }

    for(ulindex = 0; ulindex < NUM_I2C_DATA; ulindex++)
    {
        //
        // Display the data that I2C0 slave module is transferring.
        //
        UARTprintf("  Sending: '%c'  . . .  ", ulDataTx[ulindex]);

        //
        // Place the data to be sent in the data register
        //
        I2CSlaveDataPut(I2C0_SLAVE_BASE, ulDataTx[ulindex]);

        //
        // Tell the master to read data.
        //
        I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_SINGLE_RECEIVE);

        //
        // Wait until the slave is done sending data.
        //
        while(!(I2CSlaveStatus(I2C0_SLAVE_BASE) & I2C_SLAVE_ACT_TREQ))
        {
        }

        //
        // Read the data from the master.
        //
        ulDataRx[ulindex] = I2CMasterDataGet(I2C0_MASTER_BASE);

        //
        // Display the data that the slave has received.
        //
        UARTprintf("Received: '%c'\n", ulDataRx[ulindex]);
    }

    //
    // Tell the user that the test is done.
    //
    UARTprintf("\nDone.\n\n");

    //
    // Return no errors
    //
    return(0);
}

redpajama_set_name: RedPajamaGithub


text:
@echo off

set base=%~1

set clspath=
setlocal enabledelayedexpansion

for %%j in (%base%lib\*.jar) do (
	set clspath=!clspath!%%j;
)

setlocal disabledelayedexpansion
set clspath=%clspath:~0,-1%


text:
package com.google.gwt.sample.dynatablerf.server;

import static com.google.gwt.sample.dynatablerf.shared.DynaTableRequestFactory.SchoolCalendarRequest.ALL_DAYS;

import com.google.gwt.sample.dynatablerf.domain.Person;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * The server-side service class.
 */
public class SchoolCalendarService implements Filter {

  private static final ThreadLocal<PersonSource> PERSON_SOURCE = new ThreadLocal<PersonSource>();
  static final ThreadLocal<ScheduleSource> SCHEDULE_SOURCE = new ThreadLocal<ScheduleSource>();

  public static Person createPerson() {
    checkPersonSource();
    Person person = PersonFuzzer.generatePerson();
    PERSON_SOURCE.get().persist(person);
    return person;
  }

  public static Person findPerson(String id) {
    checkPersonSource();
    return PERSON_SOURCE.get().findPerson(id);
  }

  public static List<Person> getPeople(int startIndex, int maxCount,
      List<Boolean> filter) {
    checkPersonSource();
    return PERSON_SOURCE.get().getPeople(startIndex, maxCount, filter);
  }

  public static Person getRandomPerson() {
    PersonSource source = PERSON_SOURCE.get();
    return source.getPeople(new Random().nextInt(source.countPeople()), 1,
        ALL_DAYS).get(0);
  }

  public static void persist(Person person) {
    checkPersonSource();
    PERSON_SOURCE.get().persist(person);
  }

  private static void checkPersonSource() {
    if (PERSON_SOURCE.get() == null) {
      throw new IllegalStateException(
          "Calling service method outside of HTTP request");
    }
  }

  private PersonSource backingStore;
  private ScheduleSource scheduleStore;

  public void destroy() {
  }

  public void doFilter(ServletRequest req, ServletResponse resp,
      FilterChain chain) throws IOException, ServletException {
    try {
      ScheduleSource scheduleBacking = ScheduleSource.of(scheduleStore);
      SCHEDULE_SOURCE.set(scheduleBacking);
      PERSON_SOURCE.set(PersonSource.of(backingStore, scheduleBacking));
      chain.doFilter(req, resp);
    } finally {
      PERSON_SOURCE.set(null);
      SCHEDULE_SOURCE.set(null);
    }
  }

  public void init(FilterConfig config) {
    backingStore = (PersonSource) config.getServletContext().getAttribute(
        SchoolCalendarService.class.getName());
    if (backingStore == null) {
      List<Person> randomPeople = PersonFuzzer.generateRandomPeople();
      scheduleStore = ScheduleSource.of(PersonFuzzer.collectSchedules(randomPeople));
      backingStore = PersonSource.of(randomPeople, scheduleStore);
      config.getServletContext().setAttribute(
          SchoolCalendarService.class.getName(), backingStore);
    }
  }
}


text:
// Copyright 2012 Peter Hallam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package omakase.syntax.trees;

import omakase.syntax.tokens.IdentifierToken;
import omakase.syntax.tokens.Token;
import omakase.syntax.tokens.TokenKind;
import omakase.util.SourceRange;

/**
 *
 */
public class BinaryExpressionTree extends ParseTree {
  public final ParseTree left;
  public final Token operator;
  public final ParseTree right;

  public BinaryExpressionTree(SourceRange location, ParseTree left, Token operator, ParseTree right) {
    super(location, ParseTreeKind.BINARY_EXPRESSION);
    this.left = left;
    this.operator = operator;
    this.right = right;
  }
}


text:
define(function(require){
    'use strict';

    var $ = require('jquery'),
        _ = require('underscore'),
        template = require('text!./main.template.txt');

    var elm = $('body');
    elm.append(template);

    _.each([1,2,3], function(v){
        elm.append(v + '<br/>');
    });
});


text:
package com.autentia.xml.schema;

/**
 * Useful URLs:
 *  - W3C XML Schema Definition Language (XSD) 1.1 Part 1: Structures --> http://www.w3.org/TR/xmlschema11-1/
 *  - XML Schema Patterns for Common Data Structures --> http://www.w3.org/2005/07/xml-schema-patterns.html
 */
public class SchemaBuilder {

    private final ClassTypeDiscoverer classTypeDiscoverer;

    public SchemaBuilder(ClassTypeDiscoverer classTypeDiscoverer) {
        this.classTypeDiscoverer = classTypeDiscoverer;
    }

    public String buildFor(final String localPart) {
        return classTypeDiscoverer.getBy(localPart).toSchema();
    }

}


text:
ES5Harness.registerTest({

    id: "15.4.4.17-2-9",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.17/15.4.4.17-2-9.js",

    description: "Array.prototype.some - 'length' is an own accessor property that overrides an inherited accessor property on an Array-like object",

    test: function testcase() {
        function callbackfn1(val, idx, obj) {
            return val > 10;
        }

        function callbackfn2(val, idx, obj) {
            return val > 11;
        }

        var proto = {};

        Object.defineProperty(proto, "length", {
            get: function () {
                return 3;
            },
            configurable: true
        });

        var Con = function () { };
        Con.prototype = proto;

        var child = new Con();

        Object.defineProperty(child, "length", {
            get: function () {
                return 2;
            },
            configurable: true
        });

        child[0] = 9;
        child[1] = 11;
        child[2] = 12;

        return Array.prototype.some.call(child, callbackfn1) &&
            !Array.prototype.some.call(child, callbackfn2);
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.some) && fnExists(Object.defineProperty);
    }

});


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace MyVote.UI.Helpers
{
	public sealed class TextBoxHelper
	{
		[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
		public static readonly DependencyProperty BindableTextProperty = DependencyProperty.RegisterAttached(
			 "BindableText",
			 typeof(string),
			 typeof(TextBoxHelper),
			 new PropertyMetadata(null, new PropertyChangedCallback((sender, args) =>
			 {
				 var textBox = sender as TextBox;
				 if (textBox != null)
				 {
					 textBox.Text = (string)args.NewValue;
					 if (textBox.Tag == null)
					 {
						 textBox.Tag = new TextBoxHelper(textBox);
					 }
				 }
			 }))
		   );

		public TextBoxHelper(TextBox textBox)
		{
			textBox.TextChanged += (o, a) =>
			{
				textBox.SetValue(BindableTextProperty, textBox.Text);
			};
		}

		[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
		public static void SetBindableText(TextBox element, string value)
		{
			if (element != null)
			{
				element.SetValue(BindableTextProperty, value);
			}
		}
		[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
		public static string GetBindableText(TextBox element)
		{
			if (element != null)
			{
				return (string)element.GetValue(BindableTextProperty);
			}

			return null;
		}
	}
}


text:
#pragma once

#include <modules/basegl/baseglmoduledefine.h>  // for IVW_MODULE_BASEGL_API

#include <inviwo/core/util/glmvec.h>       // for ivec2, vec2
#include <modules/opengl/shader/shader.h>  // for Shader, Shader::Build

#include <functional>   // for function
#include <memory>       // for shared_ptr
#include <string_view>  // for string_view
#include <vector>       // for vector

namespace inviwo {
class Image;
class Layer;

class IVW_MODULE_BASEGL_API ImageConvolution {
public:
    template <typename Callback>
    ImageConvolution(Callback C) : ImageConvolution() {
        shader_.onReload(C);
    }
    ImageConvolution() : shader_("img_convolution.frag", Shader::Build::No) {}
    virtual ~ImageConvolution() {}

    std::shared_ptr<Image> convolution(const Layer& layer, std::function<float(vec2)> kernelWeight,
                                       const float& kernelScale, ivec2 kernelSize);
    std::shared_ptr<Image> convolution(const Layer& layer, int kw, int kh,
                                       const std::vector<float>& kernel, const float& kernelScale);

    std::shared_ptr<Image> convolution_separable(const Layer& layer, std::function<float(float)>,
                                                 int kernelSize, const float& kernelScale);

    std::shared_ptr<Image> gaussianLowpass(const Layer& layer, int kernelSize);
    std::shared_ptr<Image> gaussianLowpass(const Layer& layer, float sigma);
    std::shared_ptr<Image> gaussianLowpass(const Layer& layer, int kernelSize, float sigma);

    std::shared_ptr<Image> lowpass(const Layer& layer, int kernelSize);

protected:
    Shader shader_;
};

}  // namespace inviwo


text:
module IndexImagesHelper
end


text:
//@ts-check

const path = require('path');
const glob = require('glob');
const events = require('events');
const mocha = require('mocha');
const createStatsCollector = require('../../../node_modules/mocha/lib/stats-collector');
const MochaJUnitReporter = require('mocha-junit-reporter');
const url = require('url');
const minimatch = require('minimatch');
const playwright = require('playwright');
const { applyReporter } = require('../reporter');

// opts
const defaultReporterName = process.platform === 'win32' ? 'list' : 'spec';
const optimist = require('optimist')
	// .describe('grep', 'only run tests matching <pattern>').alias('grep', 'g').alias('grep', 'f').string('grep')
	.describe('build', 'run with build output (out-build)').boolean('build')
	.describe('run', 'only run tests matching <relative_file_path>').string('run')
	.describe('grep', 'only run tests matching <pattern>').alias('grep', 'g').alias('grep', 'f').string('grep')
	.describe('debug', 'do not run browsers headless').alias('debug', ['debug-browser']).boolean('debug')
	.describe('browser', 'browsers in which tests should run').string('browser').default('browser', ['chromium', 'firefox', 'webkit'])
	.describe('reporter', 'the mocha reporter').string('reporter').default('reporter', defaultReporterName)
	.describe('reporter-options', 'the mocha reporter options').string('reporter-options').default('reporter-options', '')
	.describe('tfs', 'tfs').string('tfs')
	.describe('help', 'show the help').alias('help', 'h');

// logic
const argv = optimist.argv;

if (argv.help) {
	optimist.showHelp();
	process.exit(0);
}

const withReporter = (function () {
	if (argv.tfs) {
		{
			return (browserType, runner) => {
				new mocha.reporters.Spec(runner);
				new MochaJUnitReporter(runner, {
					reporterOptions: {
						testsuitesTitle: `${argv.tfs} ${process.platform}`,
						mochaFile: process.env.BUILD_ARTIFACTSTAGINGDIRECTORY ? path.join(process.env.BUILD_ARTIFACTSTAGINGDIRECTORY, `test-results/${process.platform}-${process.arch}-${browserType}-${argv.tfs.toLowerCase().replace(/[^\w]/g, '-')}-results.xml`) : undefined
					}
				});
			}
		}
	} else {
		return (_, runner) => applyReporter(runner, argv);
	}
})()

const outdir = argv.build ? 'out-build' : 'out';
const out = path.join(__dirname, `../../../${outdir}`);

function ensureIsArray(a) {
	return Array.isArray(a) ? a : [a];
}

const testModules = (async function () {

	const excludeGlob = '**/{node,electron-sandbox,electron-browser,electron-main}/**/*.test.js';
	let isDefaultModules = true;
	let promise;

	if (argv.run) {
		// use file list (--run)
		isDefaultModules = false;
		promise = Promise.resolve(ensureIsArray(argv.run).map(file => {
			file = file.replace(/^src/, 'out');
			file = file.replace(/\.ts$/, '.js');
			return path.relative(out, file);
		}));

	} else {
		// glob patterns (--glob)
		const defaultGlob = '**/*.test.js';
		const pattern = argv.run || defaultGlob
		isDefaultModules = pattern === defaultGlob;

		promise = new Promise((resolve, reject) => {
			glob(pattern, { cwd: out }, (err, files) => {
				if (err) {
					reject(err);
				} else {
					resolve(files)
				}
			});
		});
	}

	return promise.then(files => {
		const modules = [];
		for (let file of files) {
			if (!minimatch(file, excludeGlob)) {
				modules.push(file.replace(/\.js$/, ''));

			} else if (!isDefaultModules) {
				console.warn(`DROPPONG ${file} because it cannot be run inside a browser`);
			}
		}
		return modules;
	})
})();

function consoleLogFn(msg) {
	const type = msg.type();
	const candidate = console[type];
	if (candidate) {
		return candidate;
	}

	if (type === 'warning') {
		return console.warn;
	}

	return console.log;
}

async function runTestsInBrowser(testModules, browserType) {
	const browser = await playwright[browserType].launch({ headless: !Boolean(argv.debug), devtools: Boolean(argv.debug) });
	const context = await browser.newContext();
	const page = await context.newPage();
	const target = url.pathToFileURL(path.join(__dirname, 'renderer.html'));
	if (argv.build) {
		target.search = `?build=true`;
	}
	await page.goto(target.href);

	const emitter = new events.EventEmitter();
	await page.exposeFunction('mocha_report', (type, data1, data2) => {
		emitter.emit(type, data1, data2)
	});

	page.on('console', async msg => {
		consoleLogFn(msg)(msg.text(), await Promise.all(msg.args().map(async arg => await arg.jsonValue())));
	});

	withReporter(browserType, new EchoRunner(emitter, browserType.toUpperCase()));

	// collection failures for console printing
	const fails = [];
	emitter.on('fail', (test, err) => {
		if (err.stack) {
			const regex = /(vs\/.*\.test)\.js/;
			for (let line of String(err.stack).split('\n')) {
				const match = regex.exec(line);
				if (match) {
					fails.push(match[1]);
					break;
				}
			}
		}
	});

	try {
		// @ts-expect-error
		await page.evaluate(opts => loadAndRun(opts), {
			modules: testModules,
			grep: argv.grep,
		});
	} catch (err) {
		console.error(err);
	}
	await browser.close();

	if (fails.length > 0) {
		return `to DEBUG, open ${browserType.toUpperCase()} and navigate to ${target.href}?${fails.map(module => `m=${module}`).join('&')}`;
	}
}

class EchoRunner extends events.EventEmitter {

	constructor(event, title = '') {
		super();
		createStatsCollector(this);
		event.on('start', () => this.emit('start'));
		event.on('end', () => this.emit('end'));
		event.on('suite', (suite) => this.emit('suite', EchoRunner.deserializeSuite(suite, title)));
		event.on('suite end', (suite) => this.emit('suite end', EchoRunner.deserializeSuite(suite, title)));
		event.on('test', (test) => this.emit('test', EchoRunner.deserializeRunnable(test)));
		event.on('test end', (test) => this.emit('test end', EchoRunner.deserializeRunnable(test)));
		event.on('hook', (hook) => this.emit('hook', EchoRunner.deserializeRunnable(hook)));
		event.on('hook end', (hook) => this.emit('hook end', EchoRunner.deserializeRunnable(hook)));
		event.on('pass', (test) => this.emit('pass', EchoRunner.deserializeRunnable(test)));
		event.on('fail', (test, err) => this.emit('fail', EchoRunner.deserializeRunnable(test, title), EchoRunner.deserializeError(err)));
		event.on('pending', (test) => this.emit('pending', EchoRunner.deserializeRunnable(test)));
	}

	static deserializeSuite(suite, titleExtra) {
		return {
			root: suite.root,
			suites: suite.suites,
			tests: suite.tests,
			title: titleExtra && suite.title ? `${suite.title} - /${titleExtra}/` : suite.title,
			titlePath: () => suite.titlePath,
			fullTitle: () => suite.fullTitle,
			timeout: () => suite.timeout,
			retries: () => suite.retries,
			slow: () => suite.slow,
			bail: () => suite.bail
		};
	}

	static deserializeRunnable(runnable, titleExtra) {
		return {
			title: runnable.title,
			fullTitle: () => titleExtra && runnable.fullTitle ? `${runnable.fullTitle} - /${titleExtra}/` : runnable.fullTitle,
			titlePath: () => runnable.titlePath,
			async: runnable.async,
			slow: () => runnable.slow,
			speed: runnable.speed,
			duration: runnable.duration,
			currentRetry: () => runnable.currentRetry,
		};
	}

	static deserializeError(err) {
		const inspect = err.inspect;
		err.inspect = () => inspect;
		return err;
	}
}

testModules.then(async modules => {

	// run tests in selected browsers
	const browserTypes = Array.isArray(argv.browser)
		? argv.browser : [argv.browser];

	const promises = browserTypes.map(async browserType => {
		try {
			return await runTestsInBrowser(modules, browserType);
		} catch (err) {
			console.error(err);
			process.exit(1);
		}
	});

	// aftermath
	let didFail = false;
	const messages = await Promise.all(promises);
	for (let msg of messages) {
		if (msg) {
			didFail = true;
			console.log(msg);
		}
	}
	process.exit(didFail ? 1 : 0);

}).catch(err => {
	console.error(err);
});


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="false">
        <shape android:shape="rectangle">
            <solid android:color="#DCDCDC"/>
            <corners android:radius="10sp"/>
        </shape>
    </item>

    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <solid android:color="#DCDCDC"/>
            <corners android:radius="10sp"/>
        </shape>
    </item>
</selector>


text:
id: bad87fee1348bd9aedf06756
title: Sovrascrivere le dichiarazioni di classe con gli stili in linea
challengeType: 0
videoUrl: 'https://scrimba.com/c/cGJDRha'
forumTopicId: 18252
dashedName: override-class-declarations-with-inline-styles
---

# --description--

Abbiamo mostrato che le dichiarazioni id sovrascrivono le dichiarazioni di classe, indipendentemente da dove vengono dichiarate nell'elemento `style`.

Ci sono altri modi in cui puoi sovrascrivere il CSS. Ti ricordi gli stili inline?

# --instructions--

Usa uno stile in linea per cercare di rendere bianco l'elemento `h1`. Ricorda, gli stili inline appaiono così:

```html
<h1 style="color: green;">
```

Lascia le classi `blue-text` e `pink-text` sul tuo elemento `h1`.

# --hints--

L'elemento `h1` dovrebbe avere la classe `pink-text`.

```js
assert($('h1').hasClass('pink-text'));
```

L'elemento `h1` dovrebbe avere la classe `blue-text`.

```js
assert($('h1').hasClass('blue-text'));
```

L'elemento `h1` dovrebbe avere l'id di `orange-text`.

```js
assert($('h1').attr('id') === 'orange-text');
```

L'elemento `h1` dovrebbe avere uno stile inline.

```js
assert(document.querySelector('h1[style]'));
```

L'elemento `h1` dovrebbe essere bianco.

```js
assert($('h1').css('color') === 'rgb(255, 255, 255)');
```

# --seed--

## --seed-contents--

```html
<style>
  body {
    background-color: black;
    font-family: monospace;
    color: green;
  }
  #orange-text {
    color: orange;
  }
  .pink-text {
    color: pink;
  }
  .blue-text {
    color: blue;
  }
</style>
<h1 id="orange-text" class="pink-text blue-text">Hello World!</h1>
```

# --solutions--

```html
<style>
  body {
    background-color: black;
    font-family: monospace;
    color: green;
  }
  #orange-text {
    color: orange;
  }
  .pink-text {
    color: pink;
  }
  .blue-text {
    color: blue;
  }
</style>
<h1 id="orange-text" class="pink-text blue-text" style="color: white">Hello World!</h1>
```


text:
import time
import functools
import threading
import collections

class RateLimiter(object):

    """Provides rate limiting for an operation with a configurable number of
    requests for a time period.
    """

    def __init__(self, max_calls, period=1.0, callback=None):
        """Initialize a RateLimiter object which enforces as much as max_calls
        operations on period (eventually floating) number of seconds.
        """
        if period <= 0:
            raise ValueError('Rate limiting period should be > 0')
        if max_calls <= 0:
            raise ValueError('Rate limiting number of calls should be > 0')

        # We're using a deque to store the last execution timestamps, not for
        # its maxlen attribute, but to allow constant time front removal.
        self.calls = collections.deque()

        self.period = period
        self.max_calls = max_calls
        self.callback = callback
        self._lock = threading.Lock()
        self._alock = None

        # Lock to protect creation of self._alock
        self._init_lock = threading.Lock()

    def __call__(self, f):
        """The __call__ function allows the RateLimiter object to be used as a
        regular function decorator.
        """
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            with self:
                return f(*args, **kwargs)
        return wrapped

    def __enter__(self):
        with self._lock:
            # We want to ensure that no more than max_calls were run in the allowed
            # period. For this, we store the last timestamps of each call and run
            # the rate verification upon each __enter__ call.
            if len(self.calls) >= self.max_calls:
                until = time.time() + self.period - self._timespan
                if self.callback:
                    t = threading.Thread(target=self.callback, args=(until,))
                    t.daemon = True
                    t.start()
                sleeptime = until - time.time()
                if sleeptime > 0:
                    time.sleep(sleeptime)
            return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        with self._lock:
            # Store the last operation timestamp.
            self.calls.append(time.time())

            # Pop the timestamp list front (ie: the older calls) until the sum goes
            # back below the period. This is our 'sliding period' window.
            while self._timespan >= self.period:
                self.calls.popleft()

    @property
    def _timespan(self):
        return self.calls[-1] - self.calls[0]


text:
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

# fetch values from package.xml
setup_args = generate_distutils_setup(
    packages=['async_stereo_calibration'],
    package_dir={'src': 'src', 'srv':'srv'},
    requires=['std_msgs', 'rospy','rviz','sensor_msgs','geometry_msgs','tf','cv_bridge','apriltags_ros']
)

setup(**setup_args)


text:
using gagvr = Google.Ads.GoogleAds.V12.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using mel = Microsoft.Extensions.Logging;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;

namespace Google.Ads.GoogleAds.V12.Services
{
    /// Settings for <see cref="AccountLinkServiceClient"/> instances.
    public sealed partial class AccountLinkServiceSettings : gaxgrpc::ServiceSettingsBase
    {
        /// Get a new instance of the default <see cref="AccountLinkServiceSettings"/>.
        /// <returns>A new instance of the default <see cref="AccountLinkServiceSettings"/>.</returns>
        public static AccountLinkServiceSettings GetDefault() => new AccountLinkServiceSettings();

        /// Constructs a new <see cref="AccountLinkServiceSettings"/> object with default settings.
        public AccountLinkServiceSettings()
        {
        }

        private AccountLinkServiceSettings(AccountLinkServiceSettings existing) : base(existing)
        {
            gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
            CreateAccountLinkSettings = existing.CreateAccountLinkSettings;
            MutateAccountLinkSettings = existing.MutateAccountLinkSettings;
            OnCopy(existing);
        }

        partial void OnCopy(AccountLinkServiceSettings existing);

        ///
        /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
        /// <c>AccountLinkServiceClient.CreateAccountLink</c> and <c>AccountLinkServiceClient.CreateAccountLinkAsync</c>
        /// .
        ///
        /// <remarks>
        /// <list type="bullet">
        /// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
        /// <item><description>Retry delay multiplier: 1.3</description></item>
        /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
        /// <item><description>Maximum attempts: Unlimited</description></item>
        /// <item>
        /// <description>
        /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
        /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
        /// </description>
        /// </item>
        /// <item><description>Timeout: 14400 seconds.</description></item>
        /// </list>
        /// </remarks>
        public gaxgrpc::CallSettings CreateAccountLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(14400000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));

        ///
        /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
        /// <c>AccountLinkServiceClient.MutateAccountLink</c> and <c>AccountLinkServiceClient.MutateAccountLinkAsync</c>
        /// .
        ///
        /// <remarks>
        /// <list type="bullet">
        /// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
        /// <item><description>Retry delay multiplier: 1.3</description></item>
        /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
        /// <item><description>Maximum attempts: Unlimited</description></item>
        /// <item>
        /// <description>
        /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
        /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
        /// </description>
        /// </item>
        /// <item><description>Timeout: 14400 seconds.</description></item>
        /// </list>
        /// </remarks>
        public gaxgrpc::CallSettings MutateAccountLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(14400000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));

        /// Creates a deep clone of this object, with all the same property values.
        /// <returns>A deep clone of this <see cref="AccountLinkServiceSettings"/> object.</returns>
        public AccountLinkServiceSettings Clone() => new AccountLinkServiceSettings(this);
    }

    ///
    /// Builder class for <see cref="AccountLinkServiceClient"/> to provide simple configuration of credentials,
    /// endpoint etc.
    ///
    internal sealed partial class AccountLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<AccountLinkServiceClient>
    {
        /// The settings to use for RPCs, or <c>null</c> for the default settings.
        public AccountLinkServiceSettings Settings { get; set; }

        /// Creates a new builder with default settings.
        public AccountLinkServiceClientBuilder() : base(AccountLinkServiceClient.ServiceMetadata)
        {
        }

        partial void InterceptBuild(ref AccountLinkServiceClient client);

        partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AccountLinkServiceClient> task);

        /// Builds the resulting client.
        public override AccountLinkServiceClient Build()
        {
            AccountLinkServiceClient client = null;
            InterceptBuild(ref client);
            return client ?? BuildImpl();
        }

        /// Builds the resulting client asynchronously.
        public override stt::Task<AccountLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
        {
            stt::Task<AccountLinkServiceClient> task = null;
            InterceptBuildAsync(cancellationToken, ref task);
            return task ?? BuildAsyncImpl(cancellationToken);
        }

        private AccountLinkServiceClient BuildImpl()
        {
            Validate();
            grpccore::CallInvoker callInvoker = CreateCallInvoker();
            return AccountLinkServiceClient.Create(callInvoker, Settings, Logger);
        }

        private async stt::Task<AccountLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
        {
            Validate();
            grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
            return AccountLinkServiceClient.Create(callInvoker, Settings, Logger);
        }

        /// Returns the channel pool to use when no other options are specified.
        protected override gaxgrpc::ChannelPool GetChannelPool() => AccountLinkServiceClient.ChannelPool;
    }

    /// AccountLinkService client wrapper, for convenient use.
    /// <remarks>
    /// This service allows management of links between Google Ads accounts and other
    /// accounts.
    /// </remarks>
    public abstract partial class AccountLinkServiceClient
    {
        ///
        /// The default endpoint for the AccountLinkService service, which is a host of "googleads.googleapis.com" and a
        /// port of 443.
        ///
        public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";

        /// The default AccountLinkService scopes.
        /// <remarks>
        /// The default AccountLinkService scopes are:
        /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
        /// </remarks>
        public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
        {
            "https://www.googleapis.com/auth/adwords",
        });

        /// The service metadata associated with this client type.
        public static gaxgrpc::ServiceMetadata ServiceMetadata { get; } = new gaxgrpc::ServiceMetadata(AccountLinkService.Descriptor, DefaultEndpoint, DefaultScopes, true, gax::ApiTransports.Grpc, PackageApiMetadata.ApiMetadata);

        internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(ServiceMetadata);

        ///
        /// Asynchronously creates a <see cref="AccountLinkServiceClient"/> using the default credentials, endpoint and
        /// settings. To specify custom credentials or other settings, use <see cref="AccountLinkServiceClientBuilder"/>
        /// .
        ///
        /// <param name="cancellationToken">
        /// The <see cref="st::CancellationToken"/> to use while creating the client.
        /// </param>
        /// <returns>The task representing the created <see cref="AccountLinkServiceClient"/>.</returns>
        public static stt::Task<AccountLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
            new AccountLinkServiceClientBuilder().BuildAsync(cancellationToken);

        ///
        /// Synchronously creates a <see cref="AccountLinkServiceClient"/> using the default credentials, endpoint and
        /// settings. To specify custom credentials or other settings, use <see cref="AccountLinkServiceClientBuilder"/>
        /// .
        ///
        /// <returns>The created <see cref="AccountLinkServiceClient"/>.</returns>
        public static AccountLinkServiceClient Create() => new AccountLinkServiceClientBuilder().Build();

        ///
        /// Creates a <see cref="AccountLinkServiceClient"/> which uses the specified call invoker for remote
        /// operations.
        ///
        /// <param name="callInvoker">
        /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
        /// </param>
        /// <param name="settings">Optional <see cref="AccountLinkServiceSettings"/>.</param>
        /// <param name="logger">Optional <see cref="mel::ILogger"/>.</param>
        /// <returns>The created <see cref="AccountLinkServiceClient"/>.</returns>
        internal static AccountLinkServiceClient Create(grpccore::CallInvoker callInvoker, AccountLinkServiceSettings settings = null, mel::ILogger logger = null)
        {
            gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
            grpcinter::Interceptor interceptor = settings?.Interceptor;
            if (interceptor != null)
            {
                callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
            }
            AccountLinkService.AccountLinkServiceClient grpcClient = new AccountLinkService.AccountLinkServiceClient(callInvoker);
            return new AccountLinkServiceClientImpl(grpcClient, settings, logger);
        }

        ///
        /// Shuts down any channels automatically created by <see cref="Create()"/> and
        /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
        /// affected.
        ///
        /// <remarks>
        /// After calling this method, further calls to <see cref="Create()"/> and
        /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
        /// by another call to this method.
        /// </remarks>
        /// <returns>A task representing the asynchronous shutdown operation.</returns>
        public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();

        /// The underlying gRPC AccountLinkService client
        public virtual AccountLinkService.AccountLinkServiceClient GrpcClient => throw new sys::NotImplementedException();

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual CreateAccountLinkResponse CreateAccountLink(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, st::CancellationToken cancellationToken) =>
            CreateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer for which the account link is created.
        /// </param>
        /// <param name="accountLink">
        /// Required. The account link to be created.
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual CreateAccountLinkResponse CreateAccountLink(string customerId, gagvr::AccountLink accountLink, gaxgrpc::CallSettings callSettings = null) =>
            CreateAccountLink(new CreateAccountLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                AccountLink = gax::GaxPreconditions.CheckNotNull(accountLink, nameof(accountLink)),
            }, callSettings);

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer for which the account link is created.
        /// </param>
        /// <param name="accountLink">
        /// Required. The account link to be created.
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<CreateAccountLinkResponse> CreateAccountLinkAsync(string customerId, gagvr::AccountLink accountLink, gaxgrpc::CallSettings callSettings = null) =>
            CreateAccountLinkAsync(new CreateAccountLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                AccountLink = gax::GaxPreconditions.CheckNotNull(accountLink, nameof(accountLink)),
            }, callSettings);

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer for which the account link is created.
        /// </param>
        /// <param name="accountLink">
        /// Required. The account link to be created.
        /// </param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<CreateAccountLinkResponse> CreateAccountLinkAsync(string customerId, gagvr::AccountLink accountLink, st::CancellationToken cancellationToken) =>
            CreateAccountLinkAsync(customerId, accountLink, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual MutateAccountLinkResponse MutateAccountLink(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, st::CancellationToken cancellationToken) =>
            MutateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer being modified.
        /// </param>
        /// <param name="operation">
        /// Required. The operation to perform on the link.
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual MutateAccountLinkResponse MutateAccountLink(string customerId, AccountLinkOperation operation, gaxgrpc::CallSettings callSettings = null) =>
            MutateAccountLink(new MutateAccountLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
            }, callSettings);

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer being modified.
        /// </param>
        /// <param name="operation">
        /// Required. The operation to perform on the link.
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateAccountLinkResponse> MutateAccountLinkAsync(string customerId, AccountLinkOperation operation, gaxgrpc::CallSettings callSettings = null) =>
            MutateAccountLinkAsync(new MutateAccountLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
            }, callSettings);

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer being modified.
        /// </param>
        /// <param name="operation">
        /// Required. The operation to perform on the link.
        /// </param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateAccountLinkResponse> MutateAccountLinkAsync(string customerId, AccountLinkOperation operation, st::CancellationToken cancellationToken) =>
            MutateAccountLinkAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
    }

    /// AccountLinkService client wrapper implementation, for convenient use.
    /// <remarks>
    /// This service allows management of links between Google Ads accounts and other
    /// accounts.
    /// </remarks>
    public sealed partial class AccountLinkServiceClientImpl : AccountLinkServiceClient
    {
        private readonly gaxgrpc::ApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse> _callCreateAccountLink;

        private readonly gaxgrpc::ApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse> _callMutateAccountLink;

        ///
        /// Constructs a client wrapper for the AccountLinkService service, with the specified gRPC client and settings.
        ///
        /// <param name="grpcClient">The underlying gRPC client.</param>
        /// <param name="settings">The base <see cref="AccountLinkServiceSettings"/> used within this client.</param>
        /// <param name="logger">Optional <see cref="mel::ILogger"/> to use within this client.</param>
        public AccountLinkServiceClientImpl(AccountLinkService.AccountLinkServiceClient grpcClient, AccountLinkServiceSettings settings, mel::ILogger logger)
        {
            GrpcClient = grpcClient;
            AccountLinkServiceSettings effectiveSettings = settings ?? AccountLinkServiceSettings.GetDefault();
            gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings, logger);
            _callCreateAccountLink = clientHelper.BuildApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse>("CreateAccountLink", grpcClient.CreateAccountLinkAsync, grpcClient.CreateAccountLink, effectiveSettings.CreateAccountLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
            Modify_ApiCall(ref _callCreateAccountLink);
            Modify_CreateAccountLinkApiCall(ref _callCreateAccountLink);
            _callMutateAccountLink = clientHelper.BuildApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse>("MutateAccountLink", grpcClient.MutateAccountLinkAsync, grpcClient.MutateAccountLink, effectiveSettings.MutateAccountLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
            Modify_ApiCall(ref _callMutateAccountLink);
            Modify_MutateAccountLinkApiCall(ref _callMutateAccountLink);
            OnConstruction(grpcClient, effectiveSettings, clientHelper);
        }

        partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;

        partial void Modify_CreateAccountLinkApiCall(ref gaxgrpc::ApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse> call);

        partial void Modify_MutateAccountLinkApiCall(ref gaxgrpc::ApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse> call);

        partial void OnConstruction(AccountLinkService.AccountLinkServiceClient grpcClient, AccountLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);

        /// The underlying gRPC AccountLinkService client
        public override AccountLinkService.AccountLinkServiceClient GrpcClient { get; }

        partial void Modify_CreateAccountLinkRequest(ref CreateAccountLinkRequest request, ref gaxgrpc::CallSettings settings);

        partial void Modify_MutateAccountLinkRequest(ref MutateAccountLinkRequest request, ref gaxgrpc::CallSettings settings);

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public override CreateAccountLinkResponse CreateAccountLink(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_CreateAccountLinkRequest(ref request, ref callSettings);
            return _callCreateAccountLink.Sync(request, callSettings);
        }

        ///
        /// Creates an account link.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        /// [ThirdPartyAppAnalyticsLinkError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public override stt::Task<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_CreateAccountLinkRequest(ref request, ref callSettings);
            return _callCreateAccountLink.Async(request, callSettings);
        }

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public override MutateAccountLinkResponse MutateAccountLink(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_MutateAccountLinkRequest(ref request, ref callSettings);
            return _callMutateAccountLink.Sync(request, callSettings);
        }

        ///
        /// Creates or removes an account link.
        /// From V5, create is not supported through
        /// AccountLinkService.MutateAccountLink. Use
        /// AccountLinkService.CreateAccountLink instead.
        ///
        /// List of thrown errors:
        /// [AccountLinkError]()
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public override stt::Task<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_MutateAccountLinkRequest(ref request, ref callSettings);
            return _callMutateAccountLink.Async(request, callSettings);
        }
    }
}


text:
title: "systemd"
code: "systemd"
---


text:
package postgresql

import (
	"testing"
)

func Test_newPendingPackets(t *testing.T) {
	pendingPackets := newPendingPacketsList()
	if packet, err := pendingPackets.GetPendingPacket(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet != nil {
		t.Fatal("Packet should be nil")
	}

	if packet, err := pendingPackets.GetLastPending(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet != nil {
		t.Fatal("Packet should be nil")
	}

	if err := pendingPackets.Add(&BindPacket{portal: "portal1"}); err != nil {
		t.Fatal(err)
	}

	if packet, err := pendingPackets.GetPendingPacket(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet == nil {
		t.Fatal("Packet should not be nil")
	} else if packet.(*BindPacket).portal != "portal1" {
		t.Fatal("Unexpected value")
	}

	if packet, err := pendingPackets.GetLastPending(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet == nil {
		t.Fatal("Packet should not be nil")
	} else if packet.(*BindPacket).portal != "portal1" {
		t.Fatal("Unexpected value")
	}

	if err := pendingPackets.Add(&BindPacket{portal: "portal2"}); err != nil {
		t.Fatal(err)
	}

	if packet, err := pendingPackets.GetPendingPacket(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet == nil {
		t.Fatal("Packet should not be nil")
	} else if packet.(*BindPacket).portal != "portal1" {
		t.Fatal("Unexpected value")
	}

	if packet, err := pendingPackets.GetLastPending(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet == nil {
		t.Fatal("Packet should not be nil")
	} else if packet.(*BindPacket).portal != "portal2" {
		t.Fatal("Unexpected value")
	}

	if err := pendingPackets.RemoveNextPendingPacket(&BindPacket{}); err != nil {
		t.Fatal(err)
	}
	if packet, err := pendingPackets.GetPendingPacket(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet == nil {
		t.Fatal("Packet should not be nil")
	} else if packet.(*BindPacket).portal != "portal2" {
		t.Fatal("Unexpected value")
	}

	if packet, err := pendingPackets.GetLastPending(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet == nil {
		t.Fatal("Packet should not be nil")
	} else if packet.(*BindPacket).portal != "portal2" {
		t.Fatal("Unexpected value")
	}

	if err := pendingPackets.RemoveAll(&BindPacket{}); err != nil {
		t.Fatal(err)
	}
	if packet, err := pendingPackets.GetPendingPacket(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet != nil {
		t.Fatal("Packet should be nil")
	}

	if packet, err := pendingPackets.GetLastPending(&BindPacket{}); err != nil {
		t.Fatal(err)
	} else if packet != nil {
		t.Fatal("Packet should be nil")
	}
}


text:
cask "microsoft-remote-desktop" do
  version "10.7.3"
  sha256 "ab4fbccf467fa39d0f3cbe90f6b590eb4240481a9914bf2e31394388a6a01ac8"

  url "https://officecdn-microsoft-com.akamaized.net/pr/C1297A47-86C4-4C1F-97FA-950631F94777/MacAutoupdate/Microsoft_Remote_Desktop_#{version}_installer.pkg",
      verified: "officecdn-microsoft-com.akamaized.net/pr/C1297A47-86C4-4C1F-97FA-950631F94777/MacAutoupdate/"
  name "Microsoft Remote Desktop"
  desc "Remote desktop client"
  homepage "https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/remote-desktop-mac"

  livecheck do
    url "https://go.microsoft.com/fwlink/?linkid=868963"
    strategy :header_match
  end

  auto_updates true
  depends_on macos: ">= :high_sierra"

  pkg "Microsoft_Remote_Desktop_#{version}_installer.pkg"

  uninstall pkgutil:   [
    "com.microsoft.rdc.macos",
  ],
            launchctl: [
              "com.microsoft.update.agent",
            ],
            quit:      [
              "com.microsoft.autoupdate2",
              "com.microsoft.autoupdate.fba",
            ]

  zap trash: [
    "~/Library/Application Scripts/com.microsoft.rdc.macos",
    "~/Library/Containers/com.microsoft.rdc.macos",
    "~/Library/Group Containers/UBF8T346G9.com.microsoft.rdc",
  ]
end


text:
package parquet.io;

/**
 * used to read reassembled records
 * @author Julien Le Dem
 *
 * @param <T> the type of the materialized record
 */
public abstract class RecordReader<T> {

  /**
   * Reads one record and returns it.
   * @return the materialized record
   */
  public abstract T read();

  /**
   * Returns whether the current record should be skipped (dropped)
   * Will be called *after* read()
   */
  public boolean shouldSkipCurrentRecord() {
    return false;
  }
}


text:
<?php

namespace ZendTest\Http\Header;

use Zend\Http\Header\AcceptRanges;

class AcceptRangesTest extends \PHPUnit_Framework_TestCase
{
    public function testAcceptRangesFromStringCreatesValidAcceptRangesHeader()
    {
        $acceptRangesHeader = AcceptRanges::fromString('Accept-Ranges: bytes');
        $this->assertInstanceOf('Zend\Http\Header\HeaderInterface', $acceptRangesHeader);
        $this->assertInstanceOf('Zend\Http\Header\AcceptRanges', $acceptRangesHeader);
    }

    public function testAcceptRangesGetFieldNameReturnsHeaderName()
    {
        $acceptRangesHeader = new AcceptRanges();
        $this->assertEquals('Accept-Ranges', $acceptRangesHeader->getFieldName());
    }

    public function testAcceptRangesGetFieldValueReturnsProperValue()
    {
        $acceptRangesHeader = AcceptRanges::fromString('Accept-Ranges: bytes');
        $this->assertEquals('bytes', $acceptRangesHeader->getFieldValue());
        $this->assertEquals('bytes', $acceptRangesHeader->getRangeUnit());
    }

    public function testAcceptRangesToStringReturnsHeaderFormattedString()
    {
        $acceptRangesHeader = new AcceptRanges();
        $acceptRangesHeader->setRangeUnit('bytes');

        // @todo set some values, then test output
        $this->assertEquals('Accept-Ranges: bytes', $acceptRangesHeader->toString());
    }

    /** Implementation specific tests here */

    /**
     * @see http://en.wikipedia.org/wiki/HTTP_response_splitting
     * @group ZF2015-04
     */
    public function testPreventsCRLFAttackViaFromString()
    {
        $this->setExpectedException('Zend\Http\Header\Exception\InvalidArgumentException');
        $header = AcceptRanges::fromString("Accept-Ranges: bytes;\r\n\r\nevilContent");
    }

    /**
     * @see http://en.wikipedia.org/wiki/HTTP_response_splitting
     * @group ZF2015-04
     */
    public function testPreventsCRLFAttackViaConstructor()
    {
        $this->setExpectedException('Zend\Http\Header\Exception\InvalidArgumentException');
        $header = new AcceptRanges("bytes;\r\n\r\nevilContent");
    }
}


text:
@interface SDLPermissionItem : SDLRPCStruct {}

-(id) init;
-(id) initWithDictionary:(NSMutableDictionary*) dict;

@property(strong) NSString* rpcName;
@property(strong) SDLHMIPermissions* hmiPermissions;
@property(strong) SDLParameterPermissions* parameterPermissions;

@end


text:
@implementation FLDefaultTheme

FLSynthesizeSingleton(FLDefaultTheme);

- (id) init {
    self = [super init];
    if(self) {
        self.alertViewThemeApplicator = [FLDefaultAlertViewThemeApplicator alertViewThemeApplicator];
    }

    return self;
}

@end


text:
require 'roar/representer/json'

module SupportToInitiativeRepresenter
  include Roar::Representer::JSON

  property :initiative_id
  property :member_id
end


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using ToDoApp.Web.Model.Domain;
using ToDoApp.Web.Model.Request;

namespace ToDoApp.Web.Services.Interfaces
{
    public interface IToDoService
    {
        List<ScheduleItem> GetAll();
        ScheduleItem GetTaskById(int id);
        int ScheduleNewTask(ScheduleTask model);
        void UpdateTask(ScheduleTaskWithId model);
        void DeleteTask(int id);
        Task<List<MotivationLink>> GetRedditPosts();
    }
}