text:
import unittest
import StringIO

import bio

class TestFastaDiff( unittest.TestCase ):

  def setUp(self):
    pass

  def _make_reader( self, l ):
    return bio.FastaReader( StringIO.StringIO( '\n'.join( l ) ) )

  def _make_fasta( self, l, log=None ):
    if log is None:
      log = self.quiet_log
    result = bio.ProbabilisticFasta(log=log)
    for fragment in l:
      result.add( fragment, 1 )
    return result

  def test_perfect(self):
    diff = bio.FastaDiff(
      self._make_reader( ( 'gg', 'cc' ) ),
      self._make_fasta( ( 'ggcc', ) ),
      self.quiet_log )
    self.assertEqual( 0, diff.error_total )
    self.assertEqual( 5, diff.candidate_pos )

  def test_snp_error(self):
    diff = bio.FastaDiff(
      self._make_reader( ( 'gg', 'cc' ) ),
      self._make_fasta( ( 'gtcc', ) ),
      self.quiet_log )
    self.assertEqual( 1, diff.error_total )
    self.assertEqual( 5, diff.candidate_pos )

  def test_single_insert_ok(self):
    candidate = self._make_fasta( ( 'ggccaa', ) )
    candidate.insert( 't', 3 )
    diff = bio.FastaDiff(
      self._make_reader( ( 'gg', 'tcc', 'aa' ) ),
      candidate,
      self.quiet_log )
    #print candidate.insertions
    self.assertEqual( 0, diff.error_total )
    self.assertEqual( 7, diff.candidate_pos )

  def test_consecutive_insert_ok(self):
    candidate = self._make_fasta( ( 'gggatgcg', ), log=self.quiet_log )
    candidate.insert( 't', 4 )
    candidate.insert( 'a', 5 )
    # correct is gggtaatggg
    diff = bio.FastaDiff(
      self._make_reader( ( 'ggg', 'taat', 'gcg' ) ),
      candidate,
      self.quiet_log )
    #print candidate.insertions
    self.assertEqual( 0, diff.error_total )
    self.assertEqual( 9, diff.candidate_pos )

  def test_contig_insert_ok(self):
    candidate = self._make_fasta( ( 'gggatgcg', ), log=self.quiet_log )
    candidate.insert( 'ta', 4 )
    # correct is gggtaatggg
    diff = bio.FastaDiff(
      self._make_reader( ( 'ggg', 'taat', 'gcg' ) ),
      candidate,
      self.quiet_log )
    #print candidate.insertions
    self.assertEqual( 0, diff.error_total )
    self.assertEqual( 9, diff.candidate_pos )

  def test_ambiguous_insert_ok(self):
    candidate = self._make_fasta( ( 'cagt', ), log=self.quiet_log )
    candidate.insert( 'a', 2 )
    # correct is caagt
    diff = bio.FastaDiff(
      self._make_reader( ( 'ca', 'agt' ) ),
      candidate,
      self.quiet_log )
    #print candidate.insertions
    self.assertEqual( 0, diff.error_total )
    self.assertEqual( 5, diff.candidate_pos )

  def test_wrong_insert(self):
    #print "enter test_insert_miss"
    candidate = self._make_fasta( ( 'cagt', ), log=self.quiet_log )
    candidate.insert( 'g', 2 )
    # correct is caagt
    reference = self._make_reader( ( 'ca', 'agt' ) )
    diff = bio.FastaDiff(
      reference,
      candidate,
      self.quiet_log )
    #print "insertions:", candidate.insertions
    self.assertEqual( 1, diff.error_total )
    self.assertEqual( 5, diff.candidate_pos )
    #print "exit test_insert_miss"

  def log(self, msg):
    print msg

  def quiet_log(self, msg):
    pass

class TestProbabilisticFasta( unittest.TestCase ):
  def setUp(self):
    pass

  def test_confidence( self ):
    p = bio.ProbabilisticFasta()
    p.add( 'AA', 0, 0.5 )
    p.add( 'CC', 1, 0.5 )
    self.assertEqual( 0.6, p.confidence(0)['A'] )
    self.assertEqual( 0.4, p.confidence(0)['C'] )
    self.assertEqual( 0.5, p.confidence(1)['A'] )
    self.assertEqual( 0.5, p.confidence(1)['C'] )
    self.assertEqual( 0.6, p.confidence(2)['C'] )

  def test_consensus_snp( self ):
    p = bio.ProbabilisticFasta()
    p.add( 'AA', 0, 1. ) # AA-
    p.add( 'CC', 1, 1. ) # -CC
    p.add( 'CG', 1, 1. ) # -CG
    c = p.consensus_at( 0 )
    self.assertEqual( 1, c[0] )
    self.assertEqual( 'A', c[1] )
    self.assertEqual( 1, c[2] )
    self.assertEqual( 1, c[3] )
    c = p.consensus_at( 1 )
    self.assertEqual( 'C', c[1] )
    self.assertEqual( 2, c[2] )
    self.assertEqual( 3, c[3] )
    c = p.consensus_at( 2 )
    self.assertEqual( 'C', c[1] )
    self.assertEqual( 1, c[2] )
    self.assertEqual( 2, c[3] )

  def test_simple_count( self ):
    p = bio.ProbabilisticFasta( log = bio.log_quiet )
    p.add( 'TTATT', 0, 1. )
    self.assertEqual( 1.0, p.count(0)['T'] ) #
    self.assertEqual( 0.0, p.count(0)['A'] )

  def test_simple( self ):
    p = bio.ProbabilisticFasta( log = bio.log_quiet )
    p.add( 'TTATT', 0, 1. )
    # num = base count + 1 => 2
    # denom = 1 (total count) + 2 (#base types) => 3
    self.assertEqual( 2./3, p.confidence(0)['T'] )
    self.assertEqual( 2./3, p.confidence(1)['T'] )
    self.assertEqual( 2./3, p.confidence(2)['A'] )
    self.assertEqual( 2./3, p.confidence(3)['T'] )
    self.assertEqual( 2./3, p.confidence(4)['T'] )

  def test_insert( self ):
    p = bio.ProbabilisticFasta( log = bio.log_quiet )
    # ref = TTATT
    # read = TTAATT
    # cigar = 3M1I2M
    p.add( 'TTA', 0, 1. ) # 2M
    p.insert( 2, 1 ) # 1I
    p.add( 'TT', 3 )
    self.assertEqual( [1., 1., 0, 1., 1.], p.genome['T'] )
    self.assertEqual( [0., 0., 1.], p.genome['A'] )

  def test_delete( self ):
    p = bio.ProbabilisticFasta( log = bio.log_quiet )
    # ref = TTAATT
    # read = TTATT
    # cigar = 3M1D2M
    p.add( 'TTA', 0, 1. ) # 2M
    p.delete( 3, 1 ) # 1D
    p.add( 'TT', 4 )
    self.assertEqual( [1., 1., 0, 0., 1., 1.], p.genome['T'] )
    self.assertEqual( [0., 0., 1.], p.genome['A'] )
    self.assertEqual( [0., 0., 0., 1.], p.genome['-'] )

class TestFastaMutate( unittest.TestCase ):
  def setUp(self):
    pass

  def _make_reader( self, l ):
    return bio.FastaReader( StringIO.StringIO( '\n'.join( l ) ) )

  def test_no_mutate(self):
    #print "test_no_mutate: start"
    reader = self._make_reader( ( 'gg', 'cc' ) )
    mutator = bio.FastaMutate( reader, log=self.quiet_log, snp_prob=0, insert_prob=0, delete_prob=0 )
    items = []
    for item in mutator.items():
      #print "appending", item
      items.append(item)
    #print "items", items
    self.assertTrue( 2, len(items) )
    self.assertEqual( 'gg', items[0] )
    self.assertEqual( 'cc', items[1] )
    #print "test_no_mutate: end"

  def test_snp(self):
    #print "test_snp: start"
    reader = self._make_reader( ( 'gg', 'cc' ) )
    mutator = bio.FastaMutate( reader, log=self.quiet_log, snp_prob=1, insert_prob=0, delete_prob=0, allow_end_mutate=True )
    items = []
    for item in mutator.items():
      #print "appending", item
      items.append(item)
    #print "items", items
    self.assertTrue( 2, len(items) )
    self.assertTrue( 2, len(items[0]) )
    self.assertTrue( 2, len(items[1]) )
    self.assertNotEqual( 'g', items[0][0] )
    self.assertNotEqual( 'g', items[0][1] )
    self.assertNotEqual( 'c', items[1][0] )
    self.assertNotEqual( 'c', items[1][1] )

  def test_insert(self):
    #print "test_snp: start"
    reader = self._make_reader( ( 'gg', 'cc' ) )
    mutator = bio.FastaMutate( reader, log=self.quiet_log, snp_prob=0, insert_prob=1, delete_prob=0, allow_end_mutate=True )
    items = []
    for item in mutator.items():
      items.append(item)
    self.assertTrue( 2, len(items) )
    self.assertTrue( 2, len(items[0]) )
    self.assertTrue( 2, len(items[1]) )
    # 1st two don't have insertions
    self.assertEqual( 'gg', items[0] )
    # 2nd two do have insertions
    self.assertEqual( 4, len(items[1]) )
    self.assertEqual( 'c', items[1][1] )
    self.assertEqual( 'c', items[1][3] )

  def test_insert_tandem(self):
    reader = self._make_reader( ( 'gc', 'at' ) )
    mutator = bio.FastaMutate( reader, log=self.quiet_log, snp_prob=0, insert_prob=1, delete_prob=0, allow_end_mutate=True, insert_source='tandem' )
    items = []
    for item in mutator.items():
      items.append(item)
    self.assertTrue( 2, len(items) )
    self.assertTrue( 2, len(items[0]) )
    self.assertTrue( 2, len(items[1]) )
    # 1st two don't have insertions
    self.assertEqual( 'gc', items[0] )
    # 2nd two do have tandem insertions of length 1
    #print items
    self.assertEqual( 4, len(items[1]) )
    self.assertEqual( 'c', items[1][0] )
    self.assertEqual( 'a', items[1][1] )
    self.assertEqual( 'a', items[1][2] )
    self.assertEqual( 't', items[1][3] )

  def test_insert_tandem_longer(self):
    reader = self._make_reader( ( 'gg', 'at' ) )
    mutator = bio.FastaMutate( reader, log=self.quiet_log, snp_prob=0, insert_prob=1, delete_prob=0, allow_end_mutate=True, insert_source='tandem', min_insert_len=2, max_insert_len=2 )
    items = []
    for item in mutator.items():
      items.append(item)
    self.assertTrue( 2, len(items) )
    self.assertTrue( 2, len(items[0]) )
    self.assertTrue( 2, len(items[1]) )
    # 1st two don't have insertions
    self.assertEqual( 'gg', items[0] )
    # insertion before the last t, ga -> gaga
    self.assertEqual( 4, len(items[1]) )
    self.assertEqual( 'a', items[1][0] )
    self.assertEqual( 'g', items[1][1] )
    self.assertEqual( 'a', items[1][2] )
    self.assertEqual( 't', items[1][3] )

  def quiet_log(self, msg):
    pass

class TestFastaReader( unittest.TestCase ):
  def setUp(self):
    pass

  def test_items( self ):
    g = StringIO.StringIO( '>\nabc\ndef' )
    p = bio.FastaReader( g )
    items = [ f for f in p.items() ]
    self.assertEqual( ['abc', 'def'], items )

  def test_items( self ):
    g = StringIO.StringIO( '>\nabc\ndef' )
    p = bio.FastaReader( g )
    count = 0
    for item in p.items():
      if count == 0:
        self.assertEqual( 'abc', item )
        self.assertTrue( p.has_next_item() )
      if count == 1:
        self.assertEqual( 'def', item )
        self.assertFalse( p.has_next_item() )
      count += 1
    self.assertEqual( 2, count )

class TestMultiFastaReaderContainer( unittest.TestCase ):
  def test_simple( self ):
    mg = StringIO.StringIO( '>s1\npqr\n>s2\nstu\nvwx' )
    mfg = bio.MultiFastaReaderContainer( mg )
    self.assertEqual( 2, len(mfg.fastas) )
    items = [ f for f in mfg.fastas['s1'].items() ]
    self.assertEqual( [ 'pqr' ], items )
    items = [ f for f in mfg.fastas['s2'].items() ]
    self.assertEqual( [ 'stu', 'vwx' ], items )

  def test_simple( self ):
    mg = StringIO.StringIO( '>s1\npqr\n>s2\nstu\nvwx' )
    mfg = bio.MultiFastaReaderContainer( mg )
    f = mfg.find_chromosome( 's1' )
    items = [ x for x in f.items() ]
    self.assertEqual( [ 'pqr' ], items )

  def test_space( self ):
    mg = StringIO.StringIO( '>s1 hi\npqr\n>s2\nstu\nvwx' )
    mfg = bio.MultiFastaReaderContainer( mg )
    f = mfg.find_chromosome( 's1' )
    items = [ x for x in f.items() ]
    self.assertEqual( [ 'pqr' ], items )

class TestMultiFastaReader( unittest.TestCase ):
  def test_simple( self ):
    mg = StringIO.StringIO( '>s1\npqr\n>s2\nstu\nvwx' )
    mfg = bio.MultiFastaReader( mg )
    count = 0
    for fr in mfg.items():
      if count == 0:
        self.assertEqual( 's1', fr.name )
        items = [ f for f in fr.items() ]
        self.assertEqual( [ 'pqr' ], items )
      if count == 1:
        self.assertEqual( 's2', fr.name )
        items = [ f for f in fr.items() ]
        self.assertEqual( [ 'stu', 'vwx' ], items )
      count += 1
    self.assertEqual( 2, count )

class TestRepeatedFastaGenerator( unittest.TestCase ):
  def test_multi( self ):
    mg = StringIO.StringIO( '>s1\npqr\n>s2\nstu\nvwx' )
    mfg = bio.MultiFastaReader( mg )
    og = StringIO.StringIO()
    cfg = { 'mult_snp_prob': 0. }
    bio.RepeatedMultiFastaGenerator( mfg, og, 2, cfg )
    self.assertEqual( '>generated fasta 2x from s1\npqr\npqr\n>generated fasta 2x from s2\nstu\nvwx\nstu\nvwx\n', og.getvalue() )

class TestFastaReaderFromVCF( unittest.TestCase ):
  def test_simple( self ):
    mg = StringIO.StringIO( '>s1\npqrstu\nvwxyz' )
    r = bio.FastaReader( mg )
    vcf = bio.VCF()
    vcf.snp( 2, 'r', 'A' )
    vcf.snp( 6, 'v', 'B' )
    ffv = bio.FastaReaderFromVCF( r, vcf )
    items = [ item for item in ffv.items() ]
    self.assertEqual( 2, len(items))
    self.assertEqual( 'pqAstu', items[0] )
    self.assertEqual( 'Bwxyz', items[1] )

class TestErrorGenerator( unittest.TestCase ):
  def test_snp( self ):
    eg = bio.ErrorGenerator( bio.ErrorGenerator.create_uniform_error_profile( 1. ) )
    m = eg.apply_errors( 'AGTC' )
    self.assertEqual( 4, len(m) )
    self.assertNotEqual( 'A', m[0] )
    self.assertNotEqual( 'G', m[1] )
    self.assertNotEqual( 'T', m[2] )
    self.assertNotEqual( 'C', m[3] )

  def test_no_snp( self ):
    eg = bio.ErrorGenerator( bio.ErrorGenerator.create_uniform_error_profile( 0. ) )
    m = eg.apply_errors( 'AGTC' )
    self.assertEqual( 4, len(m) )
    self.assertEqual( 'A', m[0] )
    self.assertEqual( 'G', m[1] )
    self.assertEqual( 'T', m[2] )
    self.assertEqual( 'C', m[3] )

  def test_homopolymer( self ):
    eg = bio.ErrorGenerator( bio.ErrorGenerator.create_homopolymer_error_profile( 1., 2 ) )
    m = eg.apply_errors( 'GG' )
    self.assertEqual( 6, len(m) )
    self.assertEqual( 'G', m[0] )
    self.assertEqual( m[1], m[2] )
    self.assertEqual( 'G', m[3] )
    self.assertEqual( m[4], m[5] )

class TestFasta( unittest.TestCase ):
  def test_read_to( self ):
    mg = StringIO.StringIO( '>s1\npqrstu\nvwxyz' )
    r = bio.FastaReader( mg )
    f = bio.Fasta( r )
    self.assertTrue( f.read_to( 6 ) )
    self.assertTrue( f.read_to( 4 ) )
    self.assertTrue( f.read_to( 10 ) )
    self.assertFalse( f.read_to( 11 ) )

class TestSequenceGenerator( unittest.TestCase ):

  def test_simple( self ):
    self.assertEqual( 'AAAA', bio.SequenceGenerator( 4, (1.0, 0, 0, 0) ).sequence )
    self.assertEqual( 'TTTT', bio.SequenceGenerator( 4, (0, 0, 0, 1.0) ).sequence )

  def test_mutate( self ):
    s = bio.SequenceGenerator( 4, (1.0, 0, 0, 0) )
    s.mutate( 0 )
    self.assertEqual( 'CAAA', s.sequence )
    s.mutate( 3 )
    self.assertEqual( 'CAAC', s.sequence )
    s.mutate( 0 )
    s.mutate( 0 )
    s.mutate( 0 )
    self.assertEqual( 'AAAC', s.sequence )

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

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn(
      'participant',
      'source_id',
      {
        type: Sequelize.INTEGER,
        references: {
          model: 'source',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      }
    )
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn(
      'participant',
      'source_id'
    )
  }
}


text:
package travel.izi.api.service.constant;

/**
 * The API provides an ability to indicate certain sections to be included
 * into responses using parameters includes and except. It allows to improve
 * performance of API calls by receiving only the portion of the data that a client
 * is interested in. The following table reflects sections names (the parameters values)
 * that can be used for partial response.
 */
@SuppressWarnings("unused")
public final class ContentSectionModifier {

    /**
     * A request with `&includes=all` will return everything in responses (above mentioned
     * sections) and an API client can indicate not required sections via `exclude` parameter in the
     * request in order to reduce response size. For example, `&exclude=city,country,
     * publisher`, `&exclude=children,download,location`.
     */
    public static final String ALL = "all";

    /**
     * None is indicated in includes parameter only `publisher`, `location` and `city_images`
     * will be included into response, when other from the table will be excluded.
     */
    public static final String NONE = "none";

    /**
     * City objects.
     */
    public static final String CITY = "city";

    /**
     * Images section of City (compact, full) object.
     */
    public static final String CITY_IMAGES = "city_images";

    /**
     * Children section from MTGObject full form.
     */
    public static final String CHILDREN = "children";

    /**
     * Museum's collections.
     */
    public static final String COLLECTIONS = "collections";

    /**
     * Country object.
     */
    public static final String COUNTRY = "country";

    /**
     * Download section from/to MTGObject full form.
     */
    public static final String DOWNLOAD = "download";

    /**
     * Location section from/to MTGObject, City and Country sections.
     */
    public static final String LOCATION = "location";

    /**
     * News from/to MTGObject full form.
     */
    public static final String NEWS = "news";

    /**
     * Publisher from/to MTGObject.
     */
    public static final String PUBLISHER = "publisher";

    /**
     * References section from/to MTGObject.
     */
    public static final String REFERENCES = "references";

    /**
     * Reviews section from/to MTGObject.
     */
    public static final String REVIEWS = "reviews";

    /**
     * Country's and City's translations.
     */
    public static final String TRANSLATIONS = "translations";

    /**
     * Sponsors from/to MTGObject full form.
     */
    public static final String SPONSORS = "sponsors";

    /**
     * Route from/to MTGObject compact form.
     */
    public static final String ROUTE = "route";

}


text:
import traceback
import sys

from job_manager.job_utils import JobVncApi

sys.path.append("/opt/contrail/fabric_ansible_playbooks/module_utils")
from filter_utils import FilterLog, _task_log, _task_done, \
    _task_error_log

class FilterModule(object):

    def filters(self):
        return {
            'topology_discovery': self.topology_discovery,
        }
    # end filters

    def _instantiate_filter_log_instance(self, device_name):
        FilterLog.instance("TopologyDiscoveryFilter", device_name)
    # end _instantiate_filter_log_instance

    def topology_discovery(self, job_ctx, prouter_fqname,
                           lldp_neighbors_payload):
        """

        :param job_ctx: Dictionary
            example:
            {
                "auth_token": "EB9ABC546F98",
                "job_input": {
                    "fabric_fq_name": [
                        "default-global-system-config",
                        "fab01"
                    ],
                    "device_auth": [{
                        "username": "root",
                        "password": "Embe1mpls"
                    }],
                    "management_subnets": [
                        {
                            "cidr": "10.87.69.0/25",
                            "gateway": "10.87.69.1"
                        }
                    ],
                    "overlay_ibgp_asn": 64512,
                    "node_profiles": [
                        {
                            "node_profile_name": "juniper-qfx5k"
                        }
                    ]
                }
            }
        :param prouter_fqname: List
            example:
            [
              "default-global-system-config",
              "5c3-qfx2"
            ]
        :param lldp_neighbors_payload: Dictionary
            example:
            {
              "neighbor_info_list":
              [
                {
                  "local_physical_interface_name": "xe-0/0/0",
                  "remote_device_name": "5b5-qfx11",
                  "remote_physical_interface_port_id": "536"
                }
              ]
            }
        :return: Dictionary
        if success, returns
            {
              'status': 'success',
              'topology_discovery_log':
                  <String: topology_discovery_log>,
              'topology_discovery_resp':
                  <Dictionary: topology_discovery_resp>
            }
        if failure, returns
            {
              'status': 'failure',
              'error_msg': <String: exception message>,
              'topology_discovery_log':
                  <String: topology_discovery_log>,
              'topology_discovery_resp':
                  <Dictionary: topology_discovery_resp>

            }
        :param topology_discovery_resp: Dictionary
            example:
            {
              "lldp_neighbors_success_names":
                  <List: <String: lldp_neighbors_success_pair_string>>,
              "lldp_neighbors_failed_info":
                  <List: <Dictionary: lldp_neighbor_failed_obj> >
            }

            :param lldp_neighbors_success_names: List
            example:
                ["bng-contrail-qfx51-15 : ge-0/0/36 --> dhawan : ge-2/3/1"]
            :param lldp_neighbors_failed_info: List
            example:
                [
                  {
                    "lldp_neighbor":
                        "bng-contrail-qfx51-15 : em0 --> sw174 : ge-1/0/46",
                    "warning_message":
                        "Unknown physical interface ng-contrail-qfx51-15:em0"
                  }
                ]
        """
        self._instantiate_filter_log_instance(prouter_fqname[-1])
        _task_log("Starting Topology Discovery")
        try:
            _task_log("Creating neighboring links")
            topology_discovery_resp = self._create_neighbor_links(
                job_ctx,
                lldp_neighbors_payload,
                prouter_fqname)

            _task_done()
            return {
                'status': 'success',
                'topology_discovery_log': FilterLog.instance().dump(),
                'topology_discovery_resp': topology_discovery_resp
            }
        except Exception as ex:
            _task_error_log(str(ex))
            _task_error_log(traceback.format_exc())
            return {'status': 'failure',
                    'error_msg': str(ex),
                    'topology_discovery_log': FilterLog.instance().dump()}
    # end topology_discovery

    def get_vnc_payload(self, prouter_fqname, lldp_neighbors_info):

        vnc_payload = []
        for lldp_neighbor_info in lldp_neighbors_info or []:
            local_phy_int = lldp_neighbor_info.get(
                'local_physical_interface_name')
            phy_int_fqname = []
            phy_int_fqname.extend(prouter_fqname)
            phy_int_fqname.append(local_phy_int.replace(":", "_"))

            remote_phy_int_fqname_str = \
                "default-global-system-config" + \
                ":" + lldp_neighbor_info['remote_device_name'] + \
                ":" +\
                lldp_neighbor_info.get('remote_physical_interface_port_id')

            vnc_payload.append((phy_int_fqname, remote_phy_int_fqname_str))
        return vnc_payload
    # end get_vnc_payload

    # group vnc functions
    def _create_neighbor_links(self, job_ctx,
                               lldp_neighbors_payload,
                               prouter_fqname):

        if not lldp_neighbors_payload.get('neighbor_info_list'):
            _task_log("No neighbors found")
            _task_done()
            return {
                'lldp_neighbors_success_names': [],
                'lldp_neighbors_failed_info': []
            }
        vnc_lib = JobVncApi.vnc_init(job_ctx)

        vnc_topology_disc_payload = self.get_vnc_payload(
            prouter_fqname, lldp_neighbors_payload['neighbor_info_list'])
        topology_disc_payload = self._do_further_parsing(
            vnc_lib, vnc_topology_disc_payload)

        _task_done("Parsed payload completely")

        _task_log("Creating links between neighboring physical interfaces")
        topology_discovery_resp = self._create_physical_interface_refs(
            vnc_lib, topology_disc_payload)
        return topology_discovery_resp
    # end _create_neighbor_links

    def _do_further_parsing(self, vnc_lib, neighbor_info_list):
        topology_disc_payload = []
        for neighbor_info in neighbor_info_list or []:
            remote_neighbor_info = neighbor_info[1].rsplit(":", 1)
            list_resp = vnc_lib.physical_interfaces_list(
                parent_fq_name=remote_neighbor_info[0].split(":"),
                filters={"physical_interface_port_id":
                         remote_neighbor_info[1]}
                )
            if list_resp['physical-interfaces']:
                topology_disc_payload.append([neighbor_info[0],
                                              list_resp['physical-interfaces']
                                              [0]['fq_name']])

        return topology_disc_payload
    # end _do_further_parsing

    def _create_physical_interface_refs(self, vnc_lib, topology_disc_payload):
        # create or update refs between physical interfaces
        # on the local device to the remote device
        object_type = "physical_interface"
        ref_type = object_type
        lldp_neighbors_success_names = []
        lldp_neighbors_failed_info = []

        for topology_disc_info in topology_disc_payload or []:
            try:
                object_fqname = topology_disc_info[0]
                ref_fqname = topology_disc_info[1]
                object_uuid = vnc_lib.fq_name_to_id(object_type, object_fqname)
                vnc_lib.ref_update(object_type, object_uuid,
                                   ref_type, None, ref_fqname, 'ADD')
                lldp_neighbors_success_names.append(object_fqname[-2] + " : " +
                                                    object_fqname[-1] +
                                                    " --> " +
                                                    ref_fqname[-2] + " : " +
                                                    ref_fqname[-1])
            except Exception as ex:
                _task_error_log(str(ex))
                _task_error_log(traceback.format_exc())
                lldp_neighbor_failed_obj = {
                    "lldp_neighbor": object_fqname[-2] + " : " +
                                     object_fqname[-1] + " --> " +
                                     ref_fqname[-2] + " : " +
                                     ref_fqname[-1],
                    "warning_message": str(ex)
                }
                lldp_neighbors_failed_info.append(lldp_neighbor_failed_obj)
        return {
            'lldp_neighbors_success_names': lldp_neighbors_success_names,
            'lldp_neighbors_failed_info': lldp_neighbors_failed_info
        }
    # end _create_physical_interface_refs


text:
const fs = require('fs');
/*
 |--------------------------------------------------------------------------
 | Browser-sync config file
 |--------------------------------------------------------------------------
 |
 | For up-to-date information about the options:
 |   http://www.browsersync.io/docs/options/
 |
 | There are more options than you see here, these are just the ones that are
 | set internally. See the website for more info.
 |
 */
module.exports = {
  ui: false,
  files: ['docs/**.*'],
  watchEvents: ['change'],
  watch: true,
  ignore: ['build'],
  single: false,
  watchOptions: {
    ignoreInitial: true,
  },
  server: "docs",
  https: {
    key: 'C:\\projects\\https\\localhost.key',
    cert: 'C:\\projects\\https\\localhost.crt',
  },
  proxy: false,
  port: 3001,
  middleware: false,
  serveStatic: [],
  ghostMode: {
    clicks: true,
    scroll: true,
    location: true,
    forms: {
      submit: true,
      inputs: true,
      toggles: true,
    },
  },
  logLevel: 'info',
  logPrefix: 'Browsersync',
  logConnections: false,
  logFileChanges: true,
  logSnippet: true,
  rewriteRules: [],
  open: false,
  browser: 'default',
  cors: false,
  xip: false,
  hostnameSuffix: false,
  reloadOnRestart: false,
  notify: true,
  scrollProportionally: true,
  scrollThrottle: 0,
  scrollRestoreTechnique: 'window.name',
  scrollElements: [],
  scrollElementMapping: [],
  reloadDelay: 0,
  reloadDebounce: 500,
  reloadThrottle: 0,
  plugins: [],
  injectChanges: true,
  startPath: null,
  minify: true,
  host: null,
  localOnly: false,
  codeSync: true,
  timestamps: true,
  clientEvents: [
    'scroll',
    'scroll:element',
    'input:text',
    'input:toggles',
    'form:submit',
    'form:reset',
    'click',
  ],
  socket: {
    socketIoOptions: {
      log: false,
    },
    socketIoClientConfig: {
      reconnectionAttempts: 50,
    },
    path: '/browser-sync/socket.io',
    clientPath: '/browser-sync',
    namespace: '/browser-sync',
    clients: {
      heartbeatTimeout: 5000,
    },
  },
  tagNames: {
    less: 'link',
    scss: 'link',
    css: 'link',
    jpg: 'img',
    jpeg: 'img',
    png: 'img',
    svg: 'img',
    gif: 'img',
    js: 'script',
  },
  injectNotification: false,
};


text:
// Copyright (c) 2015 Ionel Gog <ionel.gog@cl.cam.ac.uk>

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
 * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
 * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 */

#include <stdio.h>
#include <boost/asio.hpp>

#include <cstdlib>

#include "base/common.h"
#include "base/job.pb.h"
#include "base/utils.h"

using musketeer::Job;

DEFINE_string(force_framework, "", "Force a framework for all operators in the workflow");
DEFINE_string(beer_query, "", "BEER DSL input file");
DEFINE_string(use_frameworks, "hadoop-spark-graphchi-naiad-powergraph",
              "Specifies the frameworks that can be used. Dash separated.");
DEFINE_bool(operator_merge, true, "Activates Operator Merge");
DEFINE_string(server_port, "20000", "Server Port");
DEFINE_string(server_ip, "", "Server IP");
DEFINE_bool(best_runtime, true, "Optimize for runtime or resource utilization");

inline void init(int argc, char *argv[]) {
  // Set up usage message
  string usage("Runs a job. Sample Usage:\nsubmit_job --beer_query test.rap");
  google::SetUsageMessage(usage);
  google::ParseCommandLineFlags(&argc, &argv, false);
  google::InitGoogleLogging(argv[0]);
}

Job* populateProtobuf() {
  LOG(INFO) << "Populate Protobuf";
  Job* job = new Job();
  job->set_force_framework(FLAGS_force_framework.c_str());
  job->set_frameworks(FLAGS_use_frameworks.c_str());
  if (FLAGS_operator_merge) {
    job->set_operator_merge("1");
  } else {
    job->set_operator_merge("0");
  }
  job->set_code(FLAGS_beer_query.c_str());
  return job;
}

int main(int argc, char* argv[]) {
  LOG(INFO) << "Begin Job Submission";
  init(argc, argv);
  FLAGS_logtostderr = true;
  FLAGS_stderrthreshold = 0;
  Job* job = populateProtobuf();
  LOG(INFO) << "Send Job";
  boost::asio::io_service io_service;
  boost::asio::ip::address serv_address =
    boost::asio::ip::address::from_string(FLAGS_server_ip.c_str());
  LOG(INFO) << FLAGS_server_ip;
  int port = atoi(FLAGS_server_port.c_str());
  LOG(INFO) << "Port : " << port;
  boost::asio::ip::tcp::endpoint endpoint(serv_address, port);
  LOG(INFO) << "Connect";
  boost::asio::ip::tcp::socket socket(io_service);
  socket.connect(endpoint);
  string buffer;
  job->SerializeToString(&buffer);
  boost::system::error_code ignored_error;
  boost::asio::write(socket, boost::asio::buffer(buffer.c_str(), buffer.size()),
                     boost::asio::transfer_at_least(buffer.size()),
                     ignored_error);
  LOG(INFO) << "Message sent";
  return 0;
}


text:
import unittest

from katas.beta.for_loop import problem

class ProblemTestCase(unittest.TestCase):
    def test_equals(self):
        self.assertEqual(problem(5), [1, 2, 3, 4, 5])


text:
package com.google.ratel.deps.fileupload;

import java.io.File;
import com.google.ratel.deps.fileupload.disk.DiskFileItem;

/**
 *
 The default implementation of the
 * {@link com.google.ratel.deps.fileupload.FileItem FileItem} interface.
 *
 *
 After retrieving an instance of this class from a {@link
 * com.google.ratel.deps.fileupload.DiskFileUpload DiskFileUpload} instance (see
 * {@link com.google.ratel.deps.fileupload.DiskFileUpload
 * #parseRequest(javax.servlet.http.HttpServletRequest)}), you may
 * either request all contents of file at once using {@link #get()} or
 * request an {@link java.io.InputStream InputStream} with
 * {@link #getInputStream()} and process the file without attempting to load
 * it into memory, which may come handy with large files.
 *
 * @version $Id: DefaultFileItem.java 1454690 2013-03-09 12:08:48Z simonetripodi $
 *
 * @deprecated 1.1 Use DiskFileItem instead.
 */
@Deprecated
public class DefaultFileItem
    extends DiskFileItem {

    // ----------------------------------------------------------- Constructors

    /**
     * The UID to use when serializing this instance.
     */
    private static final long serialVersionUID = 4088572813833518255L;

    /**
     * Constructs a new DefaultFileItem instance.
     *
     * @param fieldName     The name of the form field.
     * @param contentType   The content type passed by the browser or
     *                      null if not specified.
     * @param isFormField   Whether or not this item is a plain form field, as
     *                      opposed to a file upload.
     * @param fileName      The original filename in the user's filesystem, or
     *                      null if not specified.
     * @param sizeThreshold The threshold, in bytes, below which items will be
     *                      retained in memory and above which they will be
     *                      stored as a file.
     * @param repository    The data repository, which is the directory in
     *                      which files will be created, should the item size
     *                      exceed the threshold.
     *
     * @deprecated 1.1 Use DiskFileItem instead.
     */
    @Deprecated
    public DefaultFileItem(String fieldName, String contentType,
            boolean isFormField, String fileName, int sizeThreshold,
            File repository) {
        super(fieldName, contentType, isFormField, fileName, sizeThreshold,
                repository);
    }

}


text:
package es.gob.afirma.signers.ooxml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.Logger;

import javax.xml.crypto.MarshalException;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.TransformException;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import net.java.xades.security.xml.XAdES.SignatureProductionPlace;
import net.java.xades.security.xml.XAdES.SignatureProductionPlaceImpl;
import net.java.xades.security.xml.XAdES.SignerRole;
import net.java.xades.security.xml.XAdES.SignerRoleImpl;
import net.java.xades.security.xml.XAdES.XAdES;
import net.java.xades.security.xml.XAdES.XAdES_BES;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.SAXException;

import es.gob.afirma.signers.xml.XMLConstants;

/** Firmador XAdES OOXML.
 * @author Tomás García-Merás */
final class OOXMLXAdESSigner {

	private static final String ID_PACKAGE_OBJECT = "idPackageObject"; //$NON-NLS-1$
	private static final String ID_OFFICE_OBJECT = "idOfficeObject"; //$NON-NLS-1$

	private static final Logger LOGGER = Logger.getLogger("es.gob.afirma");	//$NON-NLS-1$

    /** URI que define la versión por defecto de XAdES. */
    private static final String XADESNS = "http://uri.etsi.org/01903/v1.3.2#"; //$NON-NLS-1$

    private static final String XADES_SIGNATURE_PREFIX = "xd"; //$NON-NLS-1$
    private static final String XML_SIGNATURE_PREFIX = "ds"; //$NON-NLS-1$

    private OOXMLXAdESSigner() {
    	// No permitimos la instanciacion
    }

    /** Obtiene el XML de firma XAdES <i>enveloping</i> OOXML.
     * @param ooXmlDocument Documento OOXML original
     * @param algorithm Algoritmo de firma
     * @param pk Clave privada para la firma
     * @param certChain Cadena de certificados del firmante
     * @param xParams Parámetros adicionales de la firma
     * @return XML de firma
     * @throws ParserConfigurationException Si hay problemas con el analizador XML por defecto.
     * @throws GeneralSecurityException Si ocurre algún problema de seguridad.
     * @throws TransformerException Si hay problemas con los motores de transformadas.
     * @throws SAXException Si hay problemas en XML SAX.
     * @throws IOException Si hay problemas genéricos en el tratamiento de datos.
     * @throws TransformException Si no se puede aplicar alguna transformación necesaria.
     * @throws XMLSignatureException Si hay problemas con la firma XML.
     * @throws MarshalException Si hay problemas con la envoltura de la firma XML. */
    static byte[] getSignedXML(final byte[] ooXmlDocument,
    		                   final String algorithm,
    						   final PrivateKey pk,
    						   final X509Certificate[] certChain,
    						   final Properties xParams) throws ParserConfigurationException,
    								                            GeneralSecurityException,
    								                            IOException,
    								                            SAXException,
    								                            TransformerException,
    								                            MarshalException,
    								                            XMLSignatureException,
    								                            TransformException  {

		final String algoUri = XMLConstants.SIGN_ALGOS_URI.get(algorithm);
		if (algoUri == null) {
			throw new UnsupportedOperationException(
				"Los formatos de firma XML no soportan el algoritmo de firma '" + algorithm + "'" //$NON-NLS-1$ //$NON-NLS-2$
			);
		}

		final Properties extraParams = xParams != null ? xParams : new Properties();

		final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		final Document docSignature = dbf.newDocumentBuilder().newDocument();

		// Instancia XADES_EPES
		final XAdES_BES xades = XAdES.newInstance(
			XAdES.BES, // XAdES
			XADESNS, // XAdES NameSpace
			XADES_SIGNATURE_PREFIX, // XAdES Prefix
			XML_SIGNATURE_PREFIX, // XMLDSig Prefix
			DigestMethod.SHA512, // DigestMethod
			docSignature, // Document
			docSignature.getDocumentElement() // Element
		);

		//*******************************************************************
		//************* ATRIBUTOS XAdES *************************************

		// SigningCertificate
		xades.setSigningCertificate(certChain[0]);

		// SignatureProductionPlace
		final SignatureProductionPlace spp = getSignatureProductionPlace(
			extraParams.getProperty("signatureProductionCity"), //$NON-NLS-1$
			extraParams.getProperty("signatureProductionProvince"), //$NON-NLS-1$
			extraParams.getProperty("signatureProductionPostalCode"), //$NON-NLS-1$
			extraParams.getProperty("signatureProductionCountry") //$NON-NLS-1$
		);
		if (spp != null) {
			xades.setSignatureProductionPlace(spp);
		}

		// SignerRole
		SignerRole signerRole = null;
		try {
			final String claimedRole = extraParams.getProperty("signerClaimedRole"); //$NON-NLS-1$
			final String certifiedRole = extraParams.getProperty("signerCertifiedRole"); //$NON-NLS-1$
			signerRole = new SignerRoleImpl();
			if (claimedRole != null) {
				signerRole.addClaimedRole(claimedRole);
			}
			if (certifiedRole != null) {
				signerRole.addCertifiedRole(certifiedRole);
			}
		}
		catch (final Exception e) {
			// Se ignoran los errores, el parametro es opcional
		}
		if (signerRole != null) {
			xades.setSignerRole(signerRole);
		}

		// SigningTime
		xades.setSigningTime(new Date());

		//************* FIN ATRIBUTOS XAdES *********************************
		//*******************************************************************

		// Creamos el objeto final de firma
		final OOXMLAdvancedSignature xmlSignature = OOXMLAdvancedSignature.newInstance(xades, ooXmlDocument);

		// Lista de referencias a firmar
		final List<Reference> referenceList = new ArrayList<Reference>();

		// Identificador de primer nivel de la firma
		final String signatureId = "xmldsig-" + UUID.randomUUID().toString(); //$NON-NLS-1$

		// Creamos la factoria de firma XML
	    XMLSignatureFactory fac;

		try {
			// Primero comprobamos si hay una version nueva de XMLSec accesible, en cuyo caso, podria
			// provocar un error el no usarla. Normalmente, ClassCastException al recuperar la factoria.
			fac =  XMLSignatureFactory.getInstance(
				"DOM", //$NON-NLS-1$
				(Provider) Class.forName("org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI").newInstance() //$NON-NLS-1$
			);
			LOGGER.info("Se usara la factoria XML del XMLSec instalado"); //$NON-NLS-1$
		}
		catch (final Exception e) {
			fac = XMLSignatureFactory.getInstance("DOM"); //$NON-NLS-1$
		}

	    // Huella digital para las referencias
	    final DigestMethod digestMethod = fac.newDigestMethod(DigestMethod.SHA512, null);

		// Anadimos los nodos especificos OOXML y las referencias a ellos

		// idPackageObject
		xmlSignature.addXMLObject(
			OOXMLPackageObjectHelper.getPackageObject(
				ID_PACKAGE_OBJECT,
				fac,
				ooXmlDocument,
				docSignature,
				signatureId
			)
		);
		referenceList.add(
			fac.newReference(
				"#" + ID_PACKAGE_OBJECT, //$NON-NLS-1$
				digestMethod,
				null,
				"http://www.w3.org/2000/09/xmldsig#Object", //$NON-NLS-1$
				null
			)
		);

		// idOfficeObject
		xmlSignature.addXMLObject(
			OOXMLOfficeObjectHelper.getOfficeObject(
				ID_OFFICE_OBJECT,
				fac,
				docSignature,
				signatureId,
				extraParams.getProperty("signatureComments"), //$NON-NLS-1$
				extraParams.getProperty("signatureAddress1"), //$NON-NLS-1$
				extraParams.getProperty("signatureAddress2") //$NON-NLS-1$
			)
		);
		referenceList.add(
			fac.newReference(
				"#" + ID_OFFICE_OBJECT, //$NON-NLS-1$
				digestMethod,
				null,
				"http://www.w3.org/2000/09/xmldsig#Object", //$NON-NLS-1$
				null
			)
		);

		xmlSignature.sign(
			certChain,
			pk,
			XMLConstants.SIGN_ALGOS_URI.get(algorithm),
			referenceList,
			signatureId
		);

		return writeXML(
			docSignature.getDocumentElement()
		);
    }

    /** Escribe un XML como texto.
     * @param node Nodo XML que queremos pasar a texto
     * @return Cadena de texto con el XML en forma de array de octetos */
    private static byte[] writeXML(final Node node) {

        // La codificacion por defecto sera UTF-8
        final String xmlEncoding = "UTF-8"; //$NON-NLS-1$

        // Primero creamos un writer
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(baos, xmlEncoding);
        }
        catch (final UnsupportedEncodingException e) {
            LOGGER.warning("La codificacion '" + xmlEncoding + "' no es valida, se usara la por defecto: " + e); //$NON-NLS-1$ //$NON-NLS-2$
            writer = new OutputStreamWriter(baos);
        }

        // Ahora escribimos el XML usando XALAN
        writeXMLwithXALAN(writer, node, xmlEncoding);

        try {
            DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
        }
        catch (final Exception e) {
            LOGGER.severe("No se ha podido recargar el XML para insertar los atributos de la cabecera, quizas la codificacion se vea afectada: " + e); //$NON-NLS-1$
            return baos.toByteArray();
        }

        // Y devolvemos el resultado como array de bytes, insertando antes la
        // cabecera de hoja de estilo
        try {
            return new String(baos.toByteArray(), xmlEncoding).getBytes(xmlEncoding);
        }
        catch (final Exception e) {
            LOGGER.warning("La codificacion '" + xmlEncoding + "' no es valida, se usara la por defecto del sistema: " + e); //$NON-NLS-1$ //$NON-NLS-2$
            return new String(baos.toByteArray()).getBytes();
        }
    }

	private static void writeXMLwithXALAN(final Writer writer, final Node node, final String xmlEncoding) {
        final LSSerializer serializer = ((DOMImplementationLS) node.getOwnerDocument().getImplementation()).createLSSerializer();
        serializer.getDomConfig().setParameter("namespaces", Boolean.FALSE); //$NON-NLS-1$
        final com.sun.org.apache.xerces.internal.dom.DOMOutputImpl output = new com.sun.org.apache.xerces.internal.dom.DOMOutputImpl();
        output.setCharacterStream(writer);
        if (xmlEncoding != null) {
            output.setEncoding(xmlEncoding);
        }
        serializer.write(node, output);
    }

    private static SignatureProductionPlace getSignatureProductionPlace(final String city,
                                                                        final String province,
                                                                        final String postalCode,
                                                                        final String country) {
    	if (city == null && province == null && postalCode == null && country == null) {
    		return null;
    	}
    	return new SignatureProductionPlaceImpl(city, province, postalCode, country);
    }

}


text:
$(document).ready(function() {
    $('#selected_color').minicolors({theme: 'bootstrap'})

    // page is now ready, initialize the calendar...

    colors = {};
    for(var i = 0; i < courses.length; i++) {
        colors[courses[i]] = randomColor({luminosity: 'dark'});
    }

    function eventCourse(event) {
        return event.title.substr(0,4);
    }

    for(var i = 0; i < courses_events.length; i++) {
        courses_events[i].backgroundColor = colors[eventCourse(courses_events[i])];
    }

    $('#calendar').fullCalendar({
        defaultView: 'agendaWeek',
        minTime: '8:00:00',
        maxTime: '20:00:00',
        allDaySlot: false,
        contentHeight: 'auto',
        hiddenDays: [0],
        firstDay: 1,
        columnFormat: 'dddd',
        events: courses_events,
        eventClick: function(event, element) {

            color = $('#selected_color').val();

            $('#calendar').fullCalendar('updateEvent', event);
            var events = $('#calendar').fullCalendar('clientEvents', function(evt) {
                return eventCourse(evt) == eventCourse(event);
            });
            for (var i = 0; i < events.length; i++) {
                if (color != "") {
                    events[i].backgroundColor = color;
                    $('#calendar').fullCalendar('updateEvent', events[i]);
                }
            }

        }
    })

    $('.fc-toolbar').remove();
    $("#pngbutton").click(function () {
html2canvas($("#calendar"), {
     onrendered: function (canvas) {
         // canvas is the final rendered <canvas> element
         var myImage = canvas.toDataURL("image/png");
         window.open(myImage);
     }})
 });
    $("#pdfbutton").click(function () {
        html2canvas($('#calendar-container'), {
            logging: true,
            useCORS: true,
            background: "#ffffff",
            onrendered: function (canvas) {
                var imgData = canvas.toDataURL("image/jpeg");
		var imgTemp = new Image;
		imgTemp.src = imgData;
        // Keep image ratio while inserting into PDF
		var ratio = imgTemp.width / imgTemp.height;

                var doc = new jsPDF("landscape");
		if (ratio > 1.414) {
                	doc.addImage(imgData, 'jpeg', 10, 210-(277/ratio), 277, 277/ratio);
		} else {
                	doc.addImage(imgData, 'jpeg', (297-(190*ratio))/2, 10, 190*ratio, 190);
		}

                download(doc.output(), "edt.pdf", "text/pdf");
            }
        });
    }); // $("#calendar_btn_pdf").click(function ()

    function download(strData, strFileName, strMimeType) {
        var D = document,
            A = arguments,
            a = D.createElement("a"),
            d = A[0],
            n = A[1],
            t = A[2] || "text/plain";

        //build download link:
        a.href = "data:" + strMimeType + "," + escape(strData);

        if (window.MSBlobBuilder) {
            var bb = new MSBlobBuilder();
            bb.append(strData);
            return navigator.msSaveBlob(bb, strFileName);
        } /* end if(window.MSBlobBuilder) */

        if ('download' in a) {
            a.setAttribute("download", n);
            a.innerHTML = "downloading...";
            D.body.appendChild(a);
            setTimeout(function() {
                var e = D.createEvent("MouseEvents");
                e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                a.dispatchEvent(e);
                D.body.removeChild(a);
            }, 66);
            return true;
        } /* end if('download' in a) */

        //do iframe dataURL download:
        var f = D.createElement("iframe");
        D.body.appendChild(f);
        f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
        setTimeout(function() {
            D.body.removeChild(f);
        }, 333);
        return true;
    } /* end download() */

});


text:
#pragma once

#include "chronotext/InputSource.h"

#include "FMOD.hpp"

#include <memory>

typedef std::shared_ptr<class Effect> EffectRef;

class Effect
{
public:
    chr::InputSourceRef inputSource;
    FMOD::Sound *sound;

    Effect(chr::InputSourceRef inputSource, FMOD::Sound *sound);
    ~Effect();

    double getDuration();

protected:
    double duration;
};


text:
import warnings
from drift.contrib.flask.devapp import app
warnings.warn(
    "Use drift.contrib.flask.devapp instead of drift.devapp.",
    DeprecationWarning,
    stacklevel=2,
)


text:
using System;
using System.Security;

using GostCryptography.Gost_R3410;

using NUnit.Framework;
using System.Security.Cryptography.X509Certificates;

using GostCryptography.Base;

namespace GostCryptography.Tests.Gost_R3410
{
	[TestFixture(Description = "Проверка возможности установки пароля для контейнера ключей")]
	public class SetContainerPasswordTest
	{
		[Test]
		[TestCaseSource(typeof(TestConfig), nameof(TestConfig.Gost_R3410_2001_Certificates))]
		public void ShouldSetContainerPassword_R3410_2001(TestCertificateInfo testCase)
		{
			// Given
			var data = GetSomeData();
			var certificate = testCase.Certificate;
			var securePassword = CreateSecureString(TestConfig.ContainerPassword);

			// When

			var privateKeyInfo = certificate.GetPrivateKeyInfo();
			var privateKey = new Gost_R3410_2001_AsymmetricAlgorithm(privateKeyInfo);
			privateKey.SetContainerPassword(securePassword);

			var signature = CreateSignature(privateKey, data);
			var isValidSignature = VerifySignature(privateKey, data, signature);

			// Then
			Assert.IsTrue(isValidSignature);
		}

		[Test]
		[TestCaseSource(typeof(TestConfig), nameof(TestConfig.Gost_R3410_2012_256_Certificates))]
		public void ShouldSetContainerPassword_R3410_2012_256(TestCertificateInfo testCase)
		{
			// Given
			var data = GetSomeData();
			var certificate = testCase.Certificate;
			var securePassword = CreateSecureString(TestConfig.ContainerPassword);

			// When

			var privateKeyInfo = certificate.GetPrivateKeyInfo();
			var privateKey = new Gost_R3410_2012_256_AsymmetricAlgorithm(privateKeyInfo);
			privateKey.SetContainerPassword(securePassword);

			var signature = CreateSignature(privateKey, data);
			var isValidSignature = VerifySignature(privateKey, data, signature);

			// Then
			Assert.IsTrue(isValidSignature);
		}

		[Test]
		[TestCaseSource(typeof(TestConfig), nameof(TestConfig.Gost_R3410_2012_512_Certificates))]
		public void ShouldSetContainerPassword_R3410_2012_512(TestCertificateInfo testCase)
		{
			// Given
			var data = GetSomeData();
			var certificate = testCase.Certificate;
			var securePassword = CreateSecureString(TestConfig.ContainerPassword);

			// When

			var privateKeyInfo = certificate.GetPrivateKeyInfo();
			var privateKey = new Gost_R3410_2012_512_AsymmetricAlgorithm(privateKeyInfo);
			privateKey.SetContainerPassword(securePassword);

			var signature = CreateSignature(privateKey, data);
			var isValidSignature = VerifySignature(privateKey, data, signature);

			// Then
			Assert.IsTrue(isValidSignature);
		}

		private static byte[] CreateSignature(GostAsymmetricAlgorithm privateKey, byte[] data)
		{
			byte[] hash;

			using (var hashAlg = privateKey.CreateHashAlgorithm())
			{
				hash = hashAlg.ComputeHash(data);
			}

			return privateKey.CreateSignature(hash);
		}

		private static bool VerifySignature(GostAsymmetricAlgorithm publicKey, byte[] data, byte[] signature)
		{
			byte[] hash;

			using (var hashAlg = publicKey.CreateHashAlgorithm())
			{
				hash = hashAlg.ComputeHash(data);
			}

			return publicKey.VerifySignature(hash, signature);
		}

		private static SecureString CreateSecureString(string value)
		{
			var result = new SecureString();

			foreach (var c in value)
			{
				result.AppendChar(c);
			}

			result.MakeReadOnly();

			return result;
		}

		private static byte[] GetSomeData()
		{
			var random = new Random();
			var data = new byte[1024];
			random.NextBytes(data);
			return data;
		}
	}
}


text:
<!DOCTYPE html>

		<title>Bootstrap Multiselect</title>
		<meta name="robots" content="noindex, nofollow" />
		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<meta name="copyright" content="David Stutz" />

		<link rel="stylesheet" href="css/bootstrap-3.0.0.min.css" type="text/css">
		<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css">
		<link rel="stylesheet" href="css/prettify.css" type="text/css">

Bootstrap Multiselect

Bootstrap Multiselect is a JQuery based plugin to provide an intuitive user interface for using select inputs with the multiple attribute present. Instead of a select a bootstrap button will be shown as dropdown menu containing the single options as checkboxes.

				Note: The option names may have changed due to the latest updates.

Getting Started

<!-- Include Twitter Bootstrap and jQuery: -->
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>

<!-- Include the plugin's CSS and JS: -->
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css"/>

<!-- Build your select: -->
<select class="multiselect" multiple="multiple">
  <option value="cheese">Cheese</option>
  <option value="tomatoes">Tomatoes</option>
  <option value="mozarella">Mozzarella</option>
  <option value="mushrooms">Mushrooms</option>
  <option value="pepperoni">Pepperoni</option>
  <option value="onions">Onions</option>
</select>

<!-- Initialize the plugin: -->
<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect();
  });
</script>

Examples

				The best way learning from the examples is using firebug, chrome developer tools or similar tools for your browser. Examine the generated markup and used javascript code.

						<select id="example1">
							<option value="cheese" selected>Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Normal select. The plugin will do single selection using radio buttons rather than multiple selection using checkboxes.

			            <select id="example2" multiple="multiple">
			                <option value="cheese" selected>Cheese</option>
			                <option value="tomatoes" selected>Tomatoes</option>
			                <option value="mozarella" selected>Mozzarella</option>
			                <option value="mushrooms">Mushrooms</option>
			                <option value="pepperoni">Pepperoni</option>
			                <option value="onions">Onions</option>
			            </select>

			            Select with preselected options: <option value="cheese" selected>Cheese</option>

			            <select id="example27" multiple="multiple">
			                <option value="cheese">Cheese</option>
			                <option value="tomatoes">Tomatoes</option>
			                <option value="mozarella">Mozzarella</option>
			                <option value="mushrooms">Mushrooms</option>
			                <option value="pepperoni">Pepperoni</option>
			                <option value="onions">Onions</option>
			            </select>

			            Multiselect with a 'Select all' option

						<select id="example28" multiple="multiple"></select>

						Multiselect with a 'Select all' option and filtering enabled using the enableFiltering option.

						<select id="example3" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						As link using buttonClass: 'btn btn-link'.

						<select id="example4" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Small button using buttonClass: 'btn btn-default btn-sm'.

						<select id="example5" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Disabled using buttonClass: 'btn btn-primary disabled'.

							<select id="example6" multiple="multiple">
								<option value="cheese">Cheese</option>
								<option value="tomatoes">Tomatoes</option>
								<option value="mozarella">Mozzarella</option>
								<option value="mushrooms">Mushrooms</option>
								<option value="pepperoni">Pepperoni</option>
								<option value="onions">Onions</option>
							</select>
							<button class="btn btn-danger">Cancel</button>
							<button class="btn btn-success">Save</button>

						Multiple select within a group with add-ons and default container for the plugin: buttonContainer: '<div class="btn-group" />'.

						<select id="example9" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Using the onChange option you can add an event handler to the change event. The event handler gets the selected option as first parameter and a variable saying whether the option is checked or not as second one.

						<select id="example11" multiple="multiple">

						</select>

						For long option lists the maxHeight option can be set.

						<select id="example13" multiple="multiple">
							<option value="enabled1">Enabled 1</option>
							<option value="enabled2">Enabled 2</option>
							<option value="disabled2" disabled="disabled">Disabled 1</option>
						</select>

						The plugin supports disabled options, too: disabled="disabled"

						<select id="example14" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Use the buttonWidth option to adjust the width of the button.

						<select id="example16" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Using the onChange option to prevent user from deselecting selected options.

						<select id="example19" multiple="multiple">
							<optgroup label="Mathematics">
								<option value="analysis">Analysis</option>
								<option value="algebra">Linear Algebra</option>
								<option value="discrete">Discrete Mathematics</option>
								<option value="numerical">Numerical Analysis</option>
								<option value="probability">Probability Theory</option>
							</optgroup>
							<optgroup label="Computer Science">
								<option value="programming">Introduction to Programming</option>
								<option value="automata">Automata Theory</option>
								<option value="complexity">Complexity Theory</option>
								<option value="software">Software Engineering</option>
							</optgroup>
						</select>

						Option groups are detected automatically and for each option group an header element is added: <optgroup label="Mathematics">...</optgroup>

						<select id="example23" multiple="multiple">
							<option value="lab">Lab Course</option>
							<option value="proseminar">Proseminar</option>
							<optgroup label="Mathematics">
								<option value="analysis">Analysis</option>
								<option value="algebra">Linear Algebra</option>
								<option value="discrete">Discrete Mathematics</option>
								<option value="numerical">Numerical Analysis</option>
								<option value="probability">Probability Theory</option>
							</optgroup>
							<optgroup label="Computer Science">
								<option value="programming">Introduction to Programming</option>
								<option value="automata">Automata Theory</option>
								<option value="complexity">Complexity Theory</option>
								<option value="software">Software Engineering</option>
							</optgroup>
						</select>

						Option groups and options without any group are supported simultaneously.

						<select id="example20" multiple="multiple">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Using the selectedClass option to turn off the active class for selected options.

						<select id="example24" multiple="multiple">
							<option value="analysis" label="Ana">Analysis</option>
							<option value="algebra" label="LA">Linear Algebra</option>
							<option value="discrete" label="Discrete">Discrete Mathematics</option>
							<option value="numerical" label="NumA">Numerical Analysis</option>
							<option value="probability" label="Proba">Probability Theory</option>
						</select>

						Specifiy an alternaitve label for the options: <option label="label"></option>

                        	<select id="example25" multiple="multiple">
                                	<option value="analysis" label="Ana">Analysis</option>
                                    <option value="algebra" label="LA">Linear Algebra</option>
                                    <option value="discrete" label="Discrete">Discrete Mathematics</option>
                                    <option value="numerical" label="NumA">Numerical Analysis</option>
                                    <option value="probability" label="Proba">Probability Theory</option>
	                        </select>

                        Make the menu drop right instead of dropping left with dropRight.

						<select id="example26" multiple="multiple" data-role="multiselect">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						Using the data-role="multiselect" attribute for automatic wireup.

						<select id="example31" multiple="multiple" data-role="multiselect" disabled>
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						The multiselect will adopt the state of the select: <select disabled></select>.

						<select id="example32" multiple="multiple" tabindex="1">
							<option value="cheese">Cheese</option>
							<option value="tomatoes">Tomatoes</option>
							<option value="mozarella">Mozzarella</option>
							<option value="mushrooms">Mushrooms</option>
							<option value="pepperoni">Pepperoni</option>
							<option value="onions">Onions</option>
						</select>

						The button will keep the tabindex of the select.

Methods

						.multiselect('destroy')

								<select id="example8" multiple="multiple">
									<option value="cheese">Cheese</option>
									<option value="tomatoes">Tomatoes</option>
									<option value="mozarella">Mozzarella</option>
									<option value="mushrooms">Mushrooms</option>
									<option value="pepperoni">Pepperoni</option>
									<option value="onions">Onions</option>
								</select>
								<button id="example8-destroy" class="btn btn-danger">Destroy/Unbind</button>

							This method is used to destroy the plugin on the given element - meaning unbinding the plugin.

						.multiselect('refresh')

								<select id="example10" multiple="multiple">
									<option value="cheese">Cheese</option>
									<option value="tomatoes">Tomatoes</option>
									<option value="mozarella">Mozzarella</option>
									<option value="mushrooms">Mushrooms</option>
									<option value="pepperoni">Pepperoni</option>
									<option value="onions">Onions</option>
								</select>
								<button id="example10-select" class="btn btn-default">Select some options</button>
								<button id="example10-deselect" class="btn btn-default">Deselect all</button>
								<button id="example10-refresh" class="btn btn-primary">Refresh</button>

							This method is used to refresh the checked checkboxes based on the currently selected options within the select. Click 'Select some options' so select some of the options (meaning added the selected attribute to some of the options). Then click refresh. The plugin will update the checkboxes accordingly.

						.multiselect('rebuild')

								<select id="example12" multiple="multiple">
									<option value="cheese">Cheese</option>
									<option value="tomatoes">Tomatoes</option>
									<option value="mozarella">Mozzarella</option>
									<option value="mushrooms">Mushrooms</option>
									<option value="pepperoni">Pepperoni</option>
									<option value="onions">Onions</option>
								</select>
								<button id="example12-add" class="btn btn-default">Add some options</button>
								<button id="example12-delete" class="btn btn-default">Delete some options</button>
								<button id="example12-rebuild" class="btn btn-primary">Rebuild</button>

							Rebuilds the whole dropdown menu. All selected options will remain selected (if still existent!).

						.multiselect('select', value)

								<select id="example17" multiple="multiple">
									<option value="cheese">Cheese</option>
									<option value="tomatoes">Tomatoes</option>
									<option value="mozarella">Mozzarella</option>
									<option value="mushrooms">Mushrooms</option>
									<option value="pepperoni">Pepperoni</option>
									<option value="onions">Onions</option>
								</select>
								<button id="example17-cheese" class="btn btn-default">Select cheese</button>
								<button id="example17-mushrooms" class="btn btn-default">Select Mushrooms</button>

							Selects an option by its value. Works also using an array of values.

						.multiselect('deselect', value)

								<select id="example18" multiple="multiple">
									<option value="cheese">Cheese</option>
									<option value="tomatoes">Tomatoes</option>
									<option value="mozarella">Mozzarella</option>
									<option value="mushrooms">Mushrooms</option>
									<option value="pepperoni">Pepperoni</option>
									<option value="onions">Onions</option>
								</select>
								<button id="example18-cheese" class="btn btn-default">Deselect cheese</button>
								<button id="example18-mushrooms" class="btn btn-default">Deselect Mushrooms</button>

							Deselect an option by its value. Works also using an array of values.

						.multiselect('dataprovider', data)

							Provides data for building the select's options the following way:

var data = [
    {label: "ACNP", value: "ACNP"},
    {label: "test", value: "test"}
];
$("#multiselect").multiselect('dataprovider', data);

Further Examples

								<select id="example21" multiple="multiple">
									<option value="cheese">Cheese</option>
									<option value="tomatoes">Tomatoes</option>
									<option value="mozarella">Mozzarella</option>
									<option value="mushrooms">Mushrooms</option>
									<option value="pepperoni">Pepperoni</option>
									<option value="onions">Onions</option>
								</select>
								<button id="example21-toggle" class="btn btn-primary">Select All</button>

<script type="text/javascript">
  /**
   * Gets whether all the options are selected
   * @param {jQuery} $el
   * @returns {bool}
   */
  function multiselect_selected($el) {
    var ret = true;
    $('option', $el).each(function(element) {
      if (!!!$(this).attr('selected')) {
        ret = false;
      }
    });
    return ret;
  }

  /**
   * Selects all the options
   * @param {jQuery} $el
   * @returns {undefined}
   */
  function multiselect_selectAll($el) {
    $('option', $el).each(function(element) {
      $el.multiselect('select', $(this).val());
    });
    console.log($('option[selected]', $el).length)
  }
  /**
   * Deselects all the options
   * @param {jQuery} $el
   * @returns {undefined}
   */
  function multiselect_deselectAll($el) {
    $('option', $el).each(function(element) {
      $el.multiselect('deselect', $(this).val());
    });
    console.log($('option[selected]', $el).length)
  }

  /**
   * Clears all the selected options
   * @param {jQuery} $el
   * @returns {undefined}
   */
  function multiselect_toggle($el, $btn) {
    if (multiselect_selected($el)) {
      multiselect_deselectAll($el);
      $btn.text("Select All");
    }
    else {
      multiselect_selectAll($el);
      $btn.text("Deselect All");
    }
  }

  $(document).ready(function() {
    $('#example21').multiselect();
    $("#example21-toggle").click(function(e) {
      e.preventDefault();
      multiselect_toggle($("#example21"), $(this));
    });
  });
</script>

                            <select id="example22" multiple="multiple">
                                <option value="cheese">Cheese</option>
                                <option value="tomatoes">Tomatoes</option>
                                <option value="mozarella">Mozzarella</option>
                                <option value="mushrooms">Mushrooms</option>
                                <option value="pepperoni">Pepperoni</option>
                                <option value="onions">Onions</option>
                            </select>

<script type="text/javascript">
  $(document).ready(function() {
    $('#example22').multiselect({
      buttonClass: 'btn',
      buttonWidth: 'auto',
      buttonText: function(options) {
        if (options.length == 0) {
          return 'None selected <b class="caret"></b>';
        }
        else if (options.length > 6) {
          return options.length + ' selected  <b class="caret"></b>';
        }
        else {
          var selected = '';
          options.each(function() {
            selected += $(this).text() + ', ';
          });
          return selected.substr(0, selected.length -2) + ' <b class="caret"></b>';
        }
      },
      onChange: function(element, checked) {
        if(checked == true) {
          // action taken here if true
        }
        else if (checked == false) {
          if (confirm('Do you wish to deselect the element?')) {
            // action taken here
          }
          else {
            $("#example22").multiselect('select', element.val());
            return false;
          }
        }
      }
    });
  });
</script>

                                <select id="example33" multiple="multiple">
                                    <option value="cheese">Cheese</option>
                                    <option value="tomatoes">Tomatoes</option>
                                    <option value="mozarella">Mozzarella</option>
                                    <option value="mushrooms">Mushrooms</option>
                                    <option value="pepperoni">Pepperoni</option>
                                    <option value="onions">Onions</option>
                                </select>
                                <button id="example33-configuration-set" class="btn btn-primary">Configuration Set 2</button>

<script type="text/javascript">
  $(document).ready(function() {
    var set = 1;
    $('#example33').multiselect(firstConfigurationSet);

    function rebuildMultiselect(options) {
      $('#example33').multiselect('setOptions', options);
      $('#example33').multiselect('rebuild');
    }

    $('#example33-configuration-set').on('click', function(event) {
      switch (set) {
        case 2:
          rebuildMultiselect(firstConfigurationSet);

          $(this).text('Configuration Set 2');
          set = 1;
          break;
        case 1:
        default:
          rebuildMultiselect(secondConfigurationSet);

          $(this).text('Configuration Set 1');
          set = 2;
          break;
      }
    });
  });
</script>

Options

						Option
						Explanation
						Usage

						buttonText
						A function returning the string displayed if options are selected. All currently selected options and the select are passed as argument. In addition HTML can be added to the button, for example the caret icon seen in the examples.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      buttonText: function(options, select) {
        if (options.length == 0) {
          return 'None selected <b class="caret"></b>';
        }
        else if (options.length > 3) {
          return options.length + ' selected  <b class="caret"></b>';
        }
        else {
          var selected = '';
          options.each(function() {
            selected += $(this).text() + ', ';
          });
          return selected.substr(0, selected.length -2) + ' <b class="caret"></b>';
        }
      }
    });
  });
</script>

						buttonTitle
						Function defining the title of the button. Similar to the buttonText option.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      buttonTitle: function(options, select) {
        var selected = '';
        options.each(function () {
          selected += $(this).text() + ', ';
        });
        return selected.substr(0, selected.length - 2);
      },
    });
  });
</script>

						buttonClass
						The class of the dropdown button. Default: btn.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      buttonClass: 'btn-primary btn-lg'
    });
  });
</script>

						buttonWidth

							The width of the dropdown button. Default: auto.
							Allowed formats:

100px

50%

auto

							If the width is defined using CSS the option should be set to false.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      buttonWidth: '300px'
    });
  });
</script>

						buttonContainer

							The used container holding both the dropdown button and the dropdown menu. Default: <div class="btn-group" />.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      buttonContainer: '<span class="dropdown" />'
    });
  });
</script>

						selectedClass
						The class applied to the parent <li> of selected items. Default: active.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      selectedClass: null
    });
  });
</script>

						onChange

							This event handler is triggered when the selected options are changed.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      onChange: function(element, checked) {
      	alert('Change event invoked!');
      }
    });
  });
</script>

						maxHeight

							Used for a long list of options this option defines the maximum height of the dropdown menu. If the size is exceeded a scrollbar will appear.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      maxHeight: 400
    });
  });
</script>

						includeSelectAllOption

							If set to true a 'Select all' option will be added.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      includeSelectAllOption: true
    });
  });
</script>

						selectAllText

							The label for the 'Select all' option.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      selectAllText: true
    });
  });
</script>

						selectAllValue

							The value by which the select all option is identified.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      selectAllValue: 'multiselect-all',
    });
  });
</script>

						enableFiltering

							If set to true a search field will be added to filter the visible options.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      enableFiltering: true
    });
  });
</script>

						filterPlaceholder

							The placeholder used in the search field if filtering is enabled.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      filterPlaceholder: 'Search'
    });
  });
</script>

						dropRight

							Will make the menu drop right if set to true.

<script type="text/javascript">
  $(document).ready(function() {
    $('.multiselect').multiselect({
      dropRight: true
    });
  });
</script>

Additional Styling

For additionaly styling of the multiselect button the CSS class multiselect can be used.

							<select id="example15" multiple="multiple">
								<optgroup label="Mathematics">
									<option value="analysis">Analysis</option>
									<option value="algebra">Linear Algebra</option>
									<option value="discrete">Discrete Mathematics</option>
									<option value="numerical">Numerical Analysis</option>
									<option value="probability">Probability Theory</option>
								</optgroup>
								<optgroup label="Computer Science">
									<option value="programming">Introduction to Programming</option>
									<option value="automata">Automata Theory</option>
									<option value="complexity">Complexity Theory</option>
									<option value="software">Software Engineering</option>
								</optgroup>
							</select>

							Text alignment combined with fixed width and bold, underlined text for option group headers.

.multiselect {
  text-align: left;
}
.multiselect b.caret {
  float: right;
  margin-top: 9px;
}
.multiselect-group {
  font-weight: bold;
  text-decoration: underline;
}

							<select id="example29" multiple="multiple">

							</select>

							Access the select all option by using the .multiselect-all class. The filter search field can be manipulated by using .multiselect-search;

.multiselect-all label {
  font-weight: bold;
}
.multiselect-search {
  color: red;
}

				© 2012, 2013
				David Stutz - dual licensed: Apache License v2.0, BSD 3-Clause License


text:
package ca.bc.gov.open.cpf.api.web.builder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.jeometry.common.data.type.DataType;
import org.jeometry.common.data.type.DataTypes;
import org.jeometry.common.io.PathName;
import org.jeometry.common.logging.Logs;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ca.bc.gov.open.cpf.api.domain.BatchJob;
import ca.bc.gov.open.cpf.api.domain.ConfigProperty;
import ca.bc.gov.open.cpf.api.domain.CpfDataAccessObject;
import ca.bc.gov.open.cpf.api.scheduler.BusinessApplicationStatistics;
import ca.bc.gov.open.cpf.plugin.api.BusinessApplicationPlugin;
import ca.bc.gov.open.cpf.plugin.impl.BusinessApplication;
import ca.bc.gov.open.cpf.plugin.impl.BusinessApplicationRegistry;
import ca.bc.gov.open.cpf.plugin.impl.ConfigPropertyLoader;
import ca.bc.gov.open.cpf.plugin.impl.module.Module;

import com.revolsys.collection.list.Lists;
import com.revolsys.geometry.model.GeometryDataTypes;
import com.revolsys.geometry.model.GeometryFactory;
import com.revolsys.record.ArrayRecord;
import com.revolsys.record.Record;
import com.revolsys.record.io.ListRecordReader;
import com.revolsys.record.io.RecordReader;
import com.revolsys.record.schema.RecordDefinitionImpl;
import com.revolsys.ui.html.fields.CheckBoxField;
import com.revolsys.ui.html.fields.IntegerField;
import com.revolsys.ui.html.fields.SelectField;
import com.revolsys.ui.html.fields.SpelExpressionField;
import com.revolsys.ui.html.form.Form;
import com.revolsys.ui.html.serializer.key.BooleanImageKeySerializer;
import com.revolsys.ui.html.serializer.key.BulletListKeySerializer;
import com.revolsys.ui.html.serializer.key.PageLinkKeySerializer;
import com.revolsys.ui.html.view.ButtonsToolbarElement;
import com.revolsys.ui.html.view.Element;
import com.revolsys.ui.html.view.ElementContainer;
import com.revolsys.ui.html.view.TabElementContainer;
import com.revolsys.ui.model.Menu;
import com.revolsys.ui.web.annotation.RequestMapping;
import com.revolsys.ui.web.config.Page;
import com.revolsys.ui.web.exception.PageNotFoundException;
import com.revolsys.ui.web.utils.HttpServletUtils;
import com.revolsys.util.Property;

@Controller
public class BusinessApplicationUiBuilder extends CpfUiBuilder {

  public BusinessApplicationUiBuilder() {
    super("businessApplication", "Business Application", "Business Applications");
    setIdParameterName("businessApplicationName");
    setIdPropertyName("name");

    addPage(new Page("clientList", "Business Applications", "/ws/apps"));
    addPage(new Page("clientView", "/ws/apps/{businessApplicationName}/"));
    addPage(new Page("clientInstant", "/ws/apps/{businessApplicationName}/instant/"));
    addPage(new Page("clientSingle", "/ws/apps/{businessApplicationName}/single/"));
    addPage(new Page("clientMultiple", "/ws/apps/{businessApplicationName}/multiple/"));

    newView("clientList",
      Lists.newArray(new PageLinkKeySerializer("clientView", "title", "Name", "clientView") //
        .addParameterKey("businessApplicationName", "name"), "description"));
  }

  @RequestMapping("/ws/sample/input")
  @ResponseBody
  public RecordReader getSampleInputData() {
    final RecordDefinitionImpl recordDefinition = new RecordDefinitionImpl(
      PathName.newPathName("/Buffer"));
    final GeometryFactory factory = GeometryFactory.fixed2d(3005, 1000.0, 1000.0);
    recordDefinition.setGeometryFactory(factory);
    recordDefinition.addField("title", DataTypes.STRING);
    recordDefinition.addField("buffer", DataTypes.DOUBLE);
    recordDefinition.addField("geometry", GeometryDataTypes.GEOMETRY);

    final List<Record> objects = new ArrayList<>();

    final Record object1 = new ArrayRecord(recordDefinition);
    object1.setValue("title", "Buffered centroid of BC");
    object1.setValue("buffer", 10000);
    object1.setGeometryValue(factory.point(921100.281, 1076394.357));
    objects.add(object1);

    final Record object2 = new ArrayRecord(recordDefinition);
    object2.setValue("title", "Stanley Park");
    object2.setValue("buffer", 1000);
    object2.setGeometryValue(factory.point(1207714.288, 480508.637));
    objects.add(object2);

    final ListRecordReader reader = new ListRecordReader(recordDefinition, objects);
    return reader;
  }

  @RequestMapping("/ws/sample/result")
  @ResponseBody
  public RecordReader getSampleResultData() {
    final RecordDefinitionImpl recordDefinition = new RecordDefinitionImpl(
      PathName.newPathName("/Buffer"));
    final GeometryFactory factory = GeometryFactory.fixed2d(3005, 1000.0, 1000.0);
    recordDefinition.setGeometryFactory(factory);
    recordDefinition.addField("sequenceNumber", DataTypes.INT);
    recordDefinition.addField("resultNumber", DataTypes.INT);
    recordDefinition.addField("title", DataTypes.STRING);
    recordDefinition.addField("buffer", DataTypes.DOUBLE);
    recordDefinition.addField("geometry", GeometryDataTypes.GEOMETRY);

    final List<Record> objects = new ArrayList<>();

    final Record object1 = new ArrayRecord(recordDefinition);
    object1.setValue("sequenceNumber", 1);
    object1.setValue("resultNumber", 1);
    object1.setValue("title", "Buffered centroid of BC");
    object1.setValue("buffer", 10000);
    object1.setGeometryValue(factory.point(921100.281, 1076394.357).buffer(10000));
    objects.add(object1);

    final Record object2 = new ArrayRecord(recordDefinition);
    object2.setValue("sequenceNumber", 2);
    object2.setValue("resultNumber", 1);
    object2.setValue("title", "Stanley Park");
    object2.setValue("buffer", 1000);
    object2.setGeometryValue(factory.point(1207714.288, 480508.637).buffer(1000));
    objects.add(object2);

    final ListRecordReader reader = new ListRecordReader(recordDefinition, objects);
    return reader;
  }

  @Override
  protected void initFields() {
    super.initFields();
    addField(new SelectField("logLevel", true) //
      .addOption("ERROR") //
      .addOption("INFO") //
      .addOption("DEBUG"));
    addField(new CheckBoxField("testModeEnabled"));
    addField(new SpelExpressionField("batchModePermission", true));
    addField(new SpelExpressionField("instantModePermission", true));
    addField(new IntegerField("maxRequestsPerJob", true));
    addField(new IntegerField("maxConcurrentRequests", true));
    addField(new IntegerField("numRequestsPerWorker", true));
  }

  @Override
  protected void initSerializers() {
    super.initSerializers();

    addKeySerializer(
      new PageLinkKeySerializer("module_name_link", "module.name", "Module", "view"));
    addKeySerializer(new PageLinkKeySerializer("name_link", "name", "Name", "moduleView") //
      .addParameterKey("businessApplicationName", "name") //
      .addParameterKey("moduleName", "module.name"));
    addKeySerializer(new BulletListKeySerializer("inputDataContentTypes"));
    addKeySerializer(new BulletListKeySerializer("resultDataContentTypes"));
    addKeySerializer(new BooleanImageKeySerializer("testModeEnabled"));
  }

  @RequestMapping(value = {
    "/admin/apps"
  }, title = "Business Applications", method = RequestMethod.GET, fieldNames = {
    "name_link", "module_name_link", "title",
  }, permission = "hasRole('ROLE_ADMIN') or hasRoleRegex('ROLE_ADMIN_MODULE_.*_ADMIN')")
  @ResponseBody
  public Object list(final HttpServletRequest request, final HttpServletResponse response)
    throws IOException {
    checkAdminOrAnyModuleAdminExceptSecurity();
    HttpServletUtils.setAttribute("title", "Business Applications");
    final List<BusinessApplication> businessApplications = getBusinessApplications();
    final Map<String, Object> parameters = Collections.emptyMap();

    final ElementContainer table = newDataTable(request, "list", parameters, businessApplications);

    final TabElementContainer tabs = new TabElementContainer();
    tabs.add("Business Applications", table);
    return tabs;
  }

  @RequestMapping(value = {
    "/admin/modules/{moduleName}/apps/{businessApplicationName}/edit"
  }, method = {
    RequestMethod.GET, RequestMethod.POST
  }, fieldNames = {
    "logLevel", "testModeEnabled", "batchModePermission", "instantModePermission",
    "maxRequestsPerJob", "maxConcurrentRequests", "numRequestsPerWorker",
  }, title = "Edit Business Application {businessApplicationName}")
  @ResponseBody
  public Element moduleEdit(final HttpServletRequest request, final HttpServletResponse response,
    final @PathVariable("moduleName") String moduleName,
    final @PathVariable("businessApplicationName") String businessApplicationName)
    throws IOException, ServletException {
    checkAdminOrModuleAdmin(moduleName);
    final BusinessApplicationRegistry businessApplicationRegistry = getBusinessApplicationRegistry();
    final BusinessApplication businessApplication = businessApplicationRegistry
      .getModuleBusinessApplication(moduleName, businessApplicationName);
    if (businessApplication != null) {
      final ConfigPropertyLoader configPropertyLoader = businessApplicationRegistry
        .getConfigPropertyLoader();
      final String componentName = "APP_" + businessApplicationName;
      final Map<String, Object> configProperties = configPropertyLoader
        .getConfigProperties(moduleName, componentName);
      final String pageName = "moduleEdit";
      final String viewName = "moduleView";

      final List<String> propertyNames = getKeyList(pageName);
      for (final String propertyName : propertyNames) {
        if (!configProperties.containsKey(propertyName)) {
          final Object value = Property.get(businessApplication, propertyName);
          configProperties.put(propertyName, value);
        }
      }

      final Form form = newTableForm(configProperties, pageName);
      form.initialize(request);

      if (form.isPosted() && form.isMainFormTask()) {
        if (form.isValid()) {
          final CpfDataAccessObject dataAccessObject = getDataAccessObject();
          final BusinessApplicationPlugin pluginAnnotation = businessApplication
            .getPluginAnnotation();
          for (final String propertyName : propertyNames) {
            final Object defaultValue = Property.get(pluginAnnotation, propertyName);
            final Object newValue = form.getValue(propertyName);
            final boolean equal = DataType.equal(defaultValue, newValue);

            Record configProperty = dataAccessObject.getConfigProperty(ConfigProperty.DEFAULT,
              moduleName, componentName, propertyName);
            if (configProperty == null) {
              if (!equal) {
                try {
                  final Class<?> propertyClass = PropertyUtils.getPropertyType(businessApplication,
                    propertyName);
                  final DataType valueType = DataTypes.getDataType(propertyClass);

                  configProperty = dataAccessObject.newConfigProperty(ConfigProperty.DEFAULT,
                    moduleName, componentName, propertyName, newValue, valueType);
                } catch (final Throwable e) {
                  Logs.error(this, "Unable to set property " + propertyName, e);
                }
              }
            } else {
              if (equal) {
                dataAccessObject.delete(configProperty);
              } else {
                dataAccessObject.setConfigPropertyValue(configProperty, newValue);
                dataAccessObject.write(configProperty);
              }
            }
            Property.setSimple(businessApplication, propertyName, newValue);
          }

          final Map<String, Object> parameters = new HashMap<>();

          final String url = getPageUrl(viewName, parameters);
          response.sendRedirect(url);
          return null;
        }
      }

      final Page page = getPage(pageName);

      final String title = page.getExpandedTitle();
      request.setAttribute("title", title);

      final Menu actionMenu = new Menu();
      addMenuItem(actionMenu, null, viewName, "Cancel", "_top").addProperty("buttonClass",
        "btn-danger");
      addMenuItem(actionMenu, null, pageName, "Revert to Saved", "_top").addProperty("buttonClass",
        "btn-warning");
      final String name = form.getName();
      actionMenu.addMenuItem(new Menu("Save", "javascript:$('#" + name + "').submit()")
        .addProperty("buttonClass", "btn-primary"));

      final ButtonsToolbarElement buttonsToolbar = new ButtonsToolbarElement(actionMenu);
      final ElementContainer view = new ElementContainer(form, buttonsToolbar);
      final TabElementContainer tabs = new TabElementContainer();
      tabs.add(title, view);
      return tabs;
    }
    throw new PageNotFoundException();
  }

  @RequestMapping(value = {
    "/admin/modules/{moduleName}/apps"
  }, title = "Business Applications", method = RequestMethod.GET,
      permission = "hasRole('ROLE_ADMIN')  or hasRole('ROLE_ADMIN_MODULE_' + #moduleName + '_ADMIN')",
      fieldNames = {
        "name_link", "module_name_link", "title",
      })
  @ResponseBody
  public Object moduleList(final HttpServletRequest request, final HttpServletResponse response,
    final @PathVariable("moduleName") String moduleName) throws IOException {
    final Module module = getModule(request, moduleName);
    checkAdminOrModuleAdmin(moduleName);
    return newDataTableHandlerOrRedirect(request, "moduleList", module::getBusinessApplications,
      Module.class, "view");
  }

  @RequestMapping(value = {
    "/admin/modules/{moduleName}/apps/{businessApplicationName}"
  }, title = "Business Application {businessApplicationName}", method = RequestMethod.GET,
      fieldNames = {
        "name", "module_name_link", "title", "descriptionUrl", "logLevel", "testModeEnabled",
        "batchModePermission", "instantModePermission", "geometryFactory", "validateGeometry",
        "perRequestInputData", "inputDataContentTypes", "hasGeometryRequestAttribute",
        "perRequestResultData", "resultDataContentTypes", "hasCustomizationProperties",
        "resultListProperty", "hasResultListCustomizationProperties", "hasGeometryResultAttribute",
        "maxRequestsPerJob", "maxConcurrentRequests", "numRequestsPerWorker",
      })
  @ResponseBody
  public Element moduleView(final HttpServletRequest request, final HttpServletResponse response,
    final @PathVariable("moduleName") String moduleName,
    final @PathVariable("businessApplicationName") String businessApplicationName)
    throws IOException, ServletException {
    checkAdminOrModuleAdmin(moduleName);
    final BusinessApplication businessApplication = getBusinessApplicationRegistry()
      .getModuleBusinessApplication(moduleName, businessApplicationName);
    if (businessApplication != null) {
      final TabElementContainer tabs = new TabElementContainer();
      addObjectViewPage(tabs, businessApplication, "module");

      final Map<String, Object> parameters = new HashMap<>();
      parameters.put("serverSide", Boolean.FALSE);

      addTabDataTable(tabs, BusinessApplicationStatistics.class.getName(), "moduleAppList",
        parameters);

      parameters.put("serverSide", Boolean.TRUE);
      addTabDataTable(tabs, ConfigProperty.CONFIG_PROPERTY, "moduleAppList", parameters);
      addTabDataTable(tabs, BatchJob.BATCH_JOB, "moduleAppList", parameters);

      return tabs;
    }
    throw new PageNotFoundException();
  }
}