text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>realizar-venda-ao-poder-publico-de-alimentos-provenientes-de-agricultura-familiar-via-associacoes-ou-cooperativas</id>
    <dbId>1072</dbId>
    <nome>Realizar venda ao poder público de alimentos provenientes de agricultura familiar via associações ou cooperativas</nome>
    <sigla>PAA CDS</sigla>
    <descricao>O Programa de Aquisição de Alimentos – PAA, modalidade Compra com Doação Simultânea, executada pela CONAB, é um programa por meio do qual o Governo Federal compra alimentos de cooperativas ou associações da agricultura familiar e os destina gratuitamente às pessoas em situação de insegurança alimentar e nutricional atendidas pela rede socioassistencial e pelos equipamentos de alimentação e nutrição, como os restaurantes populares, bancos de alimentos e cozinhas comunitárias.
Neste caso, o MDS repassa recursos para CONAB e a Companhia fica responsável por contratar os projetos junto às Cooperativas e Associações da agricultura familiar.</descricao>
    <contato>(61) 3312-6000</contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <solicitantes>
        <solicitante id="1335">
            <tipo>Cooperativas e Associações da agricultura familiar</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <entre min="30" max="60" unidade="dias-corridos"/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="2875">
            <titulo>Preencher proposta de Participação</titulo>
            <descricao>Realizar download do programa, instalar, preencher e enviar a Proposta de Participação no PAANet, ou obter o modelo no site da CONAB, imprimir, preencher e entregar pessoalmente.</descricao>
            <documentos>
                <default>
                    <item id="3704">Proposta de Participação</item>
                    <item id="3705">Dados do projeto e participantes</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3819" tipo="web">
                        <descricao>http://www.conab.gov.br/produtosServicos-PAANET-proposta.php</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="3820" tipo="web-preencher">
                        <descricao>http://www.conab.gov.br/conabweb/moc.php</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="2876">
            <titulo>Habilitar-se no Programa</titulo>
            <descricao>Ir à superintendência da CONAB levanto os documentos necessários</descricao>
            <documentos>
                <default>
                    <item id="3706">Proposta de Participação preenchida</item>
                    <item id="3707">Declaração de Aptidão ao Pronaf – DAP Jurídica</item>
                    <item id="3708">Declaração de Aptidão ao Pronaf – DAP Física e extrato da DAP obtido eletronicamente dos beneficiários fornecedores não relacionados na DAP Jurídica da organização</item>
                    <item id="3709">Estatuto e Ata de eleição e da posse da atual diretoria da organização fornecedora (cópia autenticada);</item>
                    <item id="3710">Cópia da ata de reunião do Conselho Estadual ou Municipal de Segurança Alimentar e Nutricional, de Desenvolvimento Rural e Sustentável, ou de Assistência Social, contendo a ciência da Proposta apresentada;</item>
                    <item id="3711">Formulário Bipartite entre Organização Fornecedora e Representante do Poder Público Municipal;</item>
                    <item id="3712">Termo de Compromisso da Unidade Recebedora</item>
                    <item id="3713">Declaração de Aplicação de Recursos</item>
                    <item id="3714">Termo de Compromisso do Beneficiário Fornecedor</item>
                    <item id="3715">CNPJ</item>
                    <item id="3716">Cópias autenticadas de RG e CPF dos representantes legais da organização</item>
                    <item id="3717">Certificado do Cadastro Nacional de Produtores Orgânicos, quando for o caso</item>
                    <item id="3718">Documentos relativos ao cumprimento da legislação sanitária, quando for o caso</item>
                    <item id="3719">Comprovante de entrega dos documentos via protocolo</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3821" tipo="presencial">
                        <descricao>[Superintendências Regionais da CONAB](http://www.conab.gov.br/conab-superintendenciasRegionais.php)</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="2877">
            <titulo>Homologar projeto</titulo>
            <descricao></descricao>
            <documentos>
                <default>
                    <item id="3720">Certidão negativa junto ao INSS</item>
                    <item id="3721">Certidão negativa junto ao FGTS</item>
                    <item id="3722">Certidão negativa de dívidas trabalhistas</item>
                    <item id="3723">Certidão negativa de Dívida Ativa da União</item>
                    <item id="3724">Certidão negativa da Receita Federal</item>
                    <item id="3725">Certidão negativa do CEIS</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3822" tipo="presencial">
                        <descricao>[Superintendências Regionais da CONAB](http://www.conab.gov.br/conab-superintendenciasRegionais.php)</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="2878">
            <titulo>Entregar alimentos nas entidades beneficiárias</titulo>
            <descricao></descricao>
            <documentos>
                <default>
                    <item id="3726">Termo de Recebimento e Aceitabilidade</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3823" tipo="presencial">
                        <descricao>No endereço das entidades sócio-assistenciais e equipamentos de alimentação e nutrição, conforme Proposta de Participação aprovada pela CONAB.</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="2879">
            <titulo>Prestar contas</titulo>
            <descricao></descricao>
            <documentos>
                <default>
                    <item id="3727">Nota fiscal de venda à CONAB</item>
                    <item id="3728">Termo de Recebimento e Aceitabilidade assinado pelas entidades recebedoras</item>
                    <item id="3729">Relatório de Entrega</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3824" tipo="presencial">
                        <descricao>[Superintendências Regionais da CONAB](http://www.conab.gov.br/conab-superintendenciasRegionais.php)</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="3825" tipo="web">
                        <descricao>http://www.conab.gov.br/produtosServicos-PAANET-entrega.php</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="2880">
            <titulo>Receber pagamento</titulo>
            <descricao></descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3826" tipo="presencial">
                        <descricao>Rede bancária</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="2881">
            <titulo>Entregar relatórios de pagamentos</titulo>
            <descricao>A partir da 2ª entrega a entidade fornecedora tem que entregar o relatório de pagamentos.</descricao>
            <documentos>
                <default>
                    <item id="3730">Relatório de Pagamentos da organização fornecedora aos agricultores familiares</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3827" tipo="presencial">
                        <descricao>[Superintendências Regionais da CONAB](http://www.conab.gov.br/conab-superintendenciasRegionais.php)</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/1945" dbId="37542">
        <nomeOrgao>Ministério do Desenvolvimento Social e Agrário (MDSA)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="4" idServicoSegmento="2959">Demais segmentos (ONGs, organizações sociais, etc)</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Abastecimento</item>
        <item>Alimento</item>
        <item>Agropecuária</item>
        <item>Comércio e Serviços</item>
        <item>Produção agropecuária</item>
        <item>Proteção Social</item>
        <item>Cidadania</item>
        <item>Combate a desigualdade</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="3315">venda de alimentos</item>
        <item id="3316">agricultura familiar</item>
        <item id="3317">CONAB</item>
        <item id="3318">doação de alimentos</item>
        <item id="3319">cooperativa de agricultura familiar</item>
        <item id="3320">associação de agricultura familiar</item>
        <item id="3321">roça</item>
    </palavras-chave>
    <legislacoes>
        <item id="996">-</item>
    </legislacoes>
</servico>


text:
<!doctype html>

    <title>Code coverage report for lib/array.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../prettify.css">
    <link rel="stylesheet" href="../base.css">

Code coverage report for lib/array.js

        Statements: 27.83% (32 / 115)
        Branches: 20% (17 / 85)
        Functions: 3.85% (1 / 26)
        Lines: 27.83% (32 / 115)
        Ignored: none

All files » lib/ » array.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

/**
 * just.js extension package
 *
 * @author danikas2k2 (danikas2k2@gmail.com)
 */
"use strict";

(function (Array, Math, undefined) {

    Iif (typeof Array.isArray === 'undefined') {
        /**
         * Returns whether specified value is array and is empty
         *
         * @param value {Array}
         * @returns {boolean}
         * @static
         */
        Array.isArray = function (value) {
            return value instanceof Array;
        }
    }

    Eif (typeof Array.isEmpty === 'undefined') {
        /**
         * Returns whether specified value is array and is empty
         *
         * @param value {*}
         * @returns {boolean}
         * @static
         */
        Array.isEmpty = function (value) {
            return !Array.isArray(value) || !value.length;
        }
    }

    Eif (typeof Array.toArray === 'undefined') {
        /**
         * Returns whether specified value is array and is empty
         *
         * @param value {Array}
         * @returns {boolean}
         * @static
         */
        Array.toArray = function (value) {
            return Array.isArray(value) ? value : [value];
        }
    }

    /**
     * Returns array with a range of values
     *
     * @param start {number}
     * @param end {number}
     * @param step {number}
     * @returns {Array}
     * @static
     */
    Eif (typeof Array.range === 'undefined') {
        /*if (typeof Generator !== 'undefined') {
         Array.range = function* (start, end, step = (start > end ? -1 : 1)) {
         for (var i = start; i < end; i += step) {
         yield i;
         }
         };
         } else {
         }
         */

        Array.range = function (start, end, step) {
            if (typeof step === 'undefined') {
                step = (start > end ? -1 : 1);
            }
            var diff = end - start;
            var n = Math.ceil(diff / step) + 1;
            var result = new Array(n);
            for (var i = 0, j = start; i < n; i++, j += step) {
                result[i] = j;
            }
            return result;
        };
    }

    Eif (typeof Array.prototype.isEmpty === 'undefined') {
        /**
         * Returns whether array is empty
         *
         * @returns {boolean}
         */
        Array.prototype.isEmpty = function () {
            return !this.length;
        }
    }

    Eif (typeof Array.prototype.equals === 'undefined') {
        /**
         * Returns whether arrays are equal
         *
         * @param value {Array}
         * @returns {boolean}
         */
        Array.prototype.equals = function (value) {
            return !!value
                    && this.length === value.length
                    && this.every(function (element, index) {
                        return element.equals(value[index])
                    });
        }
    }

    Eif (typeof Array.prototype.compareTo === 'undefined') {
        /**
         * Compares arrays and returns -1 if an opposite is greater, 1 if an opposite is less and 0 if arrays are equal
         *
         * @param value {Array}
         * @returns {number}
         */
        Array.prototype.compareTo = function (value) {
            var diff = 1;
            return value && this.every(function (element, index) {
                return !(diff = element.compareTo(value[index]));
            }) ? 0 : diff;
        }
    }

    Eif (typeof Array.prototype.min === 'undefined') {
        /**
         * Returns a minimum of all array values or undefined for empty array
         *
         * @returns {*}
         */
        Array.prototype.min = function () {
            return this.isEmpty() ? undefined : Math.min.apply(this, this);
        }
    }

    Eif (typeof Array.prototype.max === 'undefined') {
        /**
         * Returns a maximum of all array values or undefined for empty array
         *
         * @returns {*}
         */
        Array.prototype.max = function () {
            return this.isEmpty() ? undefined : Math.max.apply(this, this);
        }
    }

    Eif (typeof Array.prototype.combine === 'undefined') {
        /**
         * Returns object combined from current array as values and specified array as keys
         *
         * @param keys {Array}
         * @returns {Object}
         */
        Array.prototype.combine = function (keys) {
            var res = {};
            if (Array.isEmpty(keys) || this.isEmpty()) {
                return res;
            }

            if (!Array.isArray(keys)) {
                keys = Object.keys(keys);
            }

            for (var i = 0, n = Math.min(keys.length, this.length); i < n; i++) {
                if (keys[i]) {
                    res[keys[i]] = this[i];
                }
            }
            return res;
        }
    }

    Eif (typeof Array.prototype.flip === 'undefined') {
        /**
         * Returns object of with flippped keys vs values
         *
         * @returns {Object}
         */
        Array.prototype.flip = function () {
            var res = {};
            if (Array.isArray(this)) {
                for (var i = 0, n = this.length; i < n; i++) {
                    res[this[i]] = i;
                }
                return res;
            }
            for (var keys = Object.keys(this), n = keys.length, i = 0, key = keys[i]; i < n; i++, key = keys[i]) {
                res[this[key]] = key;
            }
            return res;
        }
    }

    Eif (typeof Array.prototype.applyForEach === 'undefined') {
        /**
         * Apply function to every array value
         *
         * @param func {Function}
         * @param thisArg {*}
         */
        Array.prototype.applyForEach = function (func, thisArg) {
            if (typeof thisArg === 'undefined') {
                thisArg = this;
            }
            if (typeof func !== 'function') {
                throw new TypeError("Argument 1 function expected");
            }

            for (var n = this.length, i = 0; i < n; i++) {
                func.apply(thisArg, this[i]);
            }
        }
    }

    Iif (typeof Array.prototype.find === 'undefined') {
        /**
         * Search for first element matching specified function
         *
         * @param func {Function}
         * @param thisArg {*}
         * @returns {*} Returns undefined if no element found
         */
        Array.prototype.find = function (func, thisArg) {
            if (typeof thisArg === 'undefined') {
                thisArg = this;
            }
            if (typeof func !== 'function') {
                throw new TypeError("Argument 1 function expected");
            }

            var found = null;
            this.some(function (element, index, array) {
                if (func.call(thisArg, element, index, array)) {
                    found = element;
                    return true;
                }
                return false;
            }, thisArg);
            return found;
        }
    }

    Iif (typeof Array.prototype.findIndex === 'undefined') {
        /**
         * Search for index of first element matching specified function
         *
         * @param func {Function}
         * @param thisArg {*}
         * @returns {number}
         */
        Array.prototype.findIndex = function (func, thisArg) {
            if (typeof thisArg === 'undefined') {
                thisArg = this;
            }
            if (typeof func !== 'function') {
                throw new TypeError("Argument 1 function expected");
            }

            var found = -1;
            this.some(function (element, index, array) {
                if (func.call(thisArg, element, index, array)) {
                    found = index;
                    return true;
                }
                return false;
            }, thisArg);
            return found;
        }
    }

    Eif (typeof Array.prototype.has === 'undefined') {
        /**
         * Returns whether array has a specified value
         *
         * @param value {*}
         * @returns {boolean}
         */
        Array.prototype.has = function (value) {
            return this.indexOf(value) > -1;
        }
    }

    Eif (typeof Array.prototype.unique === 'undefined') {
        /**
         * Returns an array containing only unique values from current array. If custom compare function is specified,
         * then unique values are calculated according to that function compare results.
         *
         * @param [func] {function}
         * @param [thisArg] {*}
         * @returns {Array}
         */
        Array.prototype.unique = function (func, thisArg) {
            if (typeof thisArg === 'undefined') {
                thisArg = this;
            }
            if (typeof func === 'function') {
                return this.filter(function (value, index, array) {
                    var found = -1;
                    array.some(function (element, index) {
                        if (func.call(thisArg, element, value)) {
                            found = index;
                            return true;
                        }
                        return false;
                    });
                    return found === index;
                });
            }
            return this.filter(function (value, index, array) {
                return array.indexOf(value) === index;
            });
        }
    }

    Eif (typeof Array.prototype.shuffle === 'undefined') {
        /**
         * Returns shuffled array
         *
         * @returns {Array}
         */
        Array.prototype.shuffle = function () {
            return this.sort(function () {
                return 0.5 - Math.random();
            });
        }
    }

})(Array, Math);

Generated by istanbul at Thu Sep 17 2015 16:25:56 GMT+0300 (EEST)

redpajama_set_name: RedPajamaGithub


text:
cask 'parallels-client' do
  version '16.2.4-19503'
  sha256 '6f2822d45a9d67ce5ccacdb1f464d8658c9961ebe744db92df603aea717a7d47'

  url "https://download.parallels.com/ras/v#{version.major}/#{version.hyphens_to_dots}/RasClient-Mac-#{version}.pkg"
  appcast "https://download.parallels.com/ras/v#{version.major}/RAS%20Client%20for%20Mac%20Changelog.txt"
  name 'Parallels Client'
  homepage 'https://www.parallels.com/products/ras/features/rdp-client/'

  pkg "RasClient-Mac-#{version}.pkg"

  uninstall pkgutil: 'com.2X.Client.Mac',
            quit:    'com.2X.Client.Mac'
end


text:
namespace XenAdmin.Controls.GPU
{
    partial class GpuRow
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GpuRow));
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            this.allowedTypesImageList = new System.Windows.Forms.ImageList(this.components);
            this.panelWithBorder = new XenAdmin.Controls.PanelWithBorder();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.allowedTypesLabel = new XenAdmin.Controls.Common.AutoHeightLabel();
            this.pGpuLabel = new XenAdmin.Controls.Common.AutoHeightLabel();
            this.pGpuPictureBox = new System.Windows.Forms.PictureBox();
            this.allowedTypesGrid = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
            this.ImageColumn = new System.Windows.Forms.DataGridViewImageColumn();
            this.TextColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.shinyBarsContainerPanel = new System.Windows.Forms.TableLayoutPanel();
            this.editButton = new System.Windows.Forms.Button();
            this.multipleSelectionPanel = new System.Windows.Forms.Panel();
            this.clearAllButton = new System.Windows.Forms.Button();
            this.selectAllButton = new System.Windows.Forms.Button();
            this.panelWithBorder.SuspendLayout();
            this.tableLayoutPanel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pGpuPictureBox)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.allowedTypesGrid)).BeginInit();
            this.multipleSelectionPanel.SuspendLayout();
            this.SuspendLayout();
            //
            // allowedTypesImageList
            //
            this.allowedTypesImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("allowedTypesImageList.ImageStream")));
            this.allowedTypesImageList.TransparentColor = System.Drawing.Color.Transparent;
            this.allowedTypesImageList.Images.SetKeyName(0, "000_Abort_h32bit_16.png");
            this.allowedTypesImageList.Images.SetKeyName(1, "000_Tick_h32bit_16.png");
            //
            // panelWithBorder
            //
            resources.ApplyResources(this.panelWithBorder, "panelWithBorder");
            this.panelWithBorder.BackColor = System.Drawing.Color.Transparent;
            this.panelWithBorder.Controls.Add(this.tableLayoutPanel1);
            this.panelWithBorder.Controls.Add(this.multipleSelectionPanel);
            this.panelWithBorder.Name = "panelWithBorder";
            //
            // tableLayoutPanel1
            //
            resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
            this.tableLayoutPanel1.Controls.Add(this.allowedTypesLabel, 2, 0);
            this.tableLayoutPanel1.Controls.Add(this.pGpuLabel, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.pGpuPictureBox, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.allowedTypesGrid, 2, 1);
            this.tableLayoutPanel1.Controls.Add(this.shinyBarsContainerPanel, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.editButton, 2, 2);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            //
            // allowedTypesLabel
            //
            resources.ApplyResources(this.allowedTypesLabel, "allowedTypesLabel");
            this.allowedTypesLabel.AutoEllipsis = true;
            this.allowedTypesLabel.BackColor = System.Drawing.Color.Transparent;
            this.allowedTypesLabel.Name = "allowedTypesLabel";
            //
            // pGpuLabel
            //
            resources.ApplyResources(this.pGpuLabel, "pGpuLabel");
            this.pGpuLabel.AutoEllipsis = true;
            this.pGpuLabel.BackColor = System.Drawing.Color.Transparent;
            this.pGpuLabel.Name = "pGpuLabel";
            //
            // pGpuPictureBox
            //
            this.pGpuPictureBox.Image = global::XenAdmin.Properties.Resources._000_GetMemoryInfo_h32bit_16;
            resources.ApplyResources(this.pGpuPictureBox, "pGpuPictureBox");
            this.pGpuPictureBox.Name = "pGpuPictureBox";
            this.pGpuPictureBox.TabStop = false;
            //
            // allowedTypesGrid
            //
            this.allowedTypesGrid.AllowUserToResizeColumns = false;
            this.allowedTypesGrid.BackgroundColor = System.Drawing.SystemColors.Window;
            this.allowedTypesGrid.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.allowedTypesGrid.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
            this.allowedTypesGrid.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
            this.allowedTypesGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.allowedTypesGrid.ColumnHeadersVisible = false;
            this.allowedTypesGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.ImageColumn,
            this.TextColumn});
            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window;
            dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText;
            dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Window;
            dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.ControlText;
            dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
            this.allowedTypesGrid.DefaultCellStyle = dataGridViewCellStyle1;
            this.allowedTypesGrid.GridColor = System.Drawing.SystemColors.Control;
            this.allowedTypesGrid.HideSelection = true;
            resources.ApplyResources(this.allowedTypesGrid, "allowedTypesGrid");
            this.allowedTypesGrid.Name = "allowedTypesGrid";
            this.allowedTypesGrid.ReadOnly = true;
            this.allowedTypesGrid.TabStop = false;
            //
            // ImageColumn
            //
            this.ImageColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            this.ImageColumn.Frozen = true;
            resources.ApplyResources(this.ImageColumn, "ImageColumn");
            this.ImageColumn.Name = "ImageColumn";
            this.ImageColumn.ReadOnly = true;
            //
            // TextColumn
            //
            this.TextColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            this.TextColumn.FillWeight = 190F;
            this.TextColumn.Frozen = true;
            resources.ApplyResources(this.TextColumn, "TextColumn");
            this.TextColumn.Name = "TextColumn";
            this.TextColumn.ReadOnly = true;
            this.TextColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False;
            //
            // shinyBarsContainerPanel
            //
            resources.ApplyResources(this.shinyBarsContainerPanel, "shinyBarsContainerPanel");
            this.tableLayoutPanel1.SetColumnSpan(this.shinyBarsContainerPanel, 2);
            this.shinyBarsContainerPanel.Name = "shinyBarsContainerPanel";
            this.tableLayoutPanel1.SetRowSpan(this.shinyBarsContainerPanel, 2);
            //
            // editButton
            //
            resources.ApplyResources(this.editButton, "editButton");
            this.editButton.BackColor = System.Drawing.Color.Transparent;
            this.editButton.Name = "editButton";
            this.editButton.UseVisualStyleBackColor = false;
            this.editButton.Click += new System.EventHandler(this.editButton_Click);
            //
            // multipleSelectionPanel
            //
            this.multipleSelectionPanel.Controls.Add(this.clearAllButton);
            this.multipleSelectionPanel.Controls.Add(this.selectAllButton);
            resources.ApplyResources(this.multipleSelectionPanel, "multipleSelectionPanel");
            this.multipleSelectionPanel.Name = "multipleSelectionPanel";
            //
            // clearAllButton
            //
            resources.ApplyResources(this.clearAllButton, "clearAllButton");
            this.clearAllButton.Name = "clearAllButton";
            this.clearAllButton.UseVisualStyleBackColor = true;
            this.clearAllButton.Click += new System.EventHandler(this.clearAllButton_Click);
            //
            // selectAllButton
            //
            resources.ApplyResources(this.selectAllButton, "selectAllButton");
            this.selectAllButton.Name = "selectAllButton";
            this.selectAllButton.UseVisualStyleBackColor = true;
            this.selectAllButton.Click += new System.EventHandler(this.selectAllButton_Click);
            //
            // GpuRow
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.Controls.Add(this.panelWithBorder);
            this.Name = "GpuRow";
            this.panelWithBorder.ResumeLayout(false);
            this.panelWithBorder.PerformLayout();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pGpuPictureBox)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.allowedTypesGrid)).EndInit();
            this.multipleSelectionPanel.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.PictureBox pGpuPictureBox;
        private XenAdmin.Controls.Common.AutoHeightLabel pGpuLabel;
        private System.Windows.Forms.ImageList allowedTypesImageList;
        private XenAdmin.Controls.DataGridViewEx.DataGridViewEx allowedTypesGrid;
        private XenAdmin.Controls.Common.AutoHeightLabel allowedTypesLabel;
        private System.Windows.Forms.DataGridViewImageColumn ImageColumn;
        private System.Windows.Forms.DataGridViewTextBoxColumn TextColumn;
        private System.Windows.Forms.TableLayoutPanel shinyBarsContainerPanel;
        private System.Windows.Forms.Button clearAllButton;
        private System.Windows.Forms.Button selectAllButton;
        private PanelWithBorder panelWithBorder;
        private System.Windows.Forms.Panel multipleSelectionPanel;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.Button editButton;
    }
}


text:
+++ pci.cpp
@@ -17,6 +17,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND

 #include <iostream>
 #include <stdio.h>
+#include <strings.h> //for bzero
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>


text:
module Canary
  module Connections
    class SeriesWorkConnection < GraphQL::Types::Relay::BaseConnection
      edge_type Canary::Edges::SeriesWorkEdge
    end
  end
end


text:
#include <memory>

#include "absl/memory/memory.h"
#include "asylo/grpc/util/enclave_server.h"
#include "asylo/test/grpc/messenger_server_impl.h"
#include "include/grpcpp/security/server_credentials.h"

namespace asylo {

// Creates an enclave application hosting a simple gRPC server with insecure
// credentials.
TrustedApplication *BuildTrustedApplication() {
  return new EnclaveServer(absl::make_unique<test::MessengerServer1>(),
                           ::grpc::InsecureServerCredentials());
}

}  // namespace asylo


text: void    SyncNotificationPostNotification(CFStringRef notification, SyncUIObjectRef objRef) {}


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_jme3_bullet_collision_shapes_ConeCollisionShape */

#ifndef _Included_com_jme3_bullet_collision_shapes_ConeCollisionShape
#define _Included_com_jme3_bullet_collision_shapes_ConeCollisionShape
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_jme3_bullet_collision_shapes_ConeCollisionShape
 * Method:    createShape
 * Signature: (IFF)J
 */
JNIEXPORT jlong JNICALL Java_com_jme3_bullet_collision_shapes_ConeCollisionShape_createShape
  (JNIEnv *, jobject, jint, jfloat, jfloat);

#ifdef __cplusplus
}
#endif
#endif


text:
require 'yaml'

module GettyConnectAuthentication
  module Configuration

    def self.load(path_to_yaml_file)
      begin
        configuration = YAML::load(IO.read(path_to_yaml_file))
        @id = configuration['id']
        @secret = configuration['secret']
        @username = configuration['username']
        @password = configuration['password']
        return
      rescue Errno::ENOENT
        raise "YAML configuration file \"#{path_to_yaml_file}\" couldn't be found. Using defaults."
      rescue Psych::SyntaxError
        raise "YAML configuration file contains invalid syntax. Using defaults."
      end
    end

    def self.id
      @id
    end

    def self.secret
      @secret
    end

    def self.username
      @username
    end

    def self.password
      @password
    end

    def self.reset
      @id = nil
      @secret = nil
      @username = nil
      @password = nil
    end

  end
end


text:
class Texture;

class Stage
{
public:

	Stage( void );
	virtual ~Stage( void );

	bool Load( const wxString& stageFile );
	bool Unload( void );

	void Render( _3DMath::Renderer& renderer, const _3DMath::TimeKeeper& timeKeeper );
	void Simulate( const _3DMath::TimeKeeper& timeKeeper );

	Blob* GetHumanDrivenBlob( void );

private:

	BlobList blobList;
	ReceptacleList receptacleList;
	_3DMath::Vector respawnLocation;
	_3DMath::Plane deathPlane;
	ModelNameList groundList;
};

// Stage.h


text:
<?php

namespace WatsonSDK\Services\Assistant;

use WatsonSDK\Common\ServiceModel;

/**
 * Assistant `send request` model
 */
class MessageRequestModel extends ServiceModel {

    /**
     * @name(input)
     *
     * The user input.
     *
     * @var InputDataModel
     */
    protected $_input;

    /**
     * @name(alternate_intents)
     *
     * Whether to return more than one intent.
     * Set to true to return all matching intents.
     * For example, return all intents when the confidence is not high to allow users to choose their intent.
     * The default value is false.
     *
     * @var boolean
     */
    protected $_alternate_intents;

    /**
     * @name(context)
     *
     * State information for the conversation.
     * To maintain state, include the Context object from the previous response when sending multiple requests for the same conversation.
     *
     * @var ContextModel
     */
    protected $_context;

    /**
     * @array(entities)
     *
     * Entities to use when evaluating the message.
     * Include entities from the previous response to continue using those entities rather than detecting entities in the new input.
     *
     * @var RuntimeEntityModel[]
     */
    protected $_entities;

    /**
     * @array(intents)
     *
     * Intents to use when evaluating the user input.
     * Include the intents from the previous response to continue using those intents rather than trying to recognize intents in the new input.
     *
     * @var IntentModel[]
     */
    protected $_intents;

    /**
     * @array(output)
     *
     * System output.
     * Include the output from the previous response to maintain intermediate informationif you have several requests within the same dialog turn.
     *
     * @var OutputDataModel
     */
    protected $_output;

    /**
     * @name(nodes_visited_details)
     *
     * An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message.
     * Included only if nodes_visited_details is set to true in the message request.
     *
     * @var boolean
     */
    protected $_nodes_visited_details;

    /**
     * Constructor.
     *
     * @param string | InputDataModel $text
     * @param boolean | NULL $alternate_intents
     * @param ContextModel | NULL $context
     * @param RuntimeEntityModel | NULL $entities
     * @param RuntimeIntent | NULL $intents
     * @param OutputDataModel | NULL $output
     */
    function __construct($input, $alternate_intents = NULL, ContextModel $context = NULL, array $entities = NULL, array $intents = NULL, OutputDataModel $output = NULL) {

        if(is_string($input)) {
            $input = new InputDataModel($input);
        }

        $this->setInput($input);

        $this->setAlternateIntents($alternate_intents);

        $this->setContext($context);

        if(is_null($entities) === FALSE) {
            $this->setEntities($entities);
        }

        if(is_null($intents) === FALSE) {
            $this->setIntents($intents);
        }

        if(is_null($output) === FALSE) {
            $this->setOutput($output);
        }
    }

    /**
     * Get user input.
     *
     * @return InputDataModel
     */
    public function getInput() {
        return $this->_input;
    }

    /**
     * Set user input.
     *
     * @param $val InputDataModel
     */
    public function setInput($val) {
        $this->_input = $val;
    }

    /**
     * Get the value of that whether to return more than one intent.
     *
     * @return boolean
     */
    public function getAlternateIntents() {
        return $this->_alternate_intents;
    }

    /**
     * Set the value to indicate that whether to return more than one intent.
     *
     * @param $val boolean
     */
    public function setAlternateIntents($val) {
        $this->_alternate_intents = $val;
    }

    /**
     * Set state information for the conversation
     *
     * @return ContextModel
     */
    public function getContext() {
        return $this->_context;
    }

    /**
     * Set state information for the conversation
     *
     * @param ContextModel $val
     */
    public function setContext($val) {
        $this->_context = $val;
    }

    /**
     * Get entities to use when evaluating the message.
     *
     * @return array
     */
    public function getEntities() {
        return $this->_entities;
    }

    /**
     * Set entities to use when evaluating the message.
     *
     * @param $val array
     */
    public function setEntities($val) {
        $this->_entities = $val;
    }

    /**
     * Get intents to use when evaluating the user input.
     *
     * @return array
     */
    public function getIntents() {
        return $this->_intents;
    }

    /**
     * Set intents to use when evaluating the user input.
     *
     * @param $val array
     */
    public function setIntents($val) {
        $this->_intents = $val;
    }

    /**
     * Get system output.
     *
     * @return OutputDataModel
     */
    public function getOutput() {
        return $this->_output;
    }

    /**
     * Set system output.
     *
     * @param OutputDataModel $val
     */
    public function setOutput($val) {
        $this->_output = $val;
    }

    /**
     * Get the array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message.
     *
     * @return boolean
     */
    public function getNodesVisitedDetails() {
        return $this->_nodes_visited_details;
    }

    /**
     * Set the array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message.
     *
     * @param boolean $val
     */
    public function setNodesVisitedDetails($val) {
        $this->_nodes_visited_details = $val;
    }
}


text:
class CreateDisclosureTags < ActiveRecord::Migration
  def change
    create_table :disclosure_tags do |t|
      t.integer :disclosure_id
      t.integer :tag_id

      t.timestamps
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<service enable-namespace-folding="true" name="SOAQETestImplFactoryServiceV1" xmlns="http://www.ebayopensource.org/turmeric/common/config">
    <package-map>
        <package xml-namespace="http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService" name="org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.soaqetestimplfactoryservice"/>
        <package xml-namespace="http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService" name="org.ebayopensource.turmeric.common.v1.types"/>
        <package xml-namespace="http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService" name="org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice"/>
    </package-map>
    <operation-list>
        <operation name="getVersion">
            <request-message>
                <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.GetVersionRequest</java-type-name>
                <xml-type-name>GetVersionRequest</xml-type-name>
                <xml-element-name>{http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService}getVersionRequest</xml-element-name>
                <has-attachment>false</has-attachment>
            </request-message>
            <response-message>
                <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.GetVersionResponse</java-type-name>
                <xml-type-name>GetVersionResponse</xml-type-name>
                <xml-element-name>{http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService}getVersionResponse</xml-element-name>
                <has-attachment>false</has-attachment>
            </response-message>
            <error-message>
                <java-type-name>org.ebayopensource.turmeric.common.v1.types.ErrorMessage</java-type-name>
                <xml-type-name>ErrorMessage</xml-type-name>
                <xml-element-name>{http://www.ebayopensource.org/turmeric/common/v1/types}errorMessage</xml-element-name>
            </error-message>
        </operation>
        <operation name="testImplFactory">
            <request-message>
                <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.TestImplFactoryRequest</java-type-name>
                <xml-type-name>TestImplFactoryRequest</xml-type-name>
                <xml-element-name>{http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService}testImplFactoryRequest</xml-element-name>
                <has-attachment>false</has-attachment>
            </request-message>
            <response-message>
                <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.TestImplFactoryResponse</java-type-name>
                <xml-type-name>TestImplFactoryResponse</xml-type-name>
                <xml-element-name>{http://www.ebayopensource.org/turmeric/qe/SOAQETestImplFactoryService}testImplFactoryResponse</xml-element-name>
                <has-attachment>false</has-attachment>
            </response-message>
            <error-message>
                <java-type-name>org.ebayopensource.turmeric.common.v1.types.ErrorMessage</java-type-name>
                <xml-type-name>ErrorMessage</xml-type-name>
                <xml-element-name>{http://www.ebayopensource.org/turmeric/common/v1/types}errorMessage</xml-element-name>
            </error-message>
        </operation>
    </operation-list>
    <java-type-list>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.BaseRequest</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.BaseResponse</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.CommonErrorData</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.ErrorData</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.ErrorMessage</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.ErrorParameter</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.common.v1.types.ExtensionType</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.GetVersionRequest</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.GetVersionResponse</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.TestImplFactoryRequest</java-type-name>
        <java-type-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.TestImplFactoryResponse</java-type-name>
    </java-type-list>
</service>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <bytecodeTargetLevel>
      <module name="shoppingcart-example_main" target="1.8" />
      <module name="shoppingcart-example_test" target="1.8" />
    </bytecodeTargetLevel>
  </component>
</project>


text:
import Model from 'ember-data/attr'
import attr from 'ember-data/model'

export default Model.extend({
  text: attr('string')
})


text:
@interface SecondViewController : ViewController

@end


text:
import billboard
import json
import urllib
from urllib.parse import quote

apikey = 'APIKEY'

# make the empty dictionary
songs = {}

# loop through the years we're interested in
for x in range(1960, 2016):
    # another dictionary inside
    songs[x] = {}
    # get the chart for the last week of that year
    chart = billboard.ChartData('hot-100', '%s-12-19' % str(x))
    # for every song on the chart, keep its rank, title, and author
    for song in chart:
        songs[x][song.rank] = {}
        songs[x][song.rank]['rank'] = song.rank
        songs[x][song.rank]['title'] = song.title
        songs[x][song.rank]['artist'] = song.artist
        # look up the song in musixmatch
        api_url = "http://api.musixmatch.com/ws/1.1/matcher.track.get?apikey=%s&q_artist=%s&q_track=%s" % (apikey, quote(song.artist, safe=''), quote(song.title, safe=''))
        url = urllib.request.urlopen(api_url).read().decode('UTF-8')
        result = json.loads(url)
        songs[x][song.rank]['musixmatch'] = result
        # use lyrics id to get lyrics info and store that instead of all the junk from musixmatch
        api_url_lyrics = "http://api.musixmatch.com/ws/1.1/matcher.lyrics.get?apikey=%s&q_track=%s&q_artist=%s" % (apikey, quote(song.title, safe=''), quote(song.artist, safe=''))
        url_lyrics = urllib.request.urlopen(api_url_lyrics).read().decode('UTF-8')
        lyrics = json.loads(url_lyrics)
        #checks against any songs not in MusixMatch database and any songs without lyrics
        if result['message']['header']['status_code'] != 404 and result['message']['body']['track']['has_lyrics'] == 1:
            lyrics_id = result['message']['body']['track']['lyrics_id']
            get_lyrics = lyrics['message']['body']['lyrics']['lyrics_body']
            songs[x][song.rank]['lyrics'] = get_lyrics

#dump all the data to a json file (readable output)
with open('song-data.json', 'w') as out_file:
    for x in sorted(songs):
        out_file.write('>')
        json.dump(x, out_file)
        out_file.write('\n')
        for y in songs[x]:
            if 'lyrics' in songs[x][y]:
                out_file.write('(')
                json.dump(y, out_file)
                out_file.write(') ' + songs[x][y]['title'] + ' - ' + songs[x][y]['artist'])
                out_file.write('\n')
                json.dump(songs[x][y]['lyrics'].replace('\n', ' '), out_file)
                out_file.write('\n')
                out_file.write('\n')


text:
package net.liftweb
package couchdb

import java.net.ConnectException

import dispatch.{Http, StatusCode}

import common._
import json._
import JsonDSL._
import org.specs2.mutable.Specification
import DocumentHelpers.jobjectToJObjectExtension

/**
 * Systems under specification for CouchQuery.
 */
object CouchQuerySpec extends Specification  {
  "CouchQuery Specification".title
  sequential

  def setup = {
    val http = new Http
    val database = new Database("test")
    (try { http(database delete) } catch { case StatusCode(_, _) => () }) must not(throwA[ConnectException]).orSkip
    http(database create)

    (http, database)
  }

  private def verifyAndOpen[A](b: Box[A]): A = {
    b.isDefined must_== true
    b.open_!
  }

  "Queries" should {
    val design: JObject =
      ("language" -> "javascript") ~
      ("views" -> (("all_students"  -> ("map" -> "function(doc) { if (doc.type == 'student') { emit(null, doc); } }")) ~
             ("students_by_age" -> ("map" -> "function(doc) { if (doc.type == 'student') { emit(doc.age, doc); } }")) ~
             ("students_by_age_and_name" -> ("map" -> "function(doc) { if (doc.type == 'student') { emit([doc.age, doc.name], doc); } }"))))

    val docs: List[JObject] =
      (("type" -> "student") ~ ("name" -> "Alice")   ~ ("age" -> 10)) ::
      (("type" -> "student") ~ ("name" -> "Bob")   ~ ("age" -> 11)) ::
      (("type" -> "student") ~ ("name" -> "Charlie") ~ ("age" -> 11)) ::
      (("type" -> "student") ~ ("name" -> "Donna")   ~ ("age" -> 12)) ::
      (("type" -> "student") ~ ("name" -> "Eric")  ~ ("age" -> 12)) ::
      (("type" -> "student") ~ ("name" -> "Fran")  ~ ("age" -> 13)) ::
      (("type" -> "class") ~ ("name" -> "Astronomy")) ::
      (("type" -> "class") ~ ("name" -> "Baking")) ::
      (("type" -> "class") ~ ("name" -> "Chemistry")) ::
      Nil

    def findStudents(docs: List[JObject]): List[JObject] = docs.filter(_.isA("student"))

    def compareName(a: JObject, b: JObject): Boolean =
      (a.getString("name") openOr "design") < (b.getString("name") openOr "design")

    def prep(http: Http, database: Database): (JObject, List[JObject]) = {
      val storedDesign = verifyAndOpen(http(database.design("test") put design))
      val storedDocs = docs map { doc => verifyAndOpen(http(database store doc)) }

      (storedDesign, storedDocs)
    }

    def sortedAndPrintedRows(docs: Seq[QueryRow]): String = sortedAndPrintedValues(docs.flatMap(_.value.asA[JObject]).toList)
    def sortedAndPrintedValues(docs: List[JObject]): String = compact(render(docs.sortWith(compareName)))

    "work with all documents" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.all.includeDocs query)) must beLike {
        case QueryResults(Full(count), Full(offset), rows) =>
          count must_== docs.length + 1 // +1 for the design doc
          offset must_== 0
          sortedAndPrintedValues(rows.flatMap(_.doc).toList) must_== sortedAndPrintedValues(design::docs)
      }
    }

    "support multi-document fetch" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database(List(students(0)._id.open_!, students(3)._id.open_!, students(5)._id.open_!)) query)) must beLike {
        case QueryResults(Full(count), Full(offset), rows) =>
          sortedAndPrintedValues(rows.flatMap(_.doc).toList) must_== sortedAndPrintedValues(students(0)::students(3)::students(5)::Nil)
      }
    }

    "work with views" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.design("test").view("all_students") query)) must beLike {
        case QueryResults(Full(count), Full(offset), rows) =>
          count must_== students.length
          offset must_== 0
          sortedAndPrintedRows(rows) must_== sortedAndPrintedValues(students)
      }
    }

    "support minimum key bounds" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.design("test").view("students_by_age").from(11) query)) must beLike {
        case QueryResults(_, _, rows) =>
          (rows.flatMap(_.value.asA[JObject]).toList.sortWith(compareName) must_==
           students.filter(_.getInt("age").map(_ >= 11).open_!).sortWith(compareName))
      }
    }

    "support maximum key bounds" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.design("test").view("students_by_age").to(12) query)) must beLike {
        case QueryResults(_, _, rows) =>
          (rows.flatMap(_.value.asA[JObject]).toList.sortWith(compareName) must_==
           students.filter(_.getInt("age").map(_ <= 12).open_!).sortWith(compareName))
      }
    }

    "support key lookup" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.design("test").view("students_by_age").key(11) query)) must beLike {
        case QueryResults(_, _, rows) =>
          rows.length must_== 2
          (rows.flatMap(_.value.asA[JObject]).toList.sortWith(compareName) must_==
           students.filter(_.getInt("age").map(_ == 11).open_!))
      }
    }

    "support limiting the number of results" in {
      val (http, database) = setup
      prep(http, database)

      verifyAndOpen(http(database.design("test").view("students_by_age").from(12).limit(2) query)) must beLike {
        case QueryResults(_, _, rows) => rows.length must_== 2
      }
    }

    "support descending sort" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.design("test").view("students_by_age").descending.from(11) query)) must beLike {
        case QueryResults(_, _, rows) =>
          rows.length must_== 3
          (rows.flatMap(_.value.asA[JObject]).toList.sortWith(compareName) must_==
           students.filter(_.getInt("age").map(_ <= 11).open_!))
      }
    }

    "preserve query ordering" in {
      val (http, database) = setup
      val (design, docs) = prep(http, database)
      val students = findStudents(docs)

      verifyAndOpen(http(database.design("test").view("students_by_age_and_name").from(JArray(11::Nil)).to(JArray(12::JObject(Nil)::Nil)) query)) must beLike {
        case QueryResults(_, _, rows) =>
          rows.length must_== 4
          (rows.flatMap(_.value.asA[JObject]).toList must_==
            students.filter(_.getInt("age").map(age => age >= 11 && age <= 12).open_!))
      }
    }
  }
}


text:
set -eo pipefail

echo "Installing yarn v${YARN_VERSION}"
npm install -g yarn@${YARN_VERSION}


text:
import { PromiseState } from 'react-refetch';
import { update, updateMulti, refreshing, appendList, reject } from '../utils/reducer';
import EntityConfiguration from '../EntityConfiguration';
import buildRequest from 'react-refetch/lib/utils/buildRequest';

export default (/** @type EntityConfiguration */ entityConfiguration) => {
  if (!entityConfiguration instanceof EntityConfiguration) {
    throw `Expected EntityConfiguration, got ${typeof entityConfiguration}.`;
  }

  const dispatch = entityConfiguration.dispatch;

  return ({ parentId = false, query = {} }) => {
    const key = entityConfiguration.listKey({ parentId, query, flags: [ 'list' ] });
    const pageKey = entityConfiguration.listPageKey({ parentId, query });
    const hasMoreKey = entityConfiguration.listHasMoreKey({ parentId, query });
    const moreKey = entityConfiguration.refetchListMoreKey({ parentId, query });
    const moreResponseKey = entityConfiguration.refetchListMoreResponseKey({ parentId, query });

    return {
      [moreKey]: (page) => {
        const url = entityConfiguration.url({ parentId, query: { ...query, page } });

        return {
          [moreResponseKey]: {
            comparison: url,
            url: url,
            method: 'GET',
            buildRequest: (mapping) => {
              dispatch(refreshing(key));
              dispatch(update(pageKey, page));

              return buildRequest(mapping);
            },
            then: (value) => {
              const updates = {};

              if (value.length === 0) {
                dispatch(update(hasMoreKey, false));
              }

              value.forEach((item) => {
                const itemKey = entityConfiguration.singleKey({ id: item.id, parentId: parentId || false });
                const itemDraftKey = entityConfiguration.draftKey({ id: item.id, parentId: parentId || false });
                updates[itemKey] = PromiseState.resolve(item);
                updates[itemDraftKey] = PromiseState.resolve(item);
              });

              dispatch(updateMulti(updates));

              dispatch(appendList(key, value));

              return {
                value,
                force: true,
                comparison: url,
              };
            },
            catch: (exception, meta) => {
              const errorMessage = (exception && exception.message) || meta.response.statusText;

              dispatch(reject(key, errorMessage, meta));

              return undefined;
            },
          },
        };
      },
    };
  };
};


text:
"""Test the motionEye camera."""
import copy
from typing import Any, cast
from unittest.mock import AsyncMock, Mock, call

from aiohttp import web
from aiohttp.web_exceptions import HTTPBadGateway
from motioneye_client.client import (
    MotionEyeClientError,
    MotionEyeClientInvalidAuthError,
    MotionEyeClientURLParseError,
)
from motioneye_client.const import (
    KEY_CAMERAS,
    KEY_MOTION_DETECTION,
    KEY_NAME,
    KEY_TEXT_OVERLAY_CUSTOM_TEXT,
    KEY_TEXT_OVERLAY_CUSTOM_TEXT_LEFT,
    KEY_TEXT_OVERLAY_CUSTOM_TEXT_RIGHT,
    KEY_TEXT_OVERLAY_LEFT,
    KEY_TEXT_OVERLAY_RIGHT,
    KEY_TEXT_OVERLAY_TIMESTAMP,
    KEY_VIDEO_STREAMING,
)
import pytest
import voluptuous as vol

from homeassistant.components.camera import async_get_image, async_get_mjpeg_stream
from homeassistant.components.motioneye import get_motioneye_device_identifier
from homeassistant.components.motioneye.const import (
    CONF_ACTION,
    CONF_STREAM_URL_TEMPLATE,
    CONF_SURVEILLANCE_USERNAME,
    DEFAULT_SCAN_INTERVAL,
    DOMAIN,
    MOTIONEYE_MANUFACTURER,
    SERVICE_ACTION,
    SERVICE_SET_TEXT_OVERLAY,
    SERVICE_SNAPSHOT,
)
from homeassistant.const import ATTR_DEVICE_ID, ATTR_ENTITY_ID, CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
import homeassistant.util.dt as dt_util

from . import (
    TEST_CAMERA,
    TEST_CAMERA_DEVICE_IDENTIFIER,
    TEST_CAMERA_ENTITY_ID,
    TEST_CAMERA_ID,
    TEST_CAMERA_NAME,
    TEST_CAMERAS,
    TEST_CONFIG_ENTRY_ID,
    TEST_SURVEILLANCE_USERNAME,
    create_mock_motioneye_client,
    create_mock_motioneye_config_entry,
    setup_mock_motioneye_config_entry,
)

from tests.common import async_fire_time_changed

@pytest.fixture
def aiohttp_server(loop, aiohttp_server, socket_enabled):
    """Return aiohttp_server and allow opening sockets."""
    return aiohttp_server

async def test_setup_camera(hass: HomeAssistant) -> None:
    """Test a basic camera."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert entity_state.state == "streaming"
    assert entity_state.attributes.get("friendly_name") == TEST_CAMERA_NAME

async def test_setup_camera_auth_fail(hass: HomeAssistant) -> None:
    """Test a successful camera."""
    client = create_mock_motioneye_client()
    client.async_client_login = AsyncMock(side_effect=MotionEyeClientInvalidAuthError)
    await setup_mock_motioneye_config_entry(hass, client=client)
    assert not hass.states.get(TEST_CAMERA_ENTITY_ID)

async def test_setup_camera_client_error(hass: HomeAssistant) -> None:
    """Test a successful camera."""
    client = create_mock_motioneye_client()
    client.async_client_login = AsyncMock(side_effect=MotionEyeClientError)
    await setup_mock_motioneye_config_entry(hass, client=client)
    assert not hass.states.get(TEST_CAMERA_ENTITY_ID)

async def test_setup_camera_empty_data(hass: HomeAssistant) -> None:
    """Test a successful camera."""
    client = create_mock_motioneye_client()
    client.async_get_cameras = AsyncMock(return_value={})
    await setup_mock_motioneye_config_entry(hass, client=client)
    assert not hass.states.get(TEST_CAMERA_ENTITY_ID)

async def test_setup_camera_bad_data(hass: HomeAssistant) -> None:
    """Test bad camera data."""
    client = create_mock_motioneye_client()
    cameras = copy.deepcopy(TEST_CAMERAS)
    del cameras[KEY_CAMERAS][0][KEY_NAME]

    client.async_get_cameras = AsyncMock(return_value=cameras)
    await setup_mock_motioneye_config_entry(hass, client=client)
    assert not hass.states.get(TEST_CAMERA_ENTITY_ID)

async def test_setup_camera_without_streaming(hass: HomeAssistant) -> None:
    """Test a camera without streaming enabled."""
    client = create_mock_motioneye_client()
    cameras = copy.deepcopy(TEST_CAMERAS)
    cameras[KEY_CAMERAS][0][KEY_VIDEO_STREAMING] = False

    client.async_get_cameras = AsyncMock(return_value=cameras)
    await setup_mock_motioneye_config_entry(hass, client=client)
    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert entity_state.state == "unavailable"

async def test_setup_camera_new_data_same(hass: HomeAssistant) -> None:
    """Test a data refresh with the same data."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)
    async_fire_time_changed(hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL)
    await hass.async_block_till_done()
    assert hass.states.get(TEST_CAMERA_ENTITY_ID)

async def test_setup_camera_new_data_camera_removed(hass: HomeAssistant) -> None:
    """Test a data refresh with a removed camera."""
    device_registry = dr.async_get(hass)
    entity_registry = er.async_get(hass)

    client = create_mock_motioneye_client()
    config_entry = await setup_mock_motioneye_config_entry(hass, client=client)

    # Create some random old devices/entity_ids and ensure they get cleaned up.
    old_device_id = "old-device-id"
    old_entity_unique_id = "old-entity-unique_id"
    old_device = device_registry.async_get_or_create(
        config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, old_device_id)}
    )
    entity_registry.async_get_or_create(
        domain=DOMAIN,
        platform="camera",
        unique_id=old_entity_unique_id,
        config_entry=config_entry,
        device_id=old_device.id,
    )

    await hass.async_block_till_done()
    assert hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert device_registry.async_get_device({TEST_CAMERA_DEVICE_IDENTIFIER})

    client.async_get_cameras = AsyncMock(return_value={KEY_CAMERAS: []})
    async_fire_time_changed(hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL)
    await hass.async_block_till_done()
    assert not hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert not device_registry.async_get_device({TEST_CAMERA_DEVICE_IDENTIFIER})
    assert not device_registry.async_get_device({(DOMAIN, old_device_id)})
    assert not entity_registry.async_get_entity_id(
        DOMAIN, "camera", old_entity_unique_id
    )

async def test_setup_camera_new_data_error(hass: HomeAssistant) -> None:
    """Test a data refresh that fails."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)
    assert hass.states.get(TEST_CAMERA_ENTITY_ID)
    client.async_get_cameras = AsyncMock(side_effect=MotionEyeClientError)
    async_fire_time_changed(hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL)
    await hass.async_block_till_done()
    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert entity_state.state == "unavailable"

async def test_setup_camera_new_data_without_streaming(hass: HomeAssistant) -> None:
    """Test a data refresh without streaming."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)
    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert entity_state.state == "streaming"

    cameras = copy.deepcopy(TEST_CAMERAS)
    cameras[KEY_CAMERAS][0][KEY_VIDEO_STREAMING] = False
    client.async_get_cameras = AsyncMock(return_value=cameras)
    async_fire_time_changed(hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL)
    await hass.async_block_till_done()
    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert entity_state.state == "unavailable"

async def test_unload_camera(hass: HomeAssistant) -> None:
    """Test unloading camera."""
    client = create_mock_motioneye_client()
    entry = await setup_mock_motioneye_config_entry(hass, client=client)
    assert hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert not client.async_client_close.called
    await hass.config_entries.async_unload(entry.entry_id)
    assert client.async_client_close.called

async def test_get_still_image_from_camera(
    aiohttp_server: Any, hass: HomeAssistant
) -> None:
    """Test getting a still image."""

    image_handler = Mock(return_value="")

    app = web.Application()
    app.add_routes(
        [
            web.get(
                "/foo",
                image_handler,
            )
        ]
    )

    server = await aiohttp_server(app)
    client = create_mock_motioneye_client()
    client.get_camera_snapshot_url = Mock(
        return_value=f"http://127.0.0.1:{server.port}/foo"
    )
    config_entry = create_mock_motioneye_config_entry(
        hass,
        data={
            CONF_URL: f"http://127.0.0.1:{server.port}",
            CONF_SURVEILLANCE_USERNAME: TEST_SURVEILLANCE_USERNAME,
        },
    )

    await setup_mock_motioneye_config_entry(
        hass, config_entry=config_entry, client=client
    )
    await hass.async_block_till_done()

    # It won't actually get a stream from the dummy handler, so just catch
    # the expected exception, then verify the right handler was called.
    with pytest.raises(HomeAssistantError):
        await async_get_image(hass, TEST_CAMERA_ENTITY_ID, timeout=1)
    assert image_handler.called

async def test_get_stream_from_camera(aiohttp_server: Any, hass: HomeAssistant) -> None:
    """Test getting a stream."""

    stream_handler = Mock(return_value="")
    app = web.Application()
    app.add_routes([web.get("/", stream_handler)])
    stream_server = await aiohttp_server(app)

    client = create_mock_motioneye_client()
    client.get_camera_stream_url = Mock(
        return_value=f"http://127.0.0.1:{stream_server.port}/"
    )
    config_entry = create_mock_motioneye_config_entry(
        hass,
        data={
            CONF_URL: f"http://127.0.0.1:{stream_server.port}",
            # The port won't be used as the client is a mock.
            CONF_SURVEILLANCE_USERNAME: TEST_SURVEILLANCE_USERNAME,
        },
    )
    cameras = copy.deepcopy(TEST_CAMERAS)
    client.async_get_cameras = AsyncMock(return_value=cameras)
    await setup_mock_motioneye_config_entry(
        hass, config_entry=config_entry, client=client
    )
    await hass.async_block_till_done()

    # It won't actually get a stream from the dummy handler, so just catch
    # the expected exception, then verify the right handler was called.
    with pytest.raises(HTTPBadGateway):
        await async_get_mjpeg_stream(
            hass, cast(web.Request, None), TEST_CAMERA_ENTITY_ID
        )
    assert stream_handler.called

async def test_state_attributes(hass: HomeAssistant) -> None:
    """Test state attributes are set correctly."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert entity_state.attributes.get("brand") == MOTIONEYE_MANUFACTURER
    assert entity_state.attributes.get("motion_detection")

    cameras = copy.deepcopy(TEST_CAMERAS)
    cameras[KEY_CAMERAS][0][KEY_MOTION_DETECTION] = False
    client.async_get_cameras = AsyncMock(return_value=cameras)
    async_fire_time_changed(hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL)
    await hass.async_block_till_done()

    entity_state = hass.states.get(TEST_CAMERA_ENTITY_ID)
    assert entity_state
    assert not entity_state.attributes.get("motion_detection")

async def test_device_info(hass: HomeAssistant) -> None:
    """Verify device information includes expected details."""
    entry = await setup_mock_motioneye_config_entry(hass)

    device_identifier = get_motioneye_device_identifier(entry.entry_id, TEST_CAMERA_ID)
    device_registry = dr.async_get(hass)

    device = device_registry.async_get_device({device_identifier})
    assert device
    assert device.config_entries == {TEST_CONFIG_ENTRY_ID}
    assert device.identifiers == {device_identifier}
    assert device.manufacturer == MOTIONEYE_MANUFACTURER
    assert device.model == MOTIONEYE_MANUFACTURER
    assert device.name == TEST_CAMERA_NAME

    entity_registry = er.async_get(hass)
    entities_from_device = [
        entry.entity_id
        for entry in er.async_entries_for_device(entity_registry, device.id)
    ]
    assert TEST_CAMERA_ENTITY_ID in entities_from_device

async def test_camera_option_stream_url_template(
    aiohttp_server: Any, hass: HomeAssistant
) -> None:
    """Verify camera with a stream URL template option."""
    client = create_mock_motioneye_client()

    stream_handler = Mock(return_value="")
    app = web.Application()
    app.add_routes([web.get(f"/{TEST_CAMERA_NAME}/{TEST_CAMERA_ID}", stream_handler)])
    stream_server = await aiohttp_server(app)

    client = create_mock_motioneye_client()

    config_entry = create_mock_motioneye_config_entry(
        hass,
        data={
            CONF_URL: f"http://127.0.0.1:{stream_server.port}",
            # The port won't be used as the client is a mock.
            CONF_SURVEILLANCE_USERNAME: TEST_SURVEILLANCE_USERNAME,
        },
        options={
            CONF_STREAM_URL_TEMPLATE: (
                f"http://127.0.0.1:{stream_server.port}/" "{{ name }}/{{ id }}"
            )
        },
    )

    await setup_mock_motioneye_config_entry(
        hass, config_entry=config_entry, client=client
    )
    await hass.async_block_till_done()

    # It won't actually get a stream from the dummy handler, so just catch
    # the expected exception, then verify the right handler was called.
    with pytest.raises(HTTPBadGateway):
        await async_get_mjpeg_stream(hass, Mock(), TEST_CAMERA_ENTITY_ID)
    assert stream_handler.called
    assert not client.get_camera_stream_url.called

async def test_get_stream_from_camera_with_broken_host(
    aiohttp_server: Any, hass: HomeAssistant
) -> None:
    """Test getting a stream with a broken URL (no host)."""

    client = create_mock_motioneye_client()
    config_entry = create_mock_motioneye_config_entry(hass, data={CONF_URL: "http://"})
    client.get_camera_stream_url = Mock(side_effect=MotionEyeClientURLParseError)

    await setup_mock_motioneye_config_entry(
        hass, config_entry=config_entry, client=client
    )
    await hass.async_block_till_done()
    with pytest.raises(HTTPBadGateway):
        await async_get_mjpeg_stream(hass, Mock(), TEST_CAMERA_ENTITY_ID)

async def test_set_text_overlay_bad_extra_key(hass: HomeAssistant) -> None:
    """Test text overlay with incorrect input data."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID, "extra_key": "foo"}
    with pytest.raises(vol.error.MultipleInvalid):
        await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)

async def test_set_text_overlay_bad_entity_identifier(hass: HomeAssistant) -> None:
    """Test text overlay with bad entity identifier."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {
        ATTR_ENTITY_ID: "some random string",
        KEY_TEXT_OVERLAY_LEFT: KEY_TEXT_OVERLAY_TIMESTAMP,
    }

    client.reset_mock()
    with pytest.raises(vol.error.MultipleInvalid):
        await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
        await hass.async_block_till_done()

async def test_set_text_overlay_bad_empty(hass: HomeAssistant) -> None:
    """Test text overlay with incorrect input data."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)
    with pytest.raises(vol.error.MultipleInvalid):
        await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, {})
        await hass.async_block_till_done()

async def test_set_text_overlay_bad_no_left_or_right(hass: HomeAssistant) -> None:
    """Test text overlay with incorrect input data."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID}
    with pytest.raises(vol.error.MultipleInvalid):
        await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
        await hass.async_block_till_done()

async def test_set_text_overlay_good(hass: HomeAssistant) -> None:
    """Test a working text overlay."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    custom_left_text = "one\ntwo\nthree"
    custom_right_text = "four\nfive\nsix"
    data = {
        ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID,
        KEY_TEXT_OVERLAY_LEFT: KEY_TEXT_OVERLAY_CUSTOM_TEXT,
        KEY_TEXT_OVERLAY_RIGHT: KEY_TEXT_OVERLAY_CUSTOM_TEXT,
        KEY_TEXT_OVERLAY_CUSTOM_TEXT_LEFT: custom_left_text,
        KEY_TEXT_OVERLAY_CUSTOM_TEXT_RIGHT: custom_right_text,
    }
    client.async_get_camera = AsyncMock(return_value=copy.deepcopy(TEST_CAMERA))

    await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
    await hass.async_block_till_done()
    assert client.async_get_camera.called

    expected_camera = copy.deepcopy(TEST_CAMERA)
    expected_camera[KEY_TEXT_OVERLAY_LEFT] = KEY_TEXT_OVERLAY_CUSTOM_TEXT
    expected_camera[KEY_TEXT_OVERLAY_RIGHT] = KEY_TEXT_OVERLAY_CUSTOM_TEXT
    expected_camera[KEY_TEXT_OVERLAY_CUSTOM_TEXT_LEFT] = "one\\ntwo\\nthree"
    expected_camera[KEY_TEXT_OVERLAY_CUSTOM_TEXT_RIGHT] = "four\\nfive\\nsix"
    assert client.async_set_camera.call_args == call(TEST_CAMERA_ID, expected_camera)

async def test_set_text_overlay_good_entity_id(hass: HomeAssistant) -> None:
    """Test a working text overlay with entity_id."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {
        ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID,
        KEY_TEXT_OVERLAY_LEFT: KEY_TEXT_OVERLAY_TIMESTAMP,
    }
    client.async_get_camera = AsyncMock(return_value=copy.deepcopy(TEST_CAMERA))
    await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
    await hass.async_block_till_done()
    assert client.async_get_camera.called

    expected_camera = copy.deepcopy(TEST_CAMERA)
    expected_camera[KEY_TEXT_OVERLAY_LEFT] = KEY_TEXT_OVERLAY_TIMESTAMP
    assert client.async_set_camera.call_args == call(TEST_CAMERA_ID, expected_camera)

async def test_set_text_overlay_bad_device(hass: HomeAssistant) -> None:
    """Test a working text overlay."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {
        ATTR_DEVICE_ID: "not a device",
        KEY_TEXT_OVERLAY_LEFT: KEY_TEXT_OVERLAY_TIMESTAMP,
    }
    client.reset_mock()
    client.async_get_camera = AsyncMock(return_value=copy.deepcopy(TEST_CAMERA))
    await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
    await hass.async_block_till_done()
    assert not client.async_get_camera.called
    assert not client.async_set_camera.called

async def test_set_text_overlay_no_such_camera(hass: HomeAssistant) -> None:
    """Test a working text overlay."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {
        ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID,
        KEY_TEXT_OVERLAY_LEFT: KEY_TEXT_OVERLAY_TIMESTAMP,
    }
    client.reset_mock()
    client.async_get_camera = AsyncMock(return_value={})
    await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
    await hass.async_block_till_done()
    assert not client.async_set_camera.called

async def test_request_action(hass: HomeAssistant) -> None:
    """Test requesting an action."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {
        ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID,
        CONF_ACTION: "foo",
    }
    await hass.services.async_call(DOMAIN, SERVICE_ACTION, data)
    await hass.async_block_till_done()
    assert client.async_action.call_args == call(TEST_CAMERA_ID, data[CONF_ACTION])

async def test_request_snapshot(hass: HomeAssistant) -> None:
    """Test requesting a snapshot."""
    client = create_mock_motioneye_client()
    await setup_mock_motioneye_config_entry(hass, client=client)

    data = {ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID}

    await hass.services.async_call(DOMAIN, SERVICE_SNAPSHOT, data)
    await hass.async_block_till_done()
    assert client.async_action.call_args == call(TEST_CAMERA_ID, "snapshot")


text:
import pytz
from django.template.loader import render_to_string
from dimagi.utils.decorators.memoized import memoized
# For translations
from django.utils.translation import ugettext_noop
from corehq.apps.reports.util import (
    DEFAULT_CSS_FIELD_CLASS_REPORT_FILTER,
    DEFAULT_CSS_LABEL_CLASS_REPORT_FILTER,
)

class BaseReportFilter(object):
    """
        For filtering the results of CommCare HQ Reports.

        slug => the parameter you get back from the request
        template => the template to render this filter
        label => the filter's label
    """
    slug = None
    template = None
    label = None
    css_class = "span4"
    help_text = None
    is_cacheable = False
    help_style_bubble = False

    def __init__(self, request, domain=None, timezone=pytz.utc, parent_report=None,
                 css_label=None, css_field=None):
        self.domain = domain
        if self.slug is None:
            raise NotImplementedError("slug is required")
        if self.template is None:
            raise NotImplementedError("a template must be specified")
        if self.label is None:
            raise NotImplementedError("label is required")
        self.request = request
        self.timezone = timezone
        self.parent_report = parent_report
        self.css_label = css_label or DEFAULT_CSS_LABEL_CLASS_REPORT_FILTER
        self.css_field = css_field or DEFAULT_CSS_FIELD_CLASS_REPORT_FILTER
        self.context = {}

    @property
    def is_disabled(self):
        """
            If necessary, determine whether to show this filter based on the results of surrounding (related) filters.
        """
        return False

    @property
    def filter_context(self):
        """
            Context for rendering the filter.
            Should return a dict.
        """
        raise NotImplementedError("filter_context must be overridden")

    def render(self):
        if self.is_disabled:
            return ""
        self.context.update({
            'slug': self.slug,
            'label': self.label,
            'css_id': 'report_filter_%s' % self.slug,
            'css_class': self.css_class,
            'css_label_class': self.css_label,
            'css_field_class': self.css_field,
            'help_text': self.help_text,
            'help_style_bubble': self.help_style_bubble,
        })
        filter_context = self.filter_context
        if not (filter_context, dict):
            raise ValueError("filter_context must return a dict.")
        self.context.update(filter_context)
        return render_to_string(self.template, self.context)

    @classmethod
    def get_value(cls, request, domain):
        return request.GET.get(cls.slug)

class CheckboxFilter(BaseReportFilter):
    slug = "checkbox"
    label = "hello"
    template = "reports/filters/checkbox.html"

    @property
    def filter_context(self):
        return {'checked': self.request.GET.get(self.slug, False)}

    @classmethod
    def get_value(cls, request, domain):
        val = request.GET.get(cls.slug, False)
        if not val:
            return False
        else:
            return val is True or val == 'True' or val == 'true'

class BaseSingleOptionFilter(BaseReportFilter):
    """
        Displays a select field.
    """
    template = "reports/filters/single_option.html"
    default_text = ugettext_noop("Filter by...")
    placeholder = ''
    is_paginated = False
    pagination_source = None  # url for paginated data
    async_handler = None
    async_action = None

    @property
    def options(self):
        """
            Options should return a list of tuples formatted like:
            [('value', 'display_text')]
        """
        raise NotImplementedError("options must be overridden")

    @property
    @memoized
    def selected(self):
        return self.get_value(self.request, self.domain) or ""

    @property
    def filter_context(self):
        options = []
        if not self.is_paginated:
            options = self.options
            if not isinstance(options, list) and not isinstance(options[0], tuple) and not len(options[0]) == 2:
                raise ValueError("options must return a list of option tuples [('value','text')].")
            options = [dict(val=o[0], text=o[1]) for o in self.options]
        return {
            'select': {
                'options': options,
                'default_text': self.default_text,
                'selected': self.selected,
                'placeholder': self.placeholder,
            },
            'pagination': {
                'enabled': self.is_paginated,
                'url': self.pagination_source,
                'handler': self.async_handler.slug if self.async_handler else '',
                'action': self.async_action,
            },
        }

    @classmethod
    def get_value(cls, request, domain):
        value = super(BaseSingleOptionFilter, cls).get_value(request, domain)
        if cls.is_paginated:
            return value if value else None
        if isinstance(cls, cls):
            instance = cls
        else:
            instance = cls(request, domain)
        valid_options = [op[0] for op in instance.options]
        if value in valid_options:
            return value
        return None

class BaseMultipleOptionFilter(BaseSingleOptionFilter):
    """
        Displays a multiselect field.
    """
    template = "reports/filters/multi_option.html"
    default_options = [] # specify a list

    @classmethod
    def get_value(cls, request, domain):
        return request.GET.getlist(cls.slug)

    @property
    @memoized
    def selected(self):
        return self.get_value(self.request, self.domain) or self.default_options

class BaseDrilldownOptionFilter(BaseReportFilter):
    """
        Displays multiple select fields that display in a hierarchial order and drill down to one value.
        Ex:
        Select Application: <applications>
        ---> Select Module: <module options based on selected application (if selected)>
        ---------> Select Form: <form_options based on selected module (if selected)>

        use_only_last => Whether to indicate to the user that they must move all the way through the hierarchy
            and select a final option before the result is usable. For example, you can't just pick an application
            and show all of its forms, you must select exactly one form.
    """
    template = "reports/filters/drilldown_options.html"
    use_only_last = False
    drilldown_empty_text = ugettext_noop("No Data Available")
    is_cacheable = True

    @property
    def drilldown_map(self):
        """
            Should return a structure like:
            [{
                'val': <value>,
                'text': <text>,
                'next': [
                        {
                            'val': <value>,
                            'text' <text>,
                            'next': [...]
                        },
                        {...}
                    ]
            },
            {...}
            ]
        """
        raise NotImplementedError("drilldown_map must be implemented")

    @classmethod
    def get_labels(cls):
        """
            Returns a list of ('label', default text/caption', 'slug') tuples.
            ex: [
                ('Application', 'Select Application...', 'app'),
                ('Module', 'Select Module...', 'module'),
                ('Form', 'Select Form...', 'form')
            ]
        """
        raise NotImplementedError("get_labels must be implemented")

    @property
    def selected(self):
        selected = []
        for label in self.rendered_labels:
            value = self._get_label_value(self.request, label)
            if not value['value']:
                break
            selected.append(value['value'])
        return selected

    @property
    def rendered_labels(self):
        """
            Modify the default set of labels here.
        """
        return self.get_labels()

    @property
    def filter_context(self):
        controls = []
        for level, label in enumerate(self.rendered_labels):
            controls.append({
                'label': label[0],
                'default_text': label[1],
                'slug': label[2],
                'level': level,
            })

        drilldown_map = list(self.drilldown_map)
        return {
            'option_map': drilldown_map,
            'controls': controls,
            'selected': self.selected,
            'use_last': self.use_only_last,
            'notifications': self.final_notifications,
            'empty_text': self.drilldown_empty_text,
            'is_empty': not drilldown_map,
        }

    @property
    def final_notifications(self):
        """
            Not required, but this can be used to display a message when the drill down is complete
            that's based on the value of the final drill down option.
            ex: {'xmlns_of_form': 'This form does not have a unique id.'}
        """
        return {}

    @property
    @memoized
    def GET_values(self):
        values = []
        for label in self.rendered_labels:
            value = self._get_label_value(self.request, label)
            if not value['value']:
                break
            values.append(value)
        return values

    def _map_structure(self, val, text, next=None):
        if next is None:
            next = []
        return {
            'val': val,
            'text': text,
            'next': next,
            }

    @property
    def shared_pagination_GET_params(self):
        return [dict(name='%s_%s' % (self.slug, val['slug']), value=val['value']) for val in self.GET_values]

    @classmethod
    def _get_label_value(cls, request, label):
        slug = str(label[2])
        val = request.GET.get('%s_%s' % (cls.slug, slug))
        return {
            'slug': slug,
            'value': val,
        }

    @classmethod
    def get_value(cls, request, domain):
        instance = cls(request, domain)
        return instance.GET_values, instance

class BaseTagsFilter(BaseReportFilter):
    template = "reports/filters/base_tags_filter.html"
    tags = []

    @property
    def selected(self):
        return self.get_value(self.request, self.domain) or ''

    @property
    def filter_context(self):
        return {
            'tags': self.tags,
            'selected': self.selected,
            'placeholder': self.placeholder,
        }


text:
using System;
using NUnit.Framework;

namespace DotSpatial.Controls.Tests
{
    [TestFixture]
    class LayoutMapTests
    {
        [Test]
        public void CtorExceptions()
        {
            Assert.Throws<ArgumentNullException>(() => new LayoutMap(null));
        }
    }
}