text:
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.*;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.*;

public class Agenda implements Raiz{

public Vector relaciones;
protected int dni;
protected String nombre;
public int telefono;
public String fnac;
protected Vector $v_Contactos = new Vector();

public int getDni()
{ return dni; }

public void setDni(int x)
{ dni = x; }

public String getNombre()
{ return nombre; }

public void setNombre(String x)
{ nombre = x; }

public int getTelefono()
{ return telefono; }

public void setTelefono(int x)
{ telefono = x; }

public String getFnac()
{ return fnac; }

public void setFnac(String x)
{ fnac = x; }

public Vector get$v_Contactos()
{ return $v_Contactos; }

public void set$v_Contactos(Vector x)
{ $v_Contactos = x; }

public Agenda () {}
public String getClassName(){ return "Agenda";}

 public Vector getvAtb(){
   Vector salida = new Vector();
   salida.addElement("ident");  salida.addElement("dni");
  salida.addElement("nombre");
  salida.addElement("telefono");
  salida.addElement("fnac");
  salida.addElement("$v_Contactos");
 return salida;}

 public Vector getRelaciones1a1() {
   Vector salida = new Vector();
   this.relaciones = salida;
   return salida;
 }
 public Vector getRelaciones1an() {
   Vector salida = new Vector();
   Contacto xContacto= new Contacto();
   salida.add( (Raiz) xContacto);
   this.relaciones = salida;
   return salida;
 }
public Raiz getElementoRelacionado(String n){
  for (int i=0;i<this.relaciones.size();i++){
   String nom = ( (Raiz)this.relaciones.get(i)).getClassName();
   if(nom.compareTo(n)==0)
     return (Raiz)this.relaciones.get(i);
   }
  return null;
 }
public boolean buscarContacto(String n) {
boolean x = true;
return x;
}
public void ordenarPor(String t) {

}
  /**
    * Método que lee de un xml y carga los elementos del XML en un
    * vector de vectores
    * @return Vector que contiene los elementos leidos del xml.
    */
   public Vector leerXML() {
    Vector res = new Vector();
    try {
      DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().
          newDocumentBuilder();
      Document doc = docBuilder.parse(new File(VentanaPrincipal.ruta +"xml"+File.separator + this.getClassName() +
                                               ".xml"));
      tratarNodoXML(res, doc);
    }
    catch (Exception ex) {}
    //System.out.println(res);
    return res;
  }

  /**
   * Método que lee recursivamente del xml.
   * @param res Vector que se va cargando de los elementos al leer el xml.
   * @param nodo Node que se lee en cada llamada al método
   */
  public void tratarNodoXML(Vector res, Node nodo) {
    switch (nodo.getNodeType()) {

      case Node.DOCUMENT_NODE:
        Document doc = (Document) nodo;
        tratarNodoXML(res, doc.getDocumentElement());
        break;

      case Node.ELEMENT_NODE:
        NamedNodeMap ats = nodo.getAttributes();
        NodeList hijos = nodo.getChildNodes();
        if (nodo.getNodeName() == this.getClassName()) {
          Vector aux = new Vector();
          for (int i = 0; i < ats.getLength(); i++)
             if (ats.item(i).getNodeName() == "enlace") {
               tratarNodoXML(aux, ats.item(i));
               aux.add(ats.item(i).getNodeValue());
             }
          for (int i = 0; i < hijos.getLength(); i++)
            tratarNodoXML(aux, hijos.item(i));
          res.add(aux);
        }
        else {
          for (int i = 0; i < hijos.getLength(); i++)
            tratarNodoXML(res, hijos.item(i));
          for (int i = 0; i < ats.getLength(); i++)
            tratarNodoXML(res, ats.item(i));
          if ( (ats.getLength() == 0) && (hijos.getLength() == 0))
            res.add("");
        }
        break;

      case Node.TEXT_NODE:
        String texto = nodo.getNodeValue().trim();
        if (!texto.equals("")) {
          res.add(texto);
        }
        break;
    }
  }

 /**
  * Método que compone un archivo con formato xml.
  * @param vObj Vector con los datos del cual se forma el xml.
  * @throws FactoryConfigurationError excepción si no se puede crear el xml.
  * @throws ParserConfigurationException excepción si no se puede crear el xml.
  */
 public void crearXML(Vector vObj) throws
     FactoryConfigurationError, ParserConfigurationException {

   DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().
       newDocumentBuilder();
   Document doc = docBuilder.newDocument();

   Vector vAtb = new Vector();
   vAtb = getvAtb();
   Element root = doc.createElement("raiz");
   if (vObj.size() > 0) {
     for (int j = 0; j < vObj.size(); j++) {
       Vector vDatos = new Vector( (Vector) vObj.get(j));
       Element tagClase = doc.createElement(getClassName());
       tagClase.setAttribute("enlace",(String) vDatos.get(0));//añadimos un atributo al xml con el primer elemento del vector de datos
       //Creamos todos los hijos del nodo raíz
       for (int i = 0; i < vAtb.size(); i++) {
         if ( (! ( ( (String) vAtb.get(i)).substring(0, 3).compareTo("$v_") ==
                  0)) &&
             (! ( ( (String) vAtb.get(i)).substring(0, 3).compareTo("$r_") ==
                 0))) {

           Element tagAtb = doc.createElement( ( (String) vAtb.get(i)));
           Text texto = doc.createTextNode( (String) vDatos.get(i+1));
           tagAtb.appendChild(texto);
           tagClase.appendChild(tagAtb);
           root.appendChild(tagClase);
         }
       }
     }
   }
   else {
     Element tagClase = doc.createElement(getClassName());
     tagClase.setAttribute("enlace","");
     //Generamos un nuevo id para el objeto de la clase
    Date d=new Date();
    String identGenerado=getClassName().toString().substring(0,2)+"_"+ d.getTime();
    Element tagident = doc.createElement("ident");
    Text texident = doc.createTextNode( identGenerado);
    tagident.appendChild(texident);
    tagClase.appendChild(tagident);
    root.appendChild(tagClase);

       for (int i = 1; i < vAtb.size(); i++) {
       if ( (! ( ( (String) vAtb.get(i)).substring(0, 3).compareTo("$v_") == 0)) &&
           (! ( ( (String) vAtb.get(i)).substring(0, 3).compareTo("$r_") == 0))) {
         Element tagAtb = doc.createElement( ( (String) vAtb.get(i)));
         tagClase.appendChild(tagAtb);
         root.appendChild(tagClase);
       }
     }
   }
   doc.appendChild(root);

   Source source = new DOMSource(doc);

   // creación del fichero salida
   File fich = new File(VentanaPrincipal.ruta+"xml"+File.separator + getClassName() + ".xml");
   Result resultado = new StreamResult(fich);

   TransformerFactory factory = TransformerFactory.newInstance();
   Transformer transformer = null;
   try {
     transformer = factory.newTransformer();
   }
   catch (TransformerConfigurationException ex1) {
   }
   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
   transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
   try {
     transformer.transform(source, resultado);
   }
   catch (TransformerException ex2) { ex2.printStackTrace();
   }
 }

  /**
   * Método que lee los elementos de un xml y busca un elemento cuya clave
   * sea igual a la que se le pasa como parámetro.
   * @param busqueda String identificador que se busca en el xml.
   * @return Vector que contiene los elementos encontrados del xml.
   */
  public Vector buscarenXML(String busqueda) {
    Vector res = new Vector();
    try {
      DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().
          newDocumentBuilder();
      Document doc = docBuilder.parse(new File(VentanaPrincipal.ruta+ "xml"+File.separator + this.getClassName() +
                                               ".xml"));
      buscarNodoXML(res, doc, busqueda);
    }
    catch (Exception ex) {}
    //System.out.println(res);
    return res;
  }
  /**
   * Método que recorre recursivamente los elementos del xml.
   * @param res Vector que se va cargando de los elementos al leer el xml.
   * @param nodo Node que se lee en cada llamada al método.
   * @param bus String identificador que se busca en el xml.
   */
  public void buscarNodoXML(Vector res, Node nodo, String bus) {
    switch (nodo.getNodeType()) {
      case Node.DOCUMENT_NODE:
        Document doc = (Document) nodo;
        buscarNodoXML(res, doc.getDocumentElement(), bus);
        break;

      case Node.ELEMENT_NODE:
        NamedNodeMap ats = nodo.getAttributes();
        NodeList hijos = nodo.getChildNodes();
        Vector aux = new Vector();
        if (nodo.getNodeName().compareTo(this.getClassName()) == 0) {
          if (ats.getNamedItem("enlace").getNodeValue().compareTo(bus) == 0){
              aux.add(ats.item(0).getNodeValue());
            for (int i = 0; i < hijos.getLength(); i++)
              buscarNodoXML(aux, hijos.item(i), bus);
            res.add(aux);
          }
        }
        else {
        for (int i = 0; i < hijos.getLength(); i++)
          buscarNodoXML(res, hijos.item(i),bus);
        if ( (ats.getLength() == 0) && (hijos.getLength() == 0))
          res.add("");
        }
        break;

      case Node.TEXT_NODE:
        String texto = nodo.getNodeValue().trim();
        if (!texto.equals("")) {
          res.add(texto);
        }
        break;
    }
  }

}


text:
process.env.TEST = 'true';

var expect = require('chai').expect;

// Make sure import is run before export
require('./geojson-import.js');

var geojson = require('../lib/geojson'),
    Shape = require('../models/Shape'),
    gj = require('./helpers/geojson');

var shapeCS;

describe('GeoJSON', function() {

describe('#export()', function() {
    this.timeout(6000);

    it('should export a point', function(done) {
        geojson.export({
            period: gj.point.period, type: 1
        }).then(function(json) {
            var shape = json.features[0];
            expect(shape.geometry).to.deep.equal(gj.point.features[0].geometry);
            expect(shape.properties.data.type).to.equal('country');
            expect(shape.properties.data.name_sm).to.equal('ln');
        }).then(done,done);
    });

    it('should export a line', function(done) {
        geojson.export({
            period: gj.line.period, type: 1
        }).then(function(json) {
            var shape = json.features[0];
            expect(shape.geometry).to.deep.equal(gj.line.features[0].geometry);
            expect(shape.properties.data.name).to.equal('line');
        }).then(done,done);
    });

    it('should export a multiline', function(done) {
        geojson.export({
            period: gj.multiline.period, type: 1
        }).then(function(json) {
            var shape = json.features[0];
            expect(shape.geometry).to.deep.equal(gj.multiline.features[0].geometry);
            expect(shape.properties.data.name).to.equal('multi line');
        }).then(done,done);
    });

    it('should export a polygon', function(done) {
        geojson.export({
            period: gj.polygon.period, type: 1
        }).then(function(json) {
            var shape = json.features[0];
            expect(shape.geometry).to.deep.equal(gj.polygon.features[0].geometry);
            expect(shape.properties.data.name).to.equal('poly');
        }).then(done,done);
    });

    it('should export a multipolygon', function(done) {
        geojson.export({
            period: gj.multiPolygon.period,
            type: 1
        }).then(function(json) {
            var shape = json.features[0];
            expect(shape.geometry).to.deep.equal(gj.multiPolygon.features[0].geometry);
            expect(shape.properties.data.name).to.equal('multi poly');
        }).then(done,done);
    });

    it('should export using year', function(done) {
        geojson.export({
            year: 1999,
            type: 1
        }).then(function(json) {
            var shape = json.features[0];
            expect(shape.geometry).to.deep.equal(gj.multiPolygon.features[0].geometry);
            expect(shape.properties.data.name).to.equal('multi poly');
        }).then(done,done);
    });

});

});

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Usnea barbata var. cornuta Flot.

### Remarks
null


text:
ActionScriptMVC
===============


text:
/**
 * # ItemCheckbox-test.js
 *
 * This class tests that the ItemCheckbox renders correctly under
 * numerous conditions
 *
 * *Note:* if you want to understand the structures here, add a
 * ```console.log``` and then ```npm test```.
 *
 */
'use strict'

import 'react-native'
import React from 'react'

import ItemCheckbox from '../ItemCheckbox'

import ReactTestUtils from 'react-addons-test-utils'
const renderer = ReactTestUtils.createRenderer()

/**
 * ## Test
 */
describe('ItemCheckbox', () => {
  /**
   * ### if not disabled and checked, it should display check-square and text
   * change the props and call ```testItemCheckbox``` to validate
   */
  it('if not disabled and checked, it should display check-square and text', () => {
    const props = {
      checked: true,
      text: 'TextShouldDisplay',
      disabled: false
    }
    renderer.render(<ItemCheckbox {...props} />)
    const tree = renderer.getRenderOutput()
    expect(tree).toMatchSnapshot()
  })

  /**
   * ### if not disabled and not checked, it should display square-o and text
   * change the props and call ```testItemCheckbox``` to validate
   */
  it('if not disabled and not checked, it should display square-o and text', () => {
    const props = {
      checked: false,
      text: 'TextShouldDisplay',
      disabled: false
    }
    renderer.render(<ItemCheckbox {...props} />)
    const tree = renderer.getRenderOutput()
    expect(tree).toMatchSnapshot()
  })

  /**
   * ### if disabled and checked, it should display check-square and text
   * change the props and call ```testItemCheckbox``` to validate
   */
  it('if disabled and checked, it should display check-square and text', () => {
    const props = {
      checked: true,
      text: 'TextShouldDisplay',
      disabled: true
    }
    renderer.render(<ItemCheckbox {...props} />)
    const tree = renderer.getRenderOutput()
    expect(tree).toMatchSnapshot()
  })

  /**
   * ### if disabled and not checked, it should display square-o and text
   * change the props and call ```testItemCheckbox``` to validate
   */
  it('if disabled and not checked, it should display square-o and text', () => {
    const props = {
      checked: false,
      text: 'TextShouldDisplay',
      disabled: true
    }
    renderer.render(<ItemCheckbox {...props} />)
    const tree = renderer.getRenderOutput()
    expect(tree).toMatchSnapshot()
  })
})// describe ItemCheckbox


text:
import gameApi from '../../../lichess/game';
import gameStatus from '../../../lichess/status';
import helper from '../../helper';
import throttle from 'lodash/function/throttle';
import i18n from '../../../i18n';
import socket from '../../../socket';
import { getPGN } from '../roundXhr';
import { handleXhrError } from '../../../utils';
import m from 'mithril';

export default {
  standard: function(ctrl, condition, icon, hint, socketMsg) {
    return condition(ctrl.data) ? m('button', {
      className: socketMsg,
      'data-icon': icon,
      config: helper.ontouch(function() { socket.send(socketMsg); })
    }, i18n(hint)) : null;
  },
  flipBoard: function(ctrl) {
    return m('button', {
      'data-icon': 'B',
      className: ctrl.vm.flip ? 'flipped' : '',
      config: helper.ontouch(ctrl.flip)
    }, i18n('flipBoard'));
  },
  shareLink: function(ctrl) {
    return m('button', {
      config: helper.ontouch(function() {
        window.plugins.socialsharing.share(null, null, null, gameApi.publicUrl(ctrl.data));
      })
    }, [m('span.fa.fa-link'), i18n('shareGameURL')]);
  },
  sharePGN: function(ctrl) {
    function handler() {
      getPGN(ctrl.data.game.id).then(function(PGN) {
        window.plugins.socialsharing.share(PGN);
      }, err => handleXhrError(err));
    }
    return (
      <button config={helper.ontouch(handler)}>

        {i18n('sharePGN')}
      </button>
    );
  },
  submitMove: function(ctrl) {
    return (

        <button className="binary_choice" data-icon="E"
          config={helper.ontouch(ctrl.submitMove.bind(undefined, true))}
        >
          Submit move
        </button>
        <button className="binary_choice" data-icon="L"
          config={helper.ontouch(ctrl.submitMove.bind(undefined, false))}
        >
          {i18n('cancel')}
        </button>

    );
  },
  forceResign: function(ctrl) {
    return gameApi.forceResignable(ctrl.data) ?
      m('div.force_resign_zone.clearfix', [
        m('div.notice', i18n('theOtherPlayerHasLeftTheGameYouCanForceResignationOrWaitForHim')),
        m('button.binary_choice[data-icon=E]', {
          config: helper.ontouch(function() { socket.send('resign-force'); })
        }, i18n('forceResignation')),
        m('button.binary_choice[data-icon=E]', {
          config: helper.ontouch(function() { socket.send('draw-force'); })
        }, i18n('forceDraw'))
      ]) : null;
  },
  threefoldClaimDraw: function(ctrl) {
    return (ctrl.data.game.threefold) ? m('div.claim_draw_zone', [
      m('div.notice', i18n('threefoldRepetition')),
      m.trust(' '),
      m('button[data-icon=E]', {
        config: helper.ontouch(function() { socket.send('draw-claim'); })
      }, i18n('claimADraw'))
    ]) : null;
  },
  cancelDrawOffer: function(ctrl) {
    if (ctrl.data.player.offeringDraw) return m('div.negotiation', [
      m('div.notice', i18n('drawOfferSent')),
      m('button[data-icon=L]', {
        config: helper.ontouch(function() { socket.send('draw-no'); })
      }, i18n('cancel'))
    ]);
  },
  answerOpponentDrawOffer: function(ctrl) {
    if (ctrl.data.opponent.offeringDraw) return m('div.negotiation.clearfix', [
      m('div.notice', i18n('yourOpponentOffersADraw')),
      m('button.binary_choice[data-icon=E]', {
        config: helper.ontouch(function() { socket.send('draw-yes'); })
      }, i18n('accept')),
      m('button.binary_choice[data-icon=L]', {
        config: helper.ontouch(function() { socket.send('draw-no'); })
      }, i18n('decline'))
    ]);
  },
  cancelTakebackProposition: function(ctrl) {
    if (ctrl.data.player.proposingTakeback) return m('div.negotiation', [
      m('div.notice', i18n('takebackPropositionSent')),
      m('button[data-icon=L]', {
        config: helper.ontouch(function() { socket.send('takeback-no'); })
      }, i18n('cancel'))
    ]);
  },
  answerOpponentTakebackProposition: function(ctrl) {
    if (ctrl.data.opponent.proposingTakeback) return m('div.negotiation.clearfix', [
      m('div.notice', i18n('yourOpponentProposesATakeback')),
      m('button.binary_choice[data-icon=E]', {
        config: helper.ontouch(function() { socket.send('takeback-yes'); })
      }, i18n('accept')),
      m('button.binary_choice[data-icon=L]', {
        config: helper.ontouch(function() { socket.send('takeback-no'); })
      }, i18n('decline'))
    ]);
  },
  rematch: function(ctrl) {
    if ((gameStatus.finished(ctrl.data) || gameStatus.aborted(ctrl.data)) &&
      !ctrl.data.tournament && !ctrl.data.opponent.offeringRematch &&
      !ctrl.data.player.offeringRematch) {
      if (ctrl.data.opponent.onGame || ctrl.data.game.perf === 'correspondence') {
        return m('button[data-icon=B]', {
          config: helper.ontouch(function() { socket.send('rematch-yes'); })
        }, i18n('rematch'));
      } else {
        return null;
      }
    }
  },
  answerOpponentRematch: function(ctrl) {
    if (ctrl.data.opponent.offeringRematch) return m('div.negotiation.clearfix', [
      m('div.notice', i18n('yourOpponentWantsToPlayANewGameWithYou')),
      m('button.binary_choice[data-icon=E]', {
        config: helper.ontouch(function() { socket.send('rematch-yes'); })
      }, i18n('joinTheGame')),
      m('button.binary_choice[data-icon=L]', {
        config: helper.ontouch(function() { socket.send('rematch-no'); })
      }, i18n('declineInvitation'))
    ]);
  },
  cancelRematch: function(ctrl) {
    if (ctrl.data.player.offeringRematch) return m('div.negotiation', [
      m('div.notice', i18n('rematchOfferSent')),
      m('div.notice', i18n('waitingForOpponent')),
      m('button[data-icon=L]', {
        config: helper.ontouch(function() { socket.send('rematch-no'); })
      }, i18n('cancelRematchOffer'))
    ]);
  },
  moretime: function(ctrl) {
    if (gameApi.moretimeable(ctrl.data)) return m('button[data-icon=O]', {
      config: helper.ontouch(throttle(function() { socket.send('moretime'); }, 600))
    }, i18n('giveNbSeconds', 15));
  },
  backward: function(ctrl) {
    const prevPly = ctrl.vm.ply - 1;
    const enabled = ctrl.vm.ply !== prevPly && prevPly >= ctrl.firstPly();
    return m('button.game_action[data-icon=I]', {
      config: helper.ontouch(ctrl.jumpPrev, ctrl.jumpFirst),
      className: helper.classSet({
        disabled: ctrl.broken || !enabled
      })
    });
  },
  forward: function(ctrl) {
    const nextPly = ctrl.vm.ply + 1;
    const enabled = ctrl.vm.ply !== nextPly && nextPly <= ctrl.lastPly();
    return m('button.game_action[data-icon=H]', {
      config: helper.ontouch(ctrl.jumpNext, ctrl.jumpLast),
      className: helper.classSet({
        disabled: ctrl.broken || !enabled
      })
    });
  }
};


text:
ACCEPTED

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

#### Published in
Mycotaxon 33: 405 (1988)

#### Original name
Parmelia conspersa f. planilobata Gyeln.

### Remarks
null


text:
from __future__ import unicode_literals
import unittest
from collections import Iterable
from io import StringIO
import mock
import socket

from duckduckpy.core import api
from duckduckpy.core import Hook
from duckduckpy.core import query
from duckduckpy.core import secure_query
from duckduckpy.core import url_assembler
import duckduckpy.exception as exc
from duckduckpy.utils import camel_to_snake_case
from duckduckpy.utils import is_python2

class TestHook(unittest.TestCase):
    def test_non_existent_hook(self):
        self.assertTrue(Hook(1) is None)

    def test_hook_instance_returned(self):
        hook = Hook(Hook.containers[0])
        self.assertTrue(isinstance(hook, Hook))

    def test_containers_exist(self):
        self.assertTrue(isinstance(Hook.containers, Iterable))
        self.assertTrue(len(Hook.containers) > 0)

    def test_no_object_found(self):
        obj = {
            'URL': 'www.test.url.com',
            'SomeThing': 'icon',
            'Result': 20,
            'Text': 'Example of a text'}
        expected = {
            'URL': 'www.test.url.com',
            'SomeThing': 'icon',
            'Result': 20,
            'Text': 'Example of a text'}
        hook = Hook('dict')
        actual_dict = hook(obj)
        self.assertEqual(actual_dict, expected)

class TestHookExceptions(unittest.TestCase):
    def test_non_existent_hook_verbose(self):
        self.assertRaises(exc.DuckDuckDeserializeError, Hook, 1, verbose=True)

    def test_no_object_found_verbose(self):
        obj = {
            'URL': 'www.test.url.com',
            'SomeThing': 'icon',
            'Result': 20,
            'Text': 'Example of a text'}
        hook = Hook('dict', verbose=True)
        self.assertRaises(exc.DuckDuckDeserializeError, hook, obj)

class TestCamelToSnakeCase(unittest.TestCase):
    def assertConverted(self, camel_case_string, snake_case_string):
        self.assertEqual(snake_case_string,
                         camel_to_snake_case(camel_case_string))

    def test_conversion_one_word(self):
        self.assertConverted('Camel', 'camel')

    def test_conversion_two_words(self):
        self.assertConverted('CamelCase', 'camel_case')

    def test_conversion_three_words(self):
        self.assertConverted('CamelCaseToo', 'camel_case_too')

    def test_conversion_three_mixed(self):
        self.assertConverted('CamelCase_Underscore', 'camel_case__underscore')

    def test_conversion_with_numbers(self):
        self.assertConverted('Camel2CaseToo3', 'camel2_case_too3')

    def test_conversion_equal(self):
        self.assertConverted('camel_case', 'camel_case')

    def test_conversion_mixed_case(self):
        self.assertConverted('getHTTPResponseCode', 'get_http_response_code')

    def test_conversion_mixed_case_with_numbers(self):
        self.assertConverted('get2HTTPResponseCode', 'get2_http_response_code')

    def test_conversion_uppercase_one_after_another(self):
        self.assertConverted('HTTPResponseCode', 'http_response_code')

class TestURLAssembler(unittest.TestCase):
    def test_simple(self):
        expected = "/?q=test+query&format=json"
        self.assertEqual(url_assembler("test query"), expected)

    def test_cyrillic(self):
        expected = (
            "/?q=%D0%A1%D0%BB%D0%B0%D0%B2%D0%B0+%D0%"
            "A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D1%96&format=json")
        url = url_assembler('Слава Україні')
        self.assertEqual(url, expected)

    def test_no_redirect(self):
        expected = "/?q=test+query&format=json&no_redirect=1"
        url = url_assembler("test query", no_redirect=True)
        self.assertEqual(url, expected)

    def test_no_html(self):
        expected = "/?q=test+query&format=json&no_html=1"
        url = url_assembler("test query", no_html=True)
        self.assertEqual(url, expected)

    def test_skip_disambig(self):
        expected = "/?q=test+query&format=json&skip_disambig=1"
        url = url_assembler("test query", skip_disambig=True)
        self.assertEqual(url, expected)

    def test_all_options_are_on(self):
        expected = ("/?q=test+query&format=json&no_redirect=1"
                    "&no_html=1&skip_disambig=1")
        url = url_assembler("test query",
                            no_redirect=True, no_html=True, skip_disambig=True)
        self.assertEqual(url, expected)

    def test_language_region(self):
        expected = ("/?q=test+query&format=json&kl=ru-ru")
        url = url_assembler("test query", lang="ru-ru")
        self.assertEqual(url, expected)

@mock.patch('duckduckpy.core.http_client.HTTPConnection.request')
class TestQuery(unittest.TestCase):
    origin = r"""
{
  "Abstract": "",
  "AbstractSource": "Wikipedia",
  "AbstractText": "",
  "AbstractURL": "https://en.wikipedia.org/wiki/Python",
  "Answer": "",
  "AnswerType": "",
  "Definition": "",
  "DefinitionSource": "",
  "DefinitionURL": "",
  "Entity": "",
  "Heading": "Python",
  "Image": "",
  "ImageHeight": 0,
  "ImageIsLogo": 0,
  "ImageWidth": 0,
  "Infobox": {},
  "Redirect": "",
  "RelatedTopics": [
    {
      "FirstURL": "https://duckduckgo.com/Python_(programming",
      "Icon": {
        "Height": "",
        "URL": "https://duckduckgo.com/i/7eec482b.png",
        "Width": ""
      },
      "Result": "<a href=\"https://duckduckgo.com/Python_(programmin",
      "Text": "Python (programming language)A widely used general"
    },
    {
      "FirstURL": "https://duckduckgo.com/Monty_Python",
      "Icon": {
        "Height": "",
        "URL": "https://duckduckgo.com/i/4eec9e83.jpg",
        "Width": ""
      },
      "Result": "Mo",
      "Text": "Monty PythonA British surreal comedy group who"
    },
    {
      "Name": "Ancient Greece",
      "Topics": [
        {
          "FirstURL": "https://duckduckgo.com/Python_(programming",
          "Icon": {
            "Height": "",
            "URL": "https://duckduckgo.com/i/7eec482b.png",
            "Width": ""
          },
          "Result": "<a href=\"https://duckduckgo.com/Python_(programmin",
          "Text": "Python (programming language)A widely used general"
        },
        {
          "FirstURL": "https://duckduckgo.com/Monty_Python",
          "Icon": {
            "Height": "",
            "URL": "https://duckduckgo.com/i/4eec9e83.jpg",
            "Width": ""
          },
          "Result": "Mo",
          "Text": "Monty PythonA British surreal comedy group who"
        }
      ]
    }
  ],
  "Results": [],
  "Type": "D",
  "meta": {
    "attribution": null,
    "blockgroup": null,
    "created_date": null,
    "description": "Wikipedia",
    "designer": null,
    "dev_date": null,
    "dev_milestone": "live",
    "developer": [
      {
        "name": "DDG Team",
        "type": "ddg",
        "url": "http://www.duckduckhack.com"
      }
    ],
    "example_query": "nikola tesla",
    "id": "wikipedia_fathead",
    "is_stackexchange": null,
    "js_callback_name": "wikipedia",
    "live_date": null,
    "maintainer": {
      "github": "duckduckgo"
    },
    "name": "Wikipedia",
    "perl_module": "DDG::Fathead::Wikipedia",
    "producer": null,
    "production_state": "online",
    "repo": "fathead",
    "signal_from": "wikipedia_fathead",
    "src_domain": "en.wikipedia.org",
    "src_id": 1,
    "src_name": "Wikipedia",
    "src_options": {
      "directory": "",
      "is_fanon": 0,
      "is_mediawiki": 1,
      "is_wikipedia": 1,
      "language": "en",
      "min_abstract_length": "20",
      "skip_abstract": 0,
      "skip_abstract_paren": 0,
      "skip_end": "0",
      "skip_icon": 0,
      "skip_image_name": 0,
      "skip_qr": "",
      "source_skip": "",
      "src_info": ""
    },
    "src_url": null,
    "status": "live",
    "tab": "About",
    "topic": [
      "productivity"
    ],
    "unsafe": 0
  }
}"""
    icon1 = {'height': '',
             'url': 'https://duckduckgo.com/i/7eec482b.png',
             'width': ''}

    icon2 = {'height': '',
             'url': 'https://duckduckgo.com/i/4eec9e83.jpg',
             'width': ''}

    result1 = {
        'first_url': 'https://duckduckgo.com/Python_(programming',
        'icon': icon1,
        'result': '<a href="https://duckduckgo.com/Python_(programmin',
        'text': 'Python (programming language)A widely used general'}

    result2 = {
        'first_url': 'https://duckduckgo.com/Monty_Python',
        'icon': icon2,
        'result': 'Mo',
        'text': "Monty PythonA British surreal comedy group who"}

    related_topic = {
        'name': "Ancient Greece",
        'topics': []
    }

    meta = {
        "attribution": None,
        "blockgroup": None,
        "created_date": None,
        "description": "Wikipedia",
        "designer": None,
        "dev_date": None,
        "dev_milestone": "live",
        "developer": [
            {
                "name": "DDG Team",
                "type": "ddg",
                "url": "http://www.duckduckhack.com"
            }
        ],
        "example_query": "nikola tesla",
        "id": "wikipedia_fathead",
        "is_stackexchange": None,
        "js_callback_name": "wikipedia",
        "live_date": None,
        "maintainer": {
            "github": "duckduckgo"
        },
        "name": "Wikipedia",
        "perl_module": "DDG::Fathead::Wikipedia",
        "producer": None,
        "production_state": "online",
        "repo": "fathead",
        "signal_from": "wikipedia_fathead",
        "src_domain": "en.wikipedia.org",
        "src_id": 1,
        "src_name": "Wikipedia",
        "src_options": {
            "directory": "",
            "is_fanon": 0,
            "is_mediawiki": 1,
            "is_wikipedia": 1,
            "language": "en",
            "min_abstract_length": "20",
            "skip_abstract": 0,
            "skip_abstract_paren": 0,
            "skip_end": "0",
            "skip_icon": 0,
            "skip_image_name": 0,
            "skip_qr": "",
            "source_skip": "",
            "src_info": ""
        },
        "src_url": None,
        "status": "live",
        "tab": "About",
        "topic": [
            "productivity"
        ],
        "unsafe": 0
    }
    response = {
        'abstract': '',
        'abstract_source': 'Wikipedia',
        'abstract_text': '',
        'abstract_url': 'https://en.wikipedia.org/wiki/Python',
        'answer': '',
        'answer_type': '',
        'definition': '',
        'definition_source': '',
        'definition_url': '',
        'entity': '',
        'heading': 'Python',
        'image': '',
        'image_height': 0,
        'image_is_logo': 0,
        'image_width': 0,
        'infobox': {},
        'redirect': '',
        'related_topics': [],
        'results': [],
        'type': 'D',
        'meta': meta}

    @mock.patch('json.loads')
    @mock.patch('duckduckpy.core.http_client.HTTPConnection')
    def test_http_connection_used(self, conn, *args):
        query('anything', secure=False)
        conn.assert_called_once_with(api.SERVER_HOST)

    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                return_value=StringIO(origin))
    def test_smoke_dict(self, *args):
        self.related_topic['topics'] = [self.result1, self.result2]
        self.response['related_topics'] = [
            self.result1, self.result2, self.related_topic]
        resp = query('python', container='dict')
        self.assertTrue(resp == self.response)

    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                return_value=StringIO(origin))
    def test_smoke_namedtuple(self, *args):
        self.result1['icon'] = api.Icon(**self.icon1)
        self.result2['icon'] = api.Icon(**self.icon2)

        self.related_topic['topics'] = [
            api.Result(**self.result1),
            api.Result(**self.result2)]

        self.response['related_topics'] = [
            api.Result(**self.result1),
            api.Result(**self.result2),
            api.RelatedTopic(**self.related_topic)]

        expected = api.Response(**self.response)
        resp = query('python')
        self.assertEqual(resp, expected)

    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                return_value=mock.Mock(read=lambda: b"{}"))
    def test_python3_utf8_decode(self, *args):
        # Not relevant to Python 2.
        if not is_python2():
            query('python', container='dict')

    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                return_value=StringIO("[1, \"x\", true]"))
    def test_json_response_as_list(self, *args):
        res = query('anything!')
        self.assertEqual(res, [1, 'x', True])

    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                return_value=StringIO("Not JSON"))
    def test_not_json_response(self, *args):
        self.assertRaises(exc.DuckDuckDeserializeError, query, 'anything!')

class TestSecureQuery(unittest.TestCase):
    @mock.patch('json.loads')
    @mock.patch('duckduckpy.core.http_client.HTTPSConnection')
    def test_https_connection_used(self, conn, *args):
        query('anything', secure=True)
        conn.assert_called_once_with(api.SERVER_HOST)

    @mock.patch('json.loads')
    @mock.patch('duckduckpy.core.http_client.HTTPSConnection')
    def test_shortcut_https_connection_used(self, conn, *args):
        secure_query('anything', secure=True)
        conn.assert_called_once_with(api.SERVER_HOST)

class TestQueryExceptions(unittest.TestCase):
    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                side_effect=exc.DuckDuckArgumentError)
    def test_argument_error(self, *args):
        self.assertRaises(
            exc.DuckDuckArgumentError, query, '', container='non-existent')

    @mock.patch('duckduckpy.core.http_client.HTTPConnection.getresponse',
                side_effect=socket.gaierror)
    def test_connection_error(self, *args):
        self.assertRaises(exc.DuckDuckConnectionError, query, 'anything!')

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="@drawable/item">

    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:id="@+id/relativeLayout"
            android:clickable="false">

        <Button
                android:layout_width="30dp"
                android:layout_height="80dp"
                android:id="@+id/color"
                android:focusable="false"
                android:clickable="true"

                android:layout_alignParentTop="false"
                android:layout_alignParentLeft="false"
                android:layout_centerVertical="true"/>

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Large Text"
                android:id="@+id/pr_name"
                android:layout_gravity="left|center_vertical"
                android:textColor="#000000"
                android:textSize="40dp"

                android:layout_alignParentRight="false"
                android:layout_centerVertical="true"
                android:layout_marginLeft="80dp"/>

        <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/imageView"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:src="@drawable/gray_right"
                android:layout_marginRight="20dp"/>
    </RelativeLayout>

</RelativeLayout>


text:
@implementation ZCRecommendCategory
- (NSMutableArray *)users
{
    if (_users == nil) {
        _users = [NSMutableArray array];
    }

    return _users;
}
@end


text:
using System;

namespace Conference.Clients.Portable
{
    public interface IToast
    {
        void SendToast(string message);
    }
}


text:
package org.jnbis.internal.record.reader;

import org.jnbis.api.model.record.HighResolutionGrayscaleFingerprint;
import org.jnbis.internal.NistHelper;

/**
 * @author ericdsoto
 */
public class HighResolutionGrayscaleFingerprintReader extends RecordReader {

    @Override
    public HighResolutionGrayscaleFingerprint read(NistHelper.Token token) {
        if (token.pos >= token.buffer.length) {
            throw new RuntimeException("T4::NULL pointer to T4 record");
        }

        HighResolutionGrayscaleFingerprint fingerprint = new HighResolutionGrayscaleFingerprint();

        //Assigning t4-Header values
        int length = (int) read4BytesAsInt(token);

        //Refer to manual for byte positions:
        //https://www.nist.gov/sites/default/files/documents/itl/ansi/sp500-245-a16.pdf

        //Image designation character (IDC)
        int idc = token.buffer[token.pos + 4];
        fingerprint.setImageDesignationCharacter(String.valueOf(idc));

        //Impression type (IMP)
        int imp = token.buffer[token.pos + 5];
        fingerprint.setImpressionType(String.valueOf(imp));

        // Finger position (FGP)
        int fingerPrintNo = token.buffer[token.pos + 6];

        // Image scanning resolution (ISR)
        int isr = token.buffer[token.pos + 12];
        fingerprint.setImageScanningResolution(String.valueOf(isr));

        //Horizontal line length (HLL)
        long hll = read2BytesAsInt(token, 13);
        fingerprint.setHorizontalLineLength(String.valueOf(hll));

        //Vertical line length (VLL)
        long vll = read2BytesAsInt(token, 15);
        fingerprint.setVerticalLineLength(String.valueOf(vll));

        //Grayscale compression algorithm (GCA)
        int gca = token.buffer[token.pos + 17];
        fingerprint.setCompressionAlgorithm(String.valueOf(gca));

        int dataSize = length - 18;

        if (token.pos + dataSize + 17 > token.buffer.length) {
            dataSize += token.buffer.length - token.pos - 18;
        }

        byte[] data = new byte[dataSize];
        System.arraycopy(token.buffer, token.pos + 18, data, 0, data.length + 18 - 18);

        token.pos += length;
        fingerprint.setImageDesignationCharacter(String.valueOf(fingerPrintNo));
        fingerprint.setImageData(data);
        fingerprint.setLogicalRecordLength(String.valueOf(length));

        return fingerprint;
    }
}


text:
_EXTERN NSString* const kDoubanReviewsDefaultServiceVersion _INITIALIZE_AS(@"2.0");

@class GDataRating;
@interface DoubanEntryReview : GDataEntryBase

@property (nonatomic, retain) GDataRating *rating;

@end


text:
.spinner {
  margin: 100px auto;
  width: 40px;
  height: 40px;
  position: relative;
}

.cube1, .cube2 {
  background-color: #008cba;
  width: 15px;
  height: 15px;
  position: absolute;
  top: 0;
  left: 0;

  -webkit-animation: sk-cubemove 1.8s infinite ease-in-out;
  animation: sk-cubemove 1.8s infinite ease-in-out;
}

.cube2 {
  -webkit-animation-delay: -0.9s;
  animation-delay: -0.9s;
}

@-webkit-keyframes sk-cubemove {
  25% { -webkit-transform: translateX(42px) rotate(-90deg) scale(0.5) }
  50% { -webkit-transform: translateX(42px) translateY(42px) rotate(-180deg) }
  75% { -webkit-transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5) }
  100% { -webkit-transform: rotate(-360deg) }
}

@keyframes sk-cubemove {
  25% {
    transform: translateX(42px) rotate(-90deg) scale(0.5);
    -webkit-transform: translateX(42px) rotate(-90deg) scale(0.5);
  } 50% {
    transform: translateX(42px) translateY(42px) rotate(-179deg);
    -webkit-transform: translateX(42px) translateY(42px) rotate(-179deg);
  } 50.1% {
    transform: translateX(42px) translateY(42px) rotate(-180deg);
    -webkit-transform: translateX(42px) translateY(42px) rotate(-180deg);
  } 75% {
    transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5);
    -webkit-transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5);
  } 100% {
    transform: rotate(-360deg);
    -webkit-transform: rotate(-360deg);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer-array name="background_resource_ids">
        <item>@drawable/watch_face_all</item>
        <item>@drawable/watch_face_aksumite</item>
        <item>@drawable/watch_face_cahokian</item>
        <item>@drawable/watch_face_donghu</item>
        <item>@drawable/watch_face_harrapan</item>
        <item>@drawable/watch_face_koori</item>
        <item>@drawable/watch_face_latene</item>
        <item>@drawable/watch_face_minoan</item>
        <item>@drawable/watch_face_mu</item>
        <item>@drawable/watch_face_nabatean</item>
        <item>@drawable/watch_face_olmec</item>
        <item>@drawable/watch_face_shang</item>
        <item>@drawable/watch_face_sumerian</item>
    </integer-array>
</resources>


text:
<?php
//Configuración general
$config = array(
	"titulo"=>"celulares?",
	"subtitulo"=>"Inicio",
	"url"=>"http://{$_SERVER['HTTP_HOST']}/celControl/", //Con / al final
	//"url" => "http://localhost/simpleCMS/",
	"charset"=>"utf-8",

	"friendlyurls"=>false,

	//Datos para la configuracion del envio de correo
	"emailadmin"=>"",
	"emailenvios"=>"",
	"nombreenvios"=>"celulares?",
	"servidor"=>"localhost",
	"basedatos"=>"basecelulares",
	"usuario"=>"root",
	"pass"=>"",

	"googleanalytics"=>false,//Codigo UA- usado en las analiticas de Google
	"googlesiteverification"=>false,
	"mssiteverification"=>false
	); ?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using HomeAutio.Mqtt.Core;
using HomeAutio.Mqtt.Core.Utilities;
using I8Beef.Ecobee;
using I8Beef.Ecobee.Protocol;
using I8Beef.Ecobee.Protocol.Functions;
using I8Beef.Ecobee.Protocol.Objects;
using I8Beef.Ecobee.Protocol.Thermostat;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Extensions.ManagedClient;
using Newtonsoft.Json;

namespace HomeAutio.Mqtt.Ecobee
{
    /// <summary>
    /// Ecobee MQTT Topshelf service class.
    /// </summary>
    public class EcobeeMqttService : ServiceBase
    {
        private readonly ILogger<EcobeeMqttService> _log;

        private readonly Client _client;

        private readonly IDictionary<string, RevisionStatus> _revisionStatusCache;
        private readonly IDictionary<string, ThermostatStatus> _thermostatStatus;
        private readonly int _refreshInterval;

        private bool _disposed = false;
        private System.Timers.Timer _refresh;

        /// <summary>
        /// Initializes a new instance of the <see cref="EcobeeMqttService"/> class.
        /// </summary>
        /// <param name="logger">Logging instance.</param>
        /// <param name="ecobeeClient">The Ecobee client.</param>
        /// <param name="ecobeeName">The target Ecobee name.</param>
        /// <param name="refreshInterval">The refresh interval.</param>
        /// <param name="brokerSettings">MQTT broker settings.</param>
        public EcobeeMqttService(
            ILogger<EcobeeMqttService> logger,
            Client ecobeeClient,
            string ecobeeName,
            int refreshInterval,
            BrokerSettings brokerSettings)
            : base(logger, brokerSettings, "ecobee/" + ecobeeName)
        {
            _log = logger;
            _refreshInterval = refreshInterval * 1000;
            SubscribedTopics.Add(TopicRoot + "/+/+/set");

            _client = ecobeeClient;
            _revisionStatusCache = new Dictionary<string, RevisionStatus>();
            _thermostatStatus = new Dictionary<string, ThermostatStatus>();
        }

        #region Service implementation

        /// <inheritdoc />
        protected override async Task StartServiceAsync(CancellationToken cancellationToken = default)
        {
            await GetInitialStatusAsync()
                .ConfigureAwait(false);

            // Enable refresh
            if (_refresh != null)
            {
                _refresh.Dispose();
            }

            _refresh = new System.Timers.Timer();
            _refresh.Elapsed += async (sender, e) => await RefreshAsync();
            _refresh.Interval = _refreshInterval;
            _refresh.Start();
        }

        /// <inheritdoc />
        protected override Task StopServiceAsync(CancellationToken cancellationToken = default)
        {
            return Task.CompletedTask;
        }

        #endregion

        #region MQTT Implementation

        /// <summary>
        /// Handles commands for the Harmony published to MQTT.
        /// </summary>
        /// <param name="e">Event args.</param>
        protected override async void Mqtt_MqttMsgPublishReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            var message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
            _log.LogInformation("MQTT message received for topic " + e.ApplicationMessage.Topic + ": " + message);

            // Parse topic out
            var topicWithoutRoot = e.ApplicationMessage.Topic.Substring(TopicRoot.Length + 1);
            var thermostatId = topicWithoutRoot.Substring(0, topicWithoutRoot.IndexOf('/'));
            var thermostatTopic = topicWithoutRoot.Substring(topicWithoutRoot.IndexOf('/') + 1);

            // ONLY VALID OPTIONS
            // HvacMode (auto, auxHeatOnly, cool, heat, off) - hvacMode/set
            // Fan (on, off, auto) - desiredFanMode/set
            // SetHold ({ hold object }) - hold/set
            // Desired Heat - desiredHeat/set
            // Desired Cool - desiredCool/set
            var request = new ThermostatUpdateRequest
            {
                Selection = new Selection
                {
                    SelectionType = "thermostats",
                    SelectionMatch = thermostatId
                }
            };

            _log.LogInformation($"Sending request to {request.Uri} with thermostat selection {thermostatId} for action {thermostatTopic}");

            switch (thermostatTopic)
            {
                case "desiredCool/set":
                    if (int.TryParse(message, out int desiredCoolValue) && int.TryParse(_thermostatStatus[thermostatId].Status["desiredHeat"], out int currentDesiredHeatValue))
                    {
                        request.Functions = new List<Function>
                        {
                            new SetHoldFunction
                            {
                                Params = new SetHoldParams
                                {
                                    HoldType = "nextTransition",
                                    CoolHoldTemp = desiredCoolValue * 10,
                                    HeatHoldTemp = currentDesiredHeatValue * 10
                                }
                            }
                        };
                        var desiredCoolResponse = await _client.PostAsync<ThermostatUpdateRequest, Response>(request)
                            .ConfigureAwait(false);
                        _log.LogInformation($"{request.Uri} response: ({desiredCoolResponse.Status.Code}) {desiredCoolResponse.Status.Message}");

                        // Publish updates and cache new values
                        await GetInitialStatusAsync();
                    }

                    break;
                case "desiredFanMode/set":
                    if (message == "auto" || message == "off" || message == "on")
                    {
                        request.Functions = new List<Function>
                        {
                            new SetHoldFunction
                            {
                                Params = new SetHoldParams
                                {
                                    HoldType = "nextTransition",
                                    Fan = message
                                }
                            }
                        };

                        var desiredFanModeResponse = await _client.PostAsync<ThermostatUpdateRequest, Response>(request)
                            .ConfigureAwait(false);
                        _log.LogInformation($"{request.Uri} response: ({desiredFanModeResponse.Status.Code}) {desiredFanModeResponse.Status.Message}");

                        // Publish updates and cache new values
                        await GetInitialStatusAsync();
                    }

                    break;
                case "desiredHeat/set":
                    if (int.TryParse(message, out int desiredHeatValue) && int.TryParse(_thermostatStatus[thermostatId].Status["desiredCool"], out int currentDesiredCoolValue))
                    {
                        request.Functions = new List<Function>
                        {
                            new SetHoldFunction
                            {
                                Params = new SetHoldParams
                                {
                                    HoldType = "nextTransition",
                                    CoolHoldTemp = currentDesiredCoolValue * 10,
                                    HeatHoldTemp = desiredHeatValue * 10
                                }
                            }
                        };

                        var desiredHeatResponse = await _client.PostAsync<ThermostatUpdateRequest, Response>(request)
                            .ConfigureAwait(false);
                        _log.LogInformation($"{request.Uri} response: ({desiredHeatResponse.Status.Code}) {desiredHeatResponse.Status.Message}");

                        // Publish updates and cache new values
                        await GetInitialStatusAsync();
                    }

                    break;
                case "hold/set":
                    try
                    {
                        if (message.Contains("resumeProgram"))
                        {
                            var resumeFunction = JsonSerializer<ResumeProgramFunction>.Deserialize(message);
                            request.Functions = new List<Function>
                            {
                                resumeFunction
                            };
                        }
                        else
                        {
                            var holdFunction = JsonSerializer<SetHoldFunction>.Deserialize(message);
                            request.Functions = new List<Function>
                            {
                                holdFunction
                            };
                        }

                        var setHoldResponse = await _client.PostAsync<ThermostatUpdateRequest, Response>(request)
                            .ConfigureAwait(false);
                        _log.LogInformation($"{request.Uri} response: ({setHoldResponse.Status.Code}) {setHoldResponse.Status.Message}");

                        // Publish updates and cache new values
                        await GetInitialStatusAsync();
                    }
                    catch (JsonException ex)
                    {
                        _log.LogWarning(ex, $"Could not deserialize payload: {message}");
                    }

                    break;
                case "hvacMode/set":
                    if (message == "auto" || message == "auxHeatOnly" || message == "cool" || message == "heat" || message == "off")
                    {
                        request.Thermostat = new { Settings = new { HvacMode = message } };
                        var hvacModeResponse = await _client.PostAsync<ThermostatUpdateRequest, Response>(request)
                            .ConfigureAwait(false);
                        _log.LogInformation($"{request.Uri} response: ({hvacModeResponse.Status.Code}) {hvacModeResponse.Status.Message}");

                        // Publish updates and cache new values
                        await GetInitialStatusAsync();
                    }

                    break;
                default:
                    _log.LogWarning($"Unknown command topic {thermostatTopic} for thermostat {thermostatId}");
                    break;
            }
        }

        #endregion

        #region Ecobee implementation

        /// <summary>
        /// Heartbeat ping. Failure will result in the heartbeat being stopped, which will
        /// make any future calls throw an exception as the heartbeat indicator will be disabled.
        /// </summary>
        /// <returns>>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task RefreshAsync()
        {
            // Get current revision status
            var summaryRequest = new ThermostatSummaryRequest { Selection = new Selection { SelectionType = "registered" } };
            var status = await _client.GetAsync<ThermostatSummaryRequest, ThermostatSummaryResponse>(summaryRequest);
            foreach (var thermostatRevision in status.RevisionList)
            {
                _log.LogInformation($"Got revision: {thermostatRevision}");
                var revisionStatus = new RevisionStatus(thermostatRevision);

                if (_revisionStatusCache[revisionStatus.ThermostatIdentifier].ThermostatRevision != revisionStatus.ThermostatRevision ||
                    _revisionStatusCache[revisionStatus.ThermostatIdentifier].RuntimeRevision != revisionStatus.RuntimeRevision)
                {
                    await RefreshThermostatAsync(revisionStatus);
                }

                // Cache last run values
                _revisionStatusCache[revisionStatus.ThermostatIdentifier] = revisionStatus;
            }
        }

        /// <summary>
        /// Get, cache, and publish initial states.
        /// </summary>
        /// <returns>An awaitable <see cref="Task"/>.</returns>
        private async Task GetInitialStatusAsync()
        {
            var summaryRequest = new ThermostatSummaryRequest { Selection = new Selection { SelectionType = "registered" } };
            var summary = await _client.GetAsync<ThermostatSummaryRequest, ThermostatSummaryResponse>(summaryRequest)
                .ConfigureAwait(false);

            // Set initial revision cache
            _revisionStatusCache.Clear();
            _thermostatStatus.Clear();
            foreach (var revision in summary.RevisionList)
            {
                _log.LogInformation($"Got revision: {revision}");
                var revisionStatus = new RevisionStatus(revision);

                await RefreshThermostatAsync(revisionStatus);
                _revisionStatusCache.Add(revisionStatus.ThermostatIdentifier, revisionStatus);
            }
        }

        /// <summary>
        /// Handles updating status for a thermostat and publishing changes.
        /// </summary>
        /// <param name="revisionStatus">Revision status that triggered the update.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task RefreshThermostatAsync(RevisionStatus revisionStatus)
        {
            // Build single thermostat request
            var thermostatRequest = new ThermostatRequest
            {
                Selection = new Selection
                {
                    SelectionType = "thermostats",
                    SelectionMatch = revisionStatus.ThermostatIdentifier,
                    IncludeEquipmentStatus = true,
                    IncludeEvents = true,
                    IncludeRuntime = true,
                    IncludeSensors = true,
                    IncludeSettings = true,
                    IncludeWeather = true
                }
            };

            var thermostatUpdate = await _client.GetAsync<ThermostatRequest, ThermostatResponse>(thermostatRequest)
                .ConfigureAwait(false);

            // Publish updates and cache new values
            await UpdateState(thermostatUpdate?.ThermostatList?.FirstOrDefault());
        }

        /// <summary>
        /// Update state and publish new statuses.
        /// </summary>
        /// <param name="thermostat">Thermostat status.</param>
        /// <returns>>A <see cref="Task"/> representing the asynchronous operation.</returns>
        private async Task UpdateState(Thermostat thermostat)
        {
            if (thermostat == null)
            {
                return;
            }

            var thermostatStatus = new ThermostatStatus();

            // Equipment status
            foreach (var device in thermostat.EquipmentStatus.Split(',').Where(x => !string.IsNullOrEmpty(x)))
            {
                thermostatStatus.EquipmentStatus[device] = "on";
            }

            // Status
            thermostatStatus.Status["hvacMode"] = thermostat.Settings.HvacMode;
            thermostatStatus.Status["humidifierMode"] = thermostat.Settings.HumidifierMode;
            thermostatStatus.Status["dehumidifierMode"] = thermostat.Settings.DehumidifierMode;
            thermostatStatus.Status["autoAway"] = thermostat.Settings.AutoAway ? "true" : "false";
            thermostatStatus.Status["vent"] = thermostat.Settings.Vent;
            thermostatStatus.Status["actualTemperature"] = (thermostat.Runtime.ActualTemperature / 10m).ToString();
            thermostatStatus.Status["actualHumidity"] = thermostat.Runtime.ActualHumidity.ToString();
            thermostatStatus.Status["desiredHeat"] = (thermostat.Runtime.DesiredHeat / 10m).ToString();
            thermostatStatus.Status["desiredCool"] = (thermostat.Runtime.DesiredCool / 10m).ToString();
            thermostatStatus.Status["desiredHumidity"] = thermostat.Runtime.DesiredHumidity.ToString();
            thermostatStatus.Status["desiredDehumidity"] = thermostat.Runtime.DesiredDehumidity.ToString();
            thermostatStatus.Status["desiredFanMode"] = thermostat.Runtime.DesiredFanMode;

            // Weather forcasts
            var forecast = thermostat.Weather.Forecasts?.FirstOrDefault();
            if (forecast != null)
            {
                thermostatStatus.Status["weatherDewPoint"] = (forecast.Dewpoint / 10m).ToString();
                thermostatStatus.Status["weatherPrecipitationChance"] = forecast.Pop.ToString();
                thermostatStatus.Status["weatherPressure"] = (forecast.Pressure / 100m).ToString();
                thermostatStatus.Status["weatherRelativeHumidity"] = forecast.RelativeHumidity.ToString();
                thermostatStatus.Status["weatherTemperature"] = (forecast.Temperature / 10m).ToString();
                thermostatStatus.Status["weatherTempLow"] = (forecast.TempLow / 10m).ToString();
                thermostatStatus.Status["weatherTempHigh"] = (forecast.TempHigh / 10m).ToString();
                thermostatStatus.Status["weatherVisibility"] = forecast.Visibility.ToString();
                thermostatStatus.Status["weatherWindBearing"] = forecast.WindBearing.ToString();
                thermostatStatus.Status["weatherWindDirection"] = forecast.WindDirection.ToString();
                thermostatStatus.Status["weatherWindGust"] = forecast.WindGust.ToString();
                thermostatStatus.Status["weatherWindSpeed"] = forecast.WindSpeed.ToString();
            }

            // Sensors
            if (thermostat.RemoteSensors != null && thermostat.RemoteSensors.Count > 0)
            {
                foreach (var sensor in thermostat.RemoteSensors)
                {
                    thermostatStatus.Sensors[sensor.Name] = sensor.Capability.ToDictionary(
                        s => s.Type,
                        s =>
                        {
                            // Convert temperature values to human readable
                            if (string.Equals(s.Type, "temperature", System.StringComparison.OrdinalIgnoreCase))
                            {
                                if (decimal.TryParse(s.Value, out var decimalValue))
                                {
                                    return (decimalValue / 10m).ToString();
                                }
                            }

                            return s.Value;
                        });
                }
            }

            // Hold
            var holdEvent = thermostat.Events.FirstOrDefault(x => x.Type == "hold");
            if (holdEvent != null && holdEvent.Running)
            {
                thermostatStatus.ActiveHold["running"] = holdEvent.Running.ToString();
                thermostatStatus.ActiveHold["startTime"] = DateTime.Parse($"{holdEvent.StartDate} {holdEvent.StartTime}").ToString();
                thermostatStatus.ActiveHold["endTime"] = DateTime.Parse($"{holdEvent.EndDate} {holdEvent.EndTime}").ToString();
                thermostatStatus.ActiveHold["coldHoldTemp"] = (holdEvent.CoolHoldTemp / 10m).ToString();
                thermostatStatus.ActiveHold["heatHoldTemp"] = (holdEvent.HeatHoldTemp / 10m).ToString();
                thermostatStatus.ActiveHold["fan"] = holdEvent.Fan;
                thermostatStatus.ActiveHold["fanMinOnTime"] = holdEvent.FanMinOnTime.ToString();
                thermostatStatus.ActiveHold["vent"] = holdEvent.Vent;
                thermostatStatus.ActiveHold["ventilatorMinOnTime"] = holdEvent.VentilatorMinOnTime.ToString();
            }

            if (_thermostatStatus.ContainsKey(thermostat.Identifier))
            {
                // Publish updates
                foreach (var device in thermostatStatus.EquipmentStatus)
                {
                    if (device.Value != _thermostatStatus[thermostat.Identifier].EquipmentStatus[device.Key])
                    {
                        await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                            .WithTopic($"{TopicRoot}/{thermostat.Identifier}/{device.Key}")
                            .WithPayload(device.Value.ToString())
                            .WithAtLeastOnceQoS()
                            .WithRetainFlag()
                            .Build())
                            .ConfigureAwait(false);
                    }
                }

                foreach (var status in thermostatStatus.Status)
                {
                    if (status.Value != _thermostatStatus[thermostat.Identifier].Status[status.Key])
                    {
                        await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                            .WithTopic($"{TopicRoot}/{thermostat.Identifier}/{status.Key}")
                            .WithPayload(status.Value)
                            .WithAtLeastOnceQoS()
                            .WithRetainFlag()
                            .Build())
                            .ConfigureAwait(false);
                    }
                }

                // Hold status
                foreach (var holdStatus in thermostatStatus.ActiveHold)
                {
                    if (holdStatus.Value != _thermostatStatus[thermostat.Identifier].ActiveHold[holdStatus.Key])
                    {
                        await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                            .WithTopic($"{TopicRoot}/{thermostat.Identifier}/hold/{holdStatus.Key}")
                            .WithPayload(holdStatus.Value)
                            .WithAtLeastOnceQoS()
                            .WithRetainFlag()
                            .Build())
                            .ConfigureAwait(false);
                    }
                }

                // Publish everything for new sensors, new capabilities, and changes in existing ability values
                foreach (var sensor in thermostatStatus.Sensors)
                {
                    foreach (var sensorCapability in sensor.Value)
                    {
                        if (!_thermostatStatus[thermostat.Identifier].Sensors.ContainsKey(sensor.Key))
                        {
                            await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                .WithTopic($"{TopicRoot}/{thermostat.Identifier}/sensor/{sensor.Key.Sluggify()}/{sensorCapability.Key}")
                                .WithPayload(sensorCapability.Value)
                                .WithAtLeastOnceQoS()
                                .WithRetainFlag()
                                .Build())
                                .ConfigureAwait(false);
                        }
                        else if (!_thermostatStatus[thermostat.Identifier].Sensors[sensor.Key].ContainsKey(sensorCapability.Key))
                        {
                            await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                .WithTopic($"{TopicRoot}/{thermostat.Identifier}/sensor/{sensor.Key.Sluggify()}/{sensorCapability.Key}")
                                .WithPayload(sensorCapability.Value)
                                .WithAtLeastOnceQoS()
                                .WithRetainFlag()
                                .Build())
                                .ConfigureAwait(false);
                        }
                        else if (sensorCapability.Value != _thermostatStatus[thermostat.Identifier].Sensors[sensor.Key][sensorCapability.Key])
                        {
                            await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                                .WithTopic($"{TopicRoot}/{thermostat.Identifier}/sensor/{sensor.Key.Sluggify()}/{sensorCapability.Key}")
                                .WithPayload(sensorCapability.Value)
                                .WithAtLeastOnceQoS()
                                .WithRetainFlag()
                                .Build())
                                .ConfigureAwait(false);
                        }
                    }
                }
            }
            else
            {
                // Publish initial state
                foreach (var device in thermostatStatus.EquipmentStatus)
                {
                    await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                        .WithTopic($"{TopicRoot}/{thermostat.Identifier}/{device.Key}")
                        .WithPayload(device.Value.ToString())
                        .WithAtLeastOnceQoS()
                        .WithRetainFlag()
                        .Build())
                        .ConfigureAwait(false);
                }

                foreach (var status in thermostatStatus.Status)
                {
                    await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                        .WithTopic($"{TopicRoot}/{thermostat.Identifier}/{status.Key}")
                        .WithPayload(status.Value)
                        .WithAtLeastOnceQoS()
                        .WithRetainFlag()
                        .Build())
                        .ConfigureAwait(false);
                }

                // Hold status
                foreach (var holdStatus in thermostatStatus.ActiveHold)
                {
                    await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                        .WithTopic($"{TopicRoot}/{thermostat.Identifier}/hold/{holdStatus.Key}")
                        .WithPayload(holdStatus.Value)
                        .WithAtLeastOnceQoS()
                        .WithRetainFlag()
                        .Build())
                        .ConfigureAwait(false);
                }

                foreach (var sensor in thermostatStatus.Sensors)
                {
                    foreach (var sensorCapability in sensor.Value)
                    {
                        await MqttClient.PublishAsync(new MqttApplicationMessageBuilder()
                            .WithTopic($"{TopicRoot}/{thermostat.Identifier}/sensor/{sensor.Key.Sluggify()}/{sensorCapability.Key}")
                            .WithPayload(sensorCapability.Value)
                            .WithAtLeastOnceQoS()
                            .WithRetainFlag()
                            .Build())
                            .ConfigureAwait(false);
                    }
                }
            }

            _thermostatStatus[thermostat.Identifier] = thermostatStatus;
        }

        #endregion

        #region IDisposable Support

        /// <summary>
        /// Dispose implementation.
        /// </summary>
        /// <param name="disposing">Indicates if disposing.</param>
        protected override void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                if (_refresh != null)
                {
                    _refresh.Stop();
                    _refresh.Dispose();
                }
            }

            _disposed = true;
            base.Dispose(disposing);
        }

        #endregion
    }
}


text:
export default class OpenCvUtil {
    static getGrayscaleImage(inputImage) {
        if (inputImage.type() == cv.CV_8UC1) {
            return inputImage.clone()
        } else {
            const grayscaleImage = new cv.Mat()
            cv.cvtColor(inputImage, grayscaleImage, cv.COLOR_RGBA2GRAY, 0)
            return grayscaleImage
        }
    }

    static getColorImage(inputImage) {
        if (inputImage.type() == cv.CV_8UC1) {
            const colorImage = new cv.Mat()
            cv.cvtColor(inputImage, colorImage, cv.COLOR_GRAY2RGBA, 0)
            return colorImage
        } else {
            return inputImage.clone()
        }
    }
}


text:
package org.basex.query.func.fn;

import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.value.item.*;
import org.basex.query.value.type.*;
import org.basex.util.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Christian Gruen
 */
public final class FnPrefixFromQName extends StandardFunc {
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final QNm nm = toQNm(exprs[0], qc, true);
    return nm == null ? null : nm.hasPrefix() ?
      AtomType.NCN.cast(Str.get(nm.prefix()), qc, sc, info) : null;
  }
}


text:
package org.wso2.ballerina.mediators.jsontoxmltestmediator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.ballerina.core.config.ParameterHolder;
import org.wso2.ballerina.core.flow.AbstractMediator;
import org.wso2.ballerina.core.flow.contentaware.MIMEType;
import org.wso2.carbon.messaging.CarbonCallback;
import org.wso2.carbon.messaging.CarbonMessage;

/**
 * Sample JSON to XML Conversion Mediator
 */
public class JSONtoXMLTestMediator extends AbstractMediator {

    private static final Logger log = LoggerFactory.getLogger(JSONtoXMLTestMediator.class);
    private String logMessage = "Message received at JSON to XML Test Mediator";

    public JSONtoXMLTestMediator() {
    }

    /**
     * Set Parameters
     *
     * @param parameterHolder holder which contains key-value pairs of parameters
     */
    @Override
    public void setParameters(ParameterHolder parameterHolder) {
        logMessage = parameterHolder.getParameter("parameters").getValue();
    }

    @Override
    public String getName() {
        return "JSONtoXMLMediator";
    }

    /**
     * Mediate the message.
     * <p/>
     * This is the execution point of the mediator.
     *
     * @param carbonMessage  MessageContext to be mediated
     * @param carbonCallback Callback which can be use to call the previous step
     * @return whether mediation is success or not
     **/
    @Override
    public boolean receive(CarbonMessage carbonMessage, CarbonCallback carbonCallback) throws Exception {

        CarbonMessage convertedMsg = convertTo(carbonMessage, MIMEType.XML);

        //CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
        //CharBuffer charBuf = decoder.decode(convertedMsg.getMessageBody());
        //String msgBody = new String(charBuf.array());

        //log.info("\n" + msgBody);

        return next(convertedMsg, carbonCallback);
    }

    /**
     * This is a sample mediator specific method
     */
    public void setLogMessage(String logMessage) {
        this.logMessage = logMessage;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

namespace Othello
{
	class TurnSelect : MonoBehaviour
	{
		private GameObject StoneObj;
		public bool IsPlayFirst { get; set; } = true;

		private void Start()
		{
			var obj = GetComponent<GamePlay>();
			var pos = new Vector3(0, 5.0f, 0);
			var angle = new Quaternion(180,0,0,0);
			this.StoneObj = Instantiate(obj.OthelloStone, pos, angle);
			StoneObj.name = "Stone";
		}

		public IEnumerator Select(){
			while(!Input.GetKeyDown(KeyCode.A)){
				if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow)){
					IsPlayFirst = !IsPlayFirst;
					float addAngleX = (Input.GetKeyDown(KeyCode.LeftArrow) ? 10 : -10);
					yield return StartCoroutine(StoneRotation(addAngleX));
				}

				yield return null;
			}

			yield return StartCoroutine(GameStart());
			Destroy(this.StoneObj);
		}

		IEnumerator StoneRotation(float addAngleX){
			var rotateTime = (float)(180 / Mathf.Abs(addAngleX));
			for( var i = 1; i <= rotateTime; i++){
				StoneObj.transform.Rotate(new Vector3(addAngleX, 0, 0));
				yield return null;
			}
		}

		IEnumerator GameStart(){
			var startTime = 15;
			var moveX = 0.5f;
			for(var i = 1; i <= startTime; i++){
				Vector3 pos = StoneObj.transform.position;
				pos.x += moveX;
				StoneObj.transform.position = pos;
				yield return null;
			}
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Scleroderma zenkeri Henn.

### Remarks
null


text:
import csv
import os

# user define function;
def listroot(name):
	NodePathList = []
	LeafPathList = []

#	name = '35-6'
	#name = '35-6'

	root = '/home/ssfc/Dropbox/research/tog-' + name
	NodePathLayer = [root]
	NodePathList.append(root)

	#print os.listdir(root)

	NumberList = []
	for element in os.listdir(root):
		number = int(element.replace(name.replace('-', '') + 'tog', ''))
		NumberList.append(number)

	NumberList.sort()
	print NumberList

	content = []
	for element in NumberList:
		path = root + '/' + name.replace('-', '') + 'tog' + str(element) + '/root'
		content.append(path)

	return content

################################################################################

content = listroot('35-6') + listroot('35-4') + listroot('34-6') + listroot('34-4')

# save NodeList to csv file;
file = open('RootList.csv','wb')
for element in content:
	file.write(element)
	file.write('\n')
file.close()


text:
process.chdir(__dirname);

var YUITest = require('yuitest'),
    path = require('path'),
    fs = require('fs'),
    dir = path.join(__dirname, '../../../../build-npm/'),
    YUI = require(dir).YUI,
    json;

YUI({useSync: true }).use('test', function(Y) {
    Y.Test.Runner = YUITest.TestRunner;
    Y.Test.Case = YUITest.TestCase;
    Y.Test.Suite = YUITest.TestSuite;
    Y.Assert = YUITest.Assert;

    Y.applyConfig({
        modules: {
            'async-queue-tests': {
                fullpath: path.join(__dirname, '../unit/assets/async-queue-tests.js'),
                requires: ['async-queue', 'test']
            }
        }
    });

    Y.use('async-queue-tests');

    Y.Test.Runner.setName('async-queue cli tests');

});


text:
<?php

class Mob_Habitacion_Manager {

  public static function getProduccion($armeria, $municion, $taberna, $contrabando, $cerveceria, $idEdificio = null) {
      $habArmeria = Mob_Server::getHabRecurso(1);
      $habMunicion = Mob_Server::getHabRecurso(2);
      $habTaberna = Mob_Server::getHabRecurso(3);
      $habContrabando = Mob_Server::getHabRecurso(4);
      $habCerveceria  = Mob_Server::getHabRecurso(5);

      $habArmeria->setNivel($armeria);
      $habMunicion->setNivel($municion);
      $habTaberna->setNivel($taberna);
      $habContrabando->setNivel($contrabando);
      $habCerveceria->setNivel($cerveceria);

      $prodAlcohol = $cantAlcohol = $habCerveceria->getProduccion();
      if ($idEdificio != null) {
        $recursos = Mob_Loader::getModel("Edificio")->getRecursos($idEdificio);
        if (is_array($recursos) && !empty($recursos["recursos_alc"])) {
          $cantAlcohol += (int)$recursos["recursos_alc"];
        }
      }

      $prodDolares = 0;
      $consumoTaberna = $habTaberna->getConsumoAlcohol();
      $consumoContrabando = $habContrabando->getConsumoAlcohol();

      if ($cantAlcohol > $consumoTaberna) {
        // la cantidad de alcohol almacenada puede cubrir el consumo de la taberna
        $prodDolares += $habTaberna->getProduccion();
        $prodAlcohol -= $consumoTaberna;
        $cantAlcohol -= $consumoTaberna;
      } else {
        // no cubre el 100%, me fijo cuanto cubre
        $prodDolares += $habTaberna->getProduccionByConsumo($cantAlcohol);
        $prodAlcohol = 0;
        $cantAlcohol = 0;
      }

      if ($cantAlcohol > $consumoContrabando) {
        // la produccion de alcohol puede cubrir el consumo de la taberna
        $prodDolares += $habContrabando->getProduccion();
        $prodAlcohol -= $consumoContrabando;
        $cantAlcohol -= $consumoContrabando;
      } else {
        // no cubre el 100%, me fijo cuanto cubre
        $prodDolares += $habContrabando->getProduccionByConsumo($prodAlcohol);
        $prodAlcohol = 0;
        $cantAlcohol = 0;
      }

      return array("arm" => $habArmeria->getProduccion(), "mun" => $habMunicion->getProduccion(), "alc" => $prodAlcohol, "dol" => $prodDolares);
  }

}


text:
package org.apache.activemq.artemis.json;

/**
 * JsonValue which represents a string.
 */
public interface JsonString extends JsonValue {
   String getString();

   CharSequence getChars();

   @Override
   boolean equals(Object obj);

   @Override
   int hashCode();
}


text:
using Aurora.Controls;
using Aurora.Settings;
using Aurora.Utils;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace Aurora.Profiles.LeagueOfLegends
{
    /// <summary>
    /// Interaction logic for Control_LoL.xaml
    /// </summary>
    public partial class Control_LoL : UserControl
    {
        private Application profile_manager;

        public Control_LoL(Application profile)
        {
            InitializeComponent();

            profile_manager = profile;

            SetSettings();

            profile_manager.ProfileChanged += Profile_manager_ProfileChanged;
        }

        private void Profile_manager_ProfileChanged(object sender, EventArgs e)
        {
            SetSettings();
        }

        private void SetSettings()
        {
            this.game_enabled.IsChecked = profile_manager.Settings.IsEnabled;
        }

        private void game_enabled_Checked(object sender, RoutedEventArgs e)
        {
            if (IsLoaded)
            {
                profile_manager.Settings.IsEnabled = (this.game_enabled.IsChecked.HasValue) ? this.game_enabled.IsChecked.Value : false;
                profile_manager.SaveProfiles();
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string lolpath;
            try
            {
                lolpath = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Riot Games, Inc\League of Legends", "Location", null);
            }
            catch
            {
                lolpath = String.Empty;
            }

            if (string.IsNullOrWhiteSpace(lolpath))
            {
                MessageBox.Show("Could not find the league of legends path automatically. Please select the correct location(Usually in c:\\Riot Games\\League of Legends)");
                var fp = new System.Windows.Forms.FolderBrowserDialog();
                if(fp.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    MessageBox.Show("Could not remove wrapper patch");
                    return;
                }
                if(!fp.SelectedPath.EndsWith("League of Legends"))
                {
                    MessageBox.Show("Could not remove wrapper patch");
                    return;
                }
                lolpath = fp.SelectedPath;
            }

            if (FileUtils.TryDelete(Path.Combine(lolpath, "Game", "LightFx.dll")))
                MessageBox.Show("Deleted file successfully");
            else
                MessageBox.Show("Could not find the wrapper file.");
        }
    }
}


text:
#include "webrtc/modules/audio_processing/aec3/residual_echo_estimator.h"

#include <numeric>
#include <vector>

#include "webrtc/base/checks.h"

namespace webrtc {
namespace {

// Estimates the echo generating signal power as gated maximal power over a time
// window.
void EchoGeneratingPower(const RenderBuffer& render_buffer,
                         size_t min_delay,
                         size_t max_delay,
                         std::array<float, kFftLengthBy2Plus1>* X2) {
  X2->fill(0.f);
  for (size_t k = min_delay; k <= max_delay; ++k) {
    std::transform(X2->begin(), X2->end(), render_buffer.Spectrum(k).begin(),
                   X2->begin(),
                   [](float a, float b) { return std::max(a, b); });
  }

  // Apply soft noise gate of -78 dBFS.
  constexpr float kNoiseGatePower = 27509.42f;
  std::for_each(X2->begin(), X2->end(), [kNoiseGatePower](float& a) {
    if (kNoiseGatePower > a) {
      a = std::max(0.f, a - 0.3f * (kNoiseGatePower - a));
    }
  });
}

constexpr int kNoiseFloorCounterMax = 50;
constexpr float kNoiseFloorMin = 10.f * 10.f * 128.f * 128.f;

// Updates estimate for the power of the stationary noise component in the
// render signal.
void RenderNoisePower(
    const RenderBuffer& render_buffer,
    std::array<float, kFftLengthBy2Plus1>* X2_noise_floor,
    std::array<int, kFftLengthBy2Plus1>* X2_noise_floor_counter) {
  RTC_DCHECK(X2_noise_floor);
  RTC_DCHECK(X2_noise_floor_counter);

  const auto render_power = render_buffer.Spectrum(0);
  RTC_DCHECK_EQ(X2_noise_floor->size(), render_power.size());
  RTC_DCHECK_EQ(X2_noise_floor_counter->size(), render_power.size());

  // Estimate the stationary noise power in a minimum statistics manner.
  for (size_t k = 0; k < render_power.size(); ++k) {
    // Decrease rapidly.
    if (render_power[k] < (*X2_noise_floor)[k]) {
      (*X2_noise_floor)[k] = render_power[k];
      (*X2_noise_floor_counter)[k] = 0;
    } else {
      // Increase in a delayed, leaky manner.
      if ((*X2_noise_floor_counter)[k] >= kNoiseFloorCounterMax) {
        (*X2_noise_floor)[k] =
            std::max((*X2_noise_floor)[k] * 1.1f, kNoiseFloorMin);
      } else {
        ++(*X2_noise_floor_counter)[k];
      }
    }
  }
}

// Assume a minimum echo path gain of -33 dB for headsets.
constexpr float kHeadsetEchoPathGain = 0.0005f;

}  // namespace

ResidualEchoEstimator::ResidualEchoEstimator() {
  Reset();
}

ResidualEchoEstimator::~ResidualEchoEstimator() = default;

void ResidualEchoEstimator::Estimate(
    bool using_subtractor_output,
    const AecState& aec_state,
    const RenderBuffer& render_buffer,
    const std::array<float, kFftLengthBy2Plus1>& S2_linear,
    const std::array<float, kFftLengthBy2Plus1>& Y2,
    std::array<float, kFftLengthBy2Plus1>* R2) {
  RTC_DCHECK(R2);

  const rtc::Optional<size_t> delay =
      aec_state.FilterDelay()
          ? aec_state.FilterDelay()
          : (aec_state.ExternalDelay() ? aec_state.ExternalDelay()
                                       : rtc::Optional<size_t>());

  // Estimate the power of the stationary noise in the render signal.
  RenderNoisePower(render_buffer, &X2_noise_floor_, &X2_noise_floor_counter_);

  // Estimate the residual echo power.
  const bool use_linear_echo_power =
      aec_state.UsableLinearEstimate() && using_subtractor_output;
  if (use_linear_echo_power && !aec_state.HeadsetDetected()) {
    RTC_DCHECK(aec_state.FilterDelay());
    const int filter_delay = *aec_state.FilterDelay();
    LinearEstimate(S2_linear, aec_state.Erle(), filter_delay, R2);
    AddEchoReverb(S2_linear, aec_state.SaturatedEcho(), filter_delay,
                  aec_state.ReverbDecayFactor(), R2);
  } else {
    // Estimate the echo generating signal power.
    std::array<float, kFftLengthBy2Plus1> X2;
    if (aec_state.ExternalDelay() || aec_state.FilterDelay()) {
      RTC_DCHECK(delay);
      const int delay_use = static_cast<int>(*delay);

      // Computes the spectral power over the blocks surrounding the delay.
      RTC_DCHECK_LT(delay_use, kResidualEchoPowerRenderWindowSize);
      EchoGeneratingPower(
          render_buffer, std::max(0, delay_use - 1),
          std::min(kResidualEchoPowerRenderWindowSize - 1, delay_use + 1), &X2);
    } else {
      // Computes the spectral power over the latest blocks.
      EchoGeneratingPower(render_buffer, 0,
                          kResidualEchoPowerRenderWindowSize - 1, &X2);
    }

    // Subtract the stationary noise power to avoid stationary noise causing
    // excessive echo suppression.
    std::transform(
        X2.begin(), X2.end(), X2_noise_floor_.begin(), X2.begin(),
        [](float a, float b) { return std::max(0.f, a - 10.f * b); });

    NonLinearEstimate(
        aec_state.HeadsetDetected() ? kHeadsetEchoPathGain : kFixedEchoPathGain,
        X2, Y2, R2);
    AddEchoReverb(*R2, aec_state.SaturatedEcho(),
                  std::min(static_cast<size_t>(kAdaptiveFilterLength),
                           delay.value_or(kAdaptiveFilterLength)),
                  aec_state.ReverbDecayFactor(), R2);
  }

  // If the echo is saturated, estimate the echo power as the maximum echo power
  // with a leakage factor.
  if (aec_state.SaturatedEcho()) {
    R2->fill((*std::max_element(R2->begin(), R2->end())) * 100.f);
  }

  std::copy(R2->begin(), R2->end(), R2_old_.begin());
}

void ResidualEchoEstimator::Reset() {
  X2_noise_floor_counter_.fill(kNoiseFloorCounterMax);
  X2_noise_floor_.fill(kNoiseFloorMin);
  R2_reverb_.fill(0.f);
  R2_old_.fill(0.f);
  R2_hold_counter_.fill(0.f);
  for (auto& S2_k : S2_old_) {
    S2_k.fill(0.f);
  }
}

void ResidualEchoEstimator::LinearEstimate(
    const std::array<float, kFftLengthBy2Plus1>& S2_linear,
    const std::array<float, kFftLengthBy2Plus1>& erle,
    size_t delay,
    std::array<float, kFftLengthBy2Plus1>* R2) {
  std::fill(R2_hold_counter_.begin(), R2_hold_counter_.end(), 10.f);
  std::transform(erle.begin(), erle.end(), S2_linear.begin(), R2->begin(),
                 [](float a, float b) {
                   RTC_DCHECK_LT(0.f, a);
                   return b / a;
                 });
}

void ResidualEchoEstimator::NonLinearEstimate(
    float echo_path_gain,
    const std::array<float, kFftLengthBy2Plus1>& X2,
    const std::array<float, kFftLengthBy2Plus1>& Y2,
    std::array<float, kFftLengthBy2Plus1>* R2) {
  // Compute preliminary residual echo.
  std::transform(X2.begin(), X2.end(), R2->begin(),
                 [echo_path_gain](float a) { return a * echo_path_gain; });

  for (size_t k = 0; k < R2->size(); ++k) {
    // Update hold counter.
    R2_hold_counter_[k] = R2_old_[k] < (*R2)[k] ? 0 : R2_hold_counter_[k] + 1;

    // Compute the residual echo by holding a maximum echo powers and an echo
    // fading corresponding to a room with an RT60 value of about 50 ms.
    (*R2)[k] = R2_hold_counter_[k] < 2
                   ? std::max((*R2)[k], R2_old_[k])
                   : std::min((*R2)[k] + R2_old_[k] * 0.1f, Y2[k]);
  }
}

void ResidualEchoEstimator::AddEchoReverb(
    const std::array<float, kFftLengthBy2Plus1>& S2,
    bool saturated_echo,
    size_t delay,
    float reverb_decay_factor,
    std::array<float, kFftLengthBy2Plus1>* R2) {
  // Compute the decay factor for how much the echo has decayed before leaving
  // the region covered by the linear model.
  auto integer_power = [](float base, int exp) {
    float result = 1.f;
    for (int k = 0; k < exp; ++k) {
      result *= base;
    }
    return result;
  };
  RTC_DCHECK_LE(delay, S2_old_.size());
  const float reverb_decay_for_delay =
      integer_power(reverb_decay_factor, S2_old_.size() - delay);

  // Update the estimate of the reverberant residual echo power.
  S2_old_index_ = S2_old_index_ > 0 ? S2_old_index_ - 1 : S2_old_.size() - 1;
  const auto& S2_end = S2_old_[S2_old_index_];
  std::transform(
      S2_end.begin(), S2_end.end(), R2_reverb_.begin(), R2_reverb_.begin(),
      [reverb_decay_for_delay, reverb_decay_factor](float a, float b) {
        return (b + a * reverb_decay_for_delay) * reverb_decay_factor;
      });

  // Update the buffer of old echo powers.
  if (saturated_echo) {
    S2_old_[S2_old_index_].fill((*std::max_element(S2.begin(), S2.end())) *
                                100.f);
  } else {
    std::copy(S2.begin(), S2.end(), S2_old_[S2_old_index_].begin());
  }

  // Add the power of the echo reverb to the residual echo power.
  std::transform(R2->begin(), R2->end(), R2_reverb_.begin(), R2->begin(),
                 std::plus<float>());
}

}  // namespace webrtc


text:
==================
salt.modules.event
==================

.. automodule:: salt.modules.event
    :members:


text:
package org.lockss.plugin.springer.link;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.text.StringEscapeUtils;
import org.lockss.util.*;
import org.lockss.daemon.PluginException;
import org.lockss.extractor.ArticleMetadata;
import org.lockss.extractor.FileMetadataExtractor;
import org.lockss.extractor.FileMetadataExtractorFactory;
import org.lockss.extractor.MetadataField;
import org.lockss.extractor.MetadataTarget;
import org.lockss.extractor.SimpleFileMetadataExtractor;
import org.lockss.plugin.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SpringerLinkBooksHtmlMetadataExtractorFactory
    implements FileMetadataExtractorFactory {
  private static final Logger log = Logger.getLogger(SpringerLinkBooksHtmlMetadataExtractor.class);

  @Override
  public FileMetadataExtractor createFileMetadataExtractor(MetadataTarget target,
                               String contentType)
      throws PluginException {
    return new SpringerLinkBooksHtmlMetadataExtractor();
  }

  private static MultiMap tagMap = new MultiValueMap();
  static {
    tagMap.put("author", MetadataField.FIELD_AUTHOR);
    tagMap.put("abstract-about-book-chapter-copyright-year", MetadataField.FIELD_DATE);
    tagMap.put("abstract-about-title", MetadataField.FIELD_PUBLICATION_TITLE);
    tagMap.put("abstract-about-book-chapter-doi", MetadataField.FIELD_DOI);
    tagMap.put("abstract-about-book-print-isbn", MetadataField.FIELD_ISBN);
    tagMap.put("abstract-about-book-online-isbn", MetadataField.FIELD_EISBN);
  }

  public class SpringerLinkBooksHtmlMetadataExtractor
    extends SimpleFileMetadataExtractor {

    private Pattern whiteSpacePat = Pattern.compile("\\s+");

    public SpringerLinkBooksHtmlMetadataExtractor() {
    }

    /*
     * Trying to pull metadata from tag of the form:
     *
Contemporary Turkey at a Glance

     * and
     *

            Kristina Kamp
            ...

     */
    public ArticleMetadata extract(MetadataTarget target, CachedUrl cu)
        throws IOException {
      if (cu == null) {
        throw new IllegalArgumentException("extract() called with null CachedUrl");
      }
      ArticleMetadata ret = new ArticleMetadata();
      Document doc = Jsoup.parse(cu.getUnfilteredInputStream(), cu.getEncoding() ,cu.getUrl());
      Elements metadata = doc.select("dd[id]");
      Elements editors = doc.getElementsByClass("person");
      for(Element item:metadata) {
        putValue(ret, item.id(), item.text());
      }
      for(Element editor:editors) {
        putValue(ret, "author", editor.text());
      }
      ret.cook(tagMap);
      String url = ret.get(MetadataField.FIELD_ACCESS_URL);
      ArchivalUnit au = cu.getArchivalUnit();
      if (url == null || url.isEmpty() || !au.makeCachedUrl(url).hasContent()) {
        url = cu.getUrl();
      }
      ret.replace(MetadataField.FIELD_ACCESS_URL,
                 AuUtil.normalizeHttpHttpsFromBaseUrl(au, url));
      return ret;
    }

    protected void putValue(ArticleMetadata ret, String name, String content) {
      // filter raw HTML tags embedded within content -- publishers get sloppy
      content = HtmlUtil.stripHtmlTags(content);
      // remove character entities from content
      content = StringEscapeUtils.unescapeHtml4(content);
      // normalize multiple whitespace characters to a single space character
      Matcher m = whiteSpacePat.matcher(content);
      content = m.replaceAll(" ");

      if (log.isDebug3()) log.debug3("Add: " + name + " = " + content);
      ret.putRaw(name, content);
    }
  }
}


text:
nagios-cli
==========

About
-----

nagios-cli is a Nagios command line interface, exposing some features that are
available via the web based graphical user interface.

Requirements
------------

Required:

*  Nagios 2.x or 3.x
*  Python 2.4+

Optional:

*  libreadline

Usage
-----

The default configuration will look for the `status_file` file in the
`/var/log/nagios/status.dat` file, and it expects the `command_file` to be
available at `/var/log/nagios/rw/nagios.cmd`. If you wish to override
this, you can generate a configuration file with:

    nagios-cli -c nagios-cli.cfg --write

To specify a location to an alternative configuration file, use:

    nagios-cli -c <filename>

To see all available options, use:

    nagios-cli --help


text:
require 'rails_helper'

feature 'user views book show page' do

  scenario '.all book details are displayed' do

    book = FactoryGirl.create(:book)

    visit book_path(book.id)

    expect(page).to have_content(book.title, book.author, book.description, book.category)

  end

    scenario '.book reviews display on show page' do

    review = FactoryGirl.create(:review)

    visit book_path(review.book.id)

    expect(page).to have_content(review.rating, review.body, review.book.title)

  end

end


text:
package app.example;

import model.ModelManager;
import network.server.OpenRTSServer;
import app.OpenRTSApplication;

public class GameMutliplayerAlien extends Game {

	protected static String mapfilename = "assets/maps/test.btf";

	public static void main(String[] args) {

		if (args.length > 0) {
			mapfilename = args[0];
		}

		OpenRTSServer.main(args);

		GameMutliplayerAlien app = new GameMutliplayerAlien();

		OpenRTSApplication.main(app);
		app.startClient();
	}

	@Override
	public void simpleInitApp() {
		super.simpleInitApp();
		if (!mapfilename.isEmpty()) {
			ModelManager.loadBattlefield(mapfilename);
			faction = ModelManager.getBattlefield().getEngagement().getFactions().get(1);
		}

	}
}