text:
module CrossOrigen
  class IpXact < XMLDoc
    AddressSpace = Struct.new(:name, :range, :width)

    MemoryMaps = Struct.new(:name, :address_blocks)

    AddressBlock = Struct.new(:name, :base_address, :range, :width)

    # Create a shorthand way to reference Origen Core's Bit ACCESS_CODES
    @@access_hash = Origen::Registers::Bit.const_get(:ACCESS_CODES)

    # Import/reader that currently only supports creating registers and bit fields
    def import(file, options = {}) # rubocop:disable CyclomaticComplexity
      require 'kramdown'

      filename = Pathname.new(file).basename('.*').to_s

      unless options[:refresh] || CrossOrigen.refresh?
        return if owner.import(filename, allow_missing: true)
      end

      model = CrossOrigen::Model.new

      address_spaces = {}

      doc(file, options) do |doc|
        doc.xpath('//spirit:addressSpaces/spirit:addressSpace').each do |addr_space|
          name = fetch addr_space.at_xpath('spirit:name'), downcase: true, to_sym: true, get_text: true
          range = fetch addr_space.at_xpath('spirit:range'), get_text: true, to_dec: true
          width = fetch addr_space.at_xpath('spirit:width'), get_text: true, to_i: true
          address_spaces[name] = AddressSpace.new(name, range, width)
        end
        open_memory_map(doc) do |mem_map|
          if mem_map
            mem_map_name = fetch mem_map.at_xpath('spirit:name'), downcase: true, to_sym: true, get_text: true
            if mem_map_name.to_s.empty?
              mem_map_obj = model
            else
              model.sub_block mem_map_name
              mem_map_obj = model.send(mem_map_name)
            end
            addr_blocks = mem_map.xpath('spirit:addressBlock')
          else
            mem_map_obj = model
            addr_blocks = doc.xpath('//spirit:addressBlock')
          end
          addr_blocks.each do |addr_block|
            name = fetch addr_block.at_xpath('spirit:name'), downcase: true, to_sym: true, get_text: true
            base_address = fetch addr_block.at_xpath('spirit:baseAddress'), get_text: true, to_dec: true
            range = fetch addr_block.at_xpath('spirit:range'), get_text: true, to_dec: true
            width = fetch addr_block.at_xpath('spirit:width'), get_text: true, to_i: true
            if name.to_s.empty?
              addr_block_obj = mem_map_obj
            else
              mem_map_obj.sub_block name, base_address: base_address, range: range, lau: width
              addr_block_obj = mem_map_obj.send(name)
            end
            addr_block.xpath('spirit:register').each do |register|
              name = fetch register.at_xpath('spirit:name'), downcase: true, to_sym: true, get_text: true
              size = fetch register.at_xpath('spirit:size'), get_text: true, to_i: true
              addr_offset = fetch register.at_xpath('spirit:addressOffset'), get_text: true, to_dec: true
              access = fetch register.at_xpath('spirit:access'), get_text: true
              # Determine if a reset is defined for the register
              if register.at_xpath('spirit:reset').nil?
                # If a reset does not exist, need to set the reset_value to 0, as Origen does not (yet) have a concept
                # of a register without a reset.
                reset_value = 0
              else
                # If a reset exists, determine the reset_value (required) and reset_mask (if defined)
                reset_value = fetch register.at_xpath('spirit:reset/spirit:value'), get_text: true, to_dec: true
                reset_mask = fetch register.at_xpath('spirit:reset/spirit:mask'), get_text: true, to_dec: true
                # Issue #8 fix - reset_mask is optional, keep reset value as imported when a mask is not defined.
                # Only perform AND-ing if mask is defined.  Only zero-out the reset_value if reset_value was nil.
                if reset_value.nil?
                  # Set default for reset_value attribute if none was provided and issue a warning.
                  reset_value = 0
                  Origen.log.warning "Register #{name.upcase} was defined as having a reset, but did not have a defined reset value.  This is not compliant with IP-XACT standard."
                  Origen.log.warning "The reset value for #{name.upcase} has been defined as 0x0 as a result."
                elsif reset_mask.nil?
                  # If mask is undefined, leave reset_value alone.
                else
                  # Do a logical bitwise AND with the reset value and mask
                  reset_value = reset_value & reset_mask
                end
              end
              # Future expansion: pull in HDL path as abs_path in Origen.
              addr_block_obj.reg name, addr_offset, size: size, access: access, description: reg_description(register) do |reg|
                register.xpath('spirit:field').each do |field|
                  name = fetch field.at_xpath('spirit:name'), downcase: true, to_sym: true, get_text: true
                  bit_offset = fetch field.at_xpath('spirit:bitOffset'), get_text: true, to_i: true
                  bit_width = fetch field.at_xpath('spirit:bitWidth'), get_text: true, to_i: true
                  xml_access = fetch field.at_xpath('spirit:access'), get_text: true
                  # Newer IP-XACT standards list access as < read or write>-< descriptor >, such as
                  # "read-write", "read-only", or "read-writeOnce"
                  if xml_access =~ /\S+\-\S+/ || xml_access == 'writeOnce'
                    # This filter alone is not capable of interpreting the 1685-2009 (and 2014).  Therefore
                    # must reverse-interpret the content of access_hash (see top of file).
                    #
                    # First get the base access type, ie: read-write, read-only, etc.
                    # base_access = fetch field.at_xpath('spirit:access'), get_text: true
                    base_access = xml_access
                    # Next grab any modified write values or read actions
                    mod_write = fetch field.at_xpath('spirit:modifiedWriteValue'), get_text: true
                    read_action = fetch field.at_xpath('spirit:readAction'), get_text: true
                    # Using base_access, mod_write, and read_action, look up the corresponding access
                    # acronym from access_hash, noting it is not possible to differentiate write-only
                    # from write-only, read zero and read-write from dc.
                    #
                    # Matched needs to be tracked, as there is no way to differentiate :rw and :dc in IP-XACT.
                    # Everything imported will default to :rw, never :dc.
                    matched = false
                    @@access_hash.each_key do |key|
                      if @@access_hash[key][:base] == base_access && @@access_hash[key][:write] == mod_write && @@access_hash[key][:read] == read_action && !matched
                        access = key.to_sym
                        matched = true
                      end
                    end
                  # Older IP-XACT standards appear to also accept short acronyms like "ro", "w1c", "rw",
                  # etc.
                  elsif xml_access =~ /\S+/
                    access = xml_access.downcase.to_sym
                  else
                    # default to read-write if access is not specified
                    access = :rw
                  end
                  range = nil
                  if bit_width == 1
                    range = bit_offset
                  else
                    range = (bit_offset + bit_width - 1)..bit_offset
                  end
                  reg.bit range, name, reset: reset_value[range], access: access, description: bit_description(field)
                end
              end
            end
          end
        end
      end
      model.export(filename, include_timestamp: CrossOrigen.include_timestamp?)
      owner.import(filename, options)
    end

    def doc(path, options = {})
      # If a fragment of IP-XACT is given, then wrap it with a valid header and we will try our best
      if options[:fragment]
        require 'nokogiri'

        content = %(
<?xml version="1.0"?>
<spirit:component xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="$REGMEM_HOME/builder/ipxact/schema/ipxact
          $REGMEM_HOME/builder/ipxact/schema/ipxact/index.xsd">
        #{File.read(path)}
</spirit:component>
        )
        yield Nokogiri::XML(content)
      else
        super
      end
    end

    # Returns a string representing the owner object in IP-XACT XML
    # Usable / Available options:
    #   :vendor             = Company name/web address, ex: 'nxp.com'
    #   :library            = IP Library
    #   :schema             = '1685-2009' or default of Spirit 1.4 (when no :schema option passed)
    #   :bus_interface      = only 'AMBA3' supported at this time
    #   :mmap_name          = Optionally set the memoryMap name to something other than the module name
    #   :mmap_ref           = memoryMapRef name, ex: 'UserMap'
    #   :addr_block_name    = addressBlock -> Name, ex: 'ATX'
    def owner_to_xml(options = {})
      require 'nokogiri'

      options = {
        include_bit_field_values: true
      }.merge(options)

      @format = options[:format]

      # Compatible schemas: Spirit 1.4, 1685-2009
      # Assume Spirit 1.4 if no schema provided
      if options[:schema] == '1685-2009' # Magillem tool uses alternate schema
        schemas = [
          'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009',
          'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009/index.xsd'
        ]
      else # Assume Spirit 1.4 if not
        schemas = [
          'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4',
          'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4/index.xsd'
        ]
      end

      if uvm? && !(options[:schema] == '1685-2009')
        schemas << '$IREG_GEN/XMLSchema/SPIRIT/VendorExtensions.xsd'
      end

      if options[:schema] == '1685-2009' # Magillem tool uses alternate schema
        headers = {
          'xmlns:spirit'       => 'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009',
          'xmlns:xsi'          => 'http://www.w3.org/2001/XMLSchema-instance',
          'xsi:schemaLocation' => schemas.join(' ')
        }
      else # Assume Spirit 1.4 if not
        headers = {
          'xmlns:spirit'       => 'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4',
          'xmlns:xsi'          => 'http://www.w3.org/2001/XMLSchema-instance',
          'xsi:schemaLocation' => schemas.join(' ')
        }
      end

      if uvm? && !(options[:schema] == '1685-2009')
        headers['xmlns:vendorExtensions'] = '$IREG_GEN/XMLSchema/SPIRIT'
        # Else:
        # Do nothing ?
        # headers['xmlns:vendorExtensions'] = '$UVM_RGM_HOME/builder/ipxact/schema'
      end

      builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
        spirit = xml['spirit']
        spirit.component(headers) do
          spirit.vendor options[:vendor] || 'Origen'
          spirit.library options[:library] || 'Origen'
          # I guess this should really be the register owner's owner's name?
          spirit.name try(:ip_name) || owner.class.to_s.split('::').last
          spirit.version try(:ip_version, :version, :revision)
          # The 1685-2009 schema allows for a bus interface.  AMBA3 (slave) supported so far.
          if options[:schema] == '1685-2009'
            if options[:bus_interface] == 'AMBA3'
              spirit.busInterfaces do
                spirit.busInterface do
                  spirit.name 'Slave'
                  bustype_header = {
                    'spirit:vendor'  => options[:vendor] || 'Origen',
                    'spirit:library' => 'amba3',
                    'spirit:name'    => 'APB3',
                    'spirit:version' => '1.0'
                  }
                  xml['spirit'].busType bustype_header
                  spirit.slave do
                    mmapref_header = {
                      'spirit:memoryMapRef' => options[:mmap_ref] || 'APB'
                    }
                    xml['spirit'].memoryMapRef mmapref_header
                  end
                end
              end
            end
          end
          spirit.memoryMaps do
            memory_maps.each do |map_name, _map|
              spirit.memoryMap do
                # Optionally assign memory map name to something other than the module name in Ruby,
                # default to 'RegisterMap'
                spirit.name options[:mmap_name] || 'RegisterMap'
                address_blocks do |domain_name, _domain, sub_block|
                  spirit.addressBlock do
                    # When registers reside at the top level, do not assign an address block name
                    if sub_block == owner
                      if options[:addr_block_name].nil?
                        spirit.name nil
                      else
                        spirit.name options[:addr_block_name]
                      end
                    else
                      spirit.name address_block_name(domain_name, sub_block)
                    end
                    spirit.baseAddress sub_block.base_address.to_hex
                    spirit.range range(sub_block)
                    spirit.width width(sub_block)
                    sub_block.regs.each do |name, reg|
                      # Required for now to ensure that the current value is the reset value
                      reg.reset
                      spirit.register do
                        spirit.name name
                        spirit.description try(reg, :name_full, :full_name)
                        spirit.addressOffset reg.offset.to_hex
                        spirit.size reg.size
                        if reg.bits.any?(&:writable?)
                          spirit.access 'read-write'
                        else
                          spirit.access 'read-only'
                        end
                        spirit.reset do
                          spirit.value reg.data.to_hex
                          spirit.mask mask(reg).to_hex
                        end
                        reg.named_bits do |name, bits|
                          spirit.field do
                            spirit.name name
                            spirit.description try(bits, :brief_description, :name_full, :full_name)
                            spirit.bitOffset bits.position
                            spirit.bitWidth bits.size
                            # When exporting to 1685-2009 schema, need to handle special cases (writeOnce),
                            # modifiedWriteValue, and readAction fields.
                            if options[:schema] == '1685-2009'
                              if bits.writable? && bits.readable?
                                if bits.access == :w1
                                  spirit.access 'read-writeOnce'
                                else
                                  spirit.access 'read-write'
                                end
                              elsif bits.writable?
                                if bits.access == :wo1
                                  spirit.access 'writeOnce'
                                else
                                  spirit.access 'write-only'
                                end
                              elsif bits.readable?
                                spirit.access 'read-only'
                              end
                              if bits.readable?
                                unless @@access_hash[bits.access][:read].nil?
                                  spirit.readAction @@access_hash[bits.access][:read]
                                end
                              end
                              if bits.writable?
                                unless @@access_hash[bits.access][:write].nil?
                                  spirit.modifiedWriteValue @@access_hash[bits.access][:write]
                                end
                              end
                            else # Assume Spirit 1.4 if not
                              spirit.access bits.access
                            end
                            # HDL paths provide hooks for a testbench to directly manipulate the
                            # registers without having to go through a bus interface or read/write
                            # protocol.  Because the hierarchical path to a register block can vary
                            # greatly between devices, allow the user to provide an abs_path value
                            # and define "full_reg_path" to assist.
                            #
                            # When registers reside at the top level without a specified path, use 'top'.
                            if reg.owner.path.nil? || reg.owner.path.empty?
                              regpath = 'top'
                            else
                              regpath = reg.owner.path
                            end
                            # If :full_reg_path is defined, the :abs_path metadata for a register will
                            # be used for regpath.  This can be assigned at an address block (sub-block)
                            # level.
                            unless options[:full_reg_path].nil? == true
                              regpath = reg.path
                            end
                            if options[:schema] == '1685-2009'
                              spirit.parameters do
                                spirit.parameter do
                                  spirit.name '_hdlPath_'
                                  # HDL path needs to be to the declared bit field name, NOT to the bus slice
                                  # that Origen's "abs_path" will yield.  Ex:
                                  #
                                  # ~~~ ruby
                                  # reg :myreg, 0x0, size: 32 do |reg|
                                  #   bits 7..4, :bits_high
                                  #   bits 3..0, :bits_low
                                  # end
                                  # ~~~
                                  #
                                  # The abs_path to ...regs(:myreg).bits(:bits_low).abs_path will yield
                                  # "myreg.myreg[3:0]", not "myreg.bits_low".  This is not an understood path
                                  # in Origen (myreg[3:0] does not exist in either myreg's RegCollection or BitCollection),
                                  # and does not sync with how RTL would create bits_low[3:0].
                                  # Therefore, use the path to "myreg"'s owner appended with bits.name (bits_low here).
                                  #
                                  # This can be done in a register or sub_blocks definition by defining register
                                  # metadata for "abs_path".  If the reg owner's path weren't used, but instead the
                                  # reg's path, that would imply each register was a separate hierarchical path in
                                  # RTL (ex: "top.myblock.regblock.myreg.myreg_bits"), which is normally not the case.
                                  # The most likely path would be "top.myblock.regblock.myreg_bits.
                                  spirit.value "#{regpath}.#{bits.name}"
                                end
                              end
                            end
                            # C. Hume - Unclear which vendorExtensions should be included by default, if any.
                            # Future improvment: Allow passing of vendorExtensions enable & value hash/string
                            # if options[:schema] == '1685-2009'
                            #   spirit.vendorExtensions do
                            #     vendorext = { 'xmlns:vendorExtensions' => '$UVM_RGM_HOME/builder/ipxact/schema' }
                            #     xml['vendorExtensions'].hdl_path vendorext, "#{reg.path}.#{bits.name}"
                            #   end
                            # end

                            # Allow optional inclusion of bit field values and descriptions
                            if options[:include_bit_field_values]
                              if bits.bit_value_descriptions[0]
                                bits.bit_value_descriptions.each do |val, desc|
                                  spirit.values do
                                    spirit.value val.to_hex
                                    spirit.name "val_#{val.to_hex}"
                                    spirit.description desc
                                  end
                                end
                              end
                            end
                            if uvm? && !(options[:schema] == '1685-2009')
                              spirit.vendorExtensions do
                                xml['vendorExtensions'].hdl_path "#{regpath}.#{bits.name}"
                              end
                            end
                          end
                        end
                      end
                    end
                    # Unclear whether addressBlock vendor extensions are supported in Spirit 1.4
                    # if uvm?
                    #  spirit.vendorExtensions do
                    #    xml['vendorExtensions'].hdl_path sub_block.path(relative_to: owner)
                    #  end
                    # end
                  end
                end
                # Assume byte addressing if not specified
                if owner.methods.include?(:lau) == false
                  if methods.include?(:lau) == true
                    spirit.addressUnitBits lau
                  else
                    spirit.addressUnitBits 8
                  end
                else
                  spirit.addressUnitBits owner.lau
                end
              end
            end
          end
        end
      end
      # When testing with 'origen examples', travis_ci (bash) will end up with empty tags -
      # '<spirit:description/>' that do not appear on some user's tshell environments.  To
      # prevent false errors for this issue, force Nokogiri to use self-closing tags
      # ('<spirit:description></spirit:description>'), but keep the XML formatted for readability.
      # All tags with no content will appear as '<spirit:tag_name></spirit:tag_name>'.
      #
      builder.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS |
                                Nokogiri::XML::Node::SaveOptions::FORMAT)
    end

    private

    def open_memory_map(doc)
      maps = doc.xpath('//spirit:memoryMaps/spirit:memoryMap')
      maps = [nil] if maps.empty?
      maps.each do |mem_map|
        yield mem_map
      end
    end

    def reg_description(register)
      fetch register.at_xpath('spirit:description'), get_text: true, whitespace: true
    end

    def bit_description(bit)
      desc = fetch(bit.at_xpath('spirit:description'), get_text: true, whitespace: true) || ''
      bit_val_present = false
      bit.xpath('spirit:values').each do |val|
        unless bit_val_present
          desc += "\n"
          bit_val_present = true
        end
        value = extract(val, 'spirit:value', format: :integer, hex: true)
        value_desc = extract val, 'spirit:description'
        if value && value_desc
          desc += "\n#{value.to_s(2)} | #{value_desc}"
        end
      end
      desc
    end

    def mask(reg)
      m = 0
      reg.size.times do |i|
        unless reg[i].reset_val == :undefined
          m |= (1 << i)
        end
      end
      m
    end

    def uvm?
      @format == :uvm
    end

    def memory_maps
      { nil => {} }
    end

    def sub_blocks(domain_name)
      owner.all_sub_blocks.select do |sub_block|
        sub_block.owns_registers? &&
          (sub_block.domains[domain_name] || domain_name == :default)
      end
    end

    def address_blocks
      domains = owner.register_domains
      domains = { default: {} } if domains.empty?
      domains.each do |domain_name, domain|
        if owner.owns_registers?
          yield domain_name, domain, owner
        end
        sub_blocks(domain_name).each do |sub_block|
          yield domain_name, domain, sub_block
        end
      end
    end

    def address_block_name(domain_name, sub_block)
      if domain_name == :default
        sub_block.name.to_s
      else
        "#{domain_name}_#{sub_block.name}"
      end
    end

    def width(sub_block)
      sub_block.try(:width) || 32
    end

    def range(sub_block)
      range = sub_block.try(:range) || begin
        # This is to work around an Origen bug where max_address_reg_size is not updated in the case of
        # only one register being present
        # TODO: Fix in Origen
        max_address_reg_size = sub_block.max_address_reg_size || sub_block.regs.first[1].size
        (sub_block.max_reg_address + (max_address_reg_size / 8))
      end
      width_in_bytes = width(sub_block) / 8
      if range % width_in_bytes != 0
        range += (width_in_bytes - (range % width_in_bytes))
      end
      range
    end
  end
end


text:
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

# Get an object from its sid. If you do not have a sid,
# check out the list resource examples on this page
domain = client.sip \
    .domains("SD27f0288630a668bdfbf177f8e22f5ccc") \
    .update(friendly_name="Little Kevin", voice_method="GET")

print(domain.domain_name)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>CASA DOS QUADRINHOS</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

	<meta property="og:locale" content="pt_BR">

    <meta property="og:url" content="http://mortomendonca.github.io/index.html">

    <meta property="og:title" content="Casa dos Quadrinhos - TA">
    <meta property="og:site_name" content="Casa dos Quadrinhos">

    <meta property="og:description" content="Site de teste de docpad para cadeira de Tópicos Avançados">

    <meta property="og:image" content="http://mortomendonca.github.io/img/slide-2.jpg">
    <meta property="og:image:type" content="image/jpeg">

    <meta property="og:type" content="website">

Casa dos Quadrinhos

Tudo o que você procura de quadrinhos está aqui

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Casa dos Qquadrinhos

                        Página Inicial

                        Marvel

                        DC

                        Image

                        Bem Vindo à

Casa dos Quadrinhos

Novo aqui?

Casa dos quadrinhos é um site genérico feito para a cadeira de tópicos avançados com o professor Márcio Torres

Gosta de
                        Quadrinhos??

Aqui você pode ver vários quadrinhos e se divertir.

Copyright © Everton Mendonça


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

/*
 * Generic simple memory manager implementation. Intended to be used as a base
 * class implementation for more advanced memory managers.
 *
 * Note that the algorithm used is quite simple and there might be substantial
 * performance gains if a smarter free list is implemented. Currently it is just an
 * unordered stack of free regions. This could easily be improved if an RB-tree
 * is used instead. At least if we expect heavy fragmentation.
 *
 * Aligned allocations can also see improvement.
 *
 * Authors:
 * Thomas Hellström <thomas-at-tungstengraphics-dot-com>
 */

#include <dev/drm2/drmP.h>
#include <dev/drm2/drm_mm.h>

#define MM_UNUSED_TARGET 4

static struct drm_mm_node *drm_mm_kmalloc(struct drm_mm *mm, int atomic)
{
	struct drm_mm_node *child;

	child = malloc(sizeof(*child), DRM_MEM_MM, M_ZERO |
	    (atomic ? M_NOWAIT : M_WAITOK));

	if (unlikely(child == NULL)) {
		mtx_lock(&mm->unused_lock);
		if (list_empty(&mm->unused_nodes))
			child = NULL;
		else {
			child =
			    list_entry(mm->unused_nodes.next,
				       struct drm_mm_node, node_list);
			list_del(&child->node_list);
			--mm->num_unused;
		}
		mtx_unlock(&mm->unused_lock);
	}
	return child;
}

int drm_mm_pre_get(struct drm_mm *mm)
{
	struct drm_mm_node *node;

	mtx_lock(&mm->unused_lock);
	while (mm->num_unused < MM_UNUSED_TARGET) {
		mtx_unlock(&mm->unused_lock);
		node = malloc(sizeof(*node), DRM_MEM_MM, M_WAITOK);
		mtx_lock(&mm->unused_lock);

		if (unlikely(node == NULL)) {
			int ret = (mm->num_unused < 2) ? -ENOMEM : 0;
			mtx_unlock(&mm->unused_lock);
			return ret;
		}
		++mm->num_unused;
		list_add_tail(&node->node_list, &mm->unused_nodes);
	}
	mtx_unlock(&mm->unused_lock);
	return 0;
}

static inline unsigned long drm_mm_hole_node_start(struct drm_mm_node *hole_node)
{
	return hole_node->start + hole_node->size;
}

static inline unsigned long drm_mm_hole_node_end(struct drm_mm_node *hole_node)
{
	struct drm_mm_node *next_node =
		list_entry(hole_node->node_list.next, struct drm_mm_node,
			   node_list);

	return next_node->start;
}

static void drm_mm_insert_helper(struct drm_mm_node *hole_node,
				 struct drm_mm_node *node,
				 unsigned long size, unsigned alignment)
{
	struct drm_mm *mm = hole_node->mm;
	unsigned long tmp = 0, wasted = 0;
	unsigned long hole_start = drm_mm_hole_node_start(hole_node);
	unsigned long hole_end = drm_mm_hole_node_end(hole_node);

	KASSERT(hole_node->hole_follows && !node->allocated, ("hole_node"));

	if (alignment)
		tmp = hole_start % alignment;

	if (!tmp) {
		hole_node->hole_follows = 0;
		list_del_init(&hole_node->hole_stack);
	} else
		wasted = alignment - tmp;

	node->start = hole_start + wasted;
	node->size = size;
	node->mm = mm;
	node->allocated = 1;

	INIT_LIST_HEAD(&node->hole_stack);
	list_add(&node->node_list, &hole_node->node_list);

	KASSERT(node->start + node->size <= hole_end, ("hole pos"));

	if (node->start + node->size < hole_end) {
		list_add(&node->hole_stack, &mm->hole_stack);
		node->hole_follows = 1;
	} else {
		node->hole_follows = 0;
	}
}

struct drm_mm_node *drm_mm_get_block_generic(struct drm_mm_node *hole_node,
					     unsigned long size,
					     unsigned alignment,
					     int atomic)
{
	struct drm_mm_node *node;

	node = drm_mm_kmalloc(hole_node->mm, atomic);
	if (unlikely(node == NULL))
		return NULL;

	drm_mm_insert_helper(hole_node, node, size, alignment);

	return node;
}

int drm_mm_insert_node(struct drm_mm *mm, struct drm_mm_node *node,
		       unsigned long size, unsigned alignment)
{
	struct drm_mm_node *hole_node;

	hole_node = drm_mm_search_free(mm, size, alignment, 0);
	if (!hole_node)
		return -ENOSPC;

	drm_mm_insert_helper(hole_node, node, size, alignment);

	return 0;
}

static void drm_mm_insert_helper_range(struct drm_mm_node *hole_node,
				       struct drm_mm_node *node,
				       unsigned long size, unsigned alignment,
				       unsigned long start, unsigned long end)
{
	struct drm_mm *mm = hole_node->mm;
	unsigned long tmp = 0, wasted = 0;
	unsigned long hole_start = drm_mm_hole_node_start(hole_node);
	unsigned long hole_end = drm_mm_hole_node_end(hole_node);

	KASSERT(hole_node->hole_follows && !node->allocated, ("hole_node"));

	if (hole_start < start)
		wasted += start - hole_start;
	if (alignment)
		tmp = (hole_start + wasted) % alignment;

	if (tmp)
		wasted += alignment - tmp;

	if (!wasted) {
		hole_node->hole_follows = 0;
		list_del_init(&hole_node->hole_stack);
	}

	node->start = hole_start + wasted;
	node->size = size;
	node->mm = mm;
	node->allocated = 1;

	INIT_LIST_HEAD(&node->hole_stack);
	list_add(&node->node_list, &hole_node->node_list);

	KASSERT(node->start + node->size <= hole_end, ("hole_end"));
	KASSERT(node->start + node->size <= end, ("end"));

	if (node->start + node->size < hole_end) {
		list_add(&node->hole_stack, &mm->hole_stack);
		node->hole_follows = 1;
	} else {
		node->hole_follows = 0;
	}
}

struct drm_mm_node *drm_mm_get_block_range_generic(struct drm_mm_node *hole_node,
						unsigned long size,
						unsigned alignment,
						unsigned long start,
						unsigned long end,
						int atomic)
{
	struct drm_mm_node *node;

	node = drm_mm_kmalloc(hole_node->mm, atomic);
	if (unlikely(node == NULL))
		return NULL;

	drm_mm_insert_helper_range(hole_node, node, size, alignment,
				   start, end);

	return node;
}

int drm_mm_insert_node_in_range(struct drm_mm *mm, struct drm_mm_node *node,
				unsigned long size, unsigned alignment,
				unsigned long start, unsigned long end)
{
	struct drm_mm_node *hole_node;

	hole_node = drm_mm_search_free_in_range(mm, size, alignment,
						start, end, 0);
	if (!hole_node)
		return -ENOSPC;

	drm_mm_insert_helper_range(hole_node, node, size, alignment,
				   start, end);

	return 0;
}

void drm_mm_remove_node(struct drm_mm_node *node)
{
	struct drm_mm *mm = node->mm;
	struct drm_mm_node *prev_node;

	KASSERT(!node->scanned_block && !node->scanned_prev_free
	    && !node->scanned_next_free, ("node"));

	prev_node =
	    list_entry(node->node_list.prev, struct drm_mm_node, node_list);

	if (node->hole_follows) {
		KASSERT(drm_mm_hole_node_start(node)
			!= drm_mm_hole_node_end(node), ("hole_follows"));
		list_del(&node->hole_stack);
	} else
		KASSERT(drm_mm_hole_node_start(node)
		       == drm_mm_hole_node_end(node), ("!hole_follows"));

	if (!prev_node->hole_follows) {
		prev_node->hole_follows = 1;
		list_add(&prev_node->hole_stack, &mm->hole_stack);
	} else
		list_move(&prev_node->hole_stack, &mm->hole_stack);

	list_del(&node->node_list);
	node->allocated = 0;
}

/*
 * Put a block. Merge with the previous and / or next block if they are free.
 * Otherwise add to the free stack.
 */

void drm_mm_put_block(struct drm_mm_node *node)
{
	struct drm_mm *mm = node->mm;

	drm_mm_remove_node(node);

	mtx_lock(&mm->unused_lock);
	if (mm->num_unused < MM_UNUSED_TARGET) {
		list_add(&node->node_list, &mm->unused_nodes);
		++mm->num_unused;
	} else
		free(node, DRM_MEM_MM);
	mtx_unlock(&mm->unused_lock);
}

static int check_free_hole(unsigned long start, unsigned long end,
			   unsigned long size, unsigned alignment)
{
	unsigned wasted = 0;

	if (end - start < size)
		return 0;

	if (alignment) {
		unsigned tmp = start % alignment;
		if (tmp)
			wasted = alignment - tmp;
	}

	if (end >= start + size + wasted) {
		return 1;
	}

	return 0;
}

struct drm_mm_node *drm_mm_search_free(const struct drm_mm *mm,
				       unsigned long size,
				       unsigned alignment, int best_match)
{
	struct drm_mm_node *entry;
	struct drm_mm_node *best;
	unsigned long best_size;

	best = NULL;
	best_size = ~0UL;

	list_for_each_entry(entry, &mm->hole_stack, hole_stack) {
		KASSERT(entry->hole_follows, ("hole_follows"));
		if (!check_free_hole(drm_mm_hole_node_start(entry),
				     drm_mm_hole_node_end(entry),
				     size, alignment))
			continue;

		if (!best_match)
			return entry;

		if (entry->size < best_size) {
			best = entry;
			best_size = entry->size;
		}
	}

	return best;
}

struct drm_mm_node *drm_mm_search_free_in_range(const struct drm_mm *mm,
						unsigned long size,
						unsigned alignment,
						unsigned long start,
						unsigned long end,
						int best_match)
{
	struct drm_mm_node *entry;
	struct drm_mm_node *best;
	unsigned long best_size;

	KASSERT(!mm->scanned_blocks, ("scanned"));

	best = NULL;
	best_size = ~0UL;

	list_for_each_entry(entry, &mm->hole_stack, hole_stack) {
		unsigned long adj_start = drm_mm_hole_node_start(entry) < start ?
			start : drm_mm_hole_node_start(entry);
		unsigned long adj_end = drm_mm_hole_node_end(entry) > end ?
			end : drm_mm_hole_node_end(entry);

		KASSERT(entry->hole_follows, ("hole_follows"));
		if (!check_free_hole(adj_start, adj_end, size, alignment))
			continue;

		if (!best_match)
			return entry;

		if (entry->size < best_size) {
			best = entry;
			best_size = entry->size;
		}
	}

	return best;
}

void drm_mm_replace_node(struct drm_mm_node *old, struct drm_mm_node *new)
{
	list_replace(&old->node_list, &new->node_list);
	list_replace(&old->hole_stack, &new->hole_stack);
	new->hole_follows = old->hole_follows;
	new->mm = old->mm;
	new->start = old->start;
	new->size = old->size;

	old->allocated = 0;
	new->allocated = 1;
}

void drm_mm_init_scan(struct drm_mm *mm, unsigned long size,
		      unsigned alignment)
{
	mm->scan_alignment = alignment;
	mm->scan_size = size;
	mm->scanned_blocks = 0;
	mm->scan_hit_start = 0;
	mm->scan_hit_size = 0;
	mm->scan_check_range = 0;
	mm->prev_scanned_node = NULL;
}

void drm_mm_init_scan_with_range(struct drm_mm *mm, unsigned long size,
				 unsigned alignment,
				 unsigned long start,
				 unsigned long end)
{
	mm->scan_alignment = alignment;
	mm->scan_size = size;
	mm->scanned_blocks = 0;
	mm->scan_hit_start = 0;
	mm->scan_hit_size = 0;
	mm->scan_start = start;
	mm->scan_end = end;
	mm->scan_check_range = 1;
	mm->prev_scanned_node = NULL;
}

int drm_mm_scan_add_block(struct drm_mm_node *node)
{
	struct drm_mm *mm = node->mm;
	struct drm_mm_node *prev_node;
	unsigned long hole_start, hole_end;
	unsigned long adj_start;
	unsigned long adj_end;

	mm->scanned_blocks++;

	KASSERT(!node->scanned_block, ("node->scanned_block"));
	node->scanned_block = 1;

	prev_node = list_entry(node->node_list.prev, struct drm_mm_node,
			       node_list);

	node->scanned_preceeds_hole = prev_node->hole_follows;
	prev_node->hole_follows = 1;
	list_del(&node->node_list);
	node->node_list.prev = &prev_node->node_list;
	node->node_list.next = &mm->prev_scanned_node->node_list;
	mm->prev_scanned_node = node;

	hole_start = drm_mm_hole_node_start(prev_node);
	hole_end = drm_mm_hole_node_end(prev_node);
	if (mm->scan_check_range) {
		adj_start = hole_start < mm->scan_start ?
			mm->scan_start : hole_start;
		adj_end = hole_end > mm->scan_end ?
			mm->scan_end : hole_end;
	} else {
		adj_start = hole_start;
		adj_end = hole_end;
	}

	if (check_free_hole(adj_start , adj_end,
			    mm->scan_size, mm->scan_alignment)) {
		mm->scan_hit_start = hole_start;
		mm->scan_hit_size = hole_end;

		return 1;
	}

	return 0;
}

int drm_mm_scan_remove_block(struct drm_mm_node *node)
{
	struct drm_mm *mm = node->mm;
	struct drm_mm_node *prev_node;

	mm->scanned_blocks--;

	KASSERT(node->scanned_block, ("scanned_block"));
	node->scanned_block = 0;

	prev_node = list_entry(node->node_list.prev, struct drm_mm_node,
			       node_list);

	prev_node->hole_follows = node->scanned_preceeds_hole;
	INIT_LIST_HEAD(&node->node_list);
	list_add(&node->node_list, &prev_node->node_list);

	/* Only need to check for containement because start&size for the
	 * complete resulting free block (not just the desired part) is
	 * stored. */
	if (node->start >= mm->scan_hit_start &&
	    node->start + node->size
	    		<= mm->scan_hit_start + mm->scan_hit_size) {
		return 1;
	}

	return 0;
}

int drm_mm_clean(struct drm_mm * mm)
{
	struct list_head *head = &mm->head_node.node_list;

	return (head->next->next == head);
}

int drm_mm_init(struct drm_mm * mm, unsigned long start, unsigned long size)
{
	INIT_LIST_HEAD(&mm->hole_stack);
	INIT_LIST_HEAD(&mm->unused_nodes);
	mm->num_unused = 0;
	mm->scanned_blocks = 0;
	mtx_init(&mm->unused_lock, "drm_unused", NULL, MTX_DEF);

	INIT_LIST_HEAD(&mm->head_node.node_list);
	INIT_LIST_HEAD(&mm->head_node.hole_stack);
	mm->head_node.hole_follows = 1;
	mm->head_node.scanned_block = 0;
	mm->head_node.scanned_prev_free = 0;
	mm->head_node.scanned_next_free = 0;
	mm->head_node.mm = mm;
	mm->head_node.start = start + size;
	mm->head_node.size = start - mm->head_node.start;
	list_add_tail(&mm->head_node.hole_stack, &mm->hole_stack);

	return 0;
}

void drm_mm_takedown(struct drm_mm * mm)
{
	struct drm_mm_node *entry, *next;

	if (!list_empty(&mm->head_node.node_list)) {
		DRM_ERROR("Memory manager not clean. Delaying takedown\n");
		return;
	}

	mtx_lock(&mm->unused_lock);
	list_for_each_entry_safe(entry, next, &mm->unused_nodes, node_list) {
		list_del(&entry->node_list);
		free(entry, DRM_MEM_MM);
		--mm->num_unused;
	}
	mtx_unlock(&mm->unused_lock);

	mtx_destroy(&mm->unused_lock);

	KASSERT(mm->num_unused == 0, ("num_unused != 0"));
}

void drm_mm_debug_table(struct drm_mm *mm, const char *prefix)
{
	struct drm_mm_node *entry;
	unsigned long total_used = 0, total_free = 0, total = 0;
	unsigned long hole_start, hole_end, hole_size;

	hole_start = drm_mm_hole_node_start(&mm->head_node);
	hole_end = drm_mm_hole_node_end(&mm->head_node);
	hole_size = hole_end - hole_start;
	if (hole_size)
		printf("%s 0x%08lx-0x%08lx: %8lu: free\n",
			prefix, hole_start, hole_end,
			hole_size);
	total_free += hole_size;

	drm_mm_for_each_node(entry, mm) {
		printf("%s 0x%08lx-0x%08lx: %8lu: used\n",
			prefix, entry->start, entry->start + entry->size,
			entry->size);
		total_used += entry->size;

		if (entry->hole_follows) {
			hole_start = drm_mm_hole_node_start(entry);
			hole_end = drm_mm_hole_node_end(entry);
			hole_size = hole_end - hole_start;
			printf("%s 0x%08lx-0x%08lx: %8lu: free\n",
				prefix, hole_start, hole_end,
				hole_size);
			total_free += hole_size;
		}
	}
	total = total_free + total_used;

	printf("%s total: %lu, used %lu free %lu\n", prefix, total,
		total_used, total_free);
}


text:
layout: post
title: "A story about dentists... busy dentists"
author: "Marcus Hammarberg"
date: 2018-12-12 12:09:17
tags:
 - Agile
 - Lean
 - Scrum
 - Kanban
---

When I introduce agile I do that through a nice little quandrat originally from the [This is Lean](https://thisislean.com/) book by [Pär Åhlström](http://parahlstrom.com/) and [Niclas Modig](https://twitter.com/leanonmyself), and visualized by [Håkan Forss](http://www.marcusoft.net/img/thisIsLean.png). I've [wrote about it here](http://www.marcusoft.net/2017/02/comments-on-board-practices-6.html). This post will only focus on the top left triangle - where we focus on maximizing resource utilization.

But I've noticed that personal stories sticks better and I have used a story about my dentist to show an example of a setting that focuses heavily on the resource utilization.

I lately was called back to a checkup at the dentist and did some further research. It was a fascinating peek into a world where many people was working hard, smart and diligent to achieve an outcome that was not any good for me as an end customer (aka the wrong thing, in my book).

I wanted to share this story with you, as I think it teaches us a lot about where focus on resource utilization can lead us... everyone working very hard to do the *wrong* thing.

## Part I - the emergency

Here's the original story to start with: I woke up an early morning in February (2016, I think) with the worst tooth-ache in my life. I was actually screaming out loud at one point. I headed on to the "emergency dentist" and promptly x-rayed.

"That's an old root canal job that has gone bad. It needs to be redone.", the nice dentist told me cheerfully.
"Great", I said through the veil of pain. "Do it! Do it now - I'll pay you whatever you want", I calmly responded.
"Ap ap ap", the dentist smiled behind his protective mask. "You have crown on your tooth and we need to drill through it. It's really complicated and hard and needs to be done under a microscope. There's a dentist called Torbjörn that can help you. He is awesome".

In the meantime I got painkillers and antibiotics and was sent home. As I stepped inside the door I called Torbjörn and begged "Please, Torbjörn, help me. I'm in pain! Can you do something".

Torbjörn was a jovial, secure man and assured me "No problems, my friend. I'll help you. Let's see ... today is February 12". I heard him flip through, what must have been a big booking calendar... Many pages... And then suddenly

"Ok there we go." He was back. "May 18th. 1130. How's that for you"

## Reflection on part I

Why did they do that to me? I was in pain for days and on painkiller for weeks. I actually had to wait 4 months until it was my turn.

Well... Torbjörn is a specialist only doing complicated root canal jobs. He is probably compensated pretty hefty for that. And the microscope he is doing his work with / through is ... expensive to say the least.
So the Swedish dentist department wants to ensure that he is being busy all the time. I know this. Because I asked him. And it turns out that if he has a one hour without a patient one day - they ran at a loss that day!
For this reason, Torbjörn has a nurse to prep me (ah, well all patients) so that once he enters the room the drilling can begin. The dentist office also has 3-6 other dentist (all specialist, I presume), and three secretaries helping them to stack the schedule full. Reasonable, one would think, as one hour unbooked would mean a loss for the day.

I know this too, since I asked them, and sure enough; they we continuously and diligently ensuring that no hour in the day was unbooked.

This is what the second part of the story is about

## Part II - the callback

Torbjörn fixed my tooth in 2-3 pretty advanced treatments and I was then asked to schedule a callback and checkup about a year later. When a year had past, one of these secretaries called me and gave me a timeslot, just a month from the time she called me, in September.

Sadly I was out of town that day and asked for a later slot. She sighed and started that same flipping-through-pages-of-the-booking-calendar again; "Well, the next available slot is ... in ... December 5. 1130-1145. It's just a short check-up."

I took it, of course, and last week I was there to do the checkup. I came early naturally since I didn't wanted to miss that slot and risk another wait. But as I came early I couldn't bare myself but started to interview and listen to the secretaries. I even found the [time to tweet about it](https://twitter.com/marcusoftnet/status/1070278346976780288).

But sure enough, my observations since last time was correct, they all cheerfully told me. On average the dentists there was fully booked for the next 2 months. There was not even a check-up slot. Everything was packed full. The worked hard to do so, they told me.

They proudly told me that there was a waiting list for waiting. You could go on a list that they started to call through if one dentist got a cancellation, due to sickness, for example. "Then we can quickly call these people", she pointed to a list with about 30 numbers, "and quickly fill that empty slot again."

I also overheard, more than one, calls that went like this:
Secretary: "Hi... Oh, it's broken in half? Ouch - that sounds painful. Well... sadly, we are fully fully booked. The next timeslot is ... next Thursday. Can you come in around 0745?"
At this point, Torbjörns nurse, came out, moved me into the chair and Torbjörn cheerfully entered. He snapped 2-3 x-rays, looked at them for about a minute and I was on my way. I was cured!

## Reflections on part II

The thing that was so interesting for me to observe and think about was that everyone here was doing an excellent job. They even innovated and evolved the way they managed the queue to ensure it never ran empty. They met each customer with great service and were almost singing "No we are fully-booked until March. But I can put you on the waiting-list, if you want."

The waiting room was nice and had coffee and even an automated check-in system so that I didn't have to interrupt the booking-function.

But what is the value they created? Busy dentists. No one there (at least not in behavior and words) was focused on the flow and value for the end-customer. If anything we were just slowing the busyness of the dentists down - that's why Torbjörn often did other more important things, while I was prepped for his treatment.

All the patients calling in was in pain (I know I was, when I got to wait for 4 months) but could not be handled. Not because the system was overloaded but rather around the system was managed.

I didn't get that far, but I'm betting that cost is an important factor when it comes to how the dentist office was measured for success. Probably also utilization of the available dentist-hours; such-and-such many SEK is paid to keep this office open and such-and-such many percentage utilization is the average per dentist.

## Summary

The people, working at the dentist office, were nice, generally awesome and did a great job doing the wrong thing. Nowhere to be found was a focus of creating value for the patients.

The reason they did this is, most likely, because the system was setup to promote this behavior. End-customer-value was very far from the minds and actions of everyone in the office, even though they were nice and treated us with good service and respect. They might even want to focus on the end-customer-value - but the system was not set up to promote that. They, literally, *could not* do that.

What kind of behavior are the systems you are in promoting?
Are those the behaviors that we want to have? The behaviors that our company wants, even?
What can you, I, we do to accomplish a change there?


text:
namespace testbed {
namespace monv {

bool
deinit_resources();

bool
init_resources(
	const size_t w,
	const size_t h);

bool
render(
	const void* pixmap);

bool
render(
	const GLuint tex_name);

} // namespace monv
} // namespace testbed

#endif // prim_mono_view_H__


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "categories".
 *
 * @property integer $id_categories
 * @property string $title
 * @property string $discription
 * @property string $categories_img
 *
 * @property Posts[] $posts
 */
class Categories extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'categories';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title','discription'], 'required','message'=>'Вы не заполнили это поле'],
            [['title'], 'string', 'max' => 50],
            [['discription'], 'string', 'max' => 600],
            [['categories_img'], 'string', 'max' => 45]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_categories' => 'Id Categories',
            'title' => 'Title',
            'discription' => 'Discription',
            'categories_img' => 'Categories Img',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPosts()
    {
        return $this->hasMany(Posts::className(), ['id_categories' => 'id_categories']);
    }
}


text:
package qin.tinyshop8.utils;

/**
 * 超级Long型主键实体类
 *
 * @author qinzhengying
 * @since 1.8 2017/7/16
 */
public class SuperLongEntity implements ShopBaseSupport,
          SuperEntity<Long>
{
    private static final long serialVersionUID = -6850158350527621790L;

    private Long id;

    @Override
    public Long getId()
    {
        return id;
    }

    @Override
    public void setId(Long id)
    {
        this.id = id;
    }
}


text:
using Dev.Framework.FileServer;
using Dev.Framework.FileServer.Config;
using Dev.Framework.FileServer.DocFile;
using Dev.Framework.FileServer.ImageFile;
using Dev.Framework.FileServer.LocalUploaderFileImpl;
using Dev.Framework.FileServer.ShareImpl;
using Dev.Web.CompositionRootBase;
using Ninject;
using Ninject.Web.Common;

namespace CompositionRoot.Web
{
    internal class RegisterFileServer : IRegister
    {
        #region IRegister Members

        public void Register()
        {
            var x = new ReadConfig();
            this.Kernel.Bind<IKey>().To<ShareFileKey>().InRequestScope();
            this.Kernel.Bind<IUploadFile>().To<ShareUploadFile>().InRequestScope();
            //公用方法
            //var x = new ReadConfig("LocalUploadFile.config");
            //this.Kernel.Bind<IKey>().To<LocalFileKey>().InRequestScope();

            //this.Kernel.Bind<IUploadFile>().To<LocalUploadFile>().InRequestScope();

            //文档类型
            this.Kernel.Bind<IDocFile>().To<DocFileUploader>().InRequestScope();
            //图片类型
            this.Kernel.Bind<IImageFile>().To<ImageUploader>().InRequestScope();
        }

        public IKernel Kernel { get; set; }

        #endregion
    }
}


text:
from django.contrib import admin
from api.models import *

class MetricInline(admin.TabularInline):
    model = Metric
    extra = 0

class BooleanMetricInline(admin.TabularInline):
    model = BooleanMetric
    extra = 0

class BuildAdmin(admin.ModelAdmin):
    inlines = [MetricInline, BooleanMetricInline]

admin.site.register(Metric)
admin.site.register(Smell)
admin.site.register(Project)
admin.site.register(Repo)
admin.site.register(Build, BuildAdmin)


text:
package com.softwaremill.react.kafka.commit.native

import akka.actor.ActorSystem
import akka.testkit.TestKit
import com.softwaremill.react.kafka.{ConsumerProperties, KafkaTest}
import kafka.api.{ConsumerMetadataRequest, ConsumerMetadataResponse}
import kafka.cluster.Broker
import kafka.common.ErrorMapping
import kafka.consumer.KafkaConsumer
import kafka.network.BlockingChannel
import org.mockito.BDDMockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, Matchers, fixture}

import scala.util.Try

class OffsetManagerResolverSpec extends TestKit(ActorSystem("OffsetManagerResolverSpec"))
    with fixture.FlatSpecLike with Matchers with KafkaTest with MockitoSugar with BeforeAndAfterEach {

  var channelMock: BlockingChannel = _
  var channelMockFactory: (String, Int) => BlockingChannel = _

  case class OffsetManagerFixture() {
    var consumer: KafkaConsumer[String] = _
    def createConsumer(consumerProperties: ConsumerProperties[String]) = {
      consumer = new KafkaConsumer(consumerProperties)
      consumer
    }

    def clearResources(): Unit = consumer.close()
  }

  type FixtureParam = OffsetManagerFixture

  def withFixture(test: OneArgTest) = {
    val theFixture = OffsetManagerFixture()
    try withFixture(test.toNoArgTest(theFixture))
    finally {
      theFixture.clearResources()
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    channelMock = mock[BlockingChannel]
    channelMockFactory = (host: String, port: Int) => {
      given(channelMock.host).willReturn(host)
      given(channelMock.port).willReturn(port)
      channelMock
    }
  }

  behavior of "Offset manager resolver"

  it should "use broker if it equals coordinator" in { f =>
    // given
    val properties = consumerProperties(FixtureParam("topic", "groupId", kafka))
    val consumer = f.createConsumer(properties)
    val metadata = givenCoordinatorMetadata(broker(kafkaHost), ErrorMapping.NoError)
    val reader = givenCoordinatorRequestWillReturn(metadata)

    // when
    val result: Try[BlockingChannel] = new OffsetManagerResolver(channelMockFactory, reader).resolve(consumer)

    // then
    result.isSuccess should be(true)
    result.get.host should equal("localhost")
    result.get.port should equal(9092)
  }

  it should "use coordinator if it's different than initial channel" in { f =>
    // given
    val properties = consumerProperties(FixtureParam("topic", "groupId", kafka))
    val consumer = f.createConsumer(properties)
    val metadata = givenCoordinatorMetadata(broker("otherhost:12535"), ErrorMapping.NoError)
    val reader = givenCoordinatorRequestWillReturn(metadata)

    // when
    val result: Try[BlockingChannel] = new OffsetManagerResolver(channelMockFactory, reader).resolve(consumer)

    // then
    result.isSuccess should be(true)
    result.get.host should equal("otherhost")
    result.get.port should equal(12535)
  }

  it should "handle error when connecting to initial channel" in { f =>
    // given
    val properties = consumerProperties(FixtureParam("topic", "groupId", kafka))
    val consumer = f.createConsumer(properties)
    given(channelMock.connect()).willThrow(new NullPointerException("Channel closed"))

    // when
    val result: Try[BlockingChannel] = new OffsetManagerResolver(channelMockFactory).resolve(consumer)

    // then
    result.isFailure should be(true)
    result.failed.get shouldBe a[OffsetManagerResolvingException]
    result.failed.get.getCause shouldBe a[NullPointerException]
  }

  it should "handle error when connecting to coordinator" in { f =>
    // given
    val properties = consumerProperties(FixtureParam("topic", "groupId", kafka))
    val consumer = f.createConsumer(properties)
    val metadata = givenCoordinatorMetadata(broker("otherhost:12535"), ErrorMapping.NoError)
    val reader = givenCoordinatorRequestWillReturn(metadata)
    val coordinatorMock = mock[BlockingChannel]

    channelMockFactory = (host: String, port: Int) => {
      val mock = if (host == "localhost") channelMock else coordinatorMock
      given(mock.host).willReturn(host)
      given(mock.port).willReturn(port)
      mock
    }
    given(coordinatorMock.connect()).willThrow(new IllegalArgumentException("Channel closed"))

    // when
    val result: Try[BlockingChannel] = new OffsetManagerResolver(channelMockFactory, reader).resolve(consumer)
    consumer.close()

    // then
    result.isFailure should be(true)
    result.failed.get shouldBe a[OffsetManagerResolvingException]
    result.failed.get.getCause shouldBe a[IllegalArgumentException]
  }

  it should "handle error when resolving the coordinator" in { f =>
    // given
    val properties = consumerProperties(FixtureParam("topic", "groupId", kafka))
    val consumer = f.createConsumer(properties)
    val metadata = givenCoordinatorMetadata(broker("otherhost:12535"), ErrorMapping.LeaderNotAvailableCode)
    val reader = givenCoordinatorRequestWillReturn(metadata)

    // when
    val result: Try[BlockingChannel] = new OffsetManagerResolver(channelMockFactory, reader).resolve(consumer)

    // then
    result.isFailure should be(true)
    result.failed.get shouldBe a[OffsetManagerResolvingException]
    result.failed.get.getCause should have message "Cannot connect to coordinator. Error code: 5"
  }

  def broker(hostAndPort: String) = {
    val host = hostAndPort.split(":")(0)
    val port = hostAndPort.split(":")(1).toInt
    Some(new Broker(1, host, port))
  }

  def givenCoordinatorMetadata(coordinator: Option[Broker], errorCode: Short) =
    new ConsumerMetadataResponse(coordinator, errorCode)

  def givenCoordinatorRequestWillReturn(metadata: ConsumerMetadataResponse) = {
    (channel: BlockingChannel, request: ConsumerMetadataRequest) => metadata
  }
}


text:
package org.elasticsearch.action.bulk;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

/**
 * Implements the low-level details of bulk request handling
 */
public final class BulkRequestHandler {
    private final Logger logger;
    private final BiConsumer<BulkRequest, ActionListener<BulkResponse>> consumer;
    private final BulkProcessor.Listener listener;
    private final Semaphore semaphore;
    private final Retry retry;
    private final int concurrentRequests;

    BulkRequestHandler(BiConsumer<BulkRequest, ActionListener<BulkResponse>> consumer, BackoffPolicy backoffPolicy,
                       BulkProcessor.Listener listener, ThreadPool threadPool,
                       int concurrentRequests) {
        assert concurrentRequests >= 0;
        this.logger = Loggers.getLogger(getClass());
        this.consumer = consumer;
        this.listener = listener;
        this.concurrentRequests = concurrentRequests;
        this.retry = new Retry(EsRejectedExecutionException.class, backoffPolicy, threadPool);
        this.semaphore = new Semaphore(concurrentRequests > 0 ? concurrentRequests : 1);
    }

    public void execute(BulkRequest bulkRequest, long executionId) {
        Runnable toRelease = () -> {};
        boolean bulkRequestSetupSuccessful = false;
        try {
            listener.beforeBulk(executionId, bulkRequest);
            semaphore.acquire();
            toRelease = semaphore::release;
            CountDownLatch latch = new CountDownLatch(1);
            retry.withBackoff(consumer, bulkRequest, new ActionListener<BulkResponse>() {
                @Override
                public void onResponse(BulkResponse response) {
                    try {
                        listener.afterBulk(executionId, bulkRequest, response);
                    } finally {
                        semaphore.release();
                        latch.countDown();
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    try {
                        listener.afterBulk(executionId, bulkRequest, e);
                    } finally {
                        semaphore.release();
                        latch.countDown();
                    }
                }
            }, Settings.EMPTY);
            bulkRequestSetupSuccessful = true;
            if (concurrentRequests == 0) {
                latch.await();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.info((Supplier<?>) () -> new ParameterizedMessage("Bulk request {} has been cancelled.", executionId), e);
            listener.afterBulk(executionId, bulkRequest, e);
        } catch (Exception e) {
            logger.warn((Supplier<?>) () -> new ParameterizedMessage("Failed to execute bulk request {}.", executionId), e);
            listener.afterBulk(executionId, bulkRequest, e);
        } finally {
            if (bulkRequestSetupSuccessful == false) {  // if we fail on client.bulk() release the semaphore
                toRelease.run();
            }
        }
    }

    boolean awaitClose(long timeout, TimeUnit unit) throws InterruptedException {
        if (semaphore.tryAcquire(this.concurrentRequests, timeout, unit)) {
            semaphore.release(this.concurrentRequests);
            return true;
        }
        return false;
    }
}


text:
package multipleturtlecommands;
import java.util.ArrayList;
import java.util.Collection;

import objects.Turtle;
import commands.*;

public class AskWith extends BaseCommand{
	private Command myConditional;
	private Collection<Command> myCommands;
	private ArrayList<Turtle> myTurtlePointers;

	public AskWith (Command conditional, Collection<Command> commands, ArrayList<Turtle> turtlePointers) {
		this.myConditional = conditional;
		this.myCommands = commands;
		this.myTurtlePointers = turtlePointers;
	}

	@Override
	public double execute() {
		// TODO Auto-generated method stub
		if (this.myConditional.execute() != 0) {
			for(Command todo: this.myCommands) {
				todo.execute();
			}
		}
		return myTurtlePointers.get(myTurtlePointers.size()-1).getID();
	}

}


text:
Finite State Machines (FSM) modelled with Objective-C, using the GOF's [State Design pattern](http://en.wikipedia.org/wiki/State_pattern).

Initially developed for a project in a [graduate Distributed Systems course](http://web.uvic.ca/calendar2012/CDs/CSC/562.html), later refined in a [graduate Design Patterns](http://web.uvic.ca/calendar2012/CDs/CSC/578.html) course. Since then I've used this in commercial projects.

Better documentation will be provided as time allows, for now, here is a brief description of the files in this repository.

# Usage Requirements

This code requires ARC and is known to work with iOS 5.x and later in Xcode 4.5 and later.

## <RCSState> protocol

Represents a state in a FSM.

##RCSTask

Respresents a task that uses a FSM to coordinate itself - consider this an alternative to NSOperation that you can use to model a complex multi-state process.

### RCSTaskState

Implementations of the FSM States for a RCSTask.

##RCSTaskQueue

Represents a queue that undestands the semantics of RCSTasks. Consider this a lightweight alternative to NSOperationQueue.

### RCSTaskQueueState

Implementations of the FSM States for a RCSTaskQueue.


text:
<?php

declare(strict_types=1);

namespace PhpunitCoverageCheck\Format;

interface FormatInterface
{
    public function getName() : string;

    /**
     * @throws FormatException
     */
    public function getCoverage(string $content) : float;
}


text:
import { Component } from 'react'
import Svg from '../svg'

class ForceExample extends Component {
  componentDidMount () {
    if (typeof window !== 'undefined') {
      const { shape, timeline, render, play } = Wilderness

      const randomlyAdjustPoint = point => ({
        ...point,
        x: point.x + Math.floor(Math.random() * 10) - 5,
        y: point.y + Math.floor(Math.random() * 10) - 5
      })

      const shakeForce = ({ points, attributes, childFrameShapes }, framePosition) => ({
        points: points.map(randomlyAdjustPoint),
        attributes,
        childFrameShapes
      })

      const plainShapeObject = {
        type: 'rect',
        x: 5,
        y: 5,
        width: 10,
        height: 10,
        fill: '#1F9FFD'
      }

      const keyframe1 = plainShapeObject

      const keyframe2 = {
        ...plainShapeObject,
        transforms: [[ 'offset', 80 ]],
        forces: [ shakeForce ]
      }

      const shakyRect = shape(keyframe1, keyframe2)

      const animation = timeline(shakyRect, {
        duration: 2000,
        iterations: Infinity,
        alternate: true
      })

      render(document.querySelector('#force-example'), animation)

      play(animation)
    }
  }

  render () {
    return (
      <Svg id="force-example" />
    )
  }
}

export default ForceExample


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WestBlueGolfLeagueWeb.Models.Entities;
using WestBlueGolfLeagueWeb.Repositories;

namespace WestBlueGolfLeagueWeb.Services
{
    public class ResultService
    {
        private WestBlue db;
        private ResultsRepository resultsRepository;

        public ResultService()
        {
            this.db = new WestBlue();
            this.resultsRepository = new ResultsRepository(this.db);
        }

        public void GetResultsForYear(int year)
        {
            var results = this.resultsRepository.GetResultsForYear(year);
        }
    }
}


text:
/**
 *   Header elements schema
 **/

var config              = require('../../config')[APP_ENV],
    mongoose            = require('mongoose'),
    Schema              = mongoose.Schema;

var headersSchema = new Schema({
    image    : {
        type : Schema.ObjectId
    },
    video    : {
        type : String,
        default : ""
    },
    layout   : {
        type : String,
        default : "image"
    },
    is_portfolio : {
        type : Boolean,
        default : false
    },
    portfolio_url      : {
        type : String,
        default : ""
    },
    page     : {
        type : String,
        default : ""
    },
    priority : {
        type : Number,
        default : 1
    },
    created_at: {
        type : Date,
        default : Date.now,
        required : true
    }
});

module.exports = mongoose.model('Headers', headersSchema);


text:
package org.apache.accumulo.core.data;

import static org.apache.accumulo.core.util.ByteBufferUtil.toBytes;

import java.nio.ByteBuffer;
import java.util.Map;

public class KeyValue implements Map.Entry<Key,Value> {

  public Key key;
  public byte[] value;

  public KeyValue(Key key, byte[] value) {
    this.key = key;
    this.value = value;
  }

  public KeyValue(Key key, ByteBuffer value) {
    this.key = key;
    this.value = toBytes(value);
  }

  @Override
  public Key getKey() {
    return key;
  }

  @Override
  public Value getValue() {
    return new Value(value);
  }

  @Override
  public Value setValue(Value value) {
    throw new UnsupportedOperationException();
  }

  public String toString() {
    return key + " " + new String(value);
  }

}


text:
var fs = require("fs");
var path = require("path");
var rollup = require('rollup');
var babel = require('rollup-plugin-babel');

var mochaSrc = fs.readFileSync(require.resolve("mocha/mocha.js"));

var chaiSrc = (function() {
  var chaiCode = fs.readFileSync(require.resolve("chai/chai.js")),
      chaiSubsetCode = fs.readFileSync(require.resolve("chai-subset"));
  return `
;(function() {
  var GLOBAL = typeof window !== "undefined" ? window :
    typeof global!=="undefined" ? global :
      typeof self!=="undefined" ? self : this;
  (function() {
    var module = undefined, exports = undefined; // no cjs require should be used!
    ${chaiCode}
  }).call(GLOBAL);

  if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.chai;
  (function() {
    var module = {exports: {}};
    ${chaiSubsetCode}

    if (module.exports) {
      var ex = module.exports,
          chaiSubset = ex.chaiSubset || (typeof ex === "function" && ex);
    }

    if (chaiSubset)
      GLOBAL.chai.use(chaiSubset); // install then forget
  }).call(GLOBAL);
})();`

})();

var targetFile = "mocha-es6.js",
    targetFileMocha = "dist/mocha.js",
    targetFileChai = "dist/chai.js";

module.exports = Promise.resolve()

  .then(() => rollup.rollup({
    entry: "index.js",
    plugins: [babel({
      exclude: 'node_modules/**', sourceMap: false,
      presets: [["es2015", {"modules": false}]],
      plugins: [
        "external-helpers",
        "transform-async-to-generator",
        "syntax-object-rest-spread",
        "transform-object-rest-spread"
      ],
      babelrc: false
    })]
  }))

  .then(bundle =>
    bundle.generate({
      format: 'iife',
      moduleName: 'mochaEs6',
      globals: {
        "mocha": "mocha",
        "chai": "chai",
        "lively.modules": "lively.modules",
        "lively.ast": "lively.ast"
      }
    }))

  .then(bundled => {
    var source = `(function() {
var GLOBAL = typeof window !== "undefined" ? window :
    typeof global!=="undefined" ? global :
      typeof self!=="undefined" ? self : this;
${bundled.code}
  if (typeof module !== "undefined" && module.exports)
    module.exports = GLOBAL.mochaEs6;
})();`;

    return `${mochaSrc}\n${chaiSrc}\n${source}`;
  })

  .then(source => {
    fs.writeFileSync(targetFile, source);
    fs.writeFileSync(targetFileMocha, mochaSrc);
    fs.writeFileSync(targetFileChai, chaiSrc);
  })
  .then(() => console.log("Build " + targetFile))
  .catch(err => console.error(err.stack))


text:
package io.moquette.broker.metrics;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.librato.metrics.reporter.Librato;
import io.moquette.broker.config.IConfig;
import io.moquette.broker.NettyUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;

import java.util.concurrent.TimeUnit;

import static io.moquette.BrokerConstants.*;
import static io.netty.channel.ChannelHandler.Sharable;

/**
 * Pipeline handler use to track some MQTT metrics.
 */
@Sharable
public final class DropWizardMetricsHandler extends ChannelInboundHandlerAdapter {
    private MetricRegistry metrics;
    private Meter publishesMetrics;
    private Meter subscribeMetrics;
    private Counter connectedClientsMetrics;

    public void init(IConfig props) {
        this.metrics = new MetricRegistry();
        this.publishesMetrics = metrics.meter("publish.requests");
        this.subscribeMetrics = metrics.meter("subscribe.requests");
        this.connectedClientsMetrics = metrics.counter("connect.num_clients");
//        ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
//            .convertRatesTo(TimeUnit.SECONDS)
//            .convertDurationsTo(TimeUnit.MILLISECONDS)
//            .build();
//        reporter.start(1, TimeUnit.MINUTES);
        final String email = props.getProperty(METRICS_LIBRATO_EMAIL_PROPERTY_NAME);
        final String token = props.getProperty(METRICS_LIBRATO_TOKEN_PROPERTY_NAME);
        final String source = props.getProperty(METRICS_LIBRATO_SOURCE_PROPERTY_NAME);

        Librato.reporter(this.metrics, email, token)
            .setSource(source)
            .start(10, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object message) {
        MqttMessage msg = (MqttMessage) message;
        MqttMessageType messageType = msg.fixedHeader().messageType();
        switch (messageType) {
            case PUBLISH:
                this.publishesMetrics.mark();
                break;
            case SUBSCRIBE:
                this.subscribeMetrics.mark();
                break;
            case CONNECT:
                this.connectedClientsMetrics.inc();
                break;
            case DISCONNECT:
                this.connectedClientsMetrics.dec();
                break;
            default:
                break;
        }
        ctx.fireChannelRead(message);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String clientID = NettyUtils.clientID(ctx.channel());
        if (clientID != null && !clientID.isEmpty()) {
            this.connectedClientsMetrics.dec();
        }
        ctx.fireChannelInactive();
    }

}


text:
package com.accuity.xray;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by burnsj3 on 4/21/2015.
 */
public class XrayReportProcessorTest {

    @Test
    public void testProcessXrayReport() throws Exception {
        XrayReportProcessor xrayTask = new XrayReportProcessor();

        ObjectMapper mapper = new ObjectMapper();
        XrayExecution execution = new XrayExecution();
        List<XrayModule> modules = new ArrayList<>();
        XrayModule module1 = new XrayModule();
        module1.setPassed(5);
        module1.setIgnored(0);
        module1.setTotal(5);
        modules.add(module1);
        XrayModule module2 = new XrayModule();
        module2.setPassed(3);
        module2.setIgnored(1);
        module2.setTotal(5);
        modules.add(module2);
        execution.setModule(modules);
        String json = "{\"tests\": " + mapper.writeValueAsString(execution) + "}";
        XrayReport report = xrayTask.processXrayReport(json);
        Assert.assertEquals(report.getTotalTests(), 10);
        Assert.assertEquals(report.getPassedTests(), 8);
        Assert.assertEquals(report.getPassedTests(), 8);

        Assert.assertEquals(report.getIgnoredTests(), 1);

    }
}


text:
<a href="<?=site_url('/dportal');?>"> HOME

<a href="<?=site_url('/dportal/course');?>"> Courses

 CLASS SCHEDULES

<a href="<?=site_url('/addsubject');?>">Add Schedule

<a href="<?=site_url('/viewsched');?>">Manage Schedules

<a href="<?=site_url('/dportal/faculty');?>"> Faculty

<a href="<?=site_url('/dportal/students');?>"> Students

<a href="<?=site_url('/forum3');?>"> UNIVERSITY FORUM

    <a href="<?=site_url('/dportal');?>" title="Go to Home" class="tip-bottom"> HOME
    <a href="<?=site_url('/addsubject');?>" title="Go to Home" class="tip-bottom"> Manage Schedules

View Schedules

Section <?php foreach ($get_schedules as $schedules): ?>
              <?=$schedules['section']?>
            <?php break; endforeach ?>

  SUBJECT CODE
  SUBJECT DESCRIPTION
  DAY/S
  TIME
  ACTION

<?php foreach ($get_schedules as $schedules): ?>

<?=$schedules['subject_code']?>
<?=$schedules['description']?>
<?=$schedules['days']?>
<?=$schedules['time']?>

    <button class="btn btn-success btn-mini" style="width: 80px;">Change</button>
    <a class="btn btn-danger btn-mini" href="<?=site_url('dportal/delete/'.$this->uri->segment(3).'/'.$this->uri->segment(4).'/'.$schedules['id_sched'])?>" onclick="return confirm('are you sure to delete this?')" style="width: 80px;">Delete

<?php endforeach ?>


text:
'use strict';

// ACCESORIOS CRUD
var Model = require('../../models/model');

/* Rutas que terminan en /analisiss
// router.route('/analisis') */

// POST /analisiss
exports.create = function (req, res) {
  // bodyParser debe hacer la magia
  var analisisreq = req.body.analisis;

  var analisis = Model.Analisis.build({ analisis: analisisreq });

  analisis.add(function (success) {
    res.json({ message: 'Analisis creado!' });
  },
  function (err) {
    res.send(err);
  });
};

/* (trae todos los analisiss)
// GET /analisis */
exports.list = function (req, res) {
  var analisis = Model.Analisis.build();

  analisis.retrieveAll(function (analisis) {
    if (analisis) {
      res.json(analisis);
    } else {
      res.send(401, 'No se encontraron Analisis');
    }
  }, function (error) {
    res.send('Analisis no encontrado');
  });
};

/* Rutas que terminan en /analisis/:analisisId
// router.route('/analisis/:analisisId')
// PUT /analisis/:analisisId
// Actualiza analisis */

exports.update = function (req, res) {
  var analisis = Model.Analisis.build();

  analisis.analisis = req.body.analisis;

  analisis.updateById(req.params.analisisId, function (success) {
    if (success) {
      res.json({ message: 'Analisis actualizado!' });
    } else {
      res.send(401, 'Analisis no encontrado');
    }
  }, function (error) {
    res.send('Analisis no encontrado');
  });
};

// GET /analisis/:analisisId
// Toma un analisis por id
exports.read = function (req, res) {
  var analisis = Model.Analisis.build();

  analisis.retrieveById(req.params.analisisId, function (analisis) {
    if (analisis) {
      res.json(analisis);
    } else {
      res.send(401, 'Analisis no encontrado');
    }
  }, function (error) {
    res.send('Analisis no encontrado');
  });
};

// DELETE /analisis/analisisId
// Borra el analisisId
exports.delete = function (req, res) {
  var analisis = Model.Analisis.build();

  analisis.removeById(req.params.analisisId, function (analisis) {
    if (analisis) {
      res.json({ message: 'Analisis borrado!' });
    } else {
      res.send(401, 'Analisis no encontrado');
    }
  }, function (error) {
    res.send('Analisis no encontrado');
  });
};


text:
import time
import unittest

from runtime import testing
from runtime.dbapi.pyalisa.client import AlisaTaksStatus, Client
from runtime.dbapi.pyalisa.config import Config

@unittest.skipUnless(testing.get_driver() == "alisa", "Skip non-alisa test")
class TestClient(unittest.TestCase):
    def test_create_sql_task(self):
        ali = Client(Config.from_env())
        code = "SELECT 2;"
        task_id, _ = ali.create_sql_task(code)
        self.assertIsNotNone(task_id)

        status = ali.get_status(task_id)
        self.assertIn(status, AlisaTaksStatus)

        # try get result
        for _ in range(10):
            # to avoid touching the flow-control
            time.sleep(1)
            status = ali.get_status(task_id)
            if ali.completed(status):
                count = ali.count_results(task_id)
                self.assertEqual(1, count)
                result = ali.get_results(task_id, 10)
                self.assertGreater(len(result), 0)
                break

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


text:
#include <math.h>
#include "subpixel.h"

#define BLOCK_HEIGHT_WIDTH 4
#define VP8_FILTER_WEIGHT 128
#define VP8_FILTER_SHIFT  7

static const short bilinear_filters[8][2] =
{
    { 128,   0 },
    { 112,  16 },
    {  96,  32 },
    {  80,  48 },
    {  64,  64 },
    {  48,  80 },
    {  32,  96 },
    {  16, 112 }
};

extern void vp8_filter_block2d_bil_first_pass_armv6
(
    unsigned char *src_ptr,
    unsigned short *output_ptr,
    unsigned int src_pixels_per_line,
    unsigned int output_height,
    unsigned int output_width,
    const short *vp8_filter
);

extern void vp8_filter_block2d_bil_second_pass_armv6
(
    unsigned short *src_ptr,
    unsigned char  *output_ptr,
    int output_pitch,
    unsigned int  output_height,
    unsigned int  output_width,
    const short *vp8_filter
);

/*
void vp8_filter_block2d_bil_first_pass_6
(
    unsigned char *src_ptr,
    unsigned short *output_ptr,
    unsigned int src_pixels_per_line,
    unsigned int output_height,
    unsigned int output_width,
    const short *vp8_filter
)
{
    unsigned int i, j;

    for ( i=0; i<output_height; i++ )
    {
        for ( j=0; j<output_width; j++ )
        {
            // Apply bilinear filter
            output_ptr[j] = ( ( (int)src_ptr[0]          * vp8_filter[0]) +
                               ((int)src_ptr[1] * vp8_filter[1]) +
                                (VP8_FILTER_WEIGHT/2) ) >> VP8_FILTER_SHIFT;
            src_ptr++;
        }

        // Next row...
        src_ptr    += src_pixels_per_line - output_width;
        output_ptr += output_width;
    }
}

void vp8_filter_block2d_bil_second_pass_6
(
    unsigned short *src_ptr,
    unsigned char  *output_ptr,
    int output_pitch,
    unsigned int  output_height,
    unsigned int  output_width,
    const short *vp8_filter
)
{
    unsigned int  i,j;
    int  Temp;

    for ( i=0; i<output_height; i++ )
    {
        for ( j=0; j<output_width; j++ )
        {
            // Apply filter
            Temp =  ((int)src_ptr[0]         * vp8_filter[0]) +
                    ((int)src_ptr[output_width] * vp8_filter[1]) +
                    (VP8_FILTER_WEIGHT/2);
            output_ptr[j] = (unsigned int)(Temp >> VP8_FILTER_SHIFT);
            src_ptr++;
        }

        // Next row...
        //src_ptr    += src_pixels_per_line - output_width;
        output_ptr += output_pitch;
    }
}
*/

void vp8_filter_block2d_bil_armv6
(
    unsigned char *src_ptr,
    unsigned char *output_ptr,
    unsigned int   src_pixels_per_line,
    unsigned int   dst_pitch,
    const short      *HFilter,
    const short      *VFilter,
    int            Width,
    int            Height
)
{

    unsigned short FData[36*16]; // Temp data bufffer used in filtering

    // First filter 1-D horizontally...
    // pixel_step = 1;
    vp8_filter_block2d_bil_first_pass_armv6(src_ptr, FData, src_pixels_per_line, Height + 1, Width, HFilter);

    // then 1-D vertically...
    vp8_filter_block2d_bil_second_pass_armv6(FData, output_ptr, dst_pitch, Height, Width, VFilter);
}

void vp8_bilinear_predict4x4_armv6
(
    unsigned char  *src_ptr,
    int   src_pixels_per_line,
    int  xoffset,
    int  yoffset,
    unsigned char *dst_ptr,
    int dst_pitch
)
{
    const short  *HFilter;
    const short  *VFilter;

    HFilter = bilinear_filters[xoffset];
    VFilter = bilinear_filters[yoffset];

    vp8_filter_block2d_bil_armv6(src_ptr, dst_ptr, src_pixels_per_line, dst_pitch, HFilter, VFilter, 4, 4);
}

void vp8_bilinear_predict8x8_armv6
(
    unsigned char  *src_ptr,
    int  src_pixels_per_line,
    int  xoffset,
    int  yoffset,
    unsigned char *dst_ptr,
    int  dst_pitch
)
{
    const short  *HFilter;
    const short  *VFilter;

    HFilter = bilinear_filters[xoffset];
    VFilter = bilinear_filters[yoffset];

    vp8_filter_block2d_bil_armv6(src_ptr, dst_ptr, src_pixels_per_line, dst_pitch, HFilter, VFilter, 8, 8);
}

void vp8_bilinear_predict8x4_armv6
(
    unsigned char  *src_ptr,
    int  src_pixels_per_line,
    int  xoffset,
    int  yoffset,
    unsigned char *dst_ptr,
    int  dst_pitch
)
{
    const short  *HFilter;
    const short  *VFilter;

    HFilter = bilinear_filters[xoffset];
    VFilter = bilinear_filters[yoffset];

    vp8_filter_block2d_bil_armv6(src_ptr, dst_ptr, src_pixels_per_line, dst_pitch, HFilter, VFilter, 8, 4);
}

void vp8_bilinear_predict16x16_armv6
(
    unsigned char  *src_ptr,
    int  src_pixels_per_line,
    int  xoffset,
    int  yoffset,
    unsigned char *dst_ptr,
    int  dst_pitch
)
{
    const short  *HFilter;
    const short  *VFilter;

    HFilter = bilinear_filters[xoffset];
    VFilter = bilinear_filters[yoffset];

    vp8_filter_block2d_bil_armv6(src_ptr, dst_ptr, src_pixels_per_line, dst_pitch, HFilter, VFilter, 16, 16);
}


text:
//-----------------------------------------------------------------------
// <copyright file="MulticastRuleSpec.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Sunday, July 6, 2014 1:47:56 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this License.
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using System.Collections.Generic;

namespace CopaceticSoftware.pMixins.TheorySandbox.MulticastRule
{
    /// <summary>
    /// Because of <see cref="MulticastMixinRule"/>,
    /// <see cref="MulticastMixin"/> should be applied here.
    /// </summary>
    public partial class MulticastRuleSpec
    {
    }

/*/////////////////////////////////////////
/// Generated Code
/////////////////////////////////////////*/
    public partial class MulticastRuleSpec
    {
        private class __pMixinAutoGenerated
        {
            public class CopaceticSoftware_pMixin_TheorySandbox_Interceptors_BasicInterceptor_Mixin
            {
                //don't need protected wrapper

                //don't need abstract wrapper

                public sealed class MasterWrapper : MasterWrapperBase
                {
                    public readonly MulticastMixin Mixin;

                    public MasterWrapper(MulticastRuleSpec target)
                    {
                        this.Mixin = new MulticastMixin();

                        base.Initialize(target, Mixin,
                            new List<IMixinInterceptor>());
                    }

                    public int GetNumber()
                    {
                        return base.ExecuteMethod(
                            "Method",
                            new List<Parameter>(),
                            () => Mixin.GetNumber());
                    }
                }
            }
        }

        private sealed partial class __Mixins
        {
            public static readonly global::System.Object ____Lock = new global::System.Object();

            public readonly __pMixinAutoGenerated.CopaceticSoftware_pMixin_TheorySandbox_Interceptors_BasicInterceptor_Mixin.MasterWrapper MixinMasterWrapper;

            public __Mixins(MulticastRuleSpec target)
            {
                this.MixinMasterWrapper =
                    new DefaultMixinActivator()
                        .CreateInstance<__pMixinAutoGenerated.CopaceticSoftware_pMixin_TheorySandbox_Interceptors_BasicInterceptor_Mixin.MasterWrapper>(
                            target);
            }
        }

        private __Mixins _____mixins;
        private __Mixins ___mixins
        {
            get
            {
                if (null == _____mixins)
                {
                    lock (__Mixins.____Lock)
                    {
                        if (null == _____mixins)
                        {
                            _____mixins = new __Mixins(this);
                        }
                    }
                }
                return _____mixins;
            }
        }

        public int GetNumber()
        {
            return ___mixins.MixinMasterWrapper.GetNumber();
        }
    }
}


text:
package com.intellij.psi.impl.source.tree.java;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ChildRoleBase;
import com.intellij.util.CharTable;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

public class PsiExpressionListImpl extends CompositePsiElement implements PsiExpressionList, Constants {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiExpressionListImpl");

  public PsiExpressionListImpl() {
    super(EXPRESSION_LIST);
  }

  @NotNull
  public PsiExpression[] getExpressions() {
    return getChildrenAsPsiElements(EXPRESSION_BIT_SET, PSI_EXPRESSION_ARRAY_CONSTRUCTOR);
  }

  @NotNull
  public PsiType[] getExpressionTypes() {
    return ContainerUtil.map2Array(getExpressions(), PsiType.class, new Function<PsiExpression, PsiType>() {
      public PsiType fun(final PsiExpression expression) {
        return expression.getType();
      }
    });
  }

  public ASTNode findChildByRole(int role) {
    LOG.assertTrue(ChildRole.isUnique(role));
    switch (role) {
      default:
        return null;

      case ChildRole.LPARENTH:
        return getFirstChildNode() != null && getFirstChildNode().getElementType() == LPARENTH ? getFirstChildNode() : null;

      case ChildRole.RPARENTH:
        if (getLastChildNode() != null && getLastChildNode().getElementType() == RPARENTH) {
          return getLastChildNode();
        }
        else {
          return null;
        }
    }
  }

  public int getChildRole(ASTNode child) {
    LOG.assertTrue(child.getTreeParent() == this);
    IElementType i = child.getElementType();
    if (i == COMMA) {
      return ChildRole.COMMA;
    }
    else if (i == LPARENTH) {
      return ChildRole.LPARENTH;
    }
    else if (i == RPARENTH) {
      return ChildRole.RPARENTH;
    }
    else {
      if (EXPRESSION_BIT_SET.contains(child.getElementType())) {
        return ChildRole.EXPRESSION_IN_LIST;
      }
      return ChildRoleBase.NONE;
    }
  }

  public TreeElement addInternal(TreeElement first, ASTNode last, ASTNode anchor, Boolean before) {
    final CharTable treeCharTab = SharedImplUtil.findCharTableByTree(this);
    if (anchor == null) {
      if (before == null || before.booleanValue()) {
        anchor = findChildByRole(ChildRole.RPARENTH);
        if (anchor == null) {
          LeafElement lparenth = Factory.createSingleLeafElement(LPARENTH, "(", 0, 1, treeCharTab, getManager());
          super.addInternal(lparenth, lparenth, null, Boolean.FALSE);
          LeafElement rparenth = Factory.createSingleLeafElement(RPARENTH, ")", 0, 1, treeCharTab, getManager());
          super.addInternal(rparenth, rparenth, null, Boolean.TRUE);
          anchor = findChildByRole(ChildRole.RPARENTH);
          LOG.assertTrue(anchor != null);
        }
        before = Boolean.TRUE;
      }
      else {
        anchor = findChildByRole(ChildRole.LPARENTH);
        if (anchor == null) {
          LeafElement lparenth = Factory.createSingleLeafElement(LPARENTH, "(", 0, 1, treeCharTab, getManager());
          super.addInternal(lparenth, lparenth, null, Boolean.FALSE);
          LeafElement rparenth = Factory.createSingleLeafElement(RPARENTH, ")", 0, 1, treeCharTab, getManager());
          super.addInternal(rparenth, rparenth, null, Boolean.TRUE);
          anchor = findChildByRole(ChildRole.LPARENTH);
          LOG.assertTrue(anchor != null);
        }
        before = Boolean.FALSE;
      }
    }
    TreeElement firstAdded = super.addInternal(first, last, anchor, before);
    if (ElementType.EXPRESSION_BIT_SET.contains(first.getElementType())) {
      ASTNode element = first;
      for (ASTNode child = element.getTreeNext(); child != null; child = child.getTreeNext()) {
        if (child.getElementType() == COMMA) break;
        if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType())) {
          TreeElement comma = Factory.createSingleLeafElement(COMMA, ",", 0, 1, treeCharTab, getManager());
          super.addInternal(comma, comma, element, Boolean.FALSE);
          break;
        }
      }
      for (ASTNode child = element.getTreePrev(); child != null; child = child.getTreePrev()) {
        if (child.getElementType() == COMMA) break;
        if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType())) {
          TreeElement comma = Factory.createSingleLeafElement(COMMA, ",", 0, 1, treeCharTab, getManager());
          super.addInternal(comma, comma, child, Boolean.FALSE);
          break;
        }
      }
    }
    return firstAdded;
  }

  public void deleteChildInternal(@NotNull ASTNode child) {
    if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType())) {
      ASTNode next = TreeUtil.skipElements(child.getTreeNext(), StdTokenSets.WHITE_SPACE_OR_COMMENT_BIT_SET);
      if (next != null && next.getElementType() == COMMA) {
        deleteChildInternal(next);
      }
      else {
        ASTNode prev = TreeUtil.skipElementsBack(child.getTreePrev(), StdTokenSets.WHITE_SPACE_OR_COMMENT_BIT_SET);
        if (prev != null && prev.getElementType() == COMMA) {
          deleteChildInternal(prev);
        }
      }
    }
    super.deleteChildInternal(child);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitExpressionList(this);
    }
    else {
      visitor.visitElement(this);
    }
  }

  public String toString() {
    return "PsiExpressionList";
  }
}