text:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_17" class="java.beans.XMLDecoder">
 <object class="org.flowvisor.config.ConfDirEntry">
  <void property="entries">
   <object class="java.util.HashMap">
    <void method="put">
     <string>flowspace</string>
     <object class="org.flowvisor.config.ConfFlowMapEntry">
      <void property="flowMap">
       <object class="org.flowvisor.flows.LinearFlowMap">
        <void property="rules">
         <void method="add">
          <object class="org.flowvisor.flows.FlowEntry">
           <void property="DPID">
            <long>-9223372036854775808</long>
           </void>
           <void property="actionsList">
            <object class="java.util.LinkedList">
             <void method="add">
              <object class="org.flowvisor.flows.SliceAction">
               <void property="sliceName">
                <string>default</string>
               </void>
               <void property="slicePerms">
                <int>4</int>
               </void>
               <void property="vendor">
                <int>-2147483647</int>
               </void>
              </object>
             </void>
            </object>
           </void>
           <void property="priority">
            <int>1000</int>
           </void>
           <void property="ruleMatch">
            <object class="org.openflow.protocol.OFMatch"/>
           </void>
          </object>
         </void>
        </void>
       </object>
      </void>
      <void property="name">
       <string>flowspace</string>
      </void>
      <void property="persistent">
       <boolean>true</boolean>
      </void>
     </object>
    </void>
    <void method="put">
     <string>switches</string>
     <object class="org.flowvisor.config.ConfDirEntry">
      <void property="entries">
       <object class="java.util.HashMap"/>
      </void>
      <void property="name">
       <string>switches</string>
      </void>
      <void property="persistent">
       <boolean>true</boolean>
      </void>
     </object>
    </void>
    <void method="put">
     <string>flowvisor</string>
     <object class="org.flowvisor.config.ConfDirEntry">
      <void property="entries">
       <object class="java.util.HashMap">
        <void method="put">
         <string>api_webserver_port</string>
         <object class="org.flowvisor.config.ConfIntEntry">
          <void property="int">
           <int>18080</int>
          </void>
          <void property="name">
           <string>api_webserver_port</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
        <void method="put">
         <string>checkpointing</string>
         <object class="org.flowvisor.config.ConfBoolEntry">
          <void property="bool">
           <boolean>false</boolean>
          </void>
          <void property="name">
           <string>checkpointing</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
        <void method="put">
         <string>listen_port</string>
         <object class="org.flowvisor.config.ConfIntEntry">
          <void property="int">
           <int>16633</int>
          </void>
          <void property="name">
           <string>listen_port</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
        <void method="put">
         <string>track_flows</string>
         <object class="org.flowvisor.config.ConfBoolEntry">
          <void property="name">
           <string>track_flows</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
        <void method="put">
         <string>logging</string>
         <object class="org.flowvisor.config.ConfStrEntry">
          <void property="name">
           <string>logging</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
          <void property="string">
           <string>DEBUG</string>
          </void>
         </object>
        </void>
        <void method="put">
         <string>run_topology_server</string>
         <object class="org.flowvisor.config.ConfBoolEntry">
          <void property="name">
           <string>run_topology_server</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
       </object>
      </void>
      <void property="name">
       <string>flowvisor</string>
      </void>
      <void property="persistent">
       <boolean>true</boolean>
      </void>
     </object>
    </void>
    <void method="put">
     <string>slices</string>
     <object class="org.flowvisor.config.ConfDirEntry">
      <void property="entries">
       <object class="java.util.HashMap">
        <void method="put">
         <string>default</string>
         <object class="org.flowvisor.config.ConfDirEntry">
          <void property="entries">
           <object class="java.util.HashMap">
            <void method="put">
             <string>passwd_salt</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>passwd_salt</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>487950628</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>contact_email</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>contact_email</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>jbs@bbn.com</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>controller_hostname</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>controller_hostname</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>localhost</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>controller_port</string>
             <object class="org.flowvisor.config.ConfIntEntry">
              <void property="int">
               <int>50812</int>
              </void>
              <void property="name">
               <string>controller_port</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
             </object>
            </void>
            <void method="put">
             <string>passwd_crypt</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>passwd_crypt</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>0504618f7d24fa961974cabbd1c3a431</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>creator</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>creator</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>root</string>
              </void>
             </object>
            </void>
           </object>
          </void>
          <void property="name">
           <string>default</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
        <void method="put">
         <string>root</string>
         <object class="org.flowvisor.config.ConfDirEntry">
          <void property="entries">
           <object class="java.util.HashMap">
            <void method="put">
             <string>passwd_salt</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>passwd_salt</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>-335803638</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>contact_email</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>contact_email</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>root@localhost</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>controller_port</string>
             <object class="org.flowvisor.config.ConfIntEntry">
              <void property="int">
               <int>59793</int>
              </void>
              <void property="name">
               <string>controller_port</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
             </object>
            </void>
            <void method="put">
             <string>controller_hostname</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>controller_hostname</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>localhost</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>passwd_crypt</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>passwd_crypt</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>fabaf84361a65abbfc118edb92bdeeed</string>
              </void>
             </object>
            </void>
            <void method="put">
             <string>creator</string>
             <object class="org.flowvisor.config.ConfStrEntry">
              <void property="name">
               <string>creator</string>
              </void>
              <void property="persistent">
               <boolean>true</boolean>
              </void>
              <void property="string">
               <string>root</string>
              </void>
             </object>
            </void>
           </object>
          </void>
          <void property="name">
           <string>root</string>
          </void>
          <void property="persistent">
           <boolean>true</boolean>
          </void>
         </object>
        </void>
       </object>
      </void>
      <void property="name">
       <string>slices</string>
      </void>
      <void property="persistent">
       <boolean>true</boolean>
      </void>
     </object>
    </void>
    <void method="put">
     <string>version</string>
     <object class="org.flowvisor.config.ConfStrEntry">
      <void property="name">
       <string>version</string>
      </void>
      <void property="persistent">
       <boolean>true</boolean>
      </void>
      <void property="string">
       <string>flowvisor-0.6-alpha</string>
      </void>
     </object>
    </void>
   </object>
  </void>
  <void property="name">
   <string></string>
  </void>
  <void property="persistent">
   <boolean>true</boolean>
  </void>
 </object>
</java>


text:
require 'spec_helper'

describe 'omnibus-supermarket::ssl' do
  platform 'ubuntu', '18.04'
  automatic_attributes['memory']['total'] = '16000MB'

  # Shared Example Sets
  # - :create_directories - Creates the directories for SSL
  # - :create_certificates - When the recipe should create certs
  # - :create_dhparams - When the recipe should create a dhparams.pem
  # - :no_create_certificates - When the recipe should not create certs
  # - :no_create_dhparams - When the recipe should not create dhparams.pem

  shared_examples_for :create_directories do
    it 'creates /var/opt/supermarket/ssl' do
      expect(chef_run).to create_directory('/var/opt/supermarket/ssl').with(
        user: 'supermarket',
        group: 'supermarket',
        mode: '0700'
      )
    end

    it 'creates /var/opt/supermarket/ssl/ca' do
      expect(chef_run).to create_directory('/var/opt/supermarket/ssl/ca').with(
        user: 'supermarket',
        group: 'supermarket',
        mode: '0700'
      )
    end
  end

  shared_examples_for :create_certificates do
    it 'creates /var/opt/supermarket/ssl/ca/fauxhai.local.crt' do
      expect(chef_run).to create_openssl_x509_certificate(
        '/var/opt/supermarket/ssl/ca/fauxhai.local.crt'
      ).with(
        common_name: 'fauxhai.local',
        org: 'My Supermarket',
        org_unit: 'Operations',
        country: 'US',
        key_length: 2048,
        expire: 3650,
        owner: 'root',
        group: 'root',
        mode: '0644'
      )
    end
  end

  shared_examples_for :create_dhparams do
    it 'creates /var/opt/supermarket/ssl/ca/dhparams.pem' do
      expect(chef_run).to create_openssl_dhparam(
        '/var/opt/supermarket/ssl/ca/dhparams.pem'
      ).with(
        key_length: 2048,
        generator: 2,
        owner: 'root',
        group: 'root',
        mode: '0644'
      )
    end
  end

  shared_examples_for :no_create_certificates do
    it 'does not create an x509 certificate' do
      expect(chef_run).not_to create_openssl_x509_certificate(
        '/var/opt/supermarket/ssl/ca/fauxhai.local.crt')
    end
  end

  shared_examples_for :no_create_dhparams do
    it 'does not create a dhparams.pem file' do
      expect(chef_run).not_to create_openssl_dhparam(
        '/var/opt/supermarket/ssl/ca/dhparams.pem'
      )
    end
  end

  # Chef Run contexts, varied based on feature flag attributes
  # - Default run: Creates SSL certificates
  #   with certificate supplied: Uses supplied cert location
  # - SSL disabled: Creates directories, does not create or link certificates
  # - With certificate location & SSL disabled: Tests that ssl disable
  #   supercedes supplied certificate behavior.
  context 'When all attributes are default, on a fauxhai\'d platform:' do
    it_behaves_like :create_directories
    it_behaves_like :create_certificates
    it_behaves_like :create_dhparams

    it 'sets the [\'supermarket\'][\'ssl\'] attributes correctly' do
      expect(chef_run.node['supermarket']['ssl']['certificate'])
        .to eq('/var/opt/supermarket/ssl/ca/fauxhai.local.crt')
      expect(chef_run.node['supermarket']['ssl']['certificate_key'])
        .to eq('/var/opt/supermarket/ssl/ca/fauxhai.local.key')
      expect(chef_run.node['supermarket']['ssl']['ssl_dhparam'])
        .to eq('/var/opt/supermarket/ssl/ca/dhparams.pem')
    end

    it 'links the CA cert to /var/opt/supermarket/ssl/ca/fauxhai.local.crt' do
      expect(chef_run).to create_link(
        '/var/opt/supermarket/ssl/cacert.pem'
      ).with(
        to: '/var/opt/supermarket/ssl/ca/fauxhai.local.crt'
      )
    end
  end

  context 'When a certificate is supplied, on a fauxhai\'d platform:' do
    normal_attributes['supermarket']['ssl']['certificate'] = '/etc/mycert.pem'

    it_behaves_like :create_directories
    it_behaves_like :no_create_certificates
    it_behaves_like :create_dhparams

    it 'sets the [\'supermarket\'][\'ssl\'] attributes correctly' do
      expect(chef_run.node['supermarket']['ssl']['certificate'])
        .to eq('/etc/mycert.pem')
      expect(chef_run.node['supermarket']['ssl']['certificate_key'])
        .to be_nil
      expect(chef_run.node['supermarket']['ssl']['ssl_dhparam'])
        .to eq('/var/opt/supermarket/ssl/ca/dhparams.pem')
    end

    it 'links the CA cert to /opt/supermarket/embedded/ssl/certs/cacert.pem' do
      expect(chef_run).to create_link(
        '/var/opt/supermarket/ssl/cacert.pem'
      ).with(
        to: '/opt/supermarket/embedded/ssl/certs/cacert.pem'
      )
    end
  end

  context 'when ssl is disabled, on a fauxhai\'d platform' do
    normal_attributes['supermarket']['ssl']['enable'] = false

    it_behaves_like :create_directories
    it_behaves_like :no_create_certificates
    it_behaves_like :no_create_dhparams

    it 'does not set the [\'supermarket\'][\'ssl\'] attributes' do
      expect(chef_run.node['supermarket']['ssl']['certificate'])
        .to be_nil
      expect(chef_run.node['supermarket']['ssl']['certificate_key'])
        .to be_nil
      expect(chef_run.node['supermarket']['ssl']['ssl_dhparam'])
        .to be_nil
    end

    it 'does not create the CA cert symlink' do
      expect(chef_run).not_to create_link(
        '/var/opt/supermarket/ssl/cacert.pem')
    end
  end

  context 'when ssl is disabled & a certificate is supplied, ' \
          'on a fauxhai\'d platform' do
    normal_attributes['supermarket']['ssl']['enable'] = false
    normal_attributes['supermarket']['ssl']['certificate'] = '/etc/mycert.pem'

    it_behaves_like :create_directories
    it_behaves_like :no_create_certificates
    it_behaves_like :no_create_dhparams

    it 'does not modify the [\'supermarket\'][\'ssl\'] attributes' do
      expect(chef_run.node['supermarket']['ssl']['certificate'])
        .to eq('/etc/mycert.pem')
      expect(chef_run.node['supermarket']['ssl']['certificate_key'])
        .to be_nil
      expect(chef_run.node['supermarket']['ssl']['ssl_dhparam'])
        .to be_nil
    end

    it 'does not create the CA cert symlink' do
      expect(chef_run).not_to create_link(
        '/var/opt/supermarket/ssl/cacert.pem')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.obidea.semantika.mapping.parser.termalxml;

import com.obidea.semantika.mapping.MappingSet;
import com.obidea.semantika.mapping.exception.MappingParserException;

public class ProgramElementHandler extends AbstractTermalElementHandler
{
   public ProgramElementHandler(TermalXmlParserHandler handler)
   {
      super(handler);
   }

   @Override
   public void endElement() throws MappingParserException
   {
      // NO-OP
   }

   @Override
   public void attribute(String name, String value) throws MappingParserException
   {
      // NO-OP
   }

   @Override
   protected void handleChild(MappingElementHandler handler)
   {
      final MappingSet mappingSet = handler.getMappingSet();
      getMappingSet().copy(mappingSet);
   }

   @Override
   protected void handleChild(LogicalTableElementHandler handler)
   {
      // NO-OP: Not an immediate child.
   }

   @Override
   protected void handleChild(SubjectMapElementHandler handler)
   {
      // NO-OP: Not an immediate child.
   }

   @Override
   protected void handleChild(PredicateObjectMapElementHandler handler)
   {
      // NO-OP: Not an immediate child.
   }
}


text:
package de.tu_darmstadt.smastra.sensors;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.test.mock.MockContext;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import de.tu_darmstadt.smastra.sensors.hardware.AndroidGPSSensor;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * A Test for Abstract
 */
@SuppressWarnings("MissingPermission")
public class AndroidGPSSensorTest {

    /**
     * The mock Context to use.
     */
    protected Context context;

    /**
     * The Mock sensor manager to use.
     */
    protected LocationManager mockLocationManager;

    @Before
    public void setup(){
        //Stub the Location Manager:
        mockLocationManager = Mockito.mock(LocationManager.class);

        //Setup the Mock Context:
        this.context = new MockContext(){
            @Override
            public Object getSystemService(String name) {
                if(name.equals(Context.LOCATION_SERVICE)) return mockLocationManager;
                else return super.getSystemService(name);
            }
        };
    }

    /**
     * Generates a new Mock Event with the passed data.
     * @param time to use
     * @param accuracy to use
     * @param latitude to use
     * @param longitude to use
     * @param altitude to use
     * @return generates the event needed.
     */
    protected Location generateMockEvent(final long time, final float accuracy, final float latitude, final float longitude, final float altitude) throws Exception {
        return new Location("GPS"){
            @Override
            public long getTime() { return time; }
            @Override
            public float getAccuracy() { return accuracy; }
            @Override
            public double getLatitude() { return latitude; }
            @Override
            public double getLongitude() { return longitude; }
            @Override
            public double getAltitude() { return altitude; }
        };
    }

    @After
    public void teardown(){
        this.mockLocationManager = null;
        this.context = null;
    }

    //This test will fail because the sensor is registered on the Main-Thread.
    /*@Test
    public void TestIfRegisterIsCalled(){
        AndroidGPSSensor sut = new AndroidGPSSensor(context);
        sut.start();

        Mockito.verify(mockLocationManager, Mockito.times(1)).requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, sut);
    }*/

    @Test
    public void TestIfUnregisterIsCalled(){
        AndroidGPSSensor sut = new AndroidGPSSensor(context);
        sut.stop();

        Mockito.verify(mockLocationManager, Mockito.times(1)).removeUpdates(sut);
    }

    @Test
    public void TestIfDataIsAddedCorrectly() throws Exception{
        long time = System.currentTimeMillis();
        float accuracy = 42;
        float latitude = 43;
        float longitude = 44;
        float altitude = 45;

        Location location = generateMockEvent(time, accuracy, latitude, longitude, altitude);
        AndroidGPSSensor sut = new AndroidGPSSensor(context);
        sut.onLocationChanged(location);

        Data3d data3d = (Data3d) sut.getLastData();
        assertEquals(time, data3d.getTime());
        assertEquals(accuracy, data3d.getAccuracy(), 0.01);
        assertEquals(latitude, data3d.getX(), 0.01);
        assertEquals(longitude, data3d.getY(), 0.01);
        assertEquals(altitude, data3d.getZ(), 0.01);
    }

}


text:
from PyQt5.QtWidgets import QApplication
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtGui import QTextDocument
import argparse
import logging
import os
import re
import sys

try:
    import pygments
    from pygments import lexers, formatters, styles
except ImportError as ex:
    logging.warning('\nCould not import the required "pygments" \
        module:\n{}'.format(ex))
    sys.exit(1)

__version__ = '1.1.0'

def logger(func):
    def log_wrap(self, ifile=None, ofile=None, size="A4"):
        logging.getLogger().name = "code2pdf> "
        logging.getLogger().setLevel(logging.INFO)
        func(self, ifile, ofile, size)
    return log_wrap

class Code2pdf:

    """
            Convert a source file into a pdf with syntax highlighting.
    """
    @logger
    def __init__(self, ifile=None, ofile=None, size="A4"):
        self.size = size
        if not ifile:
            raise Exception("input file is required")
        self.input_file = ifile
        self.pdf_file = ofile or "{}.pdf".format(ifile.split('.')[0])

    def highlight_file(self, linenos=True, style='default'):
        """ Highlight the input file, and return HTML as a string. """
        try:
            lexer = lexers.get_lexer_for_filename(self.input_file)
        except pygments.util.ClassNotFound:
            # Try guessing the lexer (file type) later.
            lexer = None

        try:
            formatter = formatters.HtmlFormatter(
                linenos=linenos,
                style=style,
                full=True)
        except pygments.util.ClassNotFound:
            logging.error("\nInvalid style name: {}\nExpecting one of:\n \
                {}".format(style, "\n    ".join(sorted(styles.STYLE_MAP))))
            sys.exit(1)

        try:
            with open(self.input_file, "r") as f:
                content = f.read()
                try:
                    lexer = lexer or lexers.guess_lexer(content)
                except pygments.util.ClassNotFound:
                    # No lexer could be guessed.
                    lexer = lexers.get_lexer_by_name("text")
        except EnvironmentError as exread:
            fmt = "\nUnable to read file: {}\n{}"
            logging.error(fmt.format(self.input_file, exread))
            sys.exit(2)

        return pygments.highlight(content, lexer, formatter)

    def init_print(self, linenos=True, style="default"):
        app = QApplication([])  # noqa
        doc = QTextDocument()
        doc_html = self.highlight_file(linenos=linenos, style=style)
        doc_html = re.sub(re.compile(r'<http://pygments.org>'), '', doc_html)
        doc.setHtml(doc_html)
        printer = QPrinter()
        printer.setOutputFileName(self.pdf_file)
        printer.setOutputFormat(QPrinter.PdfFormat)
        page_size_dict = {"a2": QPrinter.A2, "a3": QPrinter.A3, "a4": QPrinter.A4, "letter": QPrinter.Letter}
        printer.setPageSize(page_size_dict.get(self.size.lower(), QPrinter.A4))
        printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter)
        doc.print_(printer)
        logging.info("PDF created at %s" % (self.pdf_file))

def get_output_file(inputname, outputname=None):
    """ If the output name is set, then return it.
        Otherwise, build an output name using the current directory,
        replacing the input name's extension.
    """
    if outputname:
        return outputname

    inputbase = os.path.split(inputname)[-1]
    outputbase = "{}.pdf".format(os.path.splitext(inputbase)[0])
    return os.path.join(os.getcwd(), outputbase)

def parse_arg():
    parser = argparse.ArgumentParser(
        description=(
            "Convert given source code into .pdf with syntax highlighting"),
        epilog="Author:tushar.rishav@gmail.com"
    )
    parser.add_argument(
        "filename",
        help="absolute path of the python file",
        type=str)
    parser.add_argument(
        "-l",
        "--linenos",
        help="include line numbers.",
        action="store_true")
    parser.add_argument(
        "outputfile",
        help="absolute path of the output pdf file",
        nargs="?",
        type=str)
    parser.add_argument(
        "-s",
        "--size",
        help="PDF size. A2,A3,A4,A5,letter etc",
        type=str,
        default="A3")
    parser.add_argument(
        "-S",
        "--style",
        help="the style name for highlighting.",
        type=str,
        default="default",
        metavar="NAME")
    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version="%(prog)s v. {}".format(__version__))
    return parser.parse_args()

def main():
    args = parse_arg()
    pdf_file = get_output_file(args.filename, args.outputfile)
    pdf = Code2pdf(args.filename, pdf_file, args.size)
    pdf.init_print(linenos=args.linenos, style=args.style)
    return 0

if __name__ == "__main__":
    sys.exit(main())


text:
package com.ibm.bi.dml.test.integration.functions.reorg;

import java.util.HashMap;

import org.junit.Test;

import com.ibm.bi.dml.api.DMLScript;
import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM;
import com.ibm.bi.dml.hops.OptimizerUtils;
import com.ibm.bi.dml.hops.ReorgOp;
import com.ibm.bi.dml.lops.LopProperties.ExecType;
import com.ibm.bi.dml.runtime.matrix.data.MatrixValue.CellIndex;
import com.ibm.bi.dml.test.integration.AutomatedTestBase;
import com.ibm.bi.dml.test.integration.TestConfiguration;
import com.ibm.bi.dml.test.utils.TestUtils;

/**
 * TODO add tests for dynamically computed ordering parameters; in hybrid execution mode
 * this works via dag splits and dynamic recompilation; however in this test we cannot force
 * MR and use dynamic recompilation recompilation at the same time.
 *
 */
public class FullOrderTest extends AutomatedTestBase
{

	private final static String TEST_NAME1 = "Order";
	private final static String TEST_NAME2 = "OrderDyn";

	private final static String TEST_DIR = "functions/reorg/";
	private final static double eps = 1e-10;

	private final static int rows1 = 1017;
	private final static int rows2 = 42057;
	private final static int cols1 = 7;
	private final static int by = 3;
	private final static double sparsity1 = 0.7;
	private final static double sparsity2 = 0.1;

	public enum InputType {
		DENSE,
		SPARSE,
		EMPTY,
	}

	/**
	 * Main method for running one test at a time.
	 */
	public static void main(String[] args) {
		long startMsec = System.currentTimeMillis();

		FullOrderTest t = new FullOrderTest();
		t.setUpBase();
		t.setUp();
		t.testOrderVectorIndexAscEmptyNoRewriteMR();
		t.tearDown();

		long elapsedMsec = System.currentTimeMillis() - startMsec;
		System.err.printf("Finished in %1.3f sec\n", elapsedMsec / 1000.0);

	}

	@Override
	public void setUp()
	{
		TestUtils.clearAssertionInformation();
		addTestConfiguration(TEST_NAME1,new TestConfiguration(TEST_DIR, TEST_NAME1,new String[]{"B"}));
		addTestConfiguration(TEST_NAME2,new TestConfiguration(TEST_DIR, TEST_NAME2,new String[]{"B"}));
	}

	@Test
	public void testOrderMatrixDataAscDenseCP()
	{
		runOrderTest(true, InputType.DENSE, false, false, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexAscDenseCP()
	{
		runOrderTest(true, InputType.DENSE, false, true, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataAscSparseCP()
	{
		runOrderTest(true, InputType.SPARSE, false, false, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexAscSparseCP()
	{
		runOrderTest(true, InputType.SPARSE, false, true, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataAscEmptyCP()
	{
		runOrderTest(true, InputType.EMPTY, false, false, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyCP()
	{
		runOrderTest(true, InputType.EMPTY, false, true, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataDescDenseCP()
	{
		runOrderTest(true, InputType.DENSE, true, false, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexDescDenseCP()
	{
		runOrderTest(true, InputType.DENSE, true, true, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataDescSparseCP()
	{
		runOrderTest(true, InputType.SPARSE, true, false, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexDescSparseCP()
	{
		runOrderTest(true, InputType.SPARSE, true, true, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataDescEmptyCP()
	{
		runOrderTest(true, InputType.EMPTY, true, false, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyCP()
	{
		runOrderTest(true, InputType.EMPTY, true, true, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataAscDenseCP()
	{
		runOrderTest(false, InputType.DENSE, false, false, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexAscDenseCP()
	{
		runOrderTest(false, InputType.DENSE, false, true, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataAscSparseCP()
	{
		runOrderTest(false, InputType.SPARSE, false, false, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexAscSparseCP()
	{
		runOrderTest(false, InputType.SPARSE, false, true, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataAscEmptyCP()
	{
		runOrderTest(false, InputType.EMPTY, false, false, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexAscEmptyCP()
	{
		runOrderTest(false, InputType.EMPTY, false, true, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataDescDenseCP()
	{
		runOrderTest(false, InputType.DENSE, true, false, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexDescDenseCP()
	{
		runOrderTest(false, InputType.DENSE, true, true, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataDescSparseCP()
	{
		runOrderTest(false, InputType.SPARSE, true, false, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexDescSparseCP()
	{
		runOrderTest(false, InputType.SPARSE, true, true, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataDescEmptyCP()
	{
		runOrderTest(false, InputType.EMPTY, true, false, true, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexDescEmptyCP()
	{
		runOrderTest(false, InputType.EMPTY, true, true, true, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataAscEmptyNoRewriteCP()
	{
		runOrderTest(true, InputType.EMPTY, false, false, false, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyNoRewriteCP()
	{
		runOrderTest(true, InputType.EMPTY, false, true, false, ExecType.CP);
	}

	@Test
	public void testOrderMatrixDataDescEmptyNoRewriteCP()
	{
		runOrderTest(true, InputType.EMPTY, true, false, false, ExecType.CP);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyNoRewriteCP()
	{
		runOrderTest(true, InputType.EMPTY, true, true, false, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataAscEmptyNoRewriteCP()
	{
		runOrderTest(false, InputType.EMPTY, false, false, false, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexAscEmptyNoRewriteCP()
	{
		runOrderTest(false, InputType.EMPTY, false, true, false, ExecType.CP);
	}

	@Test
	public void testOrderVectorDataDescEmptyNoRewriteCP()
	{
		runOrderTest(false, InputType.EMPTY, true, false, false, ExecType.CP);
	}

	@Test
	public void testOrderVectorIndexDescEmptyNoRewriteCP()
	{
		runOrderTest(false, InputType.EMPTY, true, true, false, ExecType.CP);
	}

	// ----------------------------

	@Test
	public void testOrderMatrixDataAscDenseSP()
	{
		runOrderTest(true, InputType.DENSE, false, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexAscDenseSP()
	{
		runOrderTest(true, InputType.DENSE, false, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataAscSparseSP()
	{
		runOrderTest(true, InputType.SPARSE, false, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexAscSparseSP()
	{
		runOrderTest(true, InputType.SPARSE, false, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataAscEmptySP()
	{
		runOrderTest(true, InputType.EMPTY, false, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexAscEmptySP()
	{
		runOrderTest(true, InputType.EMPTY, false, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataDescDenseSP()
	{
		runOrderTest(true, InputType.DENSE, true, false, true, ExecType.SPARK, true);
	}

	@Test
	public void testOrderMatrixIndexDescDenseSP()
	{
		runOrderTest(true, InputType.DENSE, true, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataDescSparseSP()
	{
		runOrderTest(true, InputType.SPARSE, true, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexDescSparseSP()
	{
		runOrderTest(true, InputType.SPARSE, true, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataDescEmptySP()
	{
		runOrderTest(true, InputType.EMPTY, true, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexDescEmptySP()
	{
		runOrderTest(true, InputType.EMPTY, true, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataAscDenseSP()
	{
		runOrderTest(false, InputType.DENSE, false, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexAscDenseSP()
	{
		runOrderTest(false, InputType.DENSE, false, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataAscSparseSP()
	{
		runOrderTest(false, InputType.SPARSE, false, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexAscSparseSP()
	{
		runOrderTest(false, InputType.SPARSE, false, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataAscEmptySP()
	{
		runOrderTest(false, InputType.EMPTY, false, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexAscEmptySP()
	{
		runOrderTest(false, InputType.EMPTY, false, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataDescDenseSP()
	{
		runOrderTest(false, InputType.DENSE, true, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexDescDenseSP()
	{
		runOrderTest(false, InputType.DENSE, true, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataDescSparseSP()
	{
		runOrderTest(false, InputType.SPARSE, true, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexDescSparseSP()
	{
		runOrderTest(false, InputType.SPARSE, true, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataDescEmptySP()
	{
		runOrderTest(false, InputType.EMPTY, true, false, true, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexDescEmptySP()
	{
		runOrderTest(false, InputType.EMPTY, true, true, true, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataAscEmptyNoRewriteSP()
	{
		runOrderTest(true, InputType.EMPTY, false, false, false, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyNoRewriteSP()
	{
		runOrderTest(true, InputType.EMPTY, false, true, false, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixDataDescEmptyNoRewriteSP()
	{
		runOrderTest(true, InputType.EMPTY, true, false, false, ExecType.SPARK);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyNoRewriteSP()
	{
		runOrderTest(true, InputType.EMPTY, true, true, false, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataAscEmptyNoRewriteSP()
	{
		runOrderTest(false, InputType.EMPTY, false, false, false, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexAscEmptyNoRewriteSP()
	{
		runOrderTest(false, InputType.EMPTY, false, true, false, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorDataDescEmptyNoRewriteSP()
	{
		runOrderTest(false, InputType.EMPTY, true, false, false, ExecType.SPARK);
	}

	@Test
	public void testOrderVectorIndexDescEmptyNoRewriteSP()
	{
		runOrderTest(false, InputType.EMPTY, true, true, false, ExecType.SPARK);
	}

	// ----------------------------

	@Test
	public void testOrderMatrixDataAscDenseMR()
	{
		runOrderTest(true, InputType.DENSE, false, false, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexAscDenseMR()
	{
		runOrderTest(true, InputType.DENSE, false, true, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataAscSparseMR()
	{
		runOrderTest(true, InputType.SPARSE, false, false, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexAscSparseMR()
	{
		runOrderTest(true, InputType.SPARSE, false, true, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataAscEmptyMR()
	{
		runOrderTest(true, InputType.EMPTY, false, false, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyMR()
	{
		runOrderTest(true, InputType.EMPTY, false, true, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataDescDenseMR()
	{
		runOrderTest(true, InputType.DENSE, true, false, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexDescDenseMR()
	{
		runOrderTest(true, InputType.DENSE, true, true, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataDescSparseMR()
	{
		runOrderTest(true, InputType.SPARSE, true, false, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexDescSparseMR()
	{
		runOrderTest(true, InputType.SPARSE, true, true, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataDescEmptyMR()
	{
		runOrderTest(true, InputType.EMPTY, true, false, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyMR()
	{
		runOrderTest(true, InputType.EMPTY, true, true, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataAscDenseMR()
	{
		runOrderTest(false, InputType.DENSE, false, false, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexAscDenseMR()
	{
		runOrderTest(false, InputType.DENSE, false, true, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataAscSparseMR()
	{
		runOrderTest(false, InputType.SPARSE, false, false, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexAscSparseMR()
	{
		runOrderTest(false, InputType.SPARSE, false, true, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataAscEmptyMR()
	{
		runOrderTest(false, InputType.EMPTY, false, false, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexAscEmptyMR()
	{
		runOrderTest(false, InputType.EMPTY, false, true, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataDescDenseMR()
	{
		runOrderTest(false, InputType.DENSE, true, false, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexDescDenseMR()
	{
		runOrderTest(false, InputType.DENSE, true, true, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataDescSparseMR()
	{
		runOrderTest(false, InputType.SPARSE, true, false, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexDescSparseMR()
	{
		runOrderTest(false, InputType.SPARSE, true, true, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataDescEmptyMR()
	{
		runOrderTest(false, InputType.EMPTY, true, false, true, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexDescEmptyMR()
	{
		runOrderTest(false, InputType.EMPTY, true, true, true, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataAscEmptyNoRewriteMR()
	{
		runOrderTest(true, InputType.EMPTY, false, false, false, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyNoRewriteMR()
	{
		runOrderTest(true, InputType.EMPTY, false, true, false, ExecType.MR);
	}

	@Test
	public void testOrderMatrixDataDescEmptyNoRewriteMR()
	{
		runOrderTest(true, InputType.EMPTY, true, false, false, ExecType.MR);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyNoRewriteMR()
	{
		runOrderTest(true, InputType.EMPTY, true, true, false, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataAscEmptyNoRewriteMR()
	{
		runOrderTest(false, InputType.EMPTY, false, false, false, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexAscEmptyNoRewriteMR()
	{
		runOrderTest(false, InputType.EMPTY, false, true, false, ExecType.MR);
	}

	@Test
	public void testOrderVectorDataDescEmptyNoRewriteMR()
	{
		runOrderTest(false, InputType.EMPTY, true, false, false, ExecType.MR);
	}

	@Test
	public void testOrderVectorIndexDescEmptyNoRewriteMR()
	{
		runOrderTest(false, InputType.EMPTY, true, true, false, ExecType.MR);
	}

	//TODO enable all index tests as soon as sort piggybacking issue is fixed.

	@Test
	public void testOrderMatrixDataAscDenseMR2()
	{
		runOrderTest(true, InputType.DENSE, false, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexAscDenseMR2()
	{
		runOrderTest(true, InputType.DENSE, false, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataAscSparseMR2()
	{
		runOrderTest(true, InputType.SPARSE, false, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexAscSparseMR2()
	{
		runOrderTest(true, InputType.SPARSE, false, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataAscEmptyMR2()
	{
		runOrderTest(true, InputType.EMPTY, false, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyMR2()
	{
		runOrderTest(true, InputType.EMPTY, false, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataDescDenseMR2()
	{
		runOrderTest(true, InputType.DENSE, true, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexDescDenseMR2()
	{
		runOrderTest(true, InputType.DENSE, true, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataDescSparseMR2()
	{
		runOrderTest(true, InputType.SPARSE, true, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexDescSparseMR2()
	{
		runOrderTest(true, InputType.SPARSE, true, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataDescEmptyMR2()
	{
		runOrderTest(true, InputType.EMPTY, true, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyMR2()
	{
		runOrderTest(true, InputType.EMPTY, true, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataAscDenseMR2()
	{
		runOrderTest(false, InputType.DENSE, false, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexAscDenseMR2()
	{
		runOrderTest(false, InputType.DENSE, false, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataAscSparseMR2()
	{
		runOrderTest(false, InputType.SPARSE, false, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexAscSparseMR2()
	{
		runOrderTest(false, InputType.SPARSE, false, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataAscEmptyMR2()
	{
		runOrderTest(false, InputType.EMPTY, false, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexAscEmptyMR2()
	{
		runOrderTest(false, InputType.EMPTY, false, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataDescDenseMR2()
	{
		runOrderTest(false, InputType.DENSE, true, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexDescDenseMR2()
	{
		runOrderTest(false, InputType.DENSE, true, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataDescSparseMR2()
	{
		runOrderTest(false, InputType.SPARSE, true, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexDescSparseMR2()
	{
		runOrderTest(false, InputType.SPARSE, true, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataDescEmptyMR2()
	{
		runOrderTest(false, InputType.EMPTY, true, false, true, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexDescEmptyMR2()
	{
		runOrderTest(false, InputType.EMPTY, true, true, true, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataAscEmptyNoRewriteMR2()
	{
		runOrderTest(true, InputType.EMPTY, false, false, false, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexAscEmptyNoRewriteMR2()
	{
		runOrderTest(true, InputType.EMPTY, false, true, false, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixDataDescEmptyNoRewriteMR2()
	{
		runOrderTest(true, InputType.EMPTY, true, false, false, ExecType.MR, true);
	}

	@Test
	public void testOrderMatrixIndexDescEmptyNoRewriteMR2()
	{
		runOrderTest(true, InputType.EMPTY, true, true, false, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataAscEmptyNoRewriteMR2()
	{
		runOrderTest(false, InputType.EMPTY, false, false, false, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexAscEmptyNoRewriteMR2()
	{
		runOrderTest(false, InputType.EMPTY, false, true, false, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorDataDescEmptyNoRewriteMR2()
	{
		runOrderTest(false, InputType.EMPTY, true, false, false, ExecType.MR, true);
	}

	@Test
	public void testOrderVectorIndexDescEmptyNoRewriteMR2()
	{
		runOrderTest(false, InputType.EMPTY, true, true, false, ExecType.MR, true);
	}

	//SPECIFIC REWRITE TESTS

	@Test
	public void testOrderMatrixDynDynDenseCP()
	{
		runOrderTest(TEST_NAME2, true, InputType.DENSE, false, false, true, ExecType.CP);
	}

	//-----------------------------
	@Test
	public void testOrderMatrixIndexAscDenseSP_ForceDist()
	{
		runOrderTest(true, InputType.DENSE, false, true, true, ExecType.SPARK, true);
	}

	@Test
	public void testOrderMatrixDataDescSparseSP_ForceDist()
	{
		runOrderTest(true, InputType.SPARSE, true, false, true, ExecType.SPARK, true);
	}

	@Test
	public void testOrderVectorDataDescDenseSP_ForceDist()
	{
		runOrderTest(false, InputType.DENSE, true, false, true, ExecType.SPARK, true);
	}

	/**
	 *
	 * @param matrix
	 * @param dtype
	 * @param desc
	 * @param ixreturn
	 * @param rewrite
	 * @param instType
	 */
	private void runOrderTest( boolean matrix, InputType dtype, boolean desc, boolean ixreturn, boolean rewrite, ExecType instType)
	{
		runOrderTest(TEST_NAME1, matrix, dtype, desc, ixreturn, rewrite, instType, false);
	}

	private void runOrderTest( String testname, boolean matrix, InputType dtype, boolean desc, boolean ixreturn, boolean rewrite, ExecType instType)
	{
		runOrderTest(TEST_NAME1, matrix, dtype, desc, ixreturn, rewrite, instType, false);
	}

	private void runOrderTest( boolean matrix, InputType dtype, boolean desc, boolean ixreturn, boolean rewrite, ExecType instType, boolean forceDistSort)
	{
		runOrderTest(TEST_NAME1, matrix, dtype, desc, ixreturn, rewrite, instType, forceDistSort);
	}

	/**
	 *
	 * @param sparseM1
	 * @param sparseM2
	 * @param instType
	 */
	private void runOrderTest( String testname, boolean matrix, InputType dtype, boolean desc, boolean ixreturn, boolean rewrite, ExecType instType, boolean forceDistSort)
	{
		RUNTIME_PLATFORM platformOld = rtplatform;
		boolean rewriteOld = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;
		boolean forceOpOld = ReorgOp.FORCE_DIST_SORT_INDEXES;

		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;

		try
		{
			String TEST_NAME = testname;

			//set flags
			if(instType == ExecType.SPARK) {
		    	rtplatform = RUNTIME_PLATFORM.SPARK;
		    }
		    else {
				rtplatform = (instType==ExecType.MR) ? RUNTIME_PLATFORM.HADOOP : RUNTIME_PLATFORM.HYBRID;
		    }
			if( rtplatform == RUNTIME_PLATFORM.SPARK )
				DMLScript.USE_LOCAL_SPARK_CONFIG = true;

			OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrite;
			ReorgOp.FORCE_DIST_SORT_INDEXES = forceDistSort;

			int rows = matrix ? rows1 : rows2;
			int cols = matrix ? cols1 : 1;
			int bycol = matrix ? by : 1;
			double sparsity = dtype==InputType.DENSE ? sparsity1 : sparsity2;

			TestConfiguration config = getTestConfiguration(TEST_NAME);

			/* This is for running the junit test the new way, i.e., construct the arguments directly */
			String HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = HOME + TEST_NAME + ".dml";
			programArgs = new String[]{"-explain","-args", HOME + INPUT_DIR + "A",
					                        Integer.toString(bycol),
					                        Boolean.toString(desc).toUpperCase(),
					                        Boolean.toString(ixreturn).toUpperCase(),
					                        HOME + OUTPUT_DIR + "B"    };
			fullRScriptName = HOME + TEST_NAME + ".R";
			rCmd = "Rscript" + " " + fullRScriptName + " " +
			       HOME + INPUT_DIR + " " + bycol + " " + Boolean.toString(desc).toUpperCase() + " " +
				   Boolean.toString(ixreturn).toUpperCase() + " " + HOME + EXPECTED_DIR;

			loadTestConfiguration(config);

			//generate actual dataset
			double min = (dtype==InputType.EMPTY)? 0 : -1;
			double max = (dtype==InputType.EMPTY)? 0 : 1;
			int nnz = (dtype==InputType.EMPTY)? 0 : -1;

			double[][] A = getRandomMatrix(rows, cols, min, max, sparsity, 7);
			writeInputMatrixWithMTD("A", A, nnz, true);

			boolean exceptionExpected = false;
			runTest(true, exceptionExpected, null, -1);

			runRScript(true);

			//compare matrices
			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("B");
			HashMap<CellIndex, Double> rfile  = readRMatrixFromFS("B");
			TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");
		}
		finally
		{
			//reset flags
			rtplatform = platformOld;
			OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewriteOld;
			ReorgOp.FORCE_DIST_SORT_INDEXES = forceOpOld;
			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
		}
	}

}


text:
package com.satanko.weballgrade.data.model;

import com.satanko.weballgrade.data.dao.impl.hibernate.HibernateLessonDAO;
import java.util.ArrayList;

/**
 * This class acts as a model class for holding data in the application.
 * It represents a variation of {@link Lesson} as posted from ExcelAllGrade in {@link HibernateLessonDAO#createOrUpdateLessons(java.util.ArrayList, java.util.ArrayList)}.
 *
 * @author Julian Tropper (julian.tropper@gmail.com)
 * ATTENTION: If not otherwise specified, the author(s) of the class is/are also responsible for all methods.
 *
 * @version 1.0
 */
public class JsonLesson {
    private String classToken;
    private String subjectToken;
    private ArrayList<String> teacherList = new ArrayList<>();

    public JsonLesson (String classToken, String subjectToken)
    {
        this.classToken = classToken;
        this.subjectToken = subjectToken;
    }

    public void addTeacher(String teacherToken)
    {
        teacherList.add(teacherToken);
    }

    public String getClassToken() {
        return classToken;
    }

    public void setClassToken(String classToken) {
        this.classToken = classToken;
    }

    public String getSubjectToken() {
        return subjectToken;
    }

    public void setSubjectToken(String subjectToken) {
        this.subjectToken = subjectToken;
    }

    public ArrayList<String> getTeacherList() {
        return teacherList;
    }

    public void setTeacherList(ArrayList<String> teacherList) {
        this.teacherList = teacherList;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        JsonLesson lesson = (JsonLesson) obj;

        String classToken = lesson.classToken;
        String subjectToken = lesson.subjectToken;
        ArrayList<String> teacherTokens = lesson.getTeacherList();

        if(this.classToken.equals(classToken) && this.subjectToken.equals(subjectToken))
        {
            for (String teacherToken : teacherTokens)
            {
                if (!this.teacherList.contains(teacherToken))
                {
                    return false;
                }
            }
        }
        else
        {
            return false;
        }

        return true;
    }
}


text:
<?php

return array(
	'attributes' => array(
		'reference' => 'Job ref:',
		'location' => 'Location:',
		'type' => '',
		'time' => '',
		'salary' => 'Salary:',
	),
	'types' => array(
		'PERMANENT_OR_TEMPORARY' => 'Permanent or Temporary',
		'PERMANENT' => 'Permanent',
		'TEMPORARY' => 'Temporary',
	),
	'times' => array(
		'FULL_OR_PART_TIME' => 'Full or part time',
		'FULL_TIME' => 'Full time',
		'PART_TIME' => 'Part time',
	),
	'filter' => array(
		'labels' => array(
			'type' => ' ',
			'time' => ' ',
			'keywords' => 'Keywords',
		),
		'submit' => 'Filter'
	),
	'salary' => array(
		'string' => '£:number',
		'decimals' => '2',
		'dec_point' => '.',
		'thousands_sep' => ',',
	),
	'misc' => array(
		'read_more' => 'Read more »',
		'no_matching_jobs' => 'Sorry, there are currently no jobs matching your criteria, please try again.',
        'sent_message' => 'Thank you for contacting us, we will get back to you shortly.',
        'apply' => 'Apply now',
	),
	'validation' => array(
        'name.required' => 'Please enter your name',
        'email.required' => 'Please enter your email address',
        'email.email' => 'Please enter a valid email address',
        'covering_letter.required' => 'Please write a covering letter',
        'cv.required' => 'Please upload your CV',
        'cv.mimes' => 'Sorry, that file type is not allowed',
	),
	'application' => array(
        'name' => 'Your name',
        'email' => 'Email address',
        'covering_letter' => 'Covering letter',
        'cv' => 'Upload your CV',
        'submit' => 'Apply',
    ),
);


text:
<?php

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Process;

class SimpleProcessTest extends AbstractProcessTest
{
    private $enabledSigchild = false;

    public function setUp()
    {
        ob_start();
        phpinfo(INFO_GENERAL);

        $this->enabledSigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
    }

    public function testGetExitCode()
    {
        $this->skipIfPHPSigchild();
        parent::testGetExitCode();
    }

    public function testExitCodeCommandFailed()
    {
        $this->skipIfPHPSigchild();
        parent::testExitCodeCommandFailed();
    }

    public function testProcessIsSignaledIfStopped()
    {
        $this->skipIfPHPSigchild();
        parent::testProcessIsSignaledIfStopped();
    }

    public function testProcessWithTermSignal()
    {
        $this->skipIfPHPSigchild();
        parent::testProcessWithTermSignal();
    }

    public function testProcessIsNotSignaled()
    {
        $this->skipIfPHPSigchild();
        parent::testProcessIsNotSignaled();
    }

    public function testProcessWithoutTermSignal()
    {
        $this->skipIfPHPSigchild();
        parent::testProcessWithoutTermSignal();
    }

    public function testExitCodeText()
    {
        $this->skipIfPHPSigchild();
        parent::testExitCodeText();
    }

    public function testIsSuccessful()
    {
        $this->skipIfPHPSigchild();
        parent::testIsSuccessful();
    }

    public function testIsNotSuccessful()
    {
        $this->skipIfPHPSigchild();
        parent::testIsNotSuccessful();
    }

    public function testGetPid()
    {
        $this->skipIfPHPSigchild();
        parent::testGetPid();
    }

    public function testGetPidIsNullBeforeStart()
    {
        $this->skipIfPHPSigchild();
        parent::testGetPidIsNullBeforeStart();
    }

    public function testGetPidIsNullAfterRun()
    {
        $this->skipIfPHPSigchild();
        parent::testGetPidIsNullAfterRun();
    }

    public function testSignal()
    {
        $this->skipIfPHPSigchild();
        parent::testSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\LogicException
     */
    public function testSignalProcessNotRunning()
    {
        $this->skipIfPHPSigchild();
        parent::testSignalProcessNotRunning();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     */
    public function testSignalWithWrongIntSignal()
    {
        $this->skipIfPHPSigchild();
        parent::testSignalWithWrongIntSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     */
    public function testSignalWithWrongNonIntSignal()
    {
        $this->skipIfPHPSigchild();
        parent::testSignalWithWrongNonIntSignal();
    }

    /**
     * {@inheritdoc}
     */
    protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
    {
        return new Process($commandline, $cwd, $env, $stdin, $timeout, $options);
    }

    private function skipIfPHPSigchild()
    {
        if ($this->enabledSigchild) {
            $this->markTestSkipped('Your PHP has been compiled with --enable-sigchild, this test can not be executed');
        }
    }
}


text:
import * as ajv from 'ajv';
import * as schema from '../op_mapper_schema';

import * as arithmetic from './arithmetic';
import * as basicMath from './basic_math';
import * as control from './control';
import * as convolution from './convolution';
import * as creation from './creation';
import * as dynamic from './dynamic';
import * as evaluation from './evaluation';
import * as graph from './graph';
import * as image from './image';
import * as logical from './logical';
import * as matrices from './matrices';
import * as normalization from './normalization';
import * as reduction from './reduction';
import * as sliceJoin from './slice_join';
import * as transformation from './transformation';

describe('OpListTest', () => {
  const jsonValidator = new ajv();
  const validator = jsonValidator.compile(schema.json);
  beforeEach(() => {});

  // tslint:disable-next-line:no-any
  const mappersJson: any = {
    arithmetic,
    basicMath,
    control,
    convolution,
    dynamic,
    evaluation,
    creation,
    logical,
    image,
    graph,
    matrices,
    normalization,
    reduction,
    sliceJoin,
    transformation
  };
  Object.keys(mappersJson).forEach(key => {
    it('should satisfy the schema: ' + key, () => {
      const valid = validator(mappersJson[key].json);
      if (!valid) console.log(validator.errors);
      expect(valid).toBeTruthy();
    });
  });
});


text:
using SnowRentLibrary.Enums;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary2.WebService
{
    public class WebServiceManager<T> where T : class
    {
        public String DataConnectionResource { get; set; }

        public WebServiceManager(DataConnectionResource resource)
        {
            DataConnectionResource = EnumString.GetStringValue(resource);
        }

        public async Task<T> Get(Int32 id)
        {
            T item = default(T);
            String url = typeof(T).Name + "/" + id + "/";
            item = await HttpClientCaller<T>(url, item);
            return item;
        }

        public async Task<List<T>> Get()
        {
            List<T> item = default(List<T>);
            String url = typeof(T).Name + "/";
            item = await HttpClientCaller<List<T>>(url, item);
            return item;
        }

        public async Task<T> Post(T item)
        {
            T result = default(T);
            String url = typeof(T).Name + "/";
            result = await HttpClientSender<T>(url, item, result);

            return result;
        }

        public async Task<List<T>> Post(List<T> items)
        {
            List<T> result = default(List<T>);
            String url = typeof(T).Name + "s/";
            result = await HttpClientSender<List<T>>(url, items, result);

            return result;
        }

        public async Task<T> Put(T item)
        {
            T result = default(T);
            String url = typeof(T).Name + "/";
            result = await HttpClientPuter<T>(url, item, result);

            return result;
        }

        public async Task<List<T>> Put(List<T> items)
        {
            List<T> result = default(List<T>);
            String url = typeof(T).Name + "s/";
            result = await HttpClientPuter<List<T>>(url, items, result);

            return result;
        }

        public async Task<Int32> Delete(T item)
        {
            Int32 result = default(Int32);
            String url = typeof(T).Name + "/";
            result = await HttpClientDeleter<T, Int32>(url, item, result);

            return result;
        }

        public async Task<Int32> Delete(List<T> items)
        {
            Int32 result = default(Int32);
            String url = typeof(T).Name + "s/";
            result = await HttpClientDeleter<List<T>, Int32>(url, items, result);

            return result;
        }

        private async Task<TItem> HttpClientCaller<TItem>(String url, TItem item)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(DataConnectionResource);
                client.DefaultRequestHeaders
                  .Accept
                  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(url);
                item = await HandleResponse(item, response);
            }

            return item;
        }

        private async Task<TItem> HttpClientSender<TItem>(String url, TItem item, TItem result)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(DataConnectionResource);
                client.DefaultRequestHeaders
                  .Accept
                  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.PostAsync(url,
                    new StringContent(JsonConvert.SerializeObject(item),
                    Encoding.UTF8, "application/json"));

                result = await HandleResponse(item, response);
            }

            return result;
        }

        private async Task<TItem> HttpClientPuter<TItem>(string url, TItem item, TItem result)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(DataConnectionResource);
                client.DefaultRequestHeaders
                  .Accept
                  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.PutAsync(url,
                    new StringContent(JsonConvert.SerializeObject(item),
                    Encoding.UTF8, "application/json"));

                result = await HandleResponse(item, response);
            }

            return result;
        }

        private async Task<TResult> HttpClientDeleter<TItem, TResult>(string url, TItem item, TResult result)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(DataConnectionResource);
                client.DefaultRequestHeaders
                  .Accept
                  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

                using (HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Delete, url))
                {
                    message.Content = new StringContent(JsonConvert.SerializeObject(item),
                    Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.SendAsync(message);

                    result = await HandleResponse(result, response);
                }
            }

            return result;
        }

        private async Task<TItem> HandleResponse<TItem>(TItem item, HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                String result = await response.Content.ReadAsStringAsync();
                item = JsonConvert.DeserializeObject<TItem>(result);
            }

            return item;
        }
    }
}


text:
/**@file thttp_header_ETag.h
 * @brief HTTP 'ETag' header.
 *
 * @author Mamadou Diop <diopmamadou(at)doubango[dot]org>
 *

 */
#ifndef _THTTP_HEADER_ETAG_H_
#define _THTTP_HEADER_ETAG_H_

#include "tinyhttp_config.h"
#include "tinyhttp/headers/thttp_header.h"

THTTP_BEGIN_DECLS

#define THTTP_HEADER_ETAG_VA_ARGS(value)		thttp_header_ETag_def_t, (const char*)value

////////////////////////////////////////////////////////////////////////////////////////////////////
/// HTTP ETag header.
///
/// @par ABNF : ETag = "ETag" ":" entity-tag
/// 	entity-tag = [ weak ] opaque-tag
/// 	weak       = "W/"
/// 	opaque-tag = quoted-string
////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct thttp_header_ETag_s
{
	THTTP_DECLARE_HEADER;

	char *value;
	tsk_bool_t isWeak;
}
thttp_header_ETag_t;

thttp_header_ETag_t *thttp_header_ETag_parse(const char *data, tsk_size_t size);

thttp_header_ETag_t* thttp_header_etag_create(const char* value);
thttp_header_ETag_t* thttp_header_etag_create_null();

TINYHTTP_GEXTERN const tsk_object_def_t *thttp_header_ETag_def_t;

THTTP_END_DECLS

#endif /* _THTTP_HEADER_ETAG_H_ */


text:
Before("@directconnect") do
  @service = Aws::DirectConnect::Resource.new
  @client = @service.client
end

After("@directconnect") do
  # shared cleanup logic
end


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
	<title>Clojure</title>

	<link rel="stylesheet" href="https://defunsm.github.io/css/style.css" />
	<link rel="stylesheet" href="https://defunsm.github.io/css/font-awesome.min.css" />
	<link type="text/css" rel="stylesheet" href="https://defunsm.github.io/featherlight.css" />
        <link rel="stylesheet" href="https://defunsm.github.io/css/screen.css" />
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.1/styles/default.min.css">

	<link rel="shortcut icon" href="images/favicon.png">

			      Home

						About

						Github

						Archives

Clojure

            Posts tagged as "Clojure"

Posts Tagged "Clojure"

                  Art with Quil

                  Graphics using Quil in Clojure (Part 4)

                  Clojure - Ring

                  Clojure - Figwheel

                  Clojure - Leiningen

                  Clojure - Shell Commands

                  Clojure - Probabilities

                  SMChat

                  Graphics using Quil in Clojure (Part 3)

                  Basics of Clojure - Watching an Atom (Part 5)

                  Basics of Clojure - Atoms (Part 4)

                  Basics of Clojure - Recursion (Part 3)

                  Basics of Clojure - Mapping (Part 2)

                  Basics of Clojure (Part 1)

                  Graphics using Quil in Clojure (Part 2)

                  Getting Started with Clojure

                  Graphics using Quil in Clojure (Part 1)

                  Creating an Exechuteable GUI

                  Clojure File to Standalone Jar

© 2016 Salman Hossain

				Top


text:
using System.Linq.Expressions;

namespace Bit.BlazorUI;

/// <summary>
/// Represents a sort order specification used within <see cref="BitDataGrid{TGridItem}"/>.
/// </summary>
/// <typeparam name="TGridItem">The type of data represented by each row in the grid.</typeparam>
public class BitDataGridSort<TGridItem>
{
    private const string ExpressionNotRepresentableMessage = "The supplied expression can't be represented as a property name for sorting. Only simple member expressions, such as @(x => x.SomeProperty), can be converted to property names.";

    private Func<IQueryable<TGridItem>, bool, IOrderedQueryable<TGridItem>> _first;
    private List<Func<IOrderedQueryable<TGridItem>, bool, IOrderedQueryable<TGridItem>>>? _then;

    private (LambdaExpression, bool) _firstExpression;
    private List<(LambdaExpression, bool)>? _thenExpressions;

    private IReadOnlyCollection<(string PropertyName, BitDataGridSortDirection Direction)>? _cachedPropertyListAscending;
    private IReadOnlyCollection<(string PropertyName, BitDataGridSortDirection Direction)>? _cachedPropertyListDescending;

    internal BitDataGridSort(Func<IQueryable<TGridItem>, bool, IOrderedQueryable<TGridItem>> first, (LambdaExpression, bool) firstExpression)
    {
        _first = first;
        _firstExpression = firstExpression;
        _then = default;
        _thenExpressions = default;
    }

    /// <summary>
    /// Produces a <see cref="BitDataGridSort{T}"/> instance that sorts according to the specified <paramref name="expression"/>, ascending.
    /// </summary>
    /// <typeparam name="U">The type of the expression's value.</typeparam>
    /// <param name="expression">An expression defining how a set of <typeparamref name="TGridItem"/> instances are to be sorted.</param>
    /// <returns>A <see cref="BitDataGridSort{T}"/> instance representing the specified sorting rule.</returns>
    public static BitDataGridSort<TGridItem> ByAscending<U>(Expression<Func<TGridItem, U>> expression)
        => new BitDataGridSort<TGridItem>((queryable, asc) => asc ? queryable.OrderBy(expression) : queryable.OrderByDescending(expression),
            (expression, true));

    /// <summary>
    /// Produces a <see cref="BitDataGridSort{T}"/> instance that sorts according to the specified <paramref name="expression"/>, descending.
    /// </summary>
    /// <typeparam name="U">The type of the expression's value.</typeparam>
    /// <param name="expression">An expression defining how a set of <typeparamref name="TGridItem"/> instances are to be sorted.</param>
    /// <returns>A <see cref="BitDataGridSort{T}"/> instance representing the specified sorting rule.</returns>
    public static BitDataGridSort<TGridItem> ByDescending<U>(Expression<Func<TGridItem, U>> expression)
        => new BitDataGridSort<TGridItem>((queryable, asc) => asc ? queryable.OrderByDescending(expression) : queryable.OrderBy(expression),
            (expression, false));

    /// <summary>
    /// Updates a <see cref="BitDataGridSort{T}"/> instance by appending a further sorting rule.
    /// </summary>
    /// <typeparam name="U">The type of the expression's value.</typeparam>
    /// <param name="expression">An expression defining how a set of <typeparamref name="TGridItem"/> instances are to be sorted.</param>
    /// <returns>A <see cref="BitDataGridSort{T}"/> instance representing the specified sorting rule.</returns>
    public BitDataGridSort<TGridItem> ThenAscending<U>(Expression<Func<TGridItem, U>> expression)
    {
        _then ??= new();
        _thenExpressions ??= new();
        _then.Add((queryable, asc) => asc ? queryable.ThenBy(expression) : queryable.ThenByDescending(expression));
        _thenExpressions.Add((expression, true));
        _cachedPropertyListAscending = null;
        _cachedPropertyListDescending = null;
        return this;
    }

    /// <summary>
    /// Updates a <see cref="BitDataGridSort{T}"/> instance by appending a further sorting rule.
    /// </summary>
    /// <typeparam name="U">The type of the expression's value.</typeparam>
    /// <param name="expression">An expression defining how a set of <typeparamref name="TGridItem"/> instances are to be sorted.</param>
    /// <returns>A <see cref="BitDataGridSort{T}"/> instance representing the specified sorting rule.</returns>
    public BitDataGridSort<TGridItem> ThenDescending<U>(Expression<Func<TGridItem, U>> expression)
    {
        _then ??= new();
        _thenExpressions ??= new();
        _then.Add((queryable, asc) => asc ? queryable.ThenByDescending(expression) : queryable.ThenBy(expression));
        _thenExpressions.Add((expression, false));
        _cachedPropertyListAscending = null;
        _cachedPropertyListDescending = null;
        return this;
    }

    internal IOrderedQueryable<TGridItem> Apply(IQueryable<TGridItem> queryable, bool ascending)
    {
        var orderedQueryable = _first(queryable, ascending);

        if (_then is not null)
        {
            foreach (var clause in _then)
            {
                orderedQueryable = clause(orderedQueryable, ascending);
            }
        }

        return orderedQueryable;
    }

    internal IReadOnlyCollection<(string PropertyName, BitDataGridSortDirection Direction)> ToPropertyList(bool ascending)
    {
        if (ascending)
        {
            _cachedPropertyListAscending ??= BuildPropertyList(ascending: true);
            return _cachedPropertyListAscending;
        }
        else
        {
            _cachedPropertyListDescending ??= BuildPropertyList(ascending: false);
            return _cachedPropertyListDescending;
        }
    }

    private IReadOnlyCollection<(string PropertyName, BitDataGridSortDirection Direction)> BuildPropertyList(bool ascending)
    {
        var result = new List<(string, BitDataGridSortDirection)>();
        result.Add((ToPropertyName(_firstExpression.Item1), (_firstExpression.Item2 ^ ascending) ? BitDataGridSortDirection.Descending : BitDataGridSortDirection.Ascending));

        if (_thenExpressions is not null)
        {
            foreach (var (thenLambda, thenAscending) in _thenExpressions)
            {
                result.Add((ToPropertyName(thenLambda), (thenAscending ^ ascending) ? BitDataGridSortDirection.Descending : BitDataGridSortDirection.Ascending));
            }
        }

        return result;
    }

    // Not sure we really want this level of complexity, but it converts expressions like @(c => c.Medals.Gold) to "Medals.Gold"
    private static string ToPropertyName(LambdaExpression expression)
    {
        var body = expression.Body as MemberExpression;
        if (body is null)
        {
            throw new ArgumentException(ExpressionNotRepresentableMessage);
        }

        // Handles cases like @(x => x.Name)
        if (body.Expression is ParameterExpression)
        {
            return body.Member.Name;
        }

        // First work out the length of the string we'll need, so that we can use string.Create
        var length = body.Member.Name.Length;
        var node = body;
        while (node.Expression is not null)
        {
            if (node.Expression is MemberExpression parentMember)
            {
                length += parentMember.Member.Name.Length + 1;
                node = parentMember;
            }
            else if (node.Expression is ParameterExpression)
            {
                break;
            }
            else
            {
                throw new ArgumentException(ExpressionNotRepresentableMessage);
            }
        }

        // Now construct the string
        return string.Create(length, body, (chars, body) =>
        {
            var nextPos = chars.Length;
            while (body is not null)
            {
                nextPos -= body.Member.Name.Length;
                body.Member.Name.CopyTo(chars.Slice(nextPos));
                if (nextPos > 0)
                {
                    chars[--nextPos] = '.';
                }
                body = (body.Expression as MemberExpression)!;
            }
        });
    }
}


text:
import itk

def LongFunction():
    # CPython loops are much slower than C++,
    # so a smaller range is used in this case.
    for i in range(int(1e5)):
        a = 0.0  # noqa: F841

clock = itk.TimeProbe()

clock.Start()
LongFunction()

clock.Stop()
print("Mean: " + str(clock.GetMean()))
print("Total: " + str(clock.GetTotal()))

clock.Start()
LongFunction()

clock.Stop()
print("Mean: " + str(clock.GetMean()))
print("Total: " + str(clock.GetTotal()))

clock.Report()


text:
from __future__ import unicode_literals

import posixpath

from django.conf import settings
from django.test import override_settings

from .cases import StaticFilesTestCase, TestDefaults

@override_settings(ROOT_URLCONF='staticfiles_tests.urls.default')
class TestServeStatic(StaticFilesTestCase):
    """
    Test static asset serving view.
    """
    def _response(self, filepath):
        return self.client.get(
            posixpath.join(settings.STATIC_URL, filepath))

    def assertFileContains(self, filepath, text):
        self.assertContains(self._response(filepath), text)

    def assertFileNotFound(self, filepath):
        self.assertEqual(self._response(filepath).status_code, 404)

@override_settings(DEBUG=False)
class TestServeDisabled(TestServeStatic):
    """
    Test serving static files disabled when DEBUG is False.
    """
    def test_disabled_serving(self):
        self.assertFileNotFound('test.txt')

@override_settings(DEBUG=True)
class TestServeStaticWithDefaultURL(TestDefaults, TestServeStatic):
    """
    Test static asset serving view with manually configured URLconf.
    """

@override_settings(DEBUG=True, ROOT_URLCONF='staticfiles_tests.urls.helper')
class TestServeStaticWithURLHelper(TestDefaults, TestServeStatic):
    """
    Test static asset serving view with staticfiles_urlpatterns helper.
    """


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Persisters;

use Doctrine\Common\Collections\Expr\Comparison;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\OneToOneAssociationMetadata;
use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
use Doctrine\Tests\Models\GeoNames\Admin1AlternateName;
use Doctrine\Tests\OrmTestCase;

class BasicEntityPersisterCompositeTypeSqlTest extends OrmTestCase
{
    /** @var BasicEntityPersister */
    protected $persister;

    /** @var EntityManagerInterface */
    protected $em;

    /**
     * {@inheritDoc}
     */
    protected function setUp() : void
    {
        parent::setUp();

        $this->em        = $this->getTestEntityManager();
        $this->persister = new BasicEntityPersister($this->em, $this->em->getClassMetadata(Admin1AlternateName::class));
    }

    public function testSelectConditionStatementEq() : void
    {
        $statement = $this->persister->getSelectConditionStatementSQL('admin1', 1, new OneToOneAssociationMetadata('admin1'), Comparison::EQ);
        self::assertEquals('t0."admin1" = ? AND t0."country" = ?', $statement);
    }

    public function testSelectConditionStatementEqNull() : void
    {
        $statement = $this->persister->getSelectConditionStatementSQL('admin1', null, new OneToOneAssociationMetadata('admin1'), Comparison::IS);
        self::assertEquals('t0."admin1" IS NULL AND t0."country" IS NULL', $statement);
    }

    public function testSelectConditionStatementNeqNull() : void
    {
        $statement = $this->persister->getSelectConditionStatementSQL('admin1', null, new OneToOneAssociationMetadata('admin1'), Comparison::NEQ);
        self::assertEquals('t0."admin1" IS NOT NULL AND t0."country" IS NOT NULL', $statement);
    }

    /**
     * @expectedException Doctrine\ORM\ORMException
     */
    public function testSelectConditionStatementIn() : void
    {
        $this->persister->getSelectConditionStatementSQL('admin1', [], new OneToOneAssociationMetadata('admin1'), Comparison::IN);
    }
}


text:
/* @flow */
/* eslint no-redeclare: "off" */

import type { Insertable } from "../types";

import { drop, toArray } from "../utils";

function prependNode(element: Element, insertable: Node): void {
  element.insertBefore(insertable, element.firstChild);
}

declare function prepend(
  element: Element,
  ...insertables: Array<Insertable>
): void;

function prepend(element) {
  drop(arguments, 1).reverse().forEach(insertable => {
    if (typeof insertable === "string") {
      element.insertAdjacentHTML("afterbegin", insertable);
    } else if (insertable instanceof Node) {
      prependNode(element, insertable);
    } else {
      toArray(insertable).reverse().forEach(node => {
        prependNode(element, node);
      });
    }
  });
}

export default prepend;


text:
package validation

import (
	"errors"
	"reflect"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/discovery"
	fakediscovery "k8s.io/client-go/discovery/fake"
	"k8s.io/client-go/kubernetes/fake"
	test "k8s.io/client-go/testing"
)

func areErrorsEqual(err1, err2 error) bool {
	return (err1 != nil && err2 != nil && err1.Error() == err2.Error()) ||
		(err1 == nil && err2 == nil)
}

type fakeServerGroupsMethod func() (*metav1.APIGroupList, error)

type FakeClient struct {
	fake.Clientset
	fakeServerGroupsMethod
}

func (self *FakeClient) Discovery() discovery.DiscoveryInterface {
	return &FakeDiscovery{
		FakeDiscovery:          fakediscovery.FakeDiscovery{Fake: &self.Fake},
		fakeServerGroupsMethod: self.fakeServerGroupsMethod,
	}
}

type FakeDiscovery struct {
	fakediscovery.FakeDiscovery
	fakeServerGroupsMethod
}

func (self *FakeDiscovery) ServerGroups() (*metav1.APIGroupList, error) {
	return self.fakeServerGroupsMethod()
}

func TestValidateRbacStatus(t *testing.T) {
	cases := []struct {
		info        string
		mockMethod  fakeServerGroupsMethod
		expected    *RbacStatus
		expectedErr error
	}{
		{
			"should throw an error when can't get api versions from server",
			func() (*metav1.APIGroupList, error) {
				return nil, errors.New("test-error")
			},
			nil,
			errors.New("Couldn't get available api versions from server: test-error"),
		},
		{
			"should disable rbacs when supported api version not enabled on the server",
			func() (*metav1.APIGroupList, error) {
				return &metav1.APIGroupList{Groups: []metav1.APIGroup{
					{Name: "rbac", Versions: []metav1.GroupVersionForDiscovery{
						{
							GroupVersion: "authorization.k8s.io/v1alpha1",
							Version:      "v1alpha1",
						},
					}},
				}}, nil
			},
			&RbacStatus{false},
			nil,
		},
		{
			"should enable rbac when supported api version is enabled on the server",
			func() (*metav1.APIGroupList, error) {
				return &metav1.APIGroupList{Groups: []metav1.APIGroup{
					{Name: "rbac", Versions: []metav1.GroupVersionForDiscovery{
						{
							GroupVersion: "authorization.k8s.io/v1beta1",
							Version:      "v1beta1",
						},
					}},
				}}, nil
			},
			&RbacStatus{true},
			nil,
		},
	}

	for _, c := range cases {
		client := &FakeClient{
			Clientset:              fake.Clientset{Fake: test.Fake{}},
			fakeServerGroupsMethod: c.mockMethod,
		}

		status, err := ValidateRbacStatus(client)
		if !areErrorsEqual(err, c.expectedErr) {
			t.Fatalf("Test case: %s. Expected error to be: %v, but got %v.", c.info,
				c.expectedErr, err)
		}

		if !reflect.DeepEqual(status, c.expected) {
			t.Fatalf("Test case: %s. Expected status to be: %v, but got %v.", c.info,
				c.expected, status)
		}
	}

}


text:
package dev.jee6demo.cdiint;

import java.util.Arrays;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class MyInterceptor {
	@AroundInvoke
    public Object logCall(InvocationContext context) throws Exception{
        System.out.println("--- Method: " + context.getMethod());
        System.out.println("--- Parameters: " + Arrays.asList(context.getParameters()));
        Object returnedObject=context.proceed();	//call method
        if(returnedObject instanceof String){		//modify returned String
        	returnedObject=((String)returnedObject)+"-intercepted-";
        }
        return returnedObject;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_rating_star_on_normal_holo_dark" android:state_pressed="true"/>
    <item android:drawable="@drawable/btn_rating_star_off_normal_holo_dark"/>

</selector>


text:
@(title: String, user: User, searchstr: String, currentPage: com.avaje.ebean.Page[CrawlPermission], currentSortBy: String, currentOrder: String, cur_status: String, cur_organisation: String, sel: String, crawlPermissionStatuses: Array[uk.bl.Const.CrawlPermissionStatus], templates: List[models.MailTemplate])

@styles = {
    <link rel="stylesheet" type="text/css" media="screen" href="@routes.Assets.at("bootstrap/typeahead/css/typeahead.css")">
}

@scripts = {

}

@****************************************
* Helper generating navigation links    *
****************************************@
@link(newPage:Int, newSortBy:String) = @{

    var sortBy = currentSortBy
    var order = currentOrder

    if(newSortBy != null) {
        sortBy = newSortBy
        if(currentSortBy == newSortBy) {
            if(currentOrder == "asc") {
                order = "desc"
            } else {
                order = "asc"
            }
        } else {
            order = "asc"
        }
    }

    // Generate the link
    routes.CrawlPermissionController.list(newPage, sortBy, order, searchstr, cur_status, cur_organisation, sel)

}

@**********************************
* Helper generating table headers *
***********************************@
@header(key:String, title:String) = {

        @title

}

@pagination = {
    @if(currentPage.getTotalPageCount() > 0) {

                @if(currentPage.hasPrev) {

                        ← Previous

                } else {

                        ← Previous

                }

                    Displaying @currentPage.getDisplayXtoYofZ(" to "," of ")

                @if(currentPage.hasNext) {

                        Next →

                } else {

                        Next →

                }

    }
}

@if(user.hasRole("sys_admin") || user.hasRole("archivist")) {

@main(title, user, scripts, styles) {

Archivist Tasks > Crawl Permissions

Permissions Queue

Mail Templates

Contact Persons

Licence Templates

Communication Logging

            @helper.form(action=routes.CrawlPermissionController.search, 'class -> "form-inline") {

                    <input type="text" class="form-control lookup-form-control" name="name" placeholder="Enter crawl permission name" value="@searchstr" id="search-query">

                        <button type="submit" class="btn btn-primary" id="search" name="action" value="search" title="Search for crawl permission by name">Search</button>

                    ▼ Filters ▲

                @warningmessage(flash)

                                        Filter by status

                                            <select name="status" id="status" class="form-control">
                                                <option value="-1">ANY</option>
                                                @for(status <- crawlPermissionStatuses) {
                                                    @if(status.name.equals(cur_status)) {
                                                        <option value="@status.name" selected>@status.getValue</option>
                                                    } else {
                                                        <option value="@status.name">@status.getValue</option>
                                                    }
                                                }
                                            </select>

                                        Filter by organisation

                                            <select name="organisation" id="organisation" class="form-control">
                                                <option value="-1">ANY</option>
                                                @for(organisation <- OrganisationController.getOrganisationList()){
                                                    @if(organisation.id == Integer.valueOf(cur_organisation)){
                                                        <option value="@organisation.id" selected>@organisation.title</option>
                                                    } else {
                                                        <option value="@organisation.id">@organisation.title</option>
                                                    }
                                                }
                                            </select>

            }

    @pagination

    @helper.form(action=routes.CrawlPermissionController.send, 'class -> "form-inline") {

                        @header("name", "Name")
                        @header("target", "Target")
                        URLs
                        Organisation
                        Contact Person
                        @header("status", "Status")
                        Licence Form
                        @header("createdAt", "Created Date")
                        @header("requestedAt", "Requested Date")
                        @header("grantedAt", "Granted Date")

                @for(permission <- currentPage.getList) {

                                @if(sel.equals("selectall")) {
                                    <input type="checkbox" name="permissionsList" value="@permission.id" checked /> @TargetController.getTitle(permission.target.id)
                                } else {
                                    <input type="checkbox" name="permissionsList" value="@permission.id" /> @TargetController.getTitle(permission.target.id)
                                }

                            View

                            @for(fieldUrl <- permission.target.fieldUrls) {
                                @fieldUrl.url
                            }

                        @OrganisationController.getTitle(permission.user.organisation.id)

                            @if( permission.contactPerson != null ) {
                                @permission.contactPerson.name
                            } else {
                                CONTACT PERSON NOT SET!
                            }

                            View Communication Log

                            @permission.status

                            @if( "GRANTED".equals(permission.status) ) {
                                View
                            }

                            @uk.bl.api.Utils.INSTANCE.convertToDateTime(permission.createdAt)

                            @uk.bl.api.Utils.INSTANCE.convertToDateTime(permission.requestedAt)

                            @uk.bl.api.Utils.INSTANCE.convertToDateTime(permission.grantedAt)

                }

        @pagination

            In order to enable send buttons check that crawl permission list is not empty and that these crawl permissions contain a contact person.

        @if(user.hasRole("sys_admin") || user.hasRole("archivist")) {

                    Template

                    <select id="selectTemplate" name="template" class="form-control">
                            <option value="" selected><Use default></option>
                        @for(template <- templates) {
                            <option value="@template.name">@template.name</option>
                        }
                    </select>

                <input type="hidden" id="statusValue" name="statusValue" value="@cur_status">
                <input type="hidden" id="pageNo" name="pageNo" value="@currentPage.getPageIndex">

                    @if(currentPage.getTotalRowCount() > 0 && CrawlPermissionController.haveContactPerson(currentPage.getList())) {
                        <button type="submit" class="btn btn-primary" name="action" value="selectall">Select all</button>
                        <button type="submit" class="btn btn-primary" name="action" value="deselectall">Deselect all</button>

                        <button type="submit" class="btn btn-primary" name="action" value="sendsome">Send</button>
                        <button type="submit" class="btn btn-primary" name="action" value="preview">Preview</button>
                        <button type="submit" class="btn btn-primary" name="action" value="reject">Reject</button>
                    } else {
                        <button type="submit" class="btn btn-primary" name="action" value="selectall" disabled>Select all</button>
                        <button type="submit" class="btn btn-primary" name="action" value="deselectall" disabled>Deselect all</button>

                        <button type="submit" class="btn btn-primary" name="action" value="sendsome" disabled>Send</button>
                        <button type="submit" class="btn btn-primary" name="action" value="preview" disabled>Preview</button>
                        <button type="submit" class="btn btn-primary" name="action" value="reject" disabled>Reject</button>
                    }

        }
    }

}
} else {
    @if(user.hasRole("expert_user") || user.hasRole("user")) {
        @infomessage.render("Your Open UKWA License email has now been queued.")
    } else {
        @infomessage.render("Access Denied for URL @routes.CrawlPermissionController.index()/list")
    }
}


text:
#import <SAObjects/SADomainObject.h>

@class NSDate, NSString;

@interface SAMovieV2ReviewListCell : SADomainObject
{
}

+ (id)reviewListCellWithDictionary:(id)arg1 context:(id)arg2;
+ (id)reviewListCell;
- (void)updateUsingSet:(id)arg1 add:(id)arg2 remove:(id)arg3;
@property(copy, nonatomic) NSString *reviewText;
@property(copy, nonatomic) NSDate *reviewDate;
@property(copy, nonatomic) NSString *reviewAuthor;
- (id)encodedClassName;
- (id)groupIdentifier;

@end


text:
#pragma once

#include <unordered_set>
#include <string>
#include "entityx/Entity.h"

namespace entityx {
namespace tags {

/**
 * Allow entities to be tagged with strings.
 *
 * entity.assign<TagsComponent>("tag1", "tag2");
 *
 * ComponentPtr<TagsComponent> tags;
 * for (Entity entity : entity_manager.entities_with_components(tags))
 */
class TagsComponent : public Component<TagsComponent> {
 public:
  /**
   * Construct a new TagsComponent with the given tags.
   *
   * eg. TagsComponent tags("a", "b", "c");
   */
  template <typename ... Args>
  TagsComponent(const std::string &tag, const Args & ... tags) {
    set_tags(tag, tags ...);
  }

  std::unordered_set<std::string> tags;

 private:
  template <typename ... Args>
  void set_tags(const std::string &tag1, const std::string &tag2, const Args & ... tags) {
    this->tags.insert(tag1);
    set_tags(tag2, tags ...);
  }

  void set_tags(const std::string &tag) {
    tags.insert(tag);
  }
};

}  // namespace tags
}  // namespace entityx


text:
<?xml version="1.0" encoding="UTF-8"?>
<window>
  <controls>
    <control type="group">
      <visible>Slideshow.IsActive</visible>
      <animation condition="Slideshow.IsPaused" effect="fade" start="100" end="0" time="200">conditional</animation>
      <animation condition="!Slideshow.IsPaused" effect="fade" start="0" end="100" time="400">conditional</animation>
      <animation condition="!Slideshow.IsPaused" effect="fade" start="100" end="0" delay="2000" time="400">conditional</animation>
      <posx>90</posx>
      <posy>870</posy>
      <control type="image">
        <posx>0</posx>
        <posy>0</posy>
        <width>129</width>
        <height>120</height>
        <texture>img/BlackDotST2.png</texture>
      </control>
      <control type="image">
        <posx>6</posx>
        <posy>0</posy>
        <width>120</width>
        <height>120</height>
        <texture>OSD/OSDProgressPlay.png</texture>
      </control>
    </control>
    <control type="group" id="13">
      <visible>Slideshow.IsPaused</visible>
      <animation effect="fade" start="0" end="100" time="400">Visible</animation>
      <posx>90</posx>
      <posy>870</posy>
      <control type="image">
        <posx>0</posx>
        <posy>0</posy>
        <width>129</width>
        <height>120</height>
        <texture>img/BlackDotST2.png</texture>
      </control>
      <control type="image">
        <posx>6</posx>
        <posy>0</posy>
        <width>120</width>
        <height>120</height>
        <texture>OSD/OSDProgressPause.png</texture>
      </control>
    </control>
  </controls>
</window>


text:
'use strict';

angular.module('redisApp').factory('Dashboards', function (Restangular) {
	return {
		metrics: Restangular.service('actuator/metrics')
	};
});