text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * The Apereo Foundation licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 -->
<hibernate-mapping package="org.unitime.timetable.model">
    <class name="Curriculum" table="curriculum">
        <cache include="non-lazy" usage="transactional"/>
        <id
            name="uniqueId"
            column="uniqueid"
            type="java.lang.Long">
            <generator class="org.unitime.commons.hibernate.id.UniqueIdGenerator">
                <param name="sequence">pref_group_seq</param>
            </generator>
        </id>

        <property
            name="abbv"
            column="abbv"
            type="java.lang.String"
            not-null="true"
            length="20"/>

        <property
            name="name"
            column="name"
            type="java.lang.String"
            not-null="true"
            length="60"/>

        <many-to-one
            name="academicArea"
            class="AcademicArea"
            column="acad_area_id"
            not-null="true"
            foreign-key="fk_curriculum_acad_area"/>

        <set
            name="majors"
            table="curriculum_major"
            inverse="false"
            lazy="true">

            <cache include="non-lazy" usage="transactional"/>
            <key column="curriculum_id"/>
            <many-to-many class="org.unitime.timetable.model.PosMajor" column="major_id"/>
        </set>

        <many-to-one
            name="department"
            class="Department"
            column="dept_id"
            not-null="true"
            foreign-key="fk_curriculum_dept"/>

        <set
            name="classifications"
            lazy="true"
            cascade="all"
            inverse="true">

            <cache include="non-lazy" usage="transactional"/>
            <key column="curriculum_id" foreign-key="fk_curriculum_clasf_curriculum"/>
            <one-to-many class="CurriculumClassification"/>
        </set>

    </class>
    <class name="CurriculumClassification" table="curriculum_clasf">
        <cache include="non-lazy" usage="transactional"/>
        <id
            name="uniqueId"
            column="uniqueid"
            type="java.lang.Long">
            <generator class="org.unitime.commons.hibernate.id.UniqueIdGenerator">
                <param name="sequence">pref_group_seq</param>
            </generator>
        </id>

        <many-to-one
            name="curriculum"
            class="Curriculum"
            column="curriculum_id"
            not-null="true"
            foreign-key="fk_curriculum_clasf_curriculum"/>

        <property
            name="name"
            column="name"
            type="java.lang.String"
            not-null="true"
            length="20"/>

        <many-to-one
            name="academicClassification"
            class="AcademicClassification"
            column="acad_clasf_id"
            not-null="true"
            foreign-key="fk_curriculum_clasf_acad_clasf"/>

        <property
            name="nrStudents"
            column="nr_students"
            type="java.lang.Integer"
            not-null="true"/>

        <property
            name="ord"
            column="ord"
            type="java.lang.Integer"
            not-null="true"/>

        <property
            lazy="true"
            name="students"
            column="students"
            type="org.unitime.commons.hibernate.blob.XmlClobType"
            not-null="false"/>

        <set
            name="courses"
            lazy="true"
            cascade="all"
            inverse="true">

            <cache include="non-lazy" usage="transactional"/>
            <key column="cur_clasf_id" foreign-key="fk_curriculum_course_clasf"/>
            <one-to-many class="CurriculumCourse"/>
        </set>

    </class>
    <class name="CurriculumCourse" table="curriculum_course">
        <cache include="non-lazy" usage="transactional"/>
        <id
            name="uniqueId"
            column="uniqueid"
            type="java.lang.Long">
            <generator class="org.unitime.commons.hibernate.id.UniqueIdGenerator">
                <param name="sequence">pref_group_seq</param>
            </generator>
        </id>

        <many-to-one
            name="classification"
            class="CurriculumClassification"
            column="cur_clasf_id"
            not-null="true"
            foreign-key="fk_curriculum_course_clasf"/>

        <many-to-one
            name="course"
            class="CourseOffering"
            column="course_id"
            not-null="true"
            foreign-key="fk_curriculum_course_course"/>

        <property
            name="percShare"
            column="pr_share"
            type="java.lang.Float"
            not-null="true"/>

        <property
            name="ord"
            column="ord"
            type="java.lang.Integer"
            not-null="true"/>

        <set
            name="groups"
            table="curriculum_course_group"
            lazy="true">
            <cache include="non-lazy" usage="transactional"/>
            <key column="cur_course_id"/>
            <many-to-many
                class="org.unitime.timetable.model.CurriculumCourseGroup"
                column="group_id"
                foreign-key="fk_cur_course_group_group"/>

        </set>

    </class>
    <class name="CurriculumCourseGroup" table="curriculum_group">
        <cache include="non-lazy" usage="transactional"/>
        <id
            name="uniqueId"
            column="uniqueid"
            type="java.lang.Long">
            <generator class="org.unitime.commons.hibernate.id.UniqueIdGenerator">
                <param name="sequence">pref_group_seq</param>
            </generator>
        </id>

        <property
            name="name"
            column="name"
            length="20"
            type="java.lang.String"
            not-null="true"/>

        <property
            name="color"
            column="color"
            length="20"
            type="java.lang.String"
            not-null="false"/>

        <property
            name="type"
            column="type"
            type="java.lang.Integer"
            not-null="true"/>

        <many-to-one
            name="curriculum"
            class="Curriculum"
            column="curriculum_id"
            not-null="true"
            foreign-key="fk_curriculum_group_curriculum"/>

    </class>
    <class name="CurriculumProjectionRule" table="curriculum_rule">
        <cache include="non-lazy" usage="transactional"/>
        <id
            name="uniqueId"
            column="uniqueid"
            type="java.lang.Long">
            <generator class="org.unitime.commons.hibernate.id.UniqueIdGenerator">
                <param name="sequence">pref_group_seq</param>
            </generator>
        </id>

        <many-to-one
            name="academicArea"
            class="AcademicArea"
            column="acad_area_id"
            not-null="true"
            foreign-key="fk_cur_rule_acad_area"/>

        <many-to-one
            name="major"
            class="PosMajor"
            column="major_id"
            not-null="false"
            foreign-key="fk_cur_rule_major"/>

        <many-to-one
            name="academicClassification"
            class="AcademicClassification"
            column="acad_clasf_id"
            not-null="true"
            foreign-key="fk_cur_rule_acad_clasf"/>

        <property
            name="projection"
            column="projection"
            type="java.lang.Float"
            not-null="true"/>

    </class>
</hibernate-mapping>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using GME.MGA;
using System.IO;

namespace MasterInterpreterTest.FunctionalTests
{
    public class AnalysisModelProcessors
    {
        //[Fact]
        public void TestCodeSample()
        {
            string ProjectConnStr;
            MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr);

            MgaProject project = new MgaProject();
            bool ro_mode;
            project.Open(ProjectConnStr, out ro_mode);

            MgaHelper.CheckParadigmVersionUpgrade(project);

            try
            {
                List<IMgaFCO> objectsToCheck = null;

                project.BeginTransactionInNewTerr();
                try
                {
                    // discover objects

                    var allObjects = project
                        .RootFolder
                        .ChildFolders
                        .Cast<MgaFolder>()
                        .Where(x => x.Name.StartsWith("0"))
                        .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>())
                        .Where(x => x.RootFCO == x);

                    // get all objects from folders starts with 0 within the root folder.
                    objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("ProcessorTypesForContexts")).ToList();

                    objectsToCheck.Sort((x, y) =>
                    {
                        return x.Meta.Name.CompareTo(y.Meta.Name) != 0 ?
                            x.Meta.Name.CompareTo(y.Meta.Name) :
                            x.AbsPath.CompareTo(y.AbsPath);
                    });
                }
                finally
                {
                    project.AbortTransaction();
                }

                Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked.");

                int numContexts = objectsToCheck.Count;
                int numSuccess = 0;
                int numFailures = 0;

                bool success = true;

                foreach (var subject in objectsToCheck)
                {
                    // single test
                    CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null;

                    project.BeginTransactionInNewTerr();
                    try
                    {
                        Assert.ThrowsDelegate d = () =>
                        {
                            analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel);
                        };

                        MgaObject parent = null;
                        GME.MGA.Meta.objtype_enum type;
                        subject.GetParent(out parent, out type);

                        var contextSupportExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true;
                        if (contextSupportExpected)
                        {
                            Assert.DoesNotThrow(d);
                            Assert.True(analysisModelProcessor != null, string.Format("Analysis model processor was not able to create the model processor for {0} {1}.", subject.Name, subject.Meta.Name));

                            if (subject.Name.Contains(analysisModelProcessor.GetType().Name))
                            {
                                numSuccess++;
                                Console.Out.WriteLine("[Passed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name);
                            }
                            else
                            {
                                success = false;
                                numFailures++;
                                Console.Out.WriteLine("[Failed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name);
                            }
                        }
                        else
                        {
                            Assert.Throws<CyPhyMasterInterpreter.AnalysisModelContextNotSupportedException>(d);
                            numSuccess++;
                            Console.Out.WriteLine("[Passed] Context not supported {0} [{1}]", subject.Name, subject.Meta.Name);
                        }
                    }
                    finally
                    {
                        project.AbortTransaction();
                    }
                }

                if (success)
                {
                    Console.Out.WriteLine("[OK] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures);
                }
                else
                {
                    Console.Error.WriteLine("[FAILED] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures);
                }

                Assert.True(success, "At least one analysis model processor was not instantiated as expected.");

            }
            finally
            {
                project.Close(true);
            }

        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
Jaw-dropping stats for your Sqwiggle-team.

**Current feature list:**

**Future feature list:**

#Pre-Requirement

  - PHP 5.X and above sever

#Installation Process

#Credits

 - [Kukiwon](https://github.com/Kukiwon)
 - [Everywhereis](http://www.everywhere.is/)


text:
<?php

defined('_JEXEC') or die('Restricted access');
?>

<div id="entry-<?php echo $row->id; ?>" class="blog-post clearfix micro-quote prel<?php echo (!empty($row->team)) ? ' teamblog-post' : '' ;?>">

	<?php echo $this->fetch( 'blog.admin.tool.php' , array( 'row' => $row ) ); ?>

		<?php if( $system->config->get( 'layout_avatar' ) && $this->getParam( 'show_avatar_frontpage' ) ){ ?>

				<?php echo $this->fetch( 'blog.avatar.php' , array( 'row' => $row ) ); ?>

		<?php } ?>

		<?php echo $this->fetch( 'blog.meta.php' , array( 'row' => $row, 'postedText' => JText::_( 'COM_EASYBLOG_QUOTE_SHARED' ) ) ); ?>

			<h2 id="title-<?php echo $row->id; ?>" class="blog-title<?php echo ($row->isFeatured) ? ' featured' : '';?> rip">
				<a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id='.$row->id); ?>"><?php echo $row->title; ?>

				<?php if( $row->isFeatured ) { ?>

					<?php echo Jtext::_('COM_EASYBLOG_FEATURED_FEATURED'); ?>
				<?php } ?>

				<?php echo $row->text; ?>

		<?php echo $row->event->afterDisplayTitle; ?>

			<?php echo $row->event->beforeDisplayContent; ?>

			<?php if( in_array( $system->config->get( 'main_socialbutton_position' ) , array( 'top' , 'left' , 'right' ) ) ){ ?>
				<?php echo EasyBlogHelper::showSocialButton( $row , true ); ?>
			<?php } ?>

			<?php if( $this->getParam( 'show_tags' ) && $this->getParam( 'show_tags_frontpage' , true ) ){ ?>
				<?php echo $this->fetch( 'tags.item.php' , array( 'tags' => $row->tags ) ); ?>
			<?php } ?>

			<?php echo $row->event->afterDisplayContent; ?>

			<?php if( $system->config->get( 'layout_copyrights' ) && !empty($row->copyrights) ) { ?>
				<?php echo $this->fetch( 'blog.copyright.php' , array( 'row' => $row ) ); ?>
			<?php } ?>

			<?php if( $system->config->get( 'main_locations_blog_frontpage' ) ){ ?>
				<?php echo EasyBlogHelper::getHelper( 'Maps' )->getHTML( true ,
																		$row->address,
																		$row->latitude ,
																		$row->longitude ,
																		$system->config->get( 'main_locations_blog_map_width') ,
																		$system->config->get( 'main_locations_blog_map_height' ),
																		JText::sprintf( 'COM_EASYBLOG_LOCATIONS_BLOG_POSTED_FROM' , $row->address ),
																		'post_map_canvas_' . $row->id );?>
			<?php } ?>

			<?php if( $system->config->get('main_facebook_like') && $system->config->get('main_facebook_like_layout') == 'standard' && $system->config->get( 'integrations_facebook_show_in_listing') ) : ?>
				<?php echo $this->fetch( 'facebook.standard.php' , array( 'facebook' => $row->facebookLike ) ); ?>
			<?php endif; ?>

			<?php if( $system->config->get( 'main_socialbutton_position' ) == 'bottom' ){ ?>
				<?php echo EasyBlogHelper::showSocialButton( $row , true ); ?>
			<?php } ?>

			<?php if( $this->getParam( 'show_last_modified' ) ){ ?>

					<?php echo JText::_( 'COM_EASYBLOG_LAST_MODIFIED' ); ?>
					<?php echo JText::_( 'COM_EASYBLOG_ON' ); ?>
					<time datetime="<?php echo $this->formatDate( '%Y-%m-%d' , $row->modified ); ?>">
						<?php echo $this->formatDate( $system->config->get('layout_dateformat') , $row->modified ); ?>
					</time>

			<?php } ?>

			<?php if( $row->readmore ) { ?>

				<?php echo $this->fetch( 'blog.readmore.php' , array( 'row' => $row ) ); ?>
			<?php } ?>

				<?php if( $this->getParam( 'show_hits' , true ) ){ ?>
					<?php echo JText::sprintf( 'COM_EASYBLOG_HITS_TOTAL' , $row->hits ); ?>
				<?php } ?>

				<?php echo $this->fetch( 'blog.item.comment.php' , array( 'row' => $row ) ); ?>

				<?php if( $system->config->get( 'main_ratings_frontpage' ) ) { ?>

					<?php echo $this->fetch( 'blog.rating.php' , array( 'row' => $row , 'locked' => $system->config->get( 'main_ratings_frontpage_locked' ) ) ); ?>
				<?php } ?>

		<?php if( $system->config->get( 'layout_showcomment' ) && EasyBlogHelper::getHelper( 'Comment')->isBuiltin() ){ ?>

			<?php echo $this->fetch( 'blog.item.comment.list.php' , array( 'row' => $row ) ); ?>
		<?php } ?>


text:
<?php

/**
 * Execute an SQL query
 *
 * @phpstub
 *
 * @param resource $link
 * @param string $query
 *
 * @return bool
 */
function maxdb_real_query($link, $query)
{
}

/**
 * Execute an SQL query
 *
 * @phpstub
 *
 * @param string $query
 *
 * @return bool
 */
function maxdb_real_query($query)
{
}


text:
class LoadBalancer(object):
    def __init__(self, name, id=None, flavor=None,
                 image=None, command=None, nw_list=None):
        self.name = name
        self.id = id  # not set
        self.out_ports = dict()
        self.in_ports = dict()


text:
package net.kemitix.ldapmanager.ldap.events;

import com.googlecode.lanterna.gui2.Label;
import lombok.val;
import net.kemitix.ldapmanager.domain.OU;
import net.kemitix.ldapmanager.domain.User;
import net.kemitix.ldapmanager.ldap.LdapNameUtil;
import net.kemitix.ldapmanager.ldap.LdapOptions;
import net.kemitix.ldapmanager.state.CurrentContainer;
import net.kemitix.ldapmanager.state.LdapEntityContainerMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import javax.naming.Name;
import java.util.Collections;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;

/**
 * Tests for the {@link CurrentContainerChangedEvent} event.
 *
 * @author Paul Campbell (pcampbell@kemitix.net)
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"test"})
public class CurrentContainerChangedEventIT {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private CurrentContainer currentContainer;

    @Autowired
    private Label currentOuLabel;

    @Autowired
    private LdapTemplate ldapTemplate;

    @Autowired
    private LdapEntityContainerMap ldapEntityContainerMap;

    @Autowired
    private LdapOptions ldapOptions;

    private Name ldapName;

    @Before
    public void setUp() {
        ldapName = LdapNameUtil.parse("ou=new");
        currentContainer.setDn(ldapName);
    }

    @After
    public void tearDown() {
        ldapEntityContainerMap.clear();
    }

    @Test
    public void shouldUpdateCurrentUiLabel() {
        //when
        eventPublisher.publishEvent(CurrentContainerChangedEvent.of(ldapName));
        //then
        assertThat(currentOuLabel.getText()).startsWith(ldapName.toString());
        assertThat(currentOuLabel.getText()).endsWith(ldapOptions.getBase());
    }

    @Test
    public void shouldLoadContainerObjects() throws InterruptedException {
        //given
        val ou = OU.builder()
                   .ou("users")
                   .build();
        val user = User.builder()
                       .cn("bob")
                       .build();
        given(ldapTemplate.find(anyObject(), eq(OU.class))).willReturn(Collections.singletonList(ou));
        given(ldapTemplate.find(anyObject(), eq(User.class))).willReturn(Collections.singletonList(user));
        //when
        eventPublisher.publishEvent(CurrentContainerChangedEvent.of(ldapName));
        //then
        val ldapEntityContainer = ldapEntityContainerMap.get(ldapName);
        assertThat(ldapEntityContainer.getContents()).containsExactlyInAnyOrder(ou, user);
    }
}


text:
module.exports = function(context, callback) {};
// valid


text:
Given an Instagram username, return the recognized objects from the user's latest image posts.

* microservice architecture based on DCOS/Marathon
* TensorFlow + ImageNet model as deep learning backend

## Architecture

#### Front api service

* Provide Web UI to accept an Instagram username as input. It then send requests to the backend recognition service.
* Routed with marathon-lb

#### Backend recognition service
* Uses TensorFlow to classify the input image with pre-trained ImageNet model.
* Routed using DCOS VIP

## Deployment

### setup

#### Clone the repo
```
git clone https://github.com/xiaoganghan/mesos-instagram-image-recognition.git
```

#### Install and boot dcos-vagrant

Follow the instructions [DC/OS-vagrant](https://dcos.io/docs/1.7/administration/installing/local/) to install DC/OS with Vagrant.

suppose your DC/OS-vagrant directory is dcos-vagrant
```
cp mesos-instagram-image-recognition/ops/VagrantConfig.yaml dcos-vagrant/VagrantConfig.yaml
cd dcos-vagrant
vagrant up m1 a1 p1 boot
```
#### Install DC/OS Command Line Interface (CLI)
Follow the instruction [DC/OS CLI](https://dcos.io/docs/1.7/usage/cli/install/) to install DC/OS CLI

#### Install marathon-lb

```
cd mesos-instagram-image-recognition/ops
dcos package install --options=marathon-lb.json marathon-lb --yes
```

### Deploy Backend recognition services (3 instances)

#### Install Docker
Install the Docker software by following the [Docker Installation](https://docs.docker.com/engine/installation/)

#### Creat a Docker Hub account

Create a [Docker Hub account](https://hub.docker.com/) to store the docker images created in the following step,
assume your docker account name is 'DockerAccount'

#### build docker image, test locally, and push it to dockerhub
```
cd mesos-instagram-image-recognition/backend
```
build a docker image called 'mesos-instagram-detect-backend'
use sudo under ubuntu if 'Cannot connect to the Docker daemon, Is the docker daemon running on this host?' error shown
```
docker build -t mesos-instagram-detect-backend .
```
find out the id of image 'mesos-instagram-detect-backend'
```
docker images
```
tag the image
```
docker tag [image_id] DockerAccount/mesos-instagram-detect-backend:latest
```
run locally to test
```
docker run -it -p 5000:5000 --rm  DockerAccount/mesos-instagram-detect-backend
```
open [url](http://localhost:5000/?image_url=https://igcdn-photos-b-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/e35/1209679_1683062908612265_1359743351_n.jpg?ig_cache_key=MTIwODEwNzI1NDU2NjQzODE4NA%3D%3D.2) in browser to test

If correct, the following results should be shown in the browser

{
objects: [
"stage (score = 0.02232)",
"wool, woolen, woollen (score = 0.01913)",
"mitten (score = 0.01680)",
"balloon (score = 0.01405)",
"cloak (score = 0.01377)"
]
}

push to Docker Hub
```
docker push DockerAccount/mesos-instagram-detect-backend:latest
```

#### deploy backend to DCOS
```
cd mesos-instagram-image-recognition/ops
```
Using [Web UI](http://m1.dcos): create application using ops/launch_backend.json
or,

Using DC/OS CLI:
```
dcos marathon app add launch_backend.json
```

### deploy front server (2 instances)

#### build docker image, test locally, and push it to dockerhub
```
cd mesos-instagram-image-recognition/front
docker build -t DockerAccount/mesos-instagram-detect-frontend:latest .
```
run locally to test
```
docker run -it -p 5001:5001 --rm  DockerAccount/mesos-instagram-detect-frontend
```
find out the id of image 'mesos-instagram-detect-frontend'
```
docker images
```
tag the image
```
docker tag [image_id] DockerAccount/mesos-instagram-detect-frontend:latest
```
push to Docker Hub
```
docker push DockerAccount/mesos-instagram-detect-frontend:latest
```

#### deploy frontend to DCOS

```
cd mesos-instagram-image-recognition/ops
```
Using [Web UI](http://m1.dcos): create application using ops/launch_front.json
or,
Using DC/OS CLI:
```
dcos marathon app add launch_front.json
```
# verify it works
open http://instagramdemo.com in your browser

## references

* marathon-lb settings
    * https://github.com/dcos/dcos-vagrant/blob/e9c0d6ade775debf0889b69b67f87cfdbf1aec9b/examples/oinker/README.md
* VIP settings
    * https://github.com/dcos/dcos-vagrant/tree/master/examples/minuteman
    * https://github.com/dcos/dcos-docs/pull/199/files


text:
/* $Id$ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.authorities;

import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.authorities.interfaces.*;
import org.apache.manifoldcf.authorities.system.*;

public class RegisterMapper extends BaseMappersInitializationCommand
{
  public static final String _rcsid = "@(#)$Id$";

  private final String className;
  private final String description;

  public RegisterMapper(String className, String description)
  {
    this.className = className;
    this.description = description;
  }

  protected void doExecute(IMappingConnectorManager mgr) throws ManifoldCFException
  {
    mgr.registerConnector(description,className);
    Logging.root.info("Successfully registered connector '"+className+"'");
  }

  public static void main(String[] args)
  {
    if (args.length != 2)
    {
      System.err.println("Usage: RegisterMapper <classname> <description>");
      System.exit(1);
    }

    String className = args[0];
    String description = args[1];

    try
    {
      RegisterMapper registerMapper = new RegisterMapper(className,description);
      registerMapper.execute();
      System.err.println("Successfully registered connector '"+className+"'");
    }
    catch (ManifoldCFException e)
    {
      e.printStackTrace();
      System.exit(1);
    }
  }
}


text:
package org.opensaml.xml.signature.impl;

import org.opensaml.xml.XMLObjectProviderBaseTestCase;
import org.opensaml.xml.mock.SimpleXMLObject;
import org.opensaml.xml.signature.X509CRL;
import org.opensaml.xml.signature.X509Certificate;
import org.opensaml.xml.signature.X509Data;
import org.opensaml.xml.signature.X509IssuerSerial;
import org.opensaml.xml.signature.X509SKI;
import org.opensaml.xml.signature.X509SubjectName;

/**
 *
 */
public class X509DataTest extends XMLObjectProviderBaseTestCase {

    /**
     * Constructor
     *
     */
    public X509DataTest() {
        singleElementFile = "/data/org/opensaml/xml/signature/impl/X509Data.xml";
        childElementsFile = "/data/org/opensaml/xml/signature/impl/X509DataChildElements.xml";
    }

    /** {@inheritDoc} */
    protected void setUp() throws Exception {
        super.setUp();
    }

    /** {@inheritDoc} */
    public void testSingleElementUnmarshall() {
        X509Data x509Data = (X509Data) unmarshallElement(singleElementFile);

        assertNotNull("X509Data", x509Data);
        assertEquals("Total # of XMLObject child elements", 0, x509Data.getXMLObjects().size());
    }

    /** {@inheritDoc} */
    public void testChildElementsUnmarshall() {
        X509Data x509Data = (X509Data) unmarshallElement(childElementsFile);

        assertNotNull("X509Data", x509Data);
        assertEquals("Total # of XMLObject child elements", 11, x509Data.getXMLObjects().size());
        assertEquals("# of X509IssuerSerial child elements", 1, x509Data.getX509IssuerSerials().size());
        assertEquals("# of X509SKI child elements", 1, x509Data.getX509SKIs().size());
        assertEquals("# of X509SubjectName child elements", 2, x509Data.getX509SubjectNames().size());
        assertEquals("# of X509Certificate child elements", 3, x509Data.getX509Certificates().size());
        assertEquals("# of X509CRL child elements", 2, x509Data.getX509CRLs().size());
        assertEquals("# of SimpleElement child elements", 2, x509Data.getXMLObjects(SimpleXMLObject.ELEMENT_NAME).size());
    }

    /** {@inheritDoc} */
    public void testSingleElementMarshall() {
        X509Data x509Data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);

        assertEquals(expectedDOM, x509Data);
    }

    /** {@inheritDoc} */
    public void testChildElementsMarshall() {
        X509Data x509Data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);

        x509Data.getXMLObjects().add(buildXMLObject(X509IssuerSerial.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509SKI.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509SubjectName.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(SimpleXMLObject.ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509CRL.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(SimpleXMLObject.ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509SubjectName.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509CRL.DEFAULT_ELEMENT_NAME));
        x509Data.getXMLObjects().add(buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME));

        assertEquals(expectedChildElementsDOM, x509Data);
    }

}


text:
package contrail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;

public class RemoveTips extends Configured implements Tool
{
	private static final Logger sLogger = Logger.getLogger(RemoveTips.class);

	// RemoveTipsMapper
	///////////////////////////////////////////////////////////////////////////

	private static class RemoveTipsMapper extends MapReduceBase
    implements Mapper<LongWritable, Text, Text, Text>
	{
		private static int K = 0;
		public static int TIPLENGTH = 0;
		public static boolean VERBOSE = false;

		public void configure(JobConf job)
		{
			K = Integer.parseInt(job.get("K"));
			TIPLENGTH = Integer.parseInt(job.get("TIPLENGTH"));
		}

		public void map(LongWritable lineid, Text nodetxt,
                OutputCollector<Text, Text> output, Reporter reporter)
		throws IOException
		{
			Node node = new Node();
			node.fromNodeMsg(nodetxt.toString());

			int fdegree = node.degree("f");
			int rdegree = node.degree("r");
			int len     = node.len();

			if ((len <= TIPLENGTH) && (fdegree + rdegree <= 1))
			{
				reporter.incrCounter("Contrail", "tips_found", 1);

				if (VERBOSE)
				{
					System.err.println("Removing tip " + node.getNodeId() + " len=" + len);
				}

				if ((fdegree == 0) && (rdegree == 0))
				{
					//this node is not connected to the rest of the graph
					//nothing to do
					reporter.incrCounter("Contrail", "tips_island", 1);
				}
				else
				{
					// Tell the one neighbor that I'm a tip
					String linkdir = (fdegree == 0) ? "r" : "f";

					for(String adj : Node.dirs)
					{
						String key = linkdir + adj;

						List<String> edges = node.getEdges(key);

						if (edges != null)
						{
							if (edges.size() != 1)
							{
								throw new IOException("Expected a single edge from " + node.getNodeId());
							}

							String p = edges.get(0);

							if (p.equals(node.getNodeId()))
							{
								// short tandem repeat, trim away
								reporter.incrCounter("Contrail", "tips_shorttandem", 1);
							}
							else
							{
								String con = Node.flip_dir(adj) + Node.flip_dir(linkdir);
								output.collect(new Text(p), new Text(Node.TRIMMSG + "\t" + con + "\t" + nodetxt));
							}
						}
					}
				}
			}
			else
			{
				output.collect(new Text(node.getNodeId()), new Text(node.toNodeMsg()));
			}

			reporter.incrCounter("Contrail", "nodes", 1);
		}
	}

	// RemoveTipsReducer
	///////////////////////////////////////////////////////////////////////////

	private static class RemoveTipsReducer extends MapReduceBase
	implements Reducer<Text, Text, Text, Text>
	{
		private static int K = 0;

		public void configure(JobConf job) {
			K = Integer.parseInt(job.get("K"));
		}

		public void reduce(Text nodeid, Iterator<Text> iter,
				OutputCollector<Text, Text> output, Reporter reporter)
				throws IOException
		{
			Node node = new Node(nodeid.toString());
			Map<String, List<Node>> tips = new HashMap<String, List<Node>>();

			int sawnode = 0;

			while(iter.hasNext())
			{
				String msg = iter.next().toString();

				//System.err.println(key.toString() + "\t" + msg);

				String [] vals = msg.split("\t");

				if (vals[0].equals(Node.NODEMSG))
				{
					node.parseNodeMsg(vals, 0);
					sawnode++;
				}
				else if (vals[0].equals(Node.TRIMMSG))
				{
					String adj = vals[1];

					Node tip = new Node(vals[2]);
					tip.parseNodeMsg(vals, 3);

					if (tips.containsKey(adj))
					{
						tips.get(adj).add(tip);
					}
					else
					{
						List<Node> tiplist = new ArrayList<Node>();
						tiplist.add(tip);
						tips.put(adj, tiplist);
					}
				}
				else
				{
					throw new IOException("Unknown msgtype: " + msg);
				}
			}

			if (sawnode != 1)
			{
				throw new IOException("ERROR: Didn't see exactly 1 nodemsg (" + sawnode + ") for " + nodeid.toString());
			}

			if (tips.size() != 0)
			{
				for(String d : Node.dirs)
				{
					int deg = node.degree(d);

					int numtrim = 0;

					List<Node> ftips = tips.get(d+"f");
					List<Node> rtips = tips.get(d+"r");

					if (ftips != null) { numtrim += ftips.size(); }
					if (rtips != null) { numtrim += rtips.size(); }

					if (numtrim == 0) { continue; }

					Node besttip = null;
					int bestlen = 0;

					if (numtrim == deg)
					{
						// All edges in this direction are tips, only keep the longest one

						if (ftips != null)
						{
							for (Node t : ftips)
							{
								if (t.len() > bestlen)
								{
									bestlen = t.len();
									besttip = t;
								}
							}
						}

						if (rtips != null)
						{
							for (Node t : rtips)
							{
								if (t.len() > bestlen)
								{
									bestlen = t.len();
									besttip = t;
								}
							}
						}

						output.collect(new Text(besttip.getNodeId()), new Text(besttip.toNodeMsg()));
						reporter.incrCounter("Contrail", "tips_kept", 1);
					}

					if (ftips != null)
					{
						String adj = d+"f";

						for (Node t : ftips)
						{
							if (t != besttip)
							{
								node.removelink(t.getNodeId(), adj);
								reporter.incrCounter("Contrail", "tips_clipped", 1);
							}
						}
					}

					if (rtips != null)
					{
						String adj = d+"r";

						for (Node t : rtips)
						{
							if (t != besttip)
							{
								node.removelink(t.getNodeId(), adj);
								reporter.incrCounter("Contrail", "tips_clipped", 1);
							}
						}
					}
				}
			}

			output.collect(nodeid, new Text(node.toNodeMsg()));
		}
	}

	// Run
	///////////////////////////////////////////////////////////////////////////

	public RunningJob run(String inputPath, String outputPath) throws Exception
	{
		sLogger.info("Tool name: RemoveTips");
		sLogger.info(" - input: "  + inputPath);
		sLogger.info(" - output: " + outputPath);

		JobConf conf = new JobConf(Stats.class);
		conf.setJobName("RemoveTips " + inputPath + " " + ContrailConfig.K);
		ContrailConfig.initializeConfiguration(conf);

		FileInputFormat.addInputPath(conf, new Path(inputPath));
		FileOutputFormat.setOutputPath(conf, new Path(outputPath));

		conf.setInputFormat(TextInputFormat.class);
		conf.setOutputFormat(TextOutputFormat.class);

		conf.setMapOutputKeyClass(Text.class);
		conf.setMapOutputValueClass(Text.class);

		conf.setOutputKeyClass(Text.class);
		conf.setOutputValueClass(Text.class);

		conf.setMapperClass(RemoveTipsMapper.class);
		conf.setReducerClass(RemoveTipsReducer.class);

		//delete the output directory if it exists already
		FileSystem.get(conf).delete(new Path(outputPath), true);

		return JobClient.runJob(conf);
	}

	// Parse Arguments and Run
	///////////////////////////////////////////////////////////////////////////

	public int run(String[] args) throws Exception
	{
		String inputPath  = "/Users/mschatz/try/02-initialcmp";
		String outputPath = "/users/mschatz/try/03-removetips.1";
		ContrailConfig.K = 21;
		run(inputPath, outputPath);
		return 0;
	}

	// Main
	///////////////////////////////////////////////////////////////////////////

	public static void main(String[] args) throws Exception
	{
		int res = ToolRunner.run(new Configuration(), new RemoveTips(), args);
		System.exit(res);
	}
}


text:
package org.drools.traits.compiler.integrationtests;

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

import org.drools.core.beliefsystem.abductive.Abducible;
import org.drools.core.factmodel.traits.Thing;
import org.drools.core.factmodel.traits.Traitable;
import org.drools.kiesession.rulebase.InternalKnowledgeBase;
import org.drools.core.io.impl.ByteArrayResource;
import org.drools.kiesession.rulebase.KnowledgeBaseFactory;
import org.drools.traits.compiler.CommonTraitTest;
import org.drools.traits.compiler.Person;
import org.drools.traits.core.factmodel.Entity;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.definition.type.FactType;
import org.kie.api.definition.type.PropertyReactive;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.utils.KieHelper;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

public class TraitTypeGenerationTest extends CommonTraitTest {

    @PropertyReactive
    @Traitable
    public static class Bean {
        private int a;
        private int b;

        public Bean() { }

        public Bean(final int a, final int b) {
            this.a = a;
            this.b = b;
        }

        public int getA() {
            return a;
        }

        public void setA(final int a) {
            this.a = a;
        }

        public int getB() {
            return b;
        }

        public void setB(final int b) {
            this.b = b;
        }
    }

    @Test(timeout=10000)
    public void testWithDeclaredTypeAndTraitInDifferentPackages() {
        // DROOLS-91
        final String str1 =
                "package org.pkg1;\n" +
                        "declare trait Trait " +
                        "    @propertyReactive\n" +
                        "    a : int\n" +
                        "end";

        final String str2 =
                "package org.pkg2;\n" +
                        "declare Bean " +
                        "    @propertyReactive\n" +
                        "    @Traitable\n" +
                        "    a : int\n" +
                        "    b : int\n" +
                        "end";

        final String str3 =
                "package org.pkg3;\n" +
                        "import org.pkg1.Trait;\n" +
                        "import org.pkg2.Bean;\n" +
                        "rule Init\n" +
                        "when\n" +
                        "then\n" +
                        "    insert(new Bean(1, 2));\n" +
                        "end\n" +
                        "rule R\n" +
                        "when\n" +
                        "   $b : Bean( b == 2)" +
                        "then\n" +
                        "   Trait t = don( $b, Trait.class, true );\n" +
                        "   modify(t) { setA(2) };\n" +
                        "end";

        final KieBase kbase = loadKnowledgeBaseFromString(str1, str2, str3);
        final KieSession ksession = kbase.newKieSession();

        ksession.fireAllRules();
    }

    @Test
    public void testWithBeanAndTraitInDifferentPackages() {
        // DROOLS-91
        final String str1 =
                "package org.drools.compiler.integrationtests;\n" +
                        "declare trait Trait " +
                        "    @propertyReactive\n" +
                        "    a : int\n" +
                        "end";

        final String str2 =
                "package org.drools.test;\n" +
                        "import org.drools.compiler.integrationtests.Trait;\n" +
                        "import " + Bean.class.getCanonicalName() + ";\n" +
                        "rule Init\n" +
                        "when\n" +
                        "then\n" +
                        "    insert(new Bean(1, 2));\n" +
                        "end\n" +
                        "rule R\n" +
                        "when\n" +
                        "   $b : Bean( b == 2)" +
                        "then\n" +
                        "   Trait t = don( $b, Trait.class, true );\n" +
                        "   modify(t) { setA(2) };\n" +
                        "end";

        final KieBase kbase = loadKnowledgeBaseFromString(str1, str2);
        final KieSession ksession = kbase.newKieSession();

        ksession.fireAllRules();
    }

    @Test
    public void testIsAWith2KContainers() {
        // BZ-996056
        String str =
                "import org.drools.traits.compiler.Person\n" +
                        "\n" +
                        "global java.util.List students\n" +
                        "\n" +
                        "declare trait Student\n" +
                        "    school : String\n" +
                        "end\n" +
                        "\n" +
                        "rule \"create student\" \n" +
                        "    when\n" +
                        "        $student : Person( age < 26, this not isA Student )\n" +
                        "    then\n" +
                        "        Student s = don( $student, Student.class );\n" +
                        "        s.setSchool(\"Masaryk University\");\n" +
                        "        update( $student );\n" +
                        "end\n" +
                        "\n" +
                        "rule \"found student\"\n" +
                        "    salience 10\n" +
                        "    when\n" +
                        "        student : Person( this isA Student )\n" +
                        "    then\n" +
                        "        students.add(student);\n" +
                        "end";

        KieServices ks = KieServices.Factory.get();
        KieFileSystem kfs = ks.newKieFileSystem();

        kfs.write( "src/main/resources/isA.drl", str );

        KieBuilder kbuilder = ks.newKieBuilder(kfs );

        kbuilder.buildAll();
        assertEquals( 0, kbuilder.getResults().getMessages().size() );

        ks.newKieContainer( kbuilder.getKieModule().getReleaseId() ).getKieBase();

        KieSession ksession = ks.newKieContainer( kbuilder.getKieModule().getReleaseId() ).newKieSession();
        assertNotNull( ksession );

        List students = new ArrayList();
        ksession.setGlobal( "students", students );
        ksession.insert( new Person("tom", 20 ) );
        ksession.fireAllRules();
        assertEquals( 1, students.size() );
    }

    public static interface FooIntf {
        public boolean isSafe();

        public void setSafe( boolean safe );
    }

    public static class BarKlass implements FooIntf {
        public boolean isSafe() {
            return true;
        }

        public void setSafe( boolean safe ) {
        }
    }

    @Test
    public void testMvelJittingWithTraitProxies() throws Exception {
        // DROOLS-291
        String drl = "package org.drools.test; \n" +
                "" +
                "import " + FooIntf.class.getCanonicalName() + ";\n" +
                "import "+ BarKlass.class.getCanonicalName() + ";\n" +
                "" +
                "declare BarKlass end \n" +
                "declare FooIntf end \n" +
                "" +
                "declare trait ExtFoo extends FooIntf end \n" +
                "" +
                "declare Kore @Traitable safe : boolean end \n" +
                "" +
                "rule \"Test2\" when FooIntf( safe == true ) then end \n" +
                "" +
                "rule \"In1\" when $s : String() then don( new Kore( true ), ExtFoo.class ); end \n" +
                "rule \"In2\" when $s : Integer() then insert( new BarKlass() ); end \n" +
                "" +
                "";
        KieBase kb = loadKnowledgeBaseFromString(drl );
        KieSession ks = kb.newKieSession();

        for ( int j = 0; j < 21; j++ ) {
            ks.insert( "x" + j );
            ks.fireAllRules();
        }

        // wait for jitting
        Thread.sleep( 100 );

        ks.insert( 0 );
        ks.fireAllRules();
    }

    @Test
    public void testNeeds() {
        // revisiting OPSJ's version of a fragment of the famous monkey&bananas AI problem
        String droolsSource =
                "package org.drools.abductive.test; \n" +
                        "" +
                        "import " + Entity.class.getPackage().getName() + ".*;" +
                        "import " + Thing.class.getPackage().getName() + ".*;" +
                        "import " + Abducible.class.getName() + "; \n" +
                        "global java.util.List list; \n" +

                        "declare Goal \n" +
                        "   entity : Thing \n" +
                        "   property : String \n" +
                        "   value : Object \n" +
                        "end \n" +

                        "query check( Thing $thing, String $prop, Object $val ) " +
                        "   Thing( this == $thing, fields[ $prop ] == $val ) " +
                        "   or" +
                        "   ( " +
                        "     need( $thing, $prop, $val ; ) " +
                        "     and" +
                        "     Thing( this == $thing, fields[ $prop ] == $val ) " +
                        "   ) " +
                        "end \n " +

                        "query need( Thing $thing, String $prop, Object $val ) " +
                        "   @Abductive( target=Goal.class ) \n" +
                        "   Thing( this == $thing, fields[ $prop ] != $val ) " +
                        "end \n "+

                        "rule HandleGoal " +
                        "when " +
                        "   $g : Goal( $m : entity, $prop : property, $val : value ) " +
                        "then " +
                        "   System.out.println( 'Satisfy ' + $g ); \n" +
                        "   modify ( $m ) { getFields().put( $prop, $val ); } \n" +
                        "end " +

                        "declare trait Monkey\n" +
                        "   position : Integer = 1 \n " +
                        "end \n" +

                        "rule Main\n" +
                        "when \n" +
                        "then \n" +
                        "   System.out.println( 'Don MONKEY ' ); " +
                        "   Entity e = new Entity(); \n" +
                        "   Monkey monkey = don( e, Monkey.class );" +
                        "end \n" +

                        "rule MoveAround " +
                        "when " +
                        "   $m : Monkey( $pos : position ) " +
                        "   ?check( $m, \"position\", 4 ; ) " +
                        "then " +
                        "   System.out.println( 'Monkey madness' + $m ); " +
                        "   list.add( $m.getPosition() ); " +
                        "end " +

                        "";

        /////////////////////////////////////

        KieSession session = loadKnowledgeBaseFromString(droolsSource ).newKieSession();
        List list = new ArrayList();
        session.setGlobal( "list", list );

        session.fireAllRules();

        for ( Object o : session.getObjects() ) {
            System.out.println( ">>> " + o );
        }

        assertEquals(Arrays.asList(4 ), list );
    }

    @Test
    public void testRedeclareClassAsTrait() {
        final String s1 = "package test; " +
                "global java.util.List list; " +

                "declare trait " + SomeClass.class.getCanonicalName() + " end ";

        KieHelper kh = new KieHelper();
        kh.addContent( s1, ResourceType.DRL );

        assertEquals( 1, kh.verify().getMessages(Message.Level.ERROR ).size() );
    }

    public static class SomeClass {}

    @Test
    public void testMultipleInheritanceWithPosition1() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 //@position(0)\n" +
                        " field1 : int = 101 //@position(1)\n" +
                        " field2 : int = 102 //@position(0)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 //@position(0)\n" +
                        " mfield1 : int = 201 @position(2)\n" +
                        "end";

        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(5, sw.getFields().size());
        assertEquals("field0", sw.getFields().get(0).getName());
        assertEquals("field1", sw.getFields().get(1).getName());
        assertEquals("mfield1", sw.getFields().get(2).getName());
        assertEquals("field2", sw.getFields().get(3).getName());
        assertEquals("mfield0", sw.getFields().get(4).getName());
    }

    @Test
    public void testMultipleInheritanceWithPosition2() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 //@position(0)\n" +
                        " field1 : int = 101 //@position(1)\n" +
                        " field2 : int = 102 //@position(0)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 @position(0)\n" +
                        " mfield1 : int = 201 @position(2)\n" +
                        "end";
        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(5, sw.getFields().size());
        assertEquals("mfield0", sw.getFields().get(0).getName());
        assertEquals("field0", sw.getFields().get(1).getName());
        assertEquals("mfield1", sw.getFields().get(2).getName());
        assertEquals("field1", sw.getFields().get(3).getName());
        assertEquals("field2", sw.getFields().get(4).getName());
    }

    @Test
    public void testMultipleInheritanceWithPosition3() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 @position(0)\n" +
                        " field1 : int = 101 @position(1)\n" +
                        " field2 : int = 102 @position(0)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 //@position(0)\n" +
                        " mfield1 : int = 201 @position(2)\n" +
                        "end";
        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(5, sw.getFields().size());
        assertEquals("field0", sw.getFields().get(0).getName());
        assertEquals("field2", sw.getFields().get(1).getName());
        assertEquals("field1", sw.getFields().get(2).getName());
        assertEquals("mfield1", sw.getFields().get(3).getName());
        assertEquals("mfield0", sw.getFields().get(4).getName());
    }

    @Test
    public void testMultipleInheritanceWithPosition4() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 @position(1)\n" +
                        " field1 : int = 101 @position(0)\n" +
                        " field2 : int = 102 @position(0)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 @position(0)\n" +
                        " mfield1 : int = 201 @position(2)\n" +
                        "end";
        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(5, sw.getFields().size());
        assertEquals("field1", sw.getFields().get(0).getName());
        assertEquals("field2", sw.getFields().get(1).getName());
        assertEquals("mfield0", sw.getFields().get(2).getName());
        assertEquals("field0", sw.getFields().get(3).getName());
        assertEquals("mfield1", sw.getFields().get(4).getName());
    }

    @Test
    public void testMultipleInheritanceWithPosition5() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 @position(2)\n" +
                        " field1 : int = 101 @position(1)\n" +
                        " field2 : int = 102 @position(8)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 @position(7)\n" +
                        " mfield1 : int = 201 @position(2)\n" +
                        "end";
        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(5, sw.getFields().size());
        assertEquals("field1", sw.getFields().get(0).getName());
        assertEquals("field0", sw.getFields().get(1).getName());
        assertEquals("mfield1", sw.getFields().get(2).getName());
        assertEquals("mfield0", sw.getFields().get(3).getName());
        assertEquals("field2", sw.getFields().get(4).getName());
    }

    @Test
    public void testMultipleInheritanceWithPosition6() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 //@position(0)\n" +
                        " field1 : int = 101 //@position(1)\n" +
                        " field2 : int = 102 //@position(0)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait SecPosTrait\n" +
                        "@propertyReactive\n" +
                        " field3 : int = 100 //@position(0)\n" +
                        " field1 : int = 101 //@position(1)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait, SecPosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 //@position(0)\n" +
                        " mfield1 : int = 201 //@position(2)\n" +
                        "end";
        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(6, sw.getFields().size());
        assertEquals("field0", sw.getFields().get(0).getName());
        assertEquals("field1", sw.getFields().get(1).getName());
        assertEquals("field2", sw.getFields().get(2).getName());
        assertEquals("field3", sw.getFields().get(3).getName());
        assertEquals("mfield0", sw.getFields().get(4).getName());
        assertEquals("mfield1", sw.getFields().get(5).getName());
    }

    @Test
    public void testMultipleInheritanceWithPosition7() throws Exception {
        // DROOLS-249
        String drl =
                "package org.drools.test\n" +
                        "declare trait PosTrait\n" +
                        "@propertyReactive\n" +
                        " field0 : int = 100 @position(0)\n" +
                        " field1 : int = 101 @position(1)\n" +
                        " field2 : int = 102 @position(0)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait SecPosTrait\n" +
                        "@propertyReactive\n" +
                        " field3 : int = 100 @position(2)\n" +
                        " field1 : int = 101 //@position(1)\n" +
                        "end\n" +
                        "\n" +
                        "declare trait MultiInhPosTrait extends PosTrait, SecPosTrait\n" +
                        "@propertyReactive\n" +
                        " mfield0 : int = 200 @position(0)\n" +
                        " mfield1 : int = 201 @position(2)\n" +
                        "end";
        KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kBuilder.add(new ByteArrayResource(drl.getBytes()), ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
        }
        assertFalse(kBuilder.hasErrors());

        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(kBuilder.getKnowledgePackages());

        FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait");
        assertEquals(6, sw.getFields().size());
        assertEquals("field0", sw.getFields().get(0).getName());
        assertEquals("field2", sw.getFields().get(1).getName());
        assertEquals("mfield0", sw.getFields().get(2).getName());
        assertEquals("field1", sw.getFields().get(3).getName());
        assertEquals("field3", sw.getFields().get(4).getName());
        assertEquals("mfield1", sw.getFields().get(5).getName());
    }
}


text:
package javasmmr.zoosome.models.animals;

import static javasmmr.zoosome.repositories.EntityRepository.createNode;

import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;

import javasmmr.zoosome.services.factories.Constants;

public class Kangaroo extends Mammal {
	private static final String DEFAULT_NAME = "Red kangaroo";
	private static final int DEFAULT_NUMBER_OF_LEGS = 4;
	private static final double DEFAULT_MAINTENANCE_COST = 1.2D;
	private static final double DEFAULT_DANGER_PERCENTAGE = 0.02D;
	private static final double DEFAULT_BODY_TEMPERATURE = 37.0D;
	private static final double DEFAULT_PERCENTAGE_BODY_HAIR = 80.2D;

	public Kangaroo() {
		super(DEFAULT_NAME, DEFAULT_NUMBER_OF_LEGS, DEFAULT_MAINTENANCE_COST, DEFAULT_DANGER_PERCENTAGE,
				DEFAULT_BODY_TEMPERATURE, DEFAULT_PERCENTAGE_BODY_HAIR);
	}

	public Kangaroo(final String animalName, final int numberOfLegs, final double maintenanceCost,
			final double dangerPerc, final double normalTemp, final double muchHair) {
		super(animalName, numberOfLegs, maintenanceCost, dangerPerc, normalTemp, muchHair);
	}

	public Kangaroo(String v1, String v2, String v3, String v4, String v5, String v6) {
		super(new String[] { v1, v2, v3, v4, v5, v6 });
	}

	public void encodeToXML(XMLEventWriter eventWriter) throws XMLStreamException {
		super.encodeToXML(eventWriter);
		createNode(eventWriter, Constants.XML_TAGS.DISCRIMINANT, String.valueOf(Constants.Animals.Mammal.KANGAROO));
	}
}


text:
<?php

namespace Frontend\Controllers;

class IndexController extends \ControllerBase
{
    public function indexAction()
    {
        die('indexAction');
    }

    public function testAction()
    {
        die('testAction');
    }

}


text:
package org.apache.sling.api.resource;

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

import org.junit.Test;

public class PathTest {

    @Test public void testRootMatching() {
        final Path path = new Path("/");

        assertTrue(path.matches("/"));
        assertTrue(path.matches("/foo"));
        assertTrue(path.matches("/foo/bar"));
    }

    @Test public void testPathMatching() {
        final Path path = new Path("/content");

        assertFalse(path.matches("/"));
        assertFalse(path.matches("/foo"));
        assertFalse(path.matches("/foo/bar"));

        assertTrue(path.matches("/content"));
        assertTrue(path.matches("/content/a"));
        assertTrue(path.matches("/content/a/b"));

        assertFalse(path.matches("/content1"));
    }
}


text:
import uuid
import json
import time
import hmac
import base64
import urllib
import logging
import requests
from hashlib import sha256

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import ugettext as _

from seahub.api2.utils import get_api_token
from seahub import auth
from seahub.profile.models import Profile
from seahub.utils import render_error, get_site_scheme_and_netloc
from seahub.utils.auth import gen_user_virtual_id
from seahub.base.accounts import User
from seahub.auth.models import SocialAuthUser
from seahub.auth.decorators import login_required
from seahub.dingtalk.utils import dingtalk_get_detailed_user_info

from seahub.dingtalk.settings import ENABLE_DINGTALK, \
        DINGTALK_QR_CONNECT_APP_ID, DINGTALK_QR_CONNECT_APP_SECRET, \
        DINGTALK_QR_CONNECT_AUTHORIZATION_URL, \
        DINGTALK_QR_CONNECT_USER_INFO_URL, DINGTALK_QR_CONNECT_RESPONSE_TYPE, \
        DINGTALK_QR_CONNECT_SCOPE, DINGTALK_QR_CONNECT_LOGIN_REMEMBER_ME

logger = logging.getLogger(__name__)

def dingtalk_login(request):

    if not ENABLE_DINGTALK:
        return render_error(request, _('Error, please contact administrator.'))

    state = str(uuid.uuid4())
    request.session['dingtalk_login_state'] = state
    request.session['dingtalk_login_redirect'] = request.GET.get(auth.REDIRECT_FIELD_NAME, '/')

    data = {
        'appid': DINGTALK_QR_CONNECT_APP_ID,
        'response_type': DINGTALK_QR_CONNECT_RESPONSE_TYPE,
        'scope': DINGTALK_QR_CONNECT_SCOPE,
        'redirect_uri': get_site_scheme_and_netloc() + reverse('dingtalk_callback'),
        'state': state,
    }
    url = DINGTALK_QR_CONNECT_AUTHORIZATION_URL + '?' + urllib.parse.urlencode(data)
    return HttpResponseRedirect(url)

def dingtalk_callback(request):

    if not ENABLE_DINGTALK:
        return render_error(request, _('Error, please contact administrator.'))

    state = request.GET.get('state', '')
    if not state or state != request.session.get('dingtalk_login_state', ''):
        logger.error('invalid state')
        return render_error(request, _('Error, please contact administrator.'))

    timestamp = str(int(time.time()*1000)).encode('utf-8')
    appsecret = DINGTALK_QR_CONNECT_APP_SECRET.encode('utf-8')
    signature = base64.b64encode(hmac.new(appsecret, timestamp, digestmod=sha256).digest())
    parameters = {
        'accessKey': DINGTALK_QR_CONNECT_APP_ID,
        'timestamp': timestamp,
        'signature': signature,
    }

    code = request.GET.get('code')
    data = {"tmp_auth_code": code}

    full_user_info_url = DINGTALK_QR_CONNECT_USER_INFO_URL + '?' + urllib.parse.urlencode(parameters)
    user_info_resp = requests.post(full_user_info_url, data=json.dumps(data))
    user_info = user_info_resp.json()['user_info']

    # seahub authenticate user
    if 'unionid' not in user_info:
        logger.error('Required user info not found.')
        logger.error(user_info)
        return render_error(request, _('Error, please contact administrator.'))

    auth_user = SocialAuthUser.objects.get_by_provider_and_uid('dingtalk', user_info['unionid'])
    if auth_user:
        email = auth_user.username
    else:
        email = gen_user_virtual_id()
        SocialAuthUser.objects.add(email, 'dingtalk', user_info['unionid'])

    try:
        user = auth.authenticate(remote_user=email)
    except User.DoesNotExist:
        user = None
    except Exception as e:
        logger.error(e)
        return render_error(request, _('Error, please contact administrator.'))

    if not user or not user.is_active:
        return render_error(request, _('User %s not found or inactive.') % email)

    # User is valid.  Set request.user and persist user in the session
    # by logging the user in.
    request.user = user
    request.session['remember_me'] = DINGTALK_QR_CONNECT_LOGIN_REMEMBER_ME
    auth.login(request, user)

    # update user's profile
    name = user_info['nick'] if 'nick' in user_info else ''
    if name:

        profile = Profile.objects.get_profile_by_user(email)
        if not profile:
            profile = Profile(user=email)

        profile.nickname = name.strip()
        profile.save()

    user_detail_info = dingtalk_get_detailed_user_info(user_info['unionid'])
    contact_email = user_detail_info.get('email', '')
    if contact_email:
        profile.contact_email = contact_email
        profile.save()

    # generate auth token for Seafile client
    api_token = get_api_token(request)

    # redirect user to home page
    response = HttpResponseRedirect(request.session.get('dingtalk_login_redirect', '/'))
    response.set_cookie('seahub_auth', email + '@' + api_token.key)
    return response

@login_required
def dingtalk_connect(request):

    if not ENABLE_DINGTALK:
        return render_error(request, _('Error, please contact administrator.'))

    state = str(uuid.uuid4())
    request.session['dingtalk_connect_state'] = state
    request.session['dingtalk_connect_redirect'] = request.GET.get(auth.REDIRECT_FIELD_NAME, '/')

    data = {
        'appid': DINGTALK_QR_CONNECT_APP_ID,
        'response_type': DINGTALK_QR_CONNECT_RESPONSE_TYPE,
        'scope': DINGTALK_QR_CONNECT_SCOPE,
        'redirect_uri': get_site_scheme_and_netloc() + reverse('dingtalk_connect_callback'),
        'state': state,
    }
    url = DINGTALK_QR_CONNECT_AUTHORIZATION_URL + '?' + urllib.parse.urlencode(data)
    return HttpResponseRedirect(url)

@login_required
def dingtalk_connect_callback(request):

    if not ENABLE_DINGTALK:
        return render_error(request, _('Error, please contact administrator.'))

    state = request.GET.get('state', '')
    if not state or state != request.session.get('dingtalk_connect_state', ''):
        logger.error('invalid state')
        return render_error(request, _('Error, please contact administrator.'))

    timestamp = str(int(time.time()*1000)).encode('utf-8')
    appsecret = DINGTALK_QR_CONNECT_APP_SECRET.encode('utf-8')
    signature = base64.b64encode(hmac.new(appsecret, timestamp, digestmod=sha256).digest())
    parameters = {
        'accessKey': DINGTALK_QR_CONNECT_APP_ID,
        'timestamp': timestamp,
        'signature': signature,
    }

    code = request.GET.get('code')
    data = {"tmp_auth_code": code}

    full_user_info_url = DINGTALK_QR_CONNECT_USER_INFO_URL + '?' + urllib.parse.urlencode(parameters)
    user_info_resp = requests.post(full_user_info_url, data=json.dumps(data))
    user_info = user_info_resp.json()['user_info']

    # seahub authenticate user
    if 'unionid' not in user_info:
        logger.error('Required user info not found.')
        logger.error(user_info)
        return render_error(request, _('Error, please contact administrator.'))

    username = request.user.username
    dingtalk_union_id = user_info['unionid']

    auth_user = SocialAuthUser.objects.get_by_provider_and_uid('dingtalk', dingtalk_union_id)
    if auth_user:
        logger.error('dingtalk account already exists %s' % dingtalk_union_id)
        return render_error(request, '出错了,此钉钉账号已被绑定')

    SocialAuthUser.objects.add(username, 'dingtalk', dingtalk_union_id)

    # update user's profile
    name = user_info['nick'] if 'nick' in user_info else ''
    if name:

        profile = Profile.objects.get_profile_by_user(username)
        if not profile:
            profile = Profile(user=username)

        profile.nickname = name.strip()
        profile.save()

    user_detail_info = dingtalk_get_detailed_user_info(user_info['unionid'])
    contact_email = user_detail_info.get('email', '')
    if contact_email:
        profile.contact_email = contact_email
        profile.save()

    response = HttpResponseRedirect(request.session['dingtalk_connect_redirect'])
    return response

@login_required
def dingtalk_disconnect(request):

    if not ENABLE_DINGTALK:
        return render_error(request, _('Error, please contact administrator.'))

    username = request.user.username
    SocialAuthUser.objects.delete_by_username_and_provider(username, 'dingtalk')
    response = HttpResponseRedirect(request.GET.get(auth.REDIRECT_FIELD_NAME, '/'))
    return response


text:
package com.koch.ambeth.util.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.koch.ambeth.util.model.INotifyPropertyChanged;

/**
 * If PropertyChangeAspect is added to a class or interface the bytecode enhancement - if connected
 * to the IOC container - will add support for PCEs (PropertyChangeEvents) implementing
 * {@link INotifyPropertyChanged}.
 *
 * @see NotifyPropertyChangedBehavior
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PropertyChangeAspect {
	boolean includeNewValue() default true;

	boolean includeOldValue() default true;
}


text:
#ifndef ATOMIC_ARM_HEADER
#define ATOMIC_ARM_HEADER

#ifdef  __cplusplus
        #define  EXTERN_PREFIX extern "C"
#else
        #define  EXTERN_PREFIX extern
#endif

#undef  ATOMIC_OPP  //Atomic operations and command not supported

#if (__STDC_VERSION__ >= 201112L) && (__STDC_NO_ATOMICS__ != 1)
// The implementation supports atomic types and <stdatomic.h> (C11)
// C is ISO/IEC 9899:2011 (C11) and __STDC_NO_ATOMICS__ is not defined
// __STDC_NO_ATOMICS__ see in 6.10.8.3 Conditional feature macros (standart C11)
// __STDC_VERSION__ in gcc defined if set -std=c11

    #define  ATOMIC_OPP     //Atomic operations supported
    #include <stdatomic.h>

#endif //#if (__STDC_VERSION__ >= 201112L) && (__STDC_NO_ATOMICS__ != 1)

#if    !defined(  ATOMIC_OPP  )   \
    && (defined(__ARM_ARCH_6__)   \
    ||  defined(__ARM_ARCH_6J__)  \
    ||  defined(__ARM_ARCH_6K__)  \
    ||  defined(__ARM_ARCH_6Z__)  \
    ||  defined(__ARM_ARCH_6ZK__) \
    ||  defined(__ARM_ARCH_7__)   \
    ||  defined(__ARM_ARCH_7A__)  \
    ||  defined(__ARM_ARCH_7R__) )

    #define  ATOMIC_OPP        //Atomic operations supported

    //use our atomic functions
    //functions only for int(32 bits): sizeof(int) == 4

    EXTERN_PREFIX int atomic_exchange(int *obj, int arg);
    EXTERN_PREFIX int atomic_fetch_add(int *obj, int arg);
    EXTERN_PREFIX int atomic_fetch_sub(int *obj, int arg);

    EXTERN_PREFIX unsigned int atomic_fetch_and(unsigned int *obj, unsigned int arg);
    EXTERN_PREFIX unsigned int atomic_fetch_xor(unsigned int *obj, unsigned int arg);
    EXTERN_PREFIX unsigned int atomic_fetch_or(unsigned int *obj, unsigned int arg);

#endif //ifdef __ARM_ARCH_XXX__

#ifdef ATOMIC_OPP

    //preg is volatile pointer to reg
    //IF use our atomic functions, reg must be sizeof(reg) == 4

    #define  ATOMIC_SET_BIT(preg, num_bit)  atomic_fetch_or (preg,  (1 << num_bit))
    #define  ATOMIC_CLR_BIT(preg, num_bit)  atomic_fetch_and(preg, ~(1 << num_bit))
    #define  ATOMIC_INV_BIT(preg, num_bit)  atomic_fetch_xor(preg,  (1 << num_bit))

    #define  ATOMIC_SET_FLAG(preg, flag)  atomic_fetch_or (preg,  (flag))
    #define  ATOMIC_CLR_FLAG(preg, flag)  atomic_fetch_and(preg, ~(flag))
    #define  ATOMIC_INV_FLAG(preg, flag)  atomic_fetch_xor(preg,  (flag))

#endif //#ifdef ATOMIC_OPP

#endif //ATOMIC_ARM_HEADER


text:
#include "GlobalDefines.h"
#include "ConsoleFuncs.h"
#include "Graphics.h"
#include "GameStateManager.h"
#include "FrameRateController.h"
#include "Input.h"
#include "Random.h"
#include "Registration.h" // Register entity classes and entity components

int main(void)
{
  // Initializes the graphics settings.
  InitGraphics( CLIENT_WIDTH, CLIENT_HEIGHT );

  // Initializes the console.
  // The first string is the name of your window. The second string is the
  // name of the font you want to use. Blank uses the default raster font,
  // though you can try strings "Lucida Console" or "Consolas" as they are
  // optional fonts in Windows 7 and Vista. A custom font can be created and
  // implemented if you're so inclined.
  initConsole(TEXT("Ascii Engine v1.02"), TEXT("Sunkure Font"), 8, 8 );

  // Seed PRNG
  // http://cecilsunkure.blogspot.com/2010/11/prngs-psuedo-random-number-generator.html
  InitRandSeed( );

  // Set the starting state
  // http://cecilsunkure.blogspot.com/2012/02/game-program-design-game-state-manager.html
  GSM_Initialize( TestLevel );

  InitFrameRateController( );

  // Registration of creators to the creator table
  // http://cecilsunkure.blogspot.com/2012/08/game-object-factory-distributed-factory.html
  RegisterEntityClasses( );
  RegisterEntityComponents( );

	while (currentState != Quit)
	{
		if (currentState == Quit)
		{
			break;
		}

		if (currentState == Restart)
		{
			currentState = previousState;
			nextState = previousState;
		}
		else
		{
			GSM_Update( );
			Load( );
		}

		Initialize( );
		SetStateStartTime( );

		while (currentState == nextState)
		{
			FrameStart( ); // get time frame started

			UpdateInput( ); // Capture input

			for (;;)
			{
        assert(_CrtCheckMemory());
				SetDT( dtCalculate( ) ); // Set's dt for the function GetDT
				Update( ); // calculate change in time since last call, for update
				if (FPSLimit( ))
				{
					Draw( );
					break;
				}
			}
		}

		Free( );

		if (nextState == Restart)
		{
			previousState = currentState;
			currentState = nextState;
		}
		else
		{
			Unload( );
			previousState = currentState;
			currentState = nextState;
		}
	}

  return RETURN_SUCCESS;
}


text:
// ----------------------------------------------------------------------------
// Copyright 2007-2017, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
//  2009/08/07  Martin D. Flynn
//     -Initial release
//  2017/01/08  Martin D. Flynn
//     -Subclass from Number
// ----------------------------------------------------------------------------
package org.opengts.util;

import java.lang.*;
import java.util.*;
import java.math.*;

/**
*** Light weight Accumulator Long container.
*** Typically used in conditions where it is desireable to pass an accumulator
*** to an inner-class and have the value accessible from outside the inner-class.
*** (If the accumulator is to be used from different threads in a multi-threaded
*** environment, use "AtomicLong" instead).
**/

public class AccumulatorLong
    extends Number
{

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

    private volatile long accum = 0L;

    /**
    *** Constructor
    **/
    public AccumulatorLong()
    {
        this(0L);
    }

    /**
    *** Constructor
    *** @param val  Initial value
    **/
    public AccumulatorLong(long val)
    {
        this.accum = val;
    }

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

    /**
    *** Sets the value of the accumulator
    *** @param v  The new value
    **/
    public void set(long v)
    {
        this.accum = v;
    }

    /**
    *** Gets the value of the accumulator
    *** @return The current value
    **/
    public long get()
    {
        return this.accum;
    }

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

    /**
    *** Adds the specified value to the accumulator
    *** @param v  The value to add
    **/
    public void add(long v)
    {
        this.accum += v;
    }

    /**
    *** Subtracts the specified value from the accumulator
    *** @param v  The value to subtract
    **/
    public void subtract(long v)
    {
        this.accum -= v;
    }

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

    /**
    *** Increment the value of the accumulator by 1
    **/
    public void increment()
    {
        ++this.accum;
    }

    /**
    *** Decrement the value of the accumulator by 1
    **/
    public void decrement()
    {
        --this.accum;
    }

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

    /**
    *** Increment the value of the accumulator by 1, and return new value.
    **/
    public long preIncrement() // incrementAndGet()
    {
        return ++this.accum;
    }

    /**
    *** Decrement the value of the accumulator by 1, and return new value.
    **/
    public long preDecrement() // decrementAndGet()
    {
        return --this.accum;
    }

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

    /**
    *** Increment the value of the accumulator by 1, and return value prior to increment.
    **/
    public long postIncrement() // getAndIncrement()
    {
        return this.accum++;
    }

    /**
    *** Decrement the value of the accumulator by 1, and return value prior to decrement
    **/
    public long postDecrement() // getAndDecrement()
    {
        return this.accum--;
    }

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

    /**
    *** Increment, and return the next value
    *** @return The next value
    **/
    public long next() // addAndGet(1L)
    {
        this.increment();
        return this.get();
    }

    /**
    *** Add the specified value, and return the result
    *** @param v The value to add
    *** @return The next value
    **/
    public long next(long v) // addAndGet(v)
    {
        this.add(v);
        return this.get();
    }

    // ------------------------------------------------------------------------
    // Number methods

    /**
    *** Returns this value as a byte
    *** @return This value converted to a byte
    **/
    @SuppressWarnings("cast")
    public byte byteValue()
    {
        return (byte)this.get();
    }

    /**
    *** Returns this value as a short
    *** @return This value converted to a short
    **/
    @SuppressWarnings("cast")
    public short shortValue()
    {
        return (short)this.get();
    }

    /**
    *** Returns this value as a int
    *** @return This value converted to a int
    **/
    @SuppressWarnings("cast")
    public int intValue()
    {
        return (int)this.get();
    }

    /**
    *** Returns this value as a long
    *** @return This value converted to a long
    **/
    @SuppressWarnings("cast")
    public long longValue()
    {
        return (long)this.get();
    }

    /**
    *** Returns this value as a float
    *** @return This value converted to a float
    **/
    @SuppressWarnings("cast")
    public float floatValue()
    {
        return (float)this.get();
    }

    /**
    *** Returns this value as a double
    *** @return This value converted to a double
    **/
    @SuppressWarnings("cast")
    public double doubleValue()
    {
        return (double)this.get();
    }

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

    /**
    *** Returns this value as a byte
    *** @return This value converted to a byte
    **/
    public boolean booleanValue()
    {
        return (this.longValue() != 0L)? true : false;
    }

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

    /**
    *** Returns true if the specified object is equal to this instance
    *** @param other  The other object to test
    *** @return True if the specified object is equal to this instance
    **/
    public boolean equals(Object other)
    {
        if (other instanceof AccumulatorLong) {
            return (this.get() == ((AccumulatorLong)other).get())? true : false;
        } else {
            return false;
        }
    }

    /**
    *** Returns a String representation of this instance
    *** @return A String representation of this instance
    **/
    public String toString()
    {
        return String.valueOf(this.get());
    }

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

}


text:
package swarm

import (
	"fmt"
	"net"

	"strings"

	"github.com/docker/machine/libmachine/host"
)

// SwarmModeGlobalConfig contain Swarm Mode global configuration
type SwarmModeGlobalConfig struct {
	ManagerToken        string
	BootstrapManagerURL string
	WorkerToken         string
}

// IsSwarmModeClusterInitialized returns true if Swarm mode cluster is initialized (Manager/Worker tokens set), and false otherwise
func (gc *SwarmModeGlobalConfig) IsSwarmModeClusterInitialized() bool {
	return (gc.ManagerToken != "") && (gc.WorkerToken != "")
}

// InitSwarmModeCluster initialize a new Swarm mode cluster on the given host and returns the Manager/Worker join tokens
func (gc *SwarmModeGlobalConfig) InitSwarmModeCluster(h *host.Host) error {
	// check if Swarm mode cluster is already initialized
	if gc.IsSwarmModeClusterInitialized() {
		return fmt.Errorf("The Swarm Mode cluster is already initialized")
	}

	// init Swarm mode cluster
	_, err := h.RunSSHCommand("docker swarm init")
	if err != nil {
		return err
	}

	// get Manager join token
	managerToken, err := h.RunSSHCommand("docker swarm join-token -q manager")
	if err != nil {
		return err
	}

	// get Worker join token
	workerToken, err := h.RunSSHCommand("docker swarm join-token -q worker")
	if err != nil {
		return err
	}

	// get IP address of the host
	ip, err := h.Driver.GetIP()
	if err != nil {
		return err
	}

	// remove spaces/new lines at the begining/end of the tokens
	gc.ManagerToken = strings.TrimSpace(managerToken)
	gc.WorkerToken = strings.TrimSpace(workerToken)

	// set this host as bootstrap Swarm Manager
	gc.BootstrapManagerURL = fmt.Sprintf("%s", net.JoinHostPort(ip, "2377"))

	return nil
}

// JoinSwarmModeCluster makes the host join a Swarm mode cluster as Manager or Worker
func (gc *SwarmModeGlobalConfig) JoinSwarmModeCluster(host *host.Host, isManager bool) error {
	// by default, join as Worker
	token := gc.WorkerToken

	// if node is a manager, change the join token to Manager token
	if isManager {
		token = gc.ManagerToken
	}

	// run swarm join command
	if _, err := host.RunSSHCommand(fmt.Sprintf("docker swarm join --token %s %s", token, gc.BootstrapManagerURL)); err != nil {
		return err
	}

	return nil
}


text:
layout:     post
title:      Responsive Blocks and Vertical Alignment
date:       2018-01-11
summary:    How to create responsive cross-browser blocks with vertically aligned content
---

Today I'm going to show you two of my favourite CSS "hacks." Responsive height blocks, and vertical alignment. These two often go hand in hand, usually with some sort grid of blocks with text in the centre. I'm sure you've come across the pattern before.

## Responsive blocks
First up, responsive blocks. We've all used responsive width columns, but you've probably never used responsive heights. If you apply `height: 50%;` to an element, you're not going to see any results. Unlike width, height cannot be set as a percentage as block container elements do not not have a height, whereas they do default to 100% width.

We can, however, make the height relative to the width. To do so, we will be making use of the `padding` rule. If you apply the rule of `padding-bottom: 100%;` to a div, you will end up with a perfect square. However, a full page square isn't exactly helpful is it. We want a grid of squares. You may think this is easy to a accomplish by setting a width on this div and watching it scale, however that is not the case. The padding is actually relative to the **parent** element, _not_ the element with the rule applied.

So to make box smaller and responsively sized, we just need a container element with a width value. This is usually fine as it's probably within a grid column anyway. Now you just tell the child how big it should be relative to the parent and there you have a perfect responsive height square.

```
<div style="margin: 0 -10px;" class="clearfix">
    <div style="width: 25%; float: left; padding: 0 10px;">
        <div class="primary" style="padding-bottom: 100%;"></div>
    </div>
    ...
</div>
```

You can of course do responsive rectangles by following the pattern and just adjusting the padding percentage.

## Vertical Alignment
Ah, vertical alignment, the bane of frontend developers lives. However it doesn't have to be. Depending on usage, you can follow a simple pattern to achieve vertical alignment that works extremely well with the above responsive blocks tip.

You'll probably shudder at the thought, but we're going to be using tables! Well, not exactly tables. Fake tables. Tables have the awesome ability of being able to make use of the `vertical-align` CSS rule for aligning content, and with the use of `display: table;` and `display: table-cell;` we can actually take advantage of this functionality with standard divs.

All you need is a div with `display: table;` and within it, a div with `display: table-cell;` and `vertical-align: middle;`. Just give the parent div a height and you'll have perfectly entered content.

            Look at me being all vertically aligned!

```
<div class="playground">
    <div class="primary" style="display: table; height: 100px; max-width: 100%; width: 100%; text-align: center;">
        <div style="display: table-cell; vertical-align: middle; padding: 15px;">
            Look at me being all vertically aligned!
        </div>
    </div>
</div>
```

Some may argue flexbox can solve this problem in much less lines of code, however table-cell is supported in every browser for a worry free dev experience.

## The double whammy
Combining with the above is simple. If you try to put your faux-table inside the responsive block however, you'll end up with a no longer reliably responsive block. This is because of the height from the padding trick combined with the height of your table. Instead we'll need to add another container block within the responsive block.

Simply set `position: relative;` on the block with the padding, and add a new div within this with `position: absolute; top: 0; right: 0; bottom: 0; left: 0;` which will make this div the same size as the parent which allow you to add content to the block.

This block also now has a fixed height, so you can now used a percentage height value for your content. Simply add your vertical aligned block to this div and give it a 100% height and width and you'll have perfectly aligned content within your block.

                            Look at me being all vertically aligned!

                            Hey, I'm vertically aligned over here too!


text:
package org.checkerframework.dataflow.constantpropagation;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.checkerframework.dataflow.analysis.FlowExpressions;
import org.checkerframework.dataflow.analysis.Store;
import org.checkerframework.dataflow.cfg.CFGVisualizer;
import org.checkerframework.dataflow.cfg.node.IntegerLiteralNode;
import org.checkerframework.dataflow.cfg.node.LocalVariableNode;
import org.checkerframework.dataflow.cfg.node.Node;
import org.checkerframework.dataflow.constantpropagation.Constant.Type;

public class ConstantPropagationStore implements Store<ConstantPropagationStore> {

    /** Information about variables gathered so far. */
    Map<Node, Constant> contents;

    public ConstantPropagationStore() {
        contents = new HashMap<>();
    }

    protected ConstantPropagationStore(Map<Node, Constant> contents) {
        this.contents = contents;
    }

    public Constant getInformation(Node n) {
        if (contents.containsKey(n)) {
            return contents.get(n);
        }
        return new Constant(Type.TOP);
    }

    public void mergeInformation(Node n, Constant val) {
        Constant value;
        if (contents.containsKey(n)) {
            value = val.leastUpperBound(contents.get(n));
        } else {
            value = val;
        }
        // TODO: remove (only two nodes supported atm)
        assert n instanceof IntegerLiteralNode || n instanceof LocalVariableNode;
        contents.put(n, value);
    }

    public void setInformation(Node n, Constant val) {
        // TODO: remove (only two nodes supported atm)
        assert n instanceof IntegerLiteralNode || n instanceof LocalVariableNode;
        contents.put(n, val);
    }

    @Override
    public ConstantPropagationStore copy() {
        return new ConstantPropagationStore(new HashMap<>(contents));
    }

    @Override
    public ConstantPropagationStore leastUpperBound(ConstantPropagationStore other) {
        Map<Node, Constant> newContents = new HashMap<>();

        // go through all of the information of the other class
        for (Entry<Node, Constant> e : other.contents.entrySet()) {
            Node n = e.getKey();
            Constant otherVal = e.getValue();
            if (contents.containsKey(n)) {
                // merge if both contain information about a variable
                newContents.put(n, otherVal.leastUpperBound(contents.get(n)));
            } else {
                // add new information
                newContents.put(n, otherVal);
            }
        }

        for (Entry<Node, Constant> e : contents.entrySet()) {
            Node n = e.getKey();
            Constant thisVal = e.getValue();
            if (!other.contents.containsKey(n)) {
                // add new information
                newContents.put(n, thisVal);
            }
        }

        return new ConstantPropagationStore(newContents);
    }

    @Override
    public ConstantPropagationStore widenedUpperBound(ConstantPropagationStore previous) {
        return leastUpperBound(previous);
    }

    @Override
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }
        if (!(o instanceof ConstantPropagationStore)) {
            return false;
        }
        ConstantPropagationStore other = (ConstantPropagationStore) o;
        // go through all of the information of the other object
        for (Entry<Node, Constant> e : other.contents.entrySet()) {
            Node n = e.getKey();
            Constant otherVal = e.getValue();
            if (otherVal.isBottom()) {
                continue; // no information
            }
            if (contents.containsKey(n)) {
                if (!otherVal.equals(contents.get(n))) {
                    return false;
                }
            } else {
                return false;
            }
        }
        // go through all of the information of the this object
        for (Entry<Node, Constant> e : contents.entrySet()) {
            Node n = e.getKey();
            Constant thisVal = e.getValue();
            if (thisVal.isBottom()) {
                continue; // no information
            }
            if (other.contents.containsKey(n)) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        int s = 0;
        for (Entry<Node, Constant> e : contents.entrySet()) {
            if (!e.getValue().isBottom()) {
                s += e.hashCode();
            }
        }
        return s;
    }

    @Override
    public String toString() {
        // only output local variable information
        Map<Node, Constant> smallerContents = new HashMap<>();
        for (Entry<Node, Constant> e : contents.entrySet()) {
            if (e.getKey() instanceof LocalVariableNode) {
                smallerContents.put(e.getKey(), e.getValue());
            }
        }
        return smallerContents.toString();
    }

    @Override
    public boolean canAlias(FlowExpressions.Receiver a, FlowExpressions.Receiver b) {
        return true;
    }

    @Override
    public void visualize(CFGVisualizer<?, ConstantPropagationStore, ?> viz) {
        // Do nothing since ConstantPropagationStore doesn't support visualize
    }
}