text:
title: Edit or Delete a message using RadContextMenu
description: Edit/Delete RadChat message using RadContextMenu
type: how-to
page_title: Edit or Delete a message using RadContextMenu
slug:  chat-edit-delete-message
position: 0
tags: RadChat, edit,delete,RadContextMenu
res_type: kb
---

|Product Version|Product|Author|
|----|----|----|
|2022.1.222|RadChatView for WinForms|[Dinko Krastev](https://www.telerik.com/blogs/author/dinko-krastev)|

# Problem

At this time of writing this KB article, the __RadChat__ control does not provide an API to edit/delete its messages through a RadContextMenu.

# Solution

The control is very customizable and you could achieve this scenario using custom code.

1. First we need to create __RadContextMenu__ with two __RadMenuItems (Edit/Delete)__ and subscribe to their __Click__ events. In their event handler, we can execute our custom logic.
2. In the __ItemFormatting__ event of the __RadChat__ we can get an instance of each message and subscribe to its MouseDown event. In its event handler, we can show the menu.
3. Editing a message will require adding additional RadTextBox placed in RadHostItem which we will use for the editing process. When the user clicks on the Edit RadMenuItem, we can show the __RadTextBox__. The user will enter the new message and pressing enter, for example, will change the actual message.
4. Deleting a message is much easier. When the user clicks on the __Delete RadMenuItem__, we can get the current clicked message and delete it from the __RadChat.ChatElement.MessagesViewElement.Items__ collection.
5. This approach can be further customized to mark the edited text and perform some other custom logic depending on the edited text.
6. Full sample code can be found below.

![radchat-edit-delete-message](images/radchat-edit-delete-message.gif)

````C#

public partial class RadForm1 : System.Windows.Forms.Form
{
    RadContextMenu contextMenu = new RadContextMenu();
    RadTextBox textBox;
    RadHostItem hostItem;
    TextMessageItemElement currentClickedTextMessageItemElement;
    private Author author2;
    public RadForm1()
    {
        InitializeComponent();

        new RadControlSpyForm().Show();
        this.radChat1.AutoAddUserMessages = true;
        this.radChat1.SendMessage += radChat1_SendMessage;

        this.radChat1.Author = new Author(Properties.Resources.Janet, "User");
        author2 = new Author(Properties.Resources.AndrewFuller, "devNXT Bot");

        RadMenuItem editItem = new RadMenuItem("Edit");
        editItem.Click += EditItem_Click;
        RadMenuItem deleteItem = new RadMenuItem("Delete");
        deleteItem.Click += DeleteItem_Click;
        contextMenu.Items.Add(editItem);
        contextMenu.Items.Add(deleteItem);
        this.radChat1.ItemFormatting += RadChat1_ItemFormatting1;

    }

    private void RadChat1_ItemFormatting1(object sender, ChatItemElementEventArgs e)
    {
        LightVisualElement bubble = e.ItemElement.MainMessageElement;
        if (e.ItemElement is TextMessageItemElement )
        {
            bubble.MouseDown -= RadForm1_MouseDown;
            bubble.MouseDown += RadForm1_MouseDown;

            bool isUpdated = (e.ItemElement as TextMessageItemElement).Tag != null ? true : false;
            if(isUpdated)
            {
                bubble.DrawFill = true;
                bubble.BackColor = Color.LightGreen;
            }
        }
        else
        {
            bubble.ResetValue(LightVisualElement.DrawBorderProperty, Telerik.WinControls.ValueResetFlags.Local);
            bubble.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local);
        }
    }

    private void DeleteItem_Click(object sender, EventArgs e)
    {
        var menuItem = sender as MenuItem;
        this.radChat1.ChatElement.MessagesViewElement.Items.Remove(currentClickedTextMessageItemElement.Data);
    }

    private void EditItem_Click(object sender, EventArgs e)
    {
        if (currentClickedTextMessageItemElement.Data.Message is ChatTextMessage)
        {
            if (textBox == null)
            {
                textBox = new RadTextBox();
                textBox.KeyDown += T_KeyDown;
                hostItem = new RadHostItem(textBox);
                hostItem.MinSize = new Size(200, 24);
            }

            currentClickedTextMessageItemElement.MainMessageElement.DrawText = false;
            currentClickedTextMessageItemElement.MainMessageElement.Children.Add(hostItem);
            textBox.Text = (currentClickedTextMessageItemElement.Data.Message as ChatTextMessage).Message;
        }
    }

    private void T_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.Return)
        {
            var ctm = currentClickedTextMessageItemElement.Data.Message as ChatTextMessage;
            ctm.Message = textBox.Text;
            // Submit
            currentClickedTextMessageItemElement.MainMessageElement.Children.Remove(hostItem);
            currentClickedTextMessageItemElement.Tag = "Updated";
            VirtualAssistanChat(ctm.Message);
        }
        else if (e.KeyData == Keys.Escape)
        {
            // Cancel
            // Remove editor
            currentClickedTextMessageItemElement.MainMessageElement.Children.Remove(hostItem);
        }
        currentClickedTextMessageItemElement.MainMessageElement.DrawText = true;
    }

    private void RadForm1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            currentClickedTextMessageItemElement = (sender as ChatMessageBubbleElement).Parent as TextMessageItemElement;
            contextMenu.Show(this, new Point(e.X, e.Y));
        }
    }

    private void radChat1_SendMessage(object sender, SendMessageEventArgs e)
    {
        Telerik.WinControls.UI.ChatTextMessage chatMessage = (Telerik.WinControls.UI.ChatTextMessage)e.Message;
        this.radChat1.AutoAddUserMessages = true;
        VirtualAssistanChat(chatMessage.Message);
    }

    private void radChat1_SuggestedActionClicked(object sender, SuggestedActionEventArgs e)
    {
        this.radChat1.AddMessage(new ChatTextMessage("You have chosen " + e.Action.Text, this.radChat1.Author, DateTime.Now));
    }

    void VirtualAssistanChat(string message)
    {
        if (message == "Hello")
        {
            ChatTextMessage message12 = new ChatTextMessage("I am your Virtual Assistant", author2, DateTime.Now.AddSeconds(15));
            this.radChat1.AddMessage(message12);
        }

        if (message.Contains("Options"))
        {
            ChatTextMessage message12 = new ChatTextMessage("Below are your Automation options:", author2, DateTime.Now.AddSeconds(15));
            this.radChat1.AddMessage(message12);
            List<SuggestedActionDataItem> suggestedActions = new List<SuggestedActionDataItem>();
            suggestedActions.Add(new SuggestedActionDataItem(".Net Core Conversion"));
            suggestedActions.Add(new SuggestedActionDataItem("Code Forensics"));
            this.radChat1.AddMessage(new ChatSuggestedActionsMessage(suggestedActions, author2, DateTime.Now));
            ChatSuggestedActionsMessage suggestionActionsMessage = new ChatSuggestedActionsMessage(suggestedActions, author2, DateTime.Now);
            this.radChat1.AddMessage(suggestionActionsMessage);
            this.radChat1.SuggestedActionClicked -= radChat1_SuggestedActionClicked;
            this.radChat1.SuggestedActionClicked += radChat1_SuggestedActionClicked;
        }

        if (message.Contains(".Net Core Conversion"))
        {
            ChatTextMessage message12 = new ChatTextMessage("Below are your Conversion options:", author2, DateTime.Now.AddSeconds(5));
            this.radChat1.AddMessage(message12);
            List<SuggestedActionDataItem> actions = new List<SuggestedActionDataItem>();
            actions.Add(new SuggestedActionDataItem("Console Application"));
            actions.Add(new SuggestedActionDataItem("MVC"));
            actions.Add(new SuggestedActionDataItem("Windows App"));
            actions.Add(new SuggestedActionDataItem("Restful"));
            actions.Add(new SuggestedActionDataItem("SOAP"));
            actions.Add(new SuggestedActionDataItem("Container"));
            actions.Add(new SuggestedActionDataItem("Others"));
            this.radChat1.AddMessage(new ChatSuggestedActionsMessage(actions, author2, DateTime.Now));
            ChatSuggestedActionsMessage suggestionActionsMessage = new ChatSuggestedActionsMessage(actions, author2, DateTime.Now);
            this.radChat1.AddMessage(suggestionActionsMessage);
            this.radChat1.SuggestedActionClicked -= radChat1_SuggestedActionClicked;
            this.radChat1.SuggestedActionClicked += radChat1_SuggestedActionClicked;
        }
    }
}

````
````VB.NET

Partial Public Class RadForm2
    Inherits System.Windows.Forms.Form

    Private contextMenu As RadContextMenu = New RadContextMenu()
    Private textBox As RadTextBox
    Private hostItem As RadHostItem
    Private currentClickedTextMessageItemElement As TextMessageItemElement
    Private author2 As Author

    Public Sub New()
        InitializeComponent()
        Me.RadChat1.AutoAddUserMessages = True
        AddHandler Me.RadChat1.SendMessage, AddressOf radChat1_SendMessage
        Me.RadChat1.Author = New Author(My.Resources.Janet, "User")
        author2 = New Author(My.Resources.AndrewFuller, "devNXT Bot")
        Dim editItem As RadMenuItem = New RadMenuItem("Edit")
        AddHandler editItem.Click, AddressOf EditItem_Click
        Dim deleteItem As RadMenuItem = New RadMenuItem("Delete")
        AddHandler deleteItem.Click, AddressOf DeleteItem_Click
        contextMenu.Items.Add(editItem)
        contextMenu.Items.Add(deleteItem)
        AddHandler Me.radChat1.ItemFormatting, AddressOf RadChat1_ItemFormatting1
    End Sub

    Private Sub RadChat1_ItemFormatting1(ByVal sender As Object, ByVal e As ChatItemElementEventArgs)
        Dim bubble As LightVisualElement = e.ItemElement.MainMessageElement

        If TypeOf e.ItemElement Is TextMessageItemElement Then
            RemoveHandler bubble.MouseDown, AddressOf RadForm1_MouseDown
            AddHandler bubble.MouseDown, AddressOf RadForm1_MouseDown
            Dim isUpdated As Boolean = If((TryCast(e.ItemElement, TextMessageItemElement)).Tag IsNot Nothing, True, False)

            If isUpdated Then
                bubble.DrawFill = True
                bubble.BackColor = Color.LightGreen
            End If
        Else
            bubble.ResetValue(LightVisualElement.DrawBorderProperty, Telerik.WinControls.ValueResetFlags.Local)
            bubble.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local)
        End If
    End Sub

    Private Sub DeleteItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim menuItem = TryCast(sender, MenuItem)
        Me.radChat1.ChatElement.MessagesViewElement.Items.Remove(currentClickedTextMessageItemElement.Data)
    End Sub

    Private Sub EditItem_Click(ByVal sender As Object, ByVal e As EventArgs)
        If TypeOf currentClickedTextMessageItemElement.Data.Message Is ChatTextMessage Then

            If textBox Is Nothing Then
                textBox = New RadTextBox()
                AddHandler textBox.KeyDown, AddressOf T_KeyDown
                hostItem = New RadHostItem(textBox)
                hostItem.MinSize = New Size(200, 24)
            End If

            currentClickedTextMessageItemElement.MainMessageElement.DrawText = False
            currentClickedTextMessageItemElement.MainMessageElement.Children.Add(hostItem)
            textBox.Text = (TryCast(currentClickedTextMessageItemElement.Data.Message, ChatTextMessage)).Message
        End If
    End Sub

    Private Sub T_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        If e.KeyData = Keys.[Return] Then
            Dim ctm = TryCast(currentClickedTextMessageItemElement.Data.Message, ChatTextMessage)
            ctm.Message = textBox.Text
            currentClickedTextMessageItemElement.MainMessageElement.Children.Remove(hostItem)
            currentClickedTextMessageItemElement.Tag = "Updated"
            VirtualAssistanChat(ctm.Message)
        ElseIf e.KeyData = Keys.Escape Then
            currentClickedTextMessageItemElement.MainMessageElement.Children.Remove(hostItem)
        End If

        currentClickedTextMessageItemElement.MainMessageElement.DrawText = True
    End Sub

    Private Sub RadForm1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
        If e.Button = MouseButtons.Right Then
            currentClickedTextMessageItemElement = TryCast((TryCast(sender, ChatMessageBubbleElement)).Parent, TextMessageItemElement)
            contextMenu.Show(Me, New Point(e.X, e.Y))
        End If
    End Sub

    Private Sub radChat1_SendMessage(ByVal sender As Object, ByVal e As SendMessageEventArgs)
        Dim chatMessage As Telerik.WinControls.UI.ChatTextMessage = CType(e.Message, Telerik.WinControls.UI.ChatTextMessage)
        Me.radChat1.AutoAddUserMessages = True
        VirtualAssistanChat(chatMessage.Message)
    End Sub

    Private Sub radChat1_SuggestedActionClicked(ByVal sender As Object, ByVal e As SuggestedActionEventArgs)
        Me.radChat1.AddMessage(New ChatTextMessage("You have chosen " & e.Action.Text, Me.radChat1.Author, DateTime.Now))
    End Sub

    Private Sub VirtualAssistanChat(ByVal message As String)
        If message = "Hello" Then
            Dim message12 As ChatTextMessage = New ChatTextMessage("I am your Virtual Assistant", author2, DateTime.Now.AddSeconds(15))
            Me.radChat1.AddMessage(message12)
        End If

        If message.Contains("Options") Then
            Dim message12 As ChatTextMessage = New ChatTextMessage("Below are your Automation options:", author2, DateTime.Now.AddSeconds(15))
            Me.radChat1.AddMessage(message12)
            Dim suggestedActions As List(Of SuggestedActionDataItem) = New List(Of SuggestedActionDataItem)()
            suggestedActions.Add(New SuggestedActionDataItem(".Net Core Conversion"))
            suggestedActions.Add(New SuggestedActionDataItem("Code Forensics"))
            Me.radChat1.AddMessage(New ChatSuggestedActionsMessage(suggestedActions, author2, DateTime.Now))
            Dim suggestionActionsMessage As ChatSuggestedActionsMessage = New ChatSuggestedActionsMessage(suggestedActions, author2, DateTime.Now)
            Me.RadChat1.AddMessage(suggestionActionsMessage)
            RemoveHandler Me.RadChat1.SuggestedActionClicked, AddressOf radChat1_SuggestedActionClicked
            AddHandler Me.RadChat1.SuggestedActionClicked, AddressOf radChat1_SuggestedActionClicked
        End If

        If message.Contains(".Net Core Conversion") Then
            Dim message12 As ChatTextMessage = New ChatTextMessage("Below are your Conversion options:", author2, DateTime.Now.AddSeconds(5))
            Me.radChat1.AddMessage(message12)
            Dim actions As List(Of SuggestedActionDataItem) = New List(Of SuggestedActionDataItem)()
            actions.Add(New SuggestedActionDataItem("Console Application"))
            actions.Add(New SuggestedActionDataItem("MVC"))
            actions.Add(New SuggestedActionDataItem("Windows App"))
            actions.Add(New SuggestedActionDataItem("Restful"))
            actions.Add(New SuggestedActionDataItem("SOAP"))
            actions.Add(New SuggestedActionDataItem("Container"))
            actions.Add(New SuggestedActionDataItem("Others"))
            Me.radChat1.AddMessage(New ChatSuggestedActionsMessage(actions, author2, DateTime.Now))
            Dim suggestionActionsMessage As ChatSuggestedActionsMessage = New ChatSuggestedActionsMessage(actions, author2, DateTime.Now)
            Me.radChat1.AddMessage(suggestionActionsMessage)
            RemoveHandler Me.RadChat1.SuggestedActionClicked, AddressOf radChat1_SuggestedActionClicked
            AddHandler Me.RadChat1.SuggestedActionClicked, AddressOf radChat1_SuggestedActionClicked
        End If
    End Sub
End Class

````


text:
@implementation MSPRoundedLabel : UILabel

- (void)awakeFromNib {
    [super awakeFromNib];
    self.layer.cornerRadius = self.frame.size.height/2.0;
    self.layer.masksToBounds = YES;
}

@end

redpajama_set_name: RedPajamaGithub


text:
/**
 * MathJax custom configuration.
 */
MathJax.Hub.Config({
    displayAlign: "left",
    displayIndent: "2em",
    imageFont: null,
    extensions: ["mml2jax.js"],
    jax: ["input/MathML","output/HTML-CSS"]
  });


text:
module SessionFlash
  extend ActiveSupport::Concern

  # Sets the flash object accordingly for the given authenticated user. The
  # method is the Devise method to be used for greeting the user (e.g.
  # `:signed_up`). If method is nil, then a generic greeting will be set. This
  # method also notifies users about their personal namespace (and whether it
  # changed or not).
  def session_flash(user, method)
    # First of all we've got a greeting.
    if method.nil?
      flash[:notice] = "Welcome!"
    else
      set_flash_message :notice, method unless method.nil?
    end

    # This will happen for the first user, which is the admin that has to
    # configure the registry.
    return if user.namespace.nil?

    # Now inform the user
    ns = user.namespace.name
    str = " Your personal namespace is '#{ns}'"
    str += if user.username == ns
             "."
           else
             " (your username was not a valid Docker namespace, " \
             "so we had to tweak it)."
           end
    flash[:notice] += str
  end
end


text:
package org.mockitousage.junitrule;

import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.quality.Strictness;
import org.mockito.internal.junit.JUnitRule;
import org.mockito.internal.util.MockitoLogger;
import org.mockito.junit.MockitoRule;
import org.mockitousage.IMethods;

import static org.mockito.Mockito.when;

public class LenientJUnitRuleTest {

    private MockitoLogger explosiveLogger = new MockitoLogger() {
        public void log(Object what) {
            throw new RuntimeException("Silent rule should not write anything to the logger");
        }
    };
    @Mock private IMethods mock;

    @Rule public MockitoRule mockitoRule = new JUnitRule(explosiveLogger, Strictness.LENIENT);

    @Test public void no_warning_for_unused_stubbing() throws Exception {
        when(mock.simpleMethod(1)).thenReturn("1");
    }

    @Test public void no_warning_for_stubbing_arg_mismatch() throws Exception {
        when(mock.simpleMethod(1)).thenReturn("1");
        mock.simpleMethod(2);
    }

    @Test(expected = IllegalStateException.class) public void no_warning_for_stubbing_arg_mismatch_on_failure() throws Exception {
        when(mock.simpleMethod(1)).thenReturn("1");
        mock.simpleMethod(2);
        throw new IllegalStateException("hey!");
    }
}


text:
=begin
	This script explains how to push an existing video to an auto push service you have previously configured.

	Parameters you need to pass:
		1. APP_TOKEN
		2. PRIVATE_KEY
		3. VIDEO_TOKEN
		4. PUSH_SERVICE_TOKEN

	Example call:
		ruby videos_count.rb APP_TOKEN PRIVATE_KEY VIDEO_TOKEN PUSH_SERVICE_TOKEN
=end

require_relative "../lib/Ziggeo"

app_token = ARGV[0];
private_key = ARGV[1];
video_token = ARGV[2]
push_service_token = ARGV[3]

ziggeo = Ziggeo.new(app_token, private_key)

ziggeo.videos.push_to_service(
	video_token,
	"pushservicetoken": push_service_token
)


text:
"""
Class for reading data from Plexion acquisition system (.plx)

Compatible with versions 100 to 106.
Other versions have not been tested.

This IO is developed thanks to the header file downloadable from:
http://www.plexon.com/downloads.html

Depend on:

Supported : Read

Author: sgarcia

"""

import datetime
import struct
import os

import numpy as np
import quantities as pq

from neo.io.baseio import BaseIO
from neo.core import Segment, AnalogSignal, SpikeTrain, EpochArray, EventArray
from neo.io.tools import iteritems

class PlexonIO(BaseIO):
    """
    Class for reading plx file.

    Usage:
        >>> from neo import io
        >>> r = io.PlexonIO(filename='File_plexon_1.plx')
        >>> seg = r.read_segment(lazy=False, cascade=True)
        >>> print seg.analogsignals
        []
        >>> print seg.spiketrains  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
        [<SpikeTrain(array([  2.75000000e-02,   5.68250000e-02,   8.52500000e-02, ...,
        ...
        >>> print seg.eventarrays
        []
    """

    is_readable        = True
    is_writable        = False

    supported_objects  = [Segment , AnalogSignal, SpikeTrain, EventArray, EpochArray]
    readable_objects    = [ Segment]
    writeable_objects   = []

    has_header         = False
    is_streameable     = False

    # This is for GUI stuf : a definition for parameters when reading.
    read_params        = {

                        Segment :  [
                                        ('load_spike_waveform' , { 'value' : False } ) ,
                                        ]
                        }
    write_params       = None

    name               = 'Plexon'
    extensions          = [ 'plx' ]

    mode = 'file'

    def __init__(self , filename = None) :
        """
        This class read a plx file.

        Arguments:
            filename : the filename
            load_spike_waveform : load or not waveform of spikes (default True)

        """
        BaseIO.__init__(self)
        self.filename = filename

    def read_segment(self,
                                        lazy = False,
                                        cascade = True,
                                        load_spike_waveform = True,
                                            ):
        """

        """

        fid = open(self.filename, 'rb')
        globalHeader = HeaderReader(fid , GlobalHeader ).read_f(offset = 0)

        # metadatas
        seg = Segment()
        seg.rec_datetime = datetime.datetime(  globalHeader['Year'] , globalHeader['Month']  , globalHeader['Day'] ,
                    globalHeader['Hour'] , globalHeader['Minute'] , globalHeader['Second'] )
        seg.file_origin = os.path.basename(self.filename)
        seg.annotate(plexon_version = globalHeader['Version'])

        if not cascade:
            return seg

        ## Step 1 : read headers
        # dsp channels header = sipkes and waveforms
        dspChannelHeaders = { }
        maxunit=0
        maxchan = 0
        for _ in range(globalHeader['NumDSPChannels']):
            # channel is 1 based
            channelHeader = HeaderReader(fid , ChannelHeader ).read_f(offset = None)
            channelHeader['Template'] = np.array(channelHeader['Template']).reshape((5,64))
            channelHeader['Boxes'] = np.array(channelHeader['Boxes']).reshape((5,2,4))
            dspChannelHeaders[channelHeader['Channel']]=channelHeader
            maxunit = max(channelHeader['NUnits'],maxunit)
            maxchan = max(channelHeader['Channel'],maxchan)

       # event channel header
        eventHeaders = { }
        for _ in range(globalHeader['NumEventChannels']):
            eventHeader = HeaderReader(fid , EventHeader ).read_f(offset = None)
            eventHeaders[eventHeader['Channel']] = eventHeader

        # slow channel header = signal
        slowChannelHeaders = { }
        for _ in range(globalHeader['NumSlowChannels']):
            slowChannelHeader = HeaderReader(fid , SlowChannelHeader ).read_f(offset = None)
            slowChannelHeaders[slowChannelHeader['Channel']] = slowChannelHeader

        ## Step 2 : a first loop for counting size
        # signal
        nb_samples = np.zeros(len(slowChannelHeaders))
        sample_positions = np.zeros(len(slowChannelHeaders))
        t_starts = np.zeros(len(slowChannelHeaders), dtype = 'f')

        #spiketimes and waveform
        nb_spikes = np.zeros((maxchan+1, maxunit+1) ,dtype='i')
        wf_sizes = np.zeros((maxchan+1, maxunit+1, 2) ,dtype='i')

        # eventarrays
        nb_events = { }
        #maxstrsizeperchannel = { }
        for chan, h in iteritems(eventHeaders):
            nb_events[chan] = 0
            #maxstrsizeperchannel[chan] = 0

        start = fid.tell()
        while fid.tell() !=-1 :
            # read block header
            dataBlockHeader = HeaderReader(fid , DataBlockHeader ).read_f(offset = None)
            if dataBlockHeader is None : break
            chan = dataBlockHeader['Channel']
            unit = dataBlockHeader['Unit']
            n1,n2 = dataBlockHeader['NumberOfWaveforms'] , dataBlockHeader['NumberOfWordsInWaveform']
            time = (dataBlockHeader['UpperByteOf5ByteTimestamp']*2.**32 +
                    dataBlockHeader['TimeStamp'])

            if dataBlockHeader['Type'] == 1:
                nb_spikes[chan,unit] +=1
                wf_sizes[chan,unit,:] = [n1,n2]
                fid.seek(n1*n2*2,1)
            elif dataBlockHeader['Type'] ==4:
                #event
                nb_events[chan] += 1
            elif dataBlockHeader['Type'] == 5:
                #continuous signal
                fid.seek(n2*2, 1)
                if n2> 0:
                    nb_samples[chan] += n2
                if nb_samples[chan] ==0:
                    t_starts[chan] = time

        ## Step 3: allocating memory and 2 loop for reading if not lazy
        if not lazy:
            # allocating mem for signal
            sigarrays = { }
            for chan, h in iteritems(slowChannelHeaders):
                sigarrays[chan] = np.zeros(nb_samples[chan])

            # allocating mem for SpikeTrain
            stimearrays = np.zeros((maxchan+1, maxunit+1) ,dtype=object)
            swfarrays = np.zeros((maxchan+1, maxunit+1) ,dtype=object)
            for (chan, unit), _ in np.ndenumerate(nb_spikes):
                stimearrays[chan,unit] = np.zeros(nb_spikes[chan,unit], dtype = 'f')
                if load_spike_waveform:
                    n1,n2 = wf_sizes[chan, unit,:]
                    swfarrays[chan, unit] = np.zeros( (nb_spikes[chan, unit], n1, n2 ) , dtype = 'f4' )
            pos_spikes = np.zeros(nb_spikes.shape, dtype = 'i')

            # allocating mem for event
            eventpositions = { }
            evarrays = { }
            for chan, nb in iteritems(nb_events):
                evarrays[chan] = np.zeros(nb, dtype = 'f' )
                eventpositions[chan]=0

            fid.seek(start)
            while fid.tell() !=-1 :
                dataBlockHeader = HeaderReader(fid , DataBlockHeader ).read_f(offset = None)
                if dataBlockHeader is None : break
                chan = dataBlockHeader['Channel']
                n1,n2 = dataBlockHeader['NumberOfWaveforms'] , dataBlockHeader['NumberOfWordsInWaveform']
                time = dataBlockHeader['UpperByteOf5ByteTimestamp']*2.**32 + dataBlockHeader['TimeStamp']
                time/= globalHeader['ADFrequency']

                if n2 <0: break
                if dataBlockHeader['Type'] == 1:
                    #spike
                    unit = dataBlockHeader['Unit']
                    pos = pos_spikes[chan,unit]
                    stimearrays[chan, unit][pos] = time
                    if load_spike_waveform and n1*n2 != 0 :
                        swfarrays[chan,unit][pos,:,:] = np.fromstring( fid.read(n1*n2*2) , dtype = 'i2').reshape(n1,n2).astype('f4')
                    else:
                        fid.seek(n1*n2*2,1)
                    pos_spikes[chan,unit] +=1

                elif dataBlockHeader['Type'] == 4:
                    # event
                    pos = eventpositions[chan]
                    evarrays[chan][pos] = time
                    eventpositions[chan]+= 1

                elif dataBlockHeader['Type'] == 5:
                    #signal
                    data = np.fromstring( fid.read(n2*2) , dtype = 'i2').astype('f4')
                    sigarrays[chan][sample_positions[chan] : sample_positions[chan]+data.size] = data
                    sample_positions[chan] += data.size

        ## Step 3: create neo object
        for chan, h in iteritems(eventHeaders):
            if lazy:
                times = [ ]
            else:
                times = evarrays[chan]
            ea = EventArray(times*pq.s,
                                            channel_name= eventHeaders[chan]['Name'],
                                            channel_index = chan)
            if lazy:
                ea.lazy_shape = nb_events[chan]
            seg.eventarrays.append(ea)

        for chan, h in iteritems(slowChannelHeaders):
            if lazy:
                signal = [ ]
            else:
                if globalHeader['Version'] ==100 or globalHeader['Version'] ==101 :
                    gain = 5000./(2048*slowChannelHeaders[chan]['Gain']*1000.)
                elif globalHeader['Version'] ==102 :
                    gain = 5000./(2048*slowChannelHeaders[chan]['Gain']*slowChannelHeaders[chan]['PreampGain'])
                elif globalHeader['Version'] >= 103:
                    gain = globalHeader['SlowMaxMagnitudeMV']/(.5*(2**globalHeader['BitsPerSpikeSample'])*\
                                                        slowChannelHeaders[chan]['Gain']*slowChannelHeaders[chan]['PreampGain'])
                signal = sigarrays[chan]*gain
            anasig =  AnalogSignal(signal*pq.V,
                                                        sampling_rate = float(slowChannelHeaders[chan]['ADFreq'])*pq.Hz,
                                                        t_start = t_starts[chan]*pq.s,
                                                        channel_index = slowChannelHeaders[chan]['Channel'],
                                                        channel_name = slowChannelHeaders[chan]['Name'],
                                                        )
            if lazy:
                anasig.lazy_shape = nb_samples[chan]
            seg.analogsignals.append(anasig)

        for (chan, unit), value in np.ndenumerate(nb_spikes):
            if nb_spikes[chan, unit] == 0: continue
            if lazy:
                times = [ ]
                waveforms = None
                t_stop = 0
            else:
                times = stimearrays[chan,unit]
                t_stop = times.max()
                if load_spike_waveform:
                    if globalHeader['Version'] <103:
                        gain = 3000./(2048*dspChannelHeaders[chan]['Gain']*1000.)
                    elif globalHeader['Version'] >=103 and globalHeader['Version'] <105:
                        gain = globalHeader['SpikeMaxMagnitudeMV']/(.5*2.**(globalHeader['BitsPerSpikeSample'])*1000.)
                    elif globalHeader['Version'] >105:
                        gain = globalHeader['SpikeMaxMagnitudeMV']/(.5*2.**(globalHeader['BitsPerSpikeSample'])*globalHeader['SpikePreAmpGain'])
                    waveforms = swfarrays[chan, unit] * gain * pq.V
                else:
                    waveforms = None
            sptr = SpikeTrain(times,
                                            units='s', t_stop=t_stop*pq.s,
                                            waveforms = waveforms,
                                            )
            sptr.annotate(unit_name = dspChannelHeaders[chan]['Name'])
            sptr.annotate(channel_index = chan)
            if lazy:
                sptr.lazy_shape = nb_spikes[chan,unit]
            seg.spiketrains.append(sptr)

        seg.create_many_to_one_relationship()
        return seg

GlobalHeader = [
    ('MagicNumber' , 'I'),
    ('Version','i'),
    ('Comment','128s'),
    ('ADFrequency','i'),
    ('NumDSPChannels','i'),
    ('NumEventChannels','i'),
    ('NumSlowChannels','i'),
    ('NumPointsWave','i'),
    ('NumPointsPreThr','i'),
    ('Year','i'),
    ('Month','i'),
    ('Day','i'),
    ('Hour','i'),
    ('Minute','i'),
    ('Second','i'),
    ('FastRead','i'),
    ('WaveformFreq','i'),
    ('LastTimestamp','d'),

    #version >103
    ('Trodalness' , 'b'),
    ('DataTrodalness' , 'b'),
    ('BitsPerSpikeSample' , 'b'),
    ('BitsPerSlowSample' , 'b'),
    ('SpikeMaxMagnitudeMV' , 'H'),
    ('SlowMaxMagnitudeMV' , 'H'),

    #version 105
    ('SpikePreAmpGain' , 'H'),

    #version 106
    ('AcquiringSoftware','18s'),
    ('ProcessingSoftware','18s'),

    ('Padding','10s'),

    # all version
    ('TSCounts','650i'),
    ('WFCounts','650i'),
    ('EVCounts','512i'),

    ]

ChannelHeader = [
    ('Name' , '32s'),
    ('SIGName','32s'),
    ('Channel','i'),
    ('WFRate','i'),
    ('SIG','i'),
    ('Ref','i'),
    ('Gain','i'),
    ('Filter','i'),
    ('Threshold','i'),
    ('Method','i'),
    ('NUnits','i'),
    ('Template','320h'),
    ('Fit','5i'),
    ('SortWidth','i'),
    ('Boxes','40h'),
    ('SortBeg','i'),
    #version 105
    ('Comment','128s'),
    #version 106
    ('SrcId','b'),
    ('reserved','b'),
    ('ChanId','H'),

    ('Padding','10i'),
    ]

EventHeader = [
    ('Name' , '32s'),
    ('Channel','i'),
    #version 105
    ('Comment' , '128s'),
    #version 106
    ('SrcId','b'),
    ('reserved','b'),
    ('ChanId','H'),

    ('Padding','32i'),
    ]

SlowChannelHeader = [
    ('Name' , '32s'),
    ('Channel','i'),
    ('ADFreq','i'),
    ('Gain','i'),
    ('Enabled','i'),
    ('PreampGain','i'),
    #version 104
    ('SpikeChannel','i'),
    #version 105
    ('Comment','128s'),
    #version 106
    ('SrcId','b'),
    ('reserved','b'),
    ('ChanId','H'),

    ('Padding','27i'),
    ]

DataBlockHeader = [
    ('Type','h'),
    ('UpperByteOf5ByteTimestamp','h'),
    ('TimeStamp','i'),
    ('Channel','h'),
    ('Unit','h'),
    ('NumberOfWaveforms','h'),
    ('NumberOfWordsInWaveform','h'),
    ]# 16 bytes

class HeaderReader():
    def __init__(self,fid ,description ):
        self.fid = fid
        self.description = description
    def read_f(self, offset =None):
        if offset is not None :
            self.fid.seek(offset)
        d = { }
        for key, fmt in self.description :
            buf = self.fid.read(struct.calcsize(fmt))
            if len(buf) != struct.calcsize(fmt) : return None
            val = list(struct.unpack(fmt , buf))
            for i, ival in enumerate(val):
                if hasattr(ival, 'replace'):
                    val[i] = ival.replace('\x00','')
            if len(val) == 1:
                val = val[0]
            d[key] = val
        return d


text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef GFX_FONT_TEST_H
#define GFX_FONT_TEST_H

#include "nsString.h"
#include "nsTArray.h"

#include "cairo.h"

#include "gfxFont.h"
#include "gfxUserFontSet.h"

struct THEBES_API gfxFontTestItem {
    gfxFontTestItem(const nsCString& fontName,
                    cairo_glyph_t *cglyphs, int nglyphs)
        : platformFont(fontName)
    {
        glyphs = new cairo_glyph_t[nglyphs];
        memcpy (glyphs, cglyphs, sizeof(cairo_glyph_t) * nglyphs);
        num_glyphs = nglyphs;
    }

    gfxFontTestItem(const gfxFontTestItem& other) {
        platformFont = other.platformFont;
        num_glyphs = other.num_glyphs;
        glyphs = new cairo_glyph_t[num_glyphs];
        memcpy (glyphs, other.glyphs, sizeof(cairo_glyph_t) * num_glyphs);
    }

    ~gfxFontTestItem() {
        delete [] glyphs;
    }

    nsCString platformFont;
    cairo_glyph_t *glyphs;
    int num_glyphs;
};

class THEBES_API gfxFontTestStore {
public:
    gfxFontTestStore() { }

    void AddItem (const nsCString& fontString,
                  cairo_glyph_t *cglyphs, int nglyphs)
    {
        items.AppendElement(gfxFontTestItem(fontString, cglyphs, nglyphs));
    }

    void AddItem (const nsString& fontString,
                  cairo_glyph_t *cglyphs, int nglyphs)
    {
        items.AppendElement(gfxFontTestItem(NS_ConvertUTF16toUTF8(fontString), cglyphs, nglyphs));
    }

    nsTArray<gfxFontTestItem> items;

public:
    static gfxFontTestStore *CurrentStore() {
        return sCurrentStore;
    }

    static gfxFontTestStore *NewStore() {
        if (sCurrentStore)
            delete sCurrentStore;

        sCurrentStore = new gfxFontTestStore;
        return sCurrentStore;
    }

    static void DeleteStore() {
        if (sCurrentStore)
            delete sCurrentStore;

        sCurrentStore = nsnull;
    }

protected:
    static gfxFontTestStore *sCurrentStore;
};

#endif /* GFX_FONT_TEST_H */


text:
package io.druid.server.sql;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.metamx.common.StringUtils;
import com.metamx.common.guava.CloseQuietly;
import io.druid.data.input.Row;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.query.Druids;
import io.druid.query.Query;
import io.druid.query.Result;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.dimension.DimensionSpec;
import io.druid.query.groupby.GroupByQuery;
import io.druid.query.timeseries.TimeseriesResultValue;
import io.druid.sql.antlr4.DruidSQLLexer;
import io.druid.sql.antlr4.DruidSQLParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ConsoleErrorListener;
import org.antlr.v4.runtime.TokenStream;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;

import javax.annotation.Nullable;
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class SQLRunner
{
  private static final String STATEMENT = "select count(*), (1 - count(*) / sum(count)) * 100 as ratio from wikipedia where"
                                          + " timestamp between '2013-02-01' and '2013-02-14'"
                                          + " and (namespace = 'article' or page ~ 'Talk:.*')"
                                          + " and language in ( 'en', 'fr' ) "
                                          + " and user ~ '(?i)^david.*'"
                                          + " group by granularity(timestamp, 'day'), language";

  public static void main(String[] args) throws Exception
  {

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if(cmd.hasOption("h")) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("SQLRunner", options);
      System.exit(2);
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
      DruidSQLParser.QueryContext queryContext = parser.query();
      if(parser.getNumberOfSyntaxErrors() > 0) throw new IllegalStateException();
//      parser.setBuildParseTree(true);
//      System.err.println(q.toStringTree(parser));
    } catch(Exception e) {
      String msg = e.getMessage();
      if(msg != null) System.err.println(e);
      System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if(parser.groupByDimensions.isEmpty()) {
      query = Druids.newTimeseriesQueryBuilder()
                  .dataSource(parser.getDataSource())
                  .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                  .postAggregators(parser.postAggregators)
                  .intervals(parser.intervals)
                  .granularity(parser.granularity)
                  .filters(parser.filter)
                  .build();

      typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>(){};
    } else {
      query = GroupByQuery.builder()
              .setDataSource(parser.getDataSource())
              .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
              .setPostAggregatorSpecs(parser.postAggregators)
              .setInterval(parser.intervals)
              .setGranularity(parser.granularity)
              .setDimFilter(parser.filter)
              .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values()))
              .build();

      typeRef = new TypeReference<List<Row>>(){};
      groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if(cmd.hasOption("v")) System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if(groupBy) {
      List<Row> rows = (List<Row>)res;
      Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(), new Function<DimensionSpec, String>()
                        {
                          @Override
                          public String apply(@Nullable DimensionSpec input)
                          {
                            return input.getOutputName();
                          }
                        });

      System.out.println(tabJoiner.join(Iterables.concat(
                Lists.newArrayList("timestamp"),
                dimensions,
                parser.fields
            )));
      for(final Row r : rows) {
        System.out.println(
            tabJoiner.join(
              Iterables.concat(
                  Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                  Iterables.transform(
                      parser.groupByDimensions.values(), new Function<DimensionSpec, String>()
                  {
                    @Override
                    public String apply(@Nullable DimensionSpec input)
                    {
                      return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                    }
                  }),
                  Iterables.transform(parser.fields, new Function<String, Object>()
                  {
                    @Override
                    public Object apply(@Nullable String input)
                    {
                      return r.getFloatMetric(input);
                    }
                  })
              )
          )
        );
      }
    }
    else {
      List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>)res;
      System.out.println(tabJoiner.join(Iterables.concat(
          Lists.newArrayList("timestamp"),
          parser.fields
      )));
      for(final Result<TimeseriesResultValue> r : rows) {
        System.out.println(
            tabJoiner.join(
              Iterables.concat(
                Lists.newArrayList(r.getTimestamp()),
                Lists.transform(
                  parser.fields,
                  new Function<String, Object>()
                  {
                    @Override
                    public Object apply(@Nullable String input)
                    {
                      return r.getValue().getMetric(input);
                    }
                  }
                )
              )
          )
        );
      }
    }

    CloseQuietly.close(stdInput);
  }
}


text:
var createToPairs = require('./_createToPairs'),
    keysIn = require('./keysIn');

/**
 * Creates an array of own and inherited enumerable string keyed-value pairs
 * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
 * or set, its entries are returned.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @alias entriesIn
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the key-value pairs.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.toPairsIn(new Foo);
 * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
 */
var toPairsIn = createToPairs(keysIn);

module.exports = toPairsIn;


text:
"""Unit tests for side inputs."""

# pytype: skip-file

from __future__ import absolute_import

import logging
import unittest

import apache_beam as beam
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to

class KeywordOnlyArgsTests(unittest.TestCase):

  # Enable nose tests running in parallel
  _multiprocess_can_split_ = True

  def test_side_input_keyword_only_args(self):
    with TestPipeline() as pipeline:

      def sort_with_side_inputs(x, *s, reverse=False):
        for y in s:
          yield sorted([x] + y, reverse=reverse)

      def sort_with_side_inputs_without_default_values(x, *s, reverse):
        for y in s:
          yield sorted([x] + y, reverse=reverse)

      pcol = pipeline | 'start' >> beam.Create([1, 2])
      side = pipeline | 'side' >> beam.Create([3, 4])  # 2 values in side input.
      result1 = pcol | 'compute1' >> beam.FlatMap(
          sort_with_side_inputs, beam.pvalue.AsList(side), reverse=True)
      assert_that(result1, equal_to([[4, 3, 1], [4, 3, 2]]), label='assert1')

      result2 = pcol | 'compute2' >> beam.FlatMap(
          sort_with_side_inputs, beam.pvalue.AsList(side))
      assert_that(result2, equal_to([[1, 3, 4], [2, 3, 4]]), label='assert2')

      result3 = pcol | 'compute3' >> beam.FlatMap(sort_with_side_inputs)
      assert_that(result3, equal_to([]), label='assert3')

      result4 = pcol | 'compute4' >> beam.FlatMap(
          sort_with_side_inputs, reverse=True)
      assert_that(result4, equal_to([]), label='assert4')

      result5 = pcol | 'compute5' >> beam.FlatMap(
          sort_with_side_inputs_without_default_values,
          beam.pvalue.AsList(side),
          reverse=True)
      assert_that(result5, equal_to([[4, 3, 1], [4, 3, 2]]), label='assert5')

      result6 = pcol | 'compute6' >> beam.FlatMap(
          sort_with_side_inputs_without_default_values,
          beam.pvalue.AsList(side),
          reverse=False)
      assert_that(result6, equal_to([[1, 3, 4], [2, 3, 4]]), label='assert6')

      result7 = pcol | 'compute7' >> beam.FlatMap(
          sort_with_side_inputs_without_default_values, reverse=False)
      assert_that(result7, equal_to([]), label='assert7')

      result8 = pcol | 'compute8' >> beam.FlatMap(
          sort_with_side_inputs_without_default_values, reverse=True)
      assert_that(result8, equal_to([]), label='assert8')

  def test_combine_keyword_only_args(self):
    with TestPipeline() as pipeline:

      def bounded_sum(values, *s, bound=500):
        return min(sum(values) + sum(s), bound)

      def bounded_sum_without_default_values(values, *s, bound):
        return min(sum(values) + sum(s), bound)

      pcoll = pipeline | 'start' >> beam.Create([6, 3, 1])
      result1 = pcoll | 'sum1' >> beam.CombineGlobally(
          bounded_sum, 5, 8, bound=20)
      result2 = pcoll | 'sum2' >> beam.CombineGlobally(bounded_sum, 0, 0)
      result3 = pcoll | 'sum3' >> beam.CombineGlobally(bounded_sum)
      result4 = pcoll | 'sum4' >> beam.CombineGlobally(bounded_sum, bound=5)
      result5 = pcoll | 'sum5' >> beam.CombineGlobally(
          bounded_sum_without_default_values, 5, 8, bound=20)
      result6 = pcoll | 'sum6' >> beam.CombineGlobally(
          bounded_sum_without_default_values, 0, 0, bound=500)
      result7 = pcoll | 'sum7' >> beam.CombineGlobally(
          bounded_sum_without_default_values, bound=500)
      result8 = pcoll | 'sum8' >> beam.CombineGlobally(
          bounded_sum_without_default_values, bound=5)

      assert_that(result1, equal_to([20]), label='assert1')
      assert_that(result2, equal_to([10]), label='assert2')
      assert_that(result3, equal_to([10]), label='assert3')
      assert_that(result4, equal_to([5]), label='assert4')
      assert_that(result5, equal_to([20]), label='assert5')
      assert_that(result6, equal_to([10]), label='assert6')
      assert_that(result7, equal_to([10]), label='assert7')
      assert_that(result8, equal_to([5]), label='assert8')

  def test_do_fn_keyword_only_args(self):
    with TestPipeline() as pipeline:

      class MyDoFn(beam.DoFn):
        def process(self, element, *s, bound=500):
          return [min(sum(s) + element, bound)]

      pcoll = pipeline | 'start' >> beam.Create([6, 3, 1])
      result1 = pcoll | 'sum1' >> beam.ParDo(MyDoFn(), 5, 8, bound=15)
      result2 = pcoll | 'sum2' >> beam.ParDo(MyDoFn(), 5, 8)
      result3 = pcoll | 'sum3' >> beam.ParDo(MyDoFn())
      result4 = pcoll | 'sum4' >> beam.ParDo(MyDoFn(), bound=5)

      assert_that(result1, equal_to([15, 15, 14]), label='assert1')
      assert_that(result2, equal_to([19, 16, 14]), label='assert2')
      assert_that(result3, equal_to([6, 3, 1]), label='assert3')
      assert_that(result4, equal_to([5, 3, 1]), label='assert4')

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.DEBUG)
  unittest.main()


text:
- Event: FLISOL 2015
- When: 2015, April
- Where: UDESC - Universidade do Estado de Santa Catarina
- Attendees: ≈100
- Description: A brief introduction to functional programming with Haskell and the basic concepts of functional programming
- Links:
  - [Presentation](https://github.com/haskellcamargo/talks/raw/master/Introdu%C3%A7%C3%A3o%20%C3%A0%20Programa%C3%A7%C3%A3o%20Funcional/Introdu%C3%A7%C3%A3o%20%C3%A0%20Programa%C3%A7%C3%A3o%20Funcional.odp)
  - [Video](https://www.youtube.com/watch?v=_xuQsxlndoE)

### Bizarrices JIT - Como não projetar uma linguagem de programação (How not to design a programming language)
- Event: Colóquios de Ciência da Computação - Joinville
- When: 2015, October
- Where: UDESC - Universidade do Estado de Santa Catarina
- Attendees: ≈20
- Description: A talk about programming languages design failures
- Links:
  - [Presentation](https://github.com/haskellcamargo/talks/raw/master/Bizarrices%20Just%20in%20Time%20-%20Como%20n%C3%A3o%20projetar%20uma%20linguagem%20de%20programa%C3%A7%C3%A3o/Bizarrices%20Just%20in%20Time%20-%20Como%20n%C3%A3o%20projetar%20uma%20linguagem%20de%20programa%C3%A7%C3%A3o.odp)
  - [Video](https://www.youtube.com/watch?v=7F4dLoJV5YM)

### Entendendo o Sistema de Tipos de TypeScript (Understanding TypeScript Type System)
- Event: Colóquios de Ciência da Computação - Joinville
- When: 2015, October
- Where: UDESC - Universidade do Estado de Santa Catarina
- Attendees: ≈20
- Description: A talk about typescript type system
- Links:
  - [Presentation](https://github.com/haskellcamargo/talks/raw/master/Entendendo%20o%20Sistema%20de%20Tipos%20de%20TypeScript/Entendendo%20o%20Sistema%20de%20Tipos%20de%20TypeScript.odp)
  - [Video](https://www.youtube.com/watch?v=l1SxomZB04E)


text:
/* @flow */
import styled from '@emotion/styled';
import React from 'react';
import Button from '../../../../../../library/Button';
import Card, { CardTitle } from '../../../../../../library/Card';
import { mineralTheme } from '../../../../../../library/themes';
import DemoLayout from '../../common/DemoLayout';
import type { StyledComponent } from '@emotion/styled-base/src/utils';

const CustomContent: StyledComponent<{ [key: string]: any }> = styled('div')(
  ({ theme }) => ({
    backgroundColor: theme.color_gray_20,
    margin: `${theme.space_stack_md} 0`,
    padding: theme.space_inset_md,

    '&:last-child': {
      borderRadius: `0 0 ${theme.borderRadius_1} ${theme.borderRadius_1}`,
      marginBottom: 0
    }
  })
);

const customContent = (
  <CustomContent>
    <Button fullWidth>Button</Button>
  </CustomContent>
);

export default {
  id: 'children',
  title: 'Arbitrary Children',
  backgroundColor: mineralTheme.color_gray_10,
  description: `A Card will render any children.

For best results, please ensure content matches the top/bottom margin and left/right padding of the other \`<Card*/>\` components, or use [CardBlock](/components/card-block).`,
  scope: { Button, Card, CardTitle, customContent, DemoLayout },
  source: `
    <DemoLayout>
      <Card>
        <CardTitle>Card Title</CardTitle>
        {customContent}
      </Card>
    </DemoLayout>`
};


text:
package search

import (
	"context"
	"time"

	"perkeep.org/pkg/blob"
	"perkeep.org/pkg/types/camtypes"
)

func SetTestHookBug121(hook func()) {
	testHookBug121 = hook
}

func ExportSetCandidateSourceHook(fn func(string)) { candSourceHook = fn }

func ExportSetExpandLocationHook(val bool) { expandLocationHook = val }

func ExportBufferedConst() int { return buffered }

func (s *SearchQuery) ExportPlannedQuery() *SearchQuery {
	return s.plannedQuery(nil)
}

var SortName = sortName

func (s *Handler) ExportGetPermanodeLocation(ctx context.Context, permaNode blob.Ref,
	at time.Time) (camtypes.Location, error) {
	return s.lh.PermanodeLocation(ctx, permaNode, at, s.owner)
}

func ExportBestByLocation(res *SearchResult, loc map[blob.Ref]camtypes.Location, limit int) {
	bestByLocation(res, loc, limit)
}

var ExportUitdamLC = uitdamLC


text:
package controllers.admin;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlUpdate;

import models.Commune;
import play.data.DynamicForm;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.admin.listeVilles;

public class ListeVilles extends Controller {

	public static Result main(){
		if(Admin.isAdminConnected()){
			return ok(listeVilles.render());
		}else
			return Admin.nonAutorise();
	}

	/**
	 * Change le nom customisé ville_nom_aer de la ville en argument.
	 * On est obligé de faire une mise à jour de la base à la main
	 * à cause d'un bug de play concernant les floats dans les champs.
	 * Pour plus de détails, chercher javax.persistence.OptimisticLockException: Data has changed.
	 * @param ville_id
	 * @return
	 */
	public static Result renommer(Integer ville_id){
		if(Admin.isAdminConnected()){
			Commune commune = Commune.find.byId(ville_id);
			if(commune!=null){
				DynamicForm df = DynamicForm.form().bindFromRequest();
				String nouveauNom = df.get("nouveauNom");
				SqlUpdate update = Ebean.createSqlUpdate("UPDATE commune SET ville_nom_aer=:aer WHERE ville_id=:id")
						.setParameter("aer", nouveauNom)
						.setParameter("id", ville_id);
				update.execute();
			}
			return ok("Nom de commune changé avec succès.");
		}else
			return Admin.nonAutorise();
	}
}


text:
import {Component, Input} from '@angular/core';

@Component({
    selector: 'id-view-field',
    template: `

{{label}}

    `
})
export class ViewFieldComponent {
    @Input() label: string;
    @Input() value: string;
    @Input() class: string;
}


text:
<!doctype html>

    <link rel="stylesheet" href="../vendor/qunit-1.14.0.css" type="text/css" />
    <link rel="stylesheet" href="../../dist/css/select2.css" type="text/css" />

        <select></select>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="pb_grey">#ffdedede</color>
    <color name="pb_blue">#ff0099cc</color>
    <color name="pb_blue_dark">#ff00719b</color>
    <color name="pb_red">#ffff4444</color>
    <color name="pb_red_dark">#ffcd3a3a</color>
    <color name="pb_green">#ff99cc00</color>
    <color name="pb_green_dark">#ff6d9b00</color>
    <color name="pb_white">@android:color/white</color>
    <color name="pb_orange">@android:color/holo_orange_dark</color>
</resources>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 43: 250 (1992)

#### Original name
Chrysosporium minor Skou

### Remarks
null


text:
Reports any import statements which cover entire packages ('* imports').
Some coding standards prohibit such import statements. Since IDEA can automatically
detect and fix such statements with its "Optimize Imports" command, this inspection is mostly useful
for off-line reporting on code bases that you don't intend to change.