text:
package info.guardianproject.otr.app.im.app;

import info.guardianproject.otr.TorProxyInfo;
import info.guardianproject.otr.app.im.IChatSession;
import info.guardianproject.otr.app.im.IChatSessionManager;
import info.guardianproject.otr.app.im.IConnectionListener;
import info.guardianproject.otr.app.im.IImConnection;
import info.guardianproject.otr.app.im.R;
import info.guardianproject.otr.app.im.app.adapter.ConnectionListenerAdapter;
import info.guardianproject.otr.app.im.engine.ImConnection;
import info.guardianproject.otr.app.im.engine.ImErrorInfo;
import info.guardianproject.otr.app.im.provider.Imps;
import info.guardianproject.otr.app.im.service.ImServiceConstants;
import info.guardianproject.otr.app.im.ui.TabbedContainer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.EditText;

public class SigningInActivity extends Activity {
    private static final String TAG = "SigningInActivity";

    private static final String SYNC_SETTINGS_ACTION = "android.settings.SYNC_SETTINGS";
    private static final String SYNC_SETTINGS_CATEGORY = "android.intent.category.DEFAULT";

    private IImConnection mConn;
    private IConnectionListener mListener;
    private SimpleAlertHandler mHandler;
    private ImApp mApp;
    private long mProviderId;
    private long mAccountId;
    private String mProviderName;

    private String mToAddress;

    private boolean isActive;

    protected static final int ID_CANCEL_SIGNIN = Menu.FIRST + 1;

    private Dialog dl = null;

    private Uri accountData = null;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        getWindow().requestFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.signing_in_activity);

    }

    @Override
	protected void onResume() {

		super.onResume();

		  Intent intent = getIntent();
	        mToAddress = intent.getStringExtra(ImApp.EXTRA_INTENT_SEND_TO_USER);

	   accountData = intent.getData();
	        if (accountData == null) {
	            if(Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
	                log("Need account data to sign in");
	            }
	            finish();
	            return;
	        }

        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(accountData, null, null, null, null);
        if (c == null) {
            if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
                log("Query fail:" + accountData);
            }
            finish();
            return;
        }
        if (!c.moveToFirst()) {
            if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
                log("No data for " + accountData);
            }
            c.close();
            finish();
            return;
        }

        mProviderId = c.getLong(c.getColumnIndexOrThrow(Imps.Account.PROVIDER));
        mAccountId = c.getLong(c.getColumnIndexOrThrow(Imps.Account._ID));
        isActive = c.getInt(c.getColumnIndexOrThrow(Imps.Account.ACTIVE)) == 1;

        final String pwExtra = intent.getStringExtra(ImApp.EXTRA_INTENT_PASSWORD);
        String mPassword = null;

        if (pwExtra != null) {
        	mPassword = pwExtra;
        } else {
        	mPassword = c.getString(c.getColumnIndexOrThrow(Imps.Account.PASSWORD));
        }

        c.close();

        mApp = ImApp.getApplication(this);

        IImConnection conn = mApp.getConnection(mProviderId);
        try {
        	if (conn == null || (conn.getState() != ImConnection.LOGGED_IN)) {
        		if (mPassword == null || mPassword.length() == 0) {
        			//show password prompt
        			showPasswordDialog();
        		} else {
        			connectService(mPassword);
        		}
        	} else if (conn.getState() == ImConnection.LOGGED_IN)
        	{

        		 // assume we can sign in successfully.
                setResult(RESULT_OK);
        			//conn.logout(); // in case we are already logged
        			//connectService();
        	}
        } catch (Exception e) {
        	Log.w(TAG, "bad things: " + e);
        	showPasswordDialog();
        }
    }

    public void connectService(String password) {

        final ProviderDef provider = mApp.getProvider(mProviderId);
        mProviderName = provider.mName;

        /*
        BrandingResources brandingRes = mApp.getBrandingResource(mProviderId);
        getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON,
                brandingRes.getDrawable(BrandingResourceIDs.DRAWABLE_LOGO));
*/

        setTitle(getResources().getString(R.string.signing_in_to,
                provider.mFullName));

        mHandler = new SimpleAlertHandler(this);
        mListener = new MyConnectionListener(mHandler);

        mApp.callWhenServiceConnected(mHandler, new ConnectHandler(password));

        // assume we can sign in successfully.
        setResult(RESULT_OK);
    }

    class ConnectHandler implements Runnable
    {
    	String mPassword;

    	ConnectHandler (String password)
    	{
    		mPassword = password;
    	}

    	public void run() {
            if (mApp.serviceConnected()) {
                if (!isActive) {
                    activateAccount(mProviderId, mAccountId);
                }
                signInAccount(mPassword);
            }
        }
    }

	private void showPasswordDialog() {

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Password");
		String message = getString(R.string.signin_password_prompt);
		alert.setMessage(message);

		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		input.setTransformationMethod(new PasswordTransformationMethod());
		alert.setView(input);
		alert.setNeutralButton("Remember",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						String pwd = input.getText().toString();
						SharedPreferences prefs = PreferenceManager
								.getDefaultSharedPreferences(getApplication());
						Editor edit = prefs.edit();
						edit.putString("pref_account_pass", pwd);
						edit.commit();
						connectService(pwd);
					}
				});

         alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int whichButton) {
        	 String pwd = input.getText().toString();
        	 connectService(pwd);
           }
         });

         alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int whichButton) {
        	 showAccount();
        	 finish();
             return;
           }
        });

        alert.show();
	}

    /*
    @Override
    protected void onRestart() {
        super.onRestart();

        if (mApp.serviceConnected() && mApp.isBackgroundDataEnabled()) {
            signInAccount();
        } else {
            if(Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
                log("onRestart: service disconnected or background data disabled...");
            }
            setResult(RESULT_CANCELED);
            finish();
        }
    }
*/

    private void signInAccount(String password) {

    	boolean autoLoadContacts = true;
    	boolean autoRetryLogin = false;

        try {
            IImConnection conn = mApp.getConnection(mProviderId);
            if (conn != null) {
                mConn = conn;
                // register listener before get state so that we won't miss
                // any state change event.
                conn.registerConnectionListener(mListener);
                int state = conn.getState();
                if (state != ImConnection.LOGGING_IN) {
                    // already signed in or failed
                    conn.unregisterConnectionListener(mListener);
                    handleConnectionEvent(state, null);
                }
            } else {
                if (mApp.isBackgroundDataEnabled()) {
                    mConn = mApp.createConnection(mProviderId);
                    if (mConn == null) {
                        // This can happen when service did not come up for any reason
                        return;
                    }
                    mConn.registerConnectionListener(mListener);
                    // TODO UsrTor should probably be set in the intent rather than fetched from the settings
                    final Imps.ProviderSettings.QueryMap settings = new Imps.ProviderSettings.QueryMap(
                            getContentResolver(),
                            mProviderId,
                            false /* don't keep updated */,
                            null /* no handler */);
                    if (settings.getUseTor()) {
                        mConn.setProxy(TorProxyInfo.PROXY_TYPE, TorProxyInfo.PROXY_HOST, TorProxyInfo.PROXY_PORT);
                    }
                    settings.close();

                 	mConn.login(mAccountId, password, autoLoadContacts, autoRetryLogin);

                } else {
                    promptForBackgroundDataSetting();
                    return;
                }
            }

        } catch (RemoteException e) {
            mHandler.showServiceErrorAlert();

        }
    }

    private void activateAccount(long providerId, long accountId) {
        // Update the active value. We restrict to only one active
        // account per provider right now, so update all accounts of
        // this provider to inactive first and then update this
        // account to active.
        ContentValues values = new ContentValues(1);
        values.put(Imps.Account.ACTIVE, 0);
        ContentResolver cr = getContentResolver();
        cr.update(Imps.Account.CONTENT_URI, values,
                Imps.Account.PROVIDER + "=" + providerId, null);

        values.put(Imps.Account.ACTIVE, 1);
        cr.update(ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId),
                values, null, null);
    }

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

        if (mApp != null) {
            mApp.removePendingCall(mHandler);
        }
        if (mConn != null) {
            try {
                if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
                    log("unregisterConnectonListener");
                }
                mConn.unregisterConnectionListener(mListener);
            } catch (RemoteException e) {
                Log.w(ImApp.LOG_TAG, "<SigningInActivity> Connection disappeared!");
            }
        }
        // When background data is enabled, we don't want this activity in the backlist
        // so we always call finish() when we leave signing in screen. Otherwise, we
        // don't finish since we need to keep signing in if user choose to enable background.
        if (mApp.isBackgroundDataEnabled()) {
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID_CANCEL_SIGNIN, 0, R.string.menu_cancel_signin)
            .setIcon(android.R.drawable.ic_menu_close_clear_cancel);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == ID_CANCEL_SIGNIN) {
            if (mConn != null) {
            	cancelSignIn();
            }
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Popup a dialog to ask the user whether he/she wants to enable
     * background connection to continue. If yes, enable the setting
     * and broadcast the change. Otherwise, quit the signing in window
     * immediately.
     */
    private void promptForBackgroundDataSetting() {
        new AlertDialog.Builder(SigningInActivity.this)
            .setTitle(R.string.bg_data_prompt_title)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(getString(R.string.bg_data_prompt_message, mProviderName))
            .setPositiveButton(R.string.bg_data_prompt_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    Intent intent = new Intent(SYNC_SETTINGS_ACTION);
                    intent.addCategory(SYNC_SETTINGS_CATEGORY);
                    startActivity(intent);
                }
             })
            .setNegativeButton(R.string.bg_data_prompt_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setResult(RESULT_CANCELED);
                        finish();
                    }
             })
            .show();
    }

    void handleConnectionEvent(int state, ImErrorInfo error) {

    	/*
    	if (isFinishing()) {
            return;
        }*/

        if (state == ImConnection.LOGGED_IN) {

            try {
                Intent intent;

                mAccountId = mConn.getAccountId();

                /*#############################################################################
                 * This (see below) intent is the one that needs to be passed to the tab Event
                 */

                if (mToAddress != null) {
                    IChatSessionManager manager = mConn.getChatSessionManager();
                    IChatSession session = manager.getChatSession(mToAddress);
                    if(session == null) {
                        session = manager.createChatSession(mToAddress);
                    }
                    Uri data = ContentUris.withAppendedId(Imps.Chats.CONTENT_URI, session.getId());
                    intent = new Intent(Intent.ACTION_VIEW, data);
                    intent.putExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS, mToAddress);
                    intent.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, mProviderId);
                    intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
                    intent.addCategory(ImApp.IMPS_CATEGORY);

                } else {
                    intent = new Intent(this, TabbedContainer.class);

                    // clear the back stack of the account setup

               //     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK && Intent.FLAG);
                    intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
                }

                startActivity(intent);

                // sign in successfully, finish and switch to contact list
                finish();

            } catch (RemoteException e) {
                // Ouch!  Service died!  We'll just disappear.
                Log.w(ImApp.LOG_TAG, "<SigningInActivity> Connection disappeared while signing in!");
            }
        } else if (state == ImConnection.DISCONNECTED) {

            // sign in failed
            Resources r = getResources();
            new AlertDialog.Builder(this)
                .setTitle(R.string.error)
                .setMessage(r.getString(R.string.login_service_failed, mProviderName,
                            error == null? "": ErrorResUtils.getErrorRes(r, error.getCode())))
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                setResult(RESULT_CANCELED);
                                showAccount();
                                finish();
                            }
                        })
                .setCancelable(false)
                .show();
        }
    }

    private static final void log(String msg) {
        Log.d(ImApp.LOG_TAG, "<SigningInActivity>" + msg);
    }

    private final class MyConnectionListener extends ConnectionListenerAdapter {
        MyConnectionListener(Handler handler) {
            super(handler);
        }

        @Override
        public void onConnectionStateChange(IImConnection connection,
                int state, ImErrorInfo error) {
            handleConnectionEvent(state, error);
        }
    }

    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {

	    	cancelSignIn();

	    }
	    return super.onKeyDown(keyCode, event);
	}

    private void cancelSignIn ()
    {

    	try
    	{
    		log("canceling login");
            try {
        		if (mConn != null && mConn.getState() == ImConnection.LOGGING_IN)
        			mConn.cancelLogin();
            } catch (RemoteException e) {
                Log.w(ImApp.LOG_TAG, "<SigningInActivity> Connection disappeared!");
            }

    		showAccount();
    		finish();
    	}
    	catch (Exception e)
    	{
    		Log.e(ImApp.LOG_TAG,"error on cancel",e);
    	}
    }

    private void showAccount()
    {
    	 Intent intent = new Intent(Intent.ACTION_EDIT, accountData);
         intent.putExtra("isSignedIn", false);
//         intent.addCategory(c.getString(WelcomeActivity.PROVIDER_CATEGORY_COLUMN));
         startActivity(intent);
         finish();
    }
}


text:
"""wit_kaggle dataset."""

from tensorflow_datasets.vision_language.wit_kaggle.wit_kaggle import WitKaggle

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  id="WebApp_ID" version="2.5">

  <display-name>test.persistence.wab</display-name>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <description></description>
    <display-name>Test</display-name>
    <servlet-name>Test</servlet-name>
    <servlet-class>com.sap.mobile.platform.server.sample.persistence.jpa.servlet.TestServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

 </web-app>


text:
EXPECTED_SIGNATURE=$(wget -q -O - https://composer.github.io/installer.sig)
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_SIGNATURE=$(php -r "echo hash_file('SHA384', 'composer-setup.php');")

if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]
then
    >&2 echo 'ERROR: Invalid installer signature'
    rm composer-setup.php
    exit 1
fi

if [ ! -f composer-setup.php ]
then
    echo "ERROR: Could not download composer, please check your connection or your file permissions."
    exit 1
fi

php composer-setup.php --quiet
RESULT=$?

if [ $RESULT -ne 1 ]
then
    rm composer-setup.php
fi

exit $RESULT


text:
package org.springframework.github;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "issues")
class Issues {
	@Id
	@GeneratedValue
	private Long id;
	@NotNull
	private String username;
	@NotNull
	private String repository;

	Issues(String username, String repository) {
		this.username = username;
		this.repository = repository;
	}

	Issues() {
	}

	String getUsername() {
		return this.username;
	}

	void setUsername(String username) {
		this.username = username;
	}

	String getRepository() {
		return this.repository;
	}

	void setRepository(String lastname) {
		this.repository = lastname;
	}

	@Override
	public String toString() {
		return "IssueCreation [username=" + this.username + ", repository=" + this.repository
				+ "]";
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <link rel="stylesheet" href="css/jqueryterminal/jquery.terminal.css"/>
  <link rel="stylesheet" href="css/tipsy.css">
  <link rel="stylesheet" href="css/drift.css">

      <svg id="graph-svg" width=500 height=500><g/></svg>


text:
cd $(dirname $0)
cd ..

sudo python setup.py sdist bdist_egg upload


text:
var blake = require('../index')
var cop = require('cop')
var fs = require('fs')
var path = require('path')

;(function () {
  var arg = process.argv.splice(2)
  if (!arg.length) {
    return console.error('Usage: blake [source_directory] target_directory [source_file ...]')
  }
  var cwd = process.cwd()
  function isFile () {
    var p = path.resolve(cwd, arg[1])
    return fs.statSync(p).isFile()
  }
  var sansSource = arg.length === 1 || isFile()
  if (sansSource) {
    arg.unshift(cwd)
  }
  var source = arg.shift()
  var target = arg.shift()
  function onerror (er) {
    console.error(er.message)
  }
  var b = blake(source, target)
  if (!arg.length) {
    blake.copy(b.resources, target)
      .on('error', onerror)
      .on('end', bake)
      .pipe(process.stdout)
  } else {
    bake()
  }
  function bake () {
    var p = arg instanceof Array && arg.length ? arg : b.data
    blake.files(p)
      .pipe(b)
      .on('error', onerror)
      .pipe(cop(function (str) { return str + '\n' }))
      .pipe(process.stdout)
  }
})()


text:
param([string]$buildFolder, [string]$docSource, [string]$repoUrl)

$workingDir = "$($buildFolder)\..\gh-pages"
$workingBranch = "gh-pages"

Push-Location

if (Test-Path("$($workingDir)")) {
    Remove-Item "$($workingDir)" -Recurse -Force
}
mkdir $workingDir

git clone --quiet --branch=$workingBranch "$($repoUrl)" "$($workingDir)"
cd $($workingDir)
git status

Get-ChildItem -Attributes !r | Remove-Item -Recurse -Force
Copy-Item -Path "$($buildFolder)\$($docSource)\**" -Destination $pwd.Path -Recurse
git status

$thereAreChanges = git status | select-string -pattern "Changes not staged for commit:","Untracked files:" -simplematch
if ($thereAreChanges -ne $null) {
    Write-Host "Committing changes to docs..."
    git add --all
    git status
    git commit -m "CI build"
    git status
    git push -q
    Write-Host "Changes pushed succesfully" -ForegroundColor Green
}
else {
    Write-Host "No changes to documentation to commit" -ForegroundColor Blue
}
Pop-Location


text:
package org.springframework.boot.context.properties.source;

import java.util.Collections;
import java.util.Iterator;

import org.junit.jupiter.api.Test;

import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.env.SystemEnvironmentPropertySource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;

/**
 * Tests for {@link SpringConfigurationPropertySources}.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 */
class SpringConfigurationPropertySourcesTests {

	@Test
	void createWhenPropertySourcesIsNullShouldThrowException() {
		assertThatIllegalArgumentException().isThrownBy(() -> new SpringConfigurationPropertySources(null))
				.withMessageContaining("Sources must not be null");
	}

	@Test
	void shouldAdaptPropertySource() {
		MutablePropertySources sources = new MutablePropertySources();
		sources.addFirst(new MapPropertySource("test", Collections.singletonMap("a", "b")));
		Iterator<ConfigurationPropertySource> iterator = new SpringConfigurationPropertySources(sources).iterator();
		ConfigurationPropertyName name = ConfigurationPropertyName.of("a");
		assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("b");
		assertThat(iterator.hasNext()).isFalse();
	}

	@Test
	void shouldAdaptSystemEnvironmentPropertySource() {
		MutablePropertySources sources = new MutablePropertySources();
		sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
				Collections.singletonMap("SERVER_PORT", "1234")));
		Iterator<ConfigurationPropertySource> iterator = new SpringConfigurationPropertySources(sources).iterator();
		ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port");
		assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234");
		assertThat(iterator.hasNext()).isFalse();
	}

	@Test
	void shouldExtendedAdaptSystemEnvironmentPropertySource() {
		MutablePropertySources sources = new MutablePropertySources();
		sources.addLast(new SystemEnvironmentPropertySource(
				"test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
				Collections.singletonMap("SERVER_PORT", "1234")));
		Iterator<ConfigurationPropertySource> iterator = new SpringConfigurationPropertySources(sources).iterator();
		ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port");
		assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234");
		assertThat(iterator.hasNext()).isFalse();
	}

	@Test
	void shouldNotAdaptSystemEnvironmentPropertyOverrideSource() {
		MutablePropertySources sources = new MutablePropertySources();
		sources.addLast(
				new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234")));
		Iterator<ConfigurationPropertySource> iterator = new SpringConfigurationPropertySources(sources).iterator();
		ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port");
		assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234");
		assertThat(iterator.hasNext()).isFalse();
	}

	@Test
	void shouldAdaptSystemEnvironmentPropertySourceWithUnderscoreValue() {
		MutablePropertySources sources = new MutablePropertySources();
		sources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
				Collections.singletonMap("_", "1234")));
		Iterator<ConfigurationPropertySource> iterator = new SpringConfigurationPropertySources(sources).iterator();
		ConfigurationPropertyName name = ConfigurationPropertyName.of("bar");
		assertThat(iterator.next().getConfigurationProperty(name)).isNull();
		assertThat(iterator.hasNext()).isFalse();
	}

	@Test
	void shouldAdaptMultiplePropertySources() {
		MutablePropertySources sources = new MutablePropertySources();
		sources.addLast(new SystemEnvironmentPropertySource("system", Collections.singletonMap("SERVER_PORT", "1234")));
		sources.addLast(new MapPropertySource("test1", Collections.singletonMap("server.po-rt", "4567")));
		sources.addLast(new MapPropertySource("test2", Collections.singletonMap("a", "b")));
		Iterator<ConfigurationPropertySource> iterator = new SpringConfigurationPropertySources(sources).iterator();
		ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port");
		assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234");
		assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("4567");
		assertThat(iterator.next().getConfigurationProperty(ConfigurationPropertyName.of("a")).getValue())
				.isEqualTo("b");
		assertThat(iterator.hasNext()).isFalse();
	}

	@Test
	void shouldFlattenEnvironment() {
		StandardEnvironment environment = new StandardEnvironment();
		environment.getPropertySources().addFirst(new MapPropertySource("foo", Collections.singletonMap("foo", "bar")));
		environment.getPropertySources().addFirst(new MapPropertySource("far", Collections.singletonMap("far", "far")));
		MutablePropertySources sources = new MutablePropertySources();
		sources.addFirst(new PropertySource<Environment>("env", environment) {

			@Override
			public String getProperty(String key) {
				return this.source.getProperty(key);
			}

		});
		sources.addLast(new MapPropertySource("baz", Collections.singletonMap("baz", "barf")));
		SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources);
		assertThat(configurationSources.iterator()).toIterable().hasSize(5);
	}

	@Test
	void shouldTrackChanges() {
		MutablePropertySources sources = new MutablePropertySources();
		SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources);
		assertThat(configurationSources.iterator()).toIterable().hasSize(0);
		MapPropertySource source1 = new MapPropertySource("test1", Collections.singletonMap("a", "b"));
		sources.addLast(source1);
		assertThat(configurationSources.iterator()).toIterable().hasSize(1);
		MapPropertySource source2 = new MapPropertySource("test2", Collections.singletonMap("b", "c"));
		sources.addLast(source2);
		assertThat(configurationSources.iterator()).toIterable().hasSize(2);
	}

	@Test
	void shouldTrackWhenSourceHasIdenticalName() {
		MutablePropertySources sources = new MutablePropertySources();
		SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources);
		ConfigurationPropertyName name = ConfigurationPropertyName.of("a");
		MapPropertySource source1 = new MapPropertySource("test", Collections.singletonMap("a", "s1"));
		sources.addLast(source1);
		assertThat(configurationSources.iterator().next().getConfigurationProperty(name).getValue()).isEqualTo("s1");
		MapPropertySource source2 = new MapPropertySource("test", Collections.singletonMap("a", "s2"));
		sources.remove("test");
		sources.addLast(source2);
		assertThat(configurationSources.iterator().next().getConfigurationProperty(name).getValue()).isEqualTo("s2");
	}

}


text:
PuppetLint.new_check(:relative_classname_inclusion) do
  def check
    tokens.each_with_index do |token, token_idx|
      if token.type == :NAME && token.value == 'include'
        s = token.next_code_token
        in_function = 0
        while s.type != :NEWLINE
          n = s.next_code_token
          if s.type == :NAME || s.type == :SSTRING
            if n && n.type == :LPAREN
              in_function += 1
            elsif in_function > 0 && n && n.type == :RPAREN
              in_function -= 1
            elsif in_function == 0 && s.value !~ /^::/
              notify :warning, {
                :message => 'class included by relative name',
                :line    => s.line,
                :column  => s.column,
                :token   => s,
              }
            end
          end
          s = s.next_token
        end
      elsif token.type == :CLASS and token.next_code_token.type == :LBRACE
        s = token.next_code_token
        while s.type != :COLON
          if (s.type == :NAME || s.type == :SSTRING) && s.value !~ /^::/
            notify :warning, {
              :message => 'class included by relative name',
              :line    => s.line,
              :column  => s.column,
              :token   => s,
            }
          end
          s = s.next_token
        end
      end
    end
  end

  def fix(problem)
    problem[:token].value = '::'+problem[:token].value
  end
end


text:
require File.expand_path(File.join(File.dirname(__FILE__), 'helper'))
#
# Check Repodata of Repo
#

class RepodataTest < Test::Unit::TestCase
  def test_repo_create
    pool = Satsolver::Pool.new
    assert pool
    pool.arch = "x86_64"
    solvpath = Pathname( File.dirname( __FILE__ ) ) + Pathname( "../../testdata" ) + "os11-biarch.solv"
    repo = pool.add_solv( solvpath )
    repo.name = "openSUSE 11.0 Beta3 BiArch"
    puts "Repo #{repo.name} loaded with #{repo.size} solvables"

#    puts "Repo has #{repo.datasize} Repodatas attached"
    assert repo.datasize > 0
    assert repo.data(-1) == nil
    assert repo.data(repo.datasize) == nil
    assert repo.data(repo.datasize-1)
    repo.each_data { |d|
      assert d
    }

    repodata = repo.data(0)
    assert repodata

    puts "Repodata has #{repodata.size} keys"
    repodata.each_key { |k|
      puts "  Key '#{k.name}' is #{k.type}[#{k.type_id}] with #{k.size} bytes"
    }

    puts "repository:addedfileprovides: #{repo.attr('repository:addedfileprovides').inspect}"

    i = 0
    repo.each { |s|
      bt = s['solvable:buildtime']
      bt = Time.at(bt) if bt.is_a? Fixnum
#      puts "Solvable #{s}: group #{s['solvable:group']}, time #{bt}, downloadsize #{s['solvable:downloadsize']}, installsize #{s['solvable:installsize']}"
      i += 1
      break if i == 10
    }
  end
end


text:
from django.shortcuts import render_to_response

from .models import Competition
from .logic import calculate_table

def table(request):
    table = calculate_table()
    cols = ['total'] + [c.name for c in Competition.objects.all()]
    return render_to_response('table.html', {
        'tables': {c: [
            (r[c], r['name'])
            for r in sorted(table, key=(lambda x: -x[c]))
        ] for c in cols},
        'cols': cols,
        'cls': 'col-sm-%d' % (12 // len(cols),)
    })


text:
layout: page
title: Andrea Hopkins's 87th Birthday
date: 2016-05-24
author: Emma Thompson
tags: weekly links, java
status: published
summary: Aliquam venenatis, diam ut dignissim iaculis, arcu.
banner: images/banner/office-01.jpg
booking:
  startDate: 08/22/2018
  endDate: 08/27/2018
  ctyhocn: PNXDSHX
  groupCode: AH8B
published: true
---
Ut id urna bibendum felis malesuada porttitor. Donec maximus tellus in porta viverra. Integer eget sapien non felis tincidunt gravida nec ac urna. Pellentesque vel nunc eleifend, pulvinar leo at, malesuada arcu. Suspendisse et orci arcu. Sed bibendum mauris vestibulum orci rutrum dapibus. Cras pretium dui euismod tortor mattis, in vulputate eros bibendum. Mauris nisl velit, tincidunt id justo et, porta elementum mi. Ut venenatis in nunc a sagittis.

* Ut mattis est vitae ornare efficitur
* Donec mattis risus sed tempus vulputate.

Donec a rutrum nunc. Aenean turpis enim, dictum ut aliquet at, lobortis ut nunc. Vivamus congue consequat metus. Donec nec felis non augue elementum consectetur in malesuada libero. Suspendisse ac augue ac quam maximus imperdiet at eu est. Suspendisse congue leo commodo, tempor metus vitae, sagittis nibh. Suspendisse eget egestas risus. Maecenas vulputate luctus imperdiet. Cras varius, neque quis placerat accumsan, ex dui tempor augue, id facilisis sapien sapien eu lacus. Aenean vehicula leo lectus, sit amet pretium turpis semper id. Cras auctor elementum tellus, ut congue magna condimentum ut.


text:
[![Build Status](https://travis-ci.org/opentok/OpenTok-PHP-SDK.svg)](https://travis-ci.org/opentok/OpenTok-PHP-SDK)

The OpenTok PHP SDK lets you generate [sessions](http://tokbox.com/opentok/tutorials/create-session/) and
[tokens](http://tokbox.com/opentok/tutorials/create-token/) for [OpenTok](http://www.tokbox.com/)
applications, and [archive](http://tokbox.com/#archiving) OpenTok 2.0 sessions.

If you are updating from a previous version of this SDK, see
[Important changes since v2.2.0](#important-changes-since-v220).

# Installation

## Composer (recommended):

Composer helps manage dependencies for PHP projects. Find more info here: <http://getcomposer.org>

Add this package (`opentok/opentok`) to your `composer.json` file, or just run the following at the
command line:

```
$ composer require opentok/opentok 2.2.x
```

## Manually:

Download the zip file for the latest release from the [Releases](https://github.com/opentok/opentok-php-sdk/releases)
page. Unzip the file and place it into your project directory. If you have a
[PSR-4](http://www.php-fig.org/psr/psr-4/) compliant loader, you should place the unzipped directory
into a place your loader can find it. Otherwise, place it in the
[include_path](http://www.php.net/manual/en/ini.core.php#ini.include-path) and include or require
the files as necessary.

# Usage

## Initializing

This package follows the [PSR-4](http://www.php-fig.org/psr/psr-4/) autoloading standard. If you are
using composer to install, you just require the generated autoloader:

```php
require "<projectpath>/vendor/autoload.php";
```

Once the files of the SDK are loaded, you initialize an `OpenTok\OpenTok` object with your own API
Key and API Secret.

```php
use OpenTok\OpenTok;

$opentok = new OpenTok($apiKey, $apiSecret);
```

## Creating Sessions

To create an OpenTok Session, use the `createSession($options)` method of the
`OpenTok\OpenTok` class. The `$options` parameter is an optional array used to specify the following:

* Setting whether the session will use the OpenTok Media Router or attempt send streams directly
  between clients.

* Specifying a location hint.

The `getSessionId()` method of the `OpenTok\Session` instance returns the session ID,
which you use to identify the session in the OpenTok client libraries.

```php
// Create a session that attempts to use peer-to-peer streaming:
$session = $openTok->createSession();
// A session that uses the OpenTok Media Router:
$session = $openTok->createSession(array( 'mediaMode' => MediaMode::ROUTED ));
// A session with a location hint:
$session = $openTok->createSession(array( 'location' => '12.34.56.78' ));

// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();
```

## Generating Tokens

Once a Session is created, you can start generating Tokens for clients to use when connecting to it.
You can generate a token either by calling the `generateToken($sessionId, $options)` method of the
`OpenTok\OpenTok` class, or by calling the `generateToken($options)` method on the `OpenTok\Session`
instance after creating it. The `$options` parameter is an optional array used to set the role,
expire time, and connection data of the Token.

```php
use OpenTok\Session;
use OpenTok\Role;

// Generate a Token from just a sessionId (fetched from a database)
$token = OpenTok->generateToken($sessionId);
// Generate a Token by calling the method on the Session (returned from createSession)
$token = $session->generateToken();

// Set some options in a token
$token = $session->generateToken(array(
    'role'       => Role::MODERATOR,
    'expireTime' => time()+(7 * 24 * 60 * 60) // in one week
    'data'       => 'name=Johnny'
));
```

## Working with Archives

You can start the recording of an OpenTok Session using the `startArchive($sessionId, $name)` method
of the `OpenTok\OpenTok` class. This will return an `OpenTok\Archive` instance. The parameter
`$name` is optional and is used to assign a name for the Archive. Note that you can only start an
Archive on a Session that has clients connected.

```php
$archive = $opentok->startArchive($sessionId, $name);

// Store this archiveId in the database for later use
$archiveId = $archive->id;
```

You can stop the recording of a started Archive using the `stopArchive($archiveId)` method of the
`OpenTok\OpenTok` object. You can also do this using the `stop()` method of the
`OpenTok\Archive` instance.

```php
// Stop an Archive from an archiveId (fetched from database)
$opentok->stopArchive($archiveId);
// Stop an Archive from an Archive instance (returned from startArchive)
$archive->stop();
```

To get an `OpenTok\Archive` instance (and all the information about it) from an archive ID, use the
`getArchvie($archiveId)` method of the `OpenTok\OpenTok` class.

```php
$archive = $opentok->getArchive($archiveId);
```

To delete an Archive, you can call the `deleteArchive($archiveId)` method of the `OpenTok\OpenTok`
class or the `delete()` method of an `OpenTok\Archive` instance.

```php
// Delete an Archive from an archiveId (fetched from database)
$opentok->deleteArchive($archiveId);
// Delete an Archive from an Archive instance (returned from startArchive, getArchive)
$archive->delete();
```

You can also get a list of all the Archives you've created (up to 1000) with your API Key. This is
done using the `listArchives($offset, $count)` method of the `OpenTok/OpenTok` class. The parameters
`$offset` and `$count` are optional and can help you paginate through the results. This will return
an instance of the `OpenTok\ArchiveList` class.

```php
$archiveList = $opentok->listArchives();

// Get an array of OpenTok\Archive instances
$archives = $archiveList->getItems();
// Get the total number of Archives for this API Key
$totalCount = $archiveList->totalCount();
```

# Samples

There are two sample applications included in this repository. To get going as fast as possible, clone the whole
repository and follow the Walkthroughs:

*  [HelloWorld](sample/HelloWorld/README.md)
*  [Archiving](sample/Archiving/README.md)

# Documentation

Reference documentation is available at <http://www.tokbox.com/opentok/libraries/server/php/reference/index.html> and in the
docs directory of the SDK.

# Requirements

You need an OpenTok API key and API secret, which you can obtain at <https://dashboard.tokbox.com>.

The OpenTok PHP SDK requires PHP 5.3 or greater.

# Release Notes

See the [Releases](https://github.com/opentok/opentok-php-sdk/releases) page for details
about each release.

# Important changes since v2.2.0

**Changes in v2.2.1:**

The default setting for the `createSession()` method is to create a session with the media mode set
to relayed. In previous versions of the SDK, the default setting was to use the OpenTok Media Router
(media mode set to routed). In a relayed session, clients will attempt to send streams directly
between each other (peer-to-peer); if clients cannot connect due to firewall restrictions, the
session uses the OpenTok TURN server to relay audio-video streams.

**Changes in v2.2.0:**

This version of the SDK includes support for working with OpenTok 2.0 archives. (This API does not
work with OpenTok 1.0 archives.)

The names of many methods of the API have changed. Many method names have
changed to use camel case, including the following:

* OpenTok.createSession()
* OpenTok.generateToken()

Note also that the `options` parameter of the `OpenTok.createSession()` method has a `mediaMode`
property instead of a `p2p` property.

The API_Config class has been removed. Store your OpenTok API key and API secret in code outside of the SDK files.

See the reference documentation
<http://www.tokbox.com/opentok/libraries/server/php/reference/index.html> and in the
docs directory of the SDK.

# Development and Contributing

Interested in contributing? We :heart: pull requests! See the [Development](DEVELOPING.md) and
[Contribution](CONTRIBUTING.md) guidelines.

# Support

See http://tokbox.com/opentok/support/ for all our support options.

Find a bug? File it on the [Issues](https://github.com/opentok/opentok-php-sdk/issues) page. Hint:
test cases are really helpful!


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 39: 341 (1941)

#### Original name
Dothidea orbis Berk. & Broome, 1873

### Remarks
null


text:
Tools
=====

The tool set
____________

Overview
********

The *portal* application we run as a proxy embeds a whole bunch of tools. Those are all little standalone Python_
scripts that the *portal* will *POpen()* from a temporary directory. They all support a *--help* switch which displays
detailed information, supported parameters and so on.

You can also use the **help** command to print out a complete list of tools.

Container definitions
*********************

In order to deploy our Ochopod_ clusters we need to feed enough information to Marathon_ and deploy specific
constructs (*applications* in the present case). This is all done by the **deploy** tool in a fairly generic fashion.

Now we of course want to pass just enough data to quantify what we need to run, what ports to expose and so on. This
is done via a tiny YAML_ file I call a *container definition*. For instance:

.. code:: yaml

    cluster:  zookeeper
    image:    paugamo/marathon-ec2-zookeeper
    ports:
        - 2181
        - 2888
        - 3888

.. note::

    This YAML_ file is **not** related to the Marathon_ API in any way. This is completely specific to Ochopod_.

This little snippet can be uploaded and passed to the **deploy** tool which will then turn it into a full-fledged
*application* call to the Marathon_ API. Any required setting for Ochopod_ will be added in there as well transparently.

.. note::

    Please note I decided to split image building & deployment as it turned out to be impractical to have the *portal*
    to build/push images on its own. With the current model you are assumed to have images already built somewhere,
    which is still fine.

Debug logging
*************

You can always get access to your Ochopod_ internal log (located at */var/log/ochopod.log*) for all your containers.
Simply use the **log** tool for that. Now the log level is by default set to *INFO* and above. You can force it to
*DEBUG* by switching the optional *debug* setting to true. For instance:

.. code:: yaml

    cluster:  zookeeper
    image:    paugamo/marathon-ec2-zookeeper
    debug:    true
    ports:
        - 2181
        - 2888
        - 3888

This can be helpful to troubleshoot problems at runtime. Beware, the Ochopod_ debug log is quite verbose.

Container settings
******************

The optional *settings* block which can hold arbitrary nested data. This will be turned into a single serialized
JSON snippet and passed to the container as the *$pod* environment variable. Very handy to specify complex runtime
settings. For instance:

.. code:: yaml

    settings:
        jvm-options:
          -Xms1g
          -Xmx2g

You also have the ability to override those settings when using the **deploy** tool. Simply use the *-o* command line
option and point to a local YAML_ file. This file simply maps arbitrary settings for a given fully qualified cluster
identifier. For instance:

.. code:: yaml

    dev.web-server:
        debug: true
        jvm-options:
          -Xmx1g

    prod.web-server:
        debug: false
        jvm-options:
          -Xmx4g

Any container from cluster *web-server* under namespace *dev* will thus see *debug* set to true in its *$pod* variable.

Port mappings
*************

You can define the TCP ports you wish to expose via the lightweight *ports* array setting. Each port binding can be
either an integer (default case mapping this port to some random port on the underlying node), two integers (the first
one being the container port and the second the corresponding port on the host) or an integer followed by a * (same
as before except both ports are the same). This will be mapped to the syntax Marathon_ expects. For instance:

.. code:: yaml

    ports:
        - 3000
        - 5000 *
        - 9000 9001

Verbatim settings
*****************

You can customize your *container definition* even further by adding optional *verbatim* settings. Those will be
included as is when making the REST call to the Marathon_ masters. This is especially useful for idiosyncrasies such
as the resource quotas. For instance:

.. code:: yaml

    cluster:  zookeeper
    image:    paugamo/k8s-ec2-zookeeper
    settings:
    verbatim:
        cpu: 1.0
        mem: 256

    ports:
        - 2181
        - 2888
        - 3888

Your clusters
*************

Once a Ochopod_ cluster is deployed you will get a new *application* (plus a certain number of *tasks*). Its
name will be assembled from the Ochopod_ cluster & namespace plus a unique timestamp. You don't have to worry about
how this is done, what the Marathon_ API looks like and so on.

The **deploy** command allows you to spawn new containers by creating a new (uniquely named) Marathon_ application.
These containers will form (or join) a cluster which depends on what _namespace_ you pick. You can optionally ask for
_cycling_ containers in which case any container previously running in the cluster will be phased out.

The **kill** command will gracefully phase containers out (e.g they will be asked to stop whatever they are doing and
go into idling). Any underlying Marathon_ application whose containers are all dead will the be automatically
deleted.

The **scale** command will scale the number of pod instances in your cluster. This is equivalent to scaling instance
counts on Marathon_ but with Ochopod_ being instructed to prepare itself beforehand.

You can inspect your clusters at runtime using for instance the **grep**, **info** or **log** commands. The **poll**
command will report user-defined metrics.

CI integration
**************

Some of the tools support a *-j* switch which will format their output to JSON. This can be used for instance to
integrate smoothly with a CI system such as Jenkins_ ! Please note the only thing you need to setup is the portal IP
address (e.g no tools to install locally).

The **ping** tool has been provided to allow direct interactions with the running containers. You can send arbitrary
YAML_ data (some commands or maybe some updated configuration settings) to whatever cluster(s). The Ochopod_ script
running on those containers has the option to implement custom logic to react to that YAML_ data and respond back. This
is a great way to quickly add controlling logic driven for instance from a Jenkins_ slave.

.. _Jenkins: https://jenkins-ci.org/
.. _Marathon: https://mesosphere.github.io/marathon/
.. _Mesos: http://mesos.apache.org/
.. _Ochopod: https://github.com/autodesk-cloud/ochopod
.. _Python: https://www.python.org/
.. _YAML: http://yaml.org/


text:
<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">

	<head>
		<title>Simple 2D Particle system</title>

		<style type="text/css">
			body {
				background-color: #000000;
				margin: 0px;
				overflow: hidden;
			}

		</style>
	</head>
	<body >

		<script src="js/ImageParticle.js"></script>
		<script>

window.addEventListener("load", setup);

// screen size variables
var	screenWidth = window.innerWidth,
	screenHeight = window.innerHeight,

	// canvas element and 2D context
	canvas = document.createElement( 'canvas' ),
	context = canvas.getContext( '2d' ),

	mouseX = screenWidth/2,
	mouseY = screenHeight/2,
	mouseDown = false,

	mouseVelX = 0,
	mouseVelY = 0,
	lastMouseX = mouseX,
	lastMouseY = mouseY,

	particles = [],
	maxParticles = 250,
	particleImage = new Image(),
	counter = 0;

particleImage.src = 'img/ParticleCyan.png';

function setup() {

	// CANVAS SET UP

	document.body.appendChild(canvas);
	canvas.width = screenWidth;
	canvas.height = screenHeight;

	initMouseListeners();

	draw();

}

//

function draw() {

	mouseVelX = mouseX-lastMouseX;
	mouseVelY = mouseY-lastMouseY;
	lastMouseX = mouseX;
	lastMouseY = mouseY;

	// make some particles

	 makeParticle(4);

	// clear the canvas
	context.clearRect(0,0, screenWidth, screenHeight);

  	// iteratate through each particle
	for (i=0; i<particles.length; i++) {
		var particle = particles[i];

		// render it
		particle.render(context);

		// and then update. We always render first so particle
		// appears in the starting point.
		particle.update();

	}

	// Keep taking the oldest particles away until we have
	// fewer than the maximum allowed.

	while(particles.length>maxParticles)
		particles.shift();

	counter++;

	window.requestAnimationFrame(draw);
}

function makeParticle(particleCount) {

	for(var i=0; i<particleCount;i++) {

		// create a new particle in the middle of the stage
		var particle = new ImageParticle(particleImage, mouseX, mouseY);

		particle.velX = random(-5,5) +  (mouseVelX*0.3) ;
		particle.velY = random(-5,5) +  (mouseVelY*0.3) ;
		particle.size = random(2,4);

		particle.gravity = 0.06;
		particle.drag = 0.96;
		particle.shrink = 0.98;

		particle.compositeOperation = 'lighter';

		particle.shimmer = true;

		// add it to the array
		particles.push(particle);

	}

}

function initMouseListeners() {
	document.addEventListener('mousemove', onMouseMove, false);
	document.addEventListener( 'mousedown', onMouseDown, false );
	document.addEventListener( 'mouseup', onMouseUp, false );
}

function onMouseMove( event ) {
	mouseX = event.clientX;
	mouseY = event.clientY;
}

function onMouseDown(event) {
	mouseDown = true;
}
function onMouseUp(event) {
	mouseDown = false;
}

function random(min, max) {
	return ((Math.random()*(max-min)) + min);
}

		</script>
	</body>
</html>


text:
package jp.gr.java_conf.kgd.library.water.java.core.value;

/**
 * 値の型を{@link Double}に特化し、デフォルトの挙動を定めた{@link MutableDoubleVector4}。
 *
 * デフォルトの挙動を定めたものであり、原則としてインターフェース部分に使ってはいけません。
 *
 * @author misakura
 */
public interface MutableDoubleVector4Trait extends MutableDoubleVector4, DoubleVector4Trait {
}


text:
package btcec

import (
	"crypto/ecdsa"
	"errors"
	"fmt"
	"math/big"
)

// These constants define the lengths of serialized public keys.
const (
	PubKeyBytesLenCompressed   = 33
	PubKeyBytesLenUncompressed = 65
	PubKeyBytesLenHybrid       = 65
)

func isOdd(a *big.Int) bool {
	return a.Bit(0) == 1
}

// decompressPoint decompresses a point on the given curve given the X point and
// the solution to use.
func decompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, error) {
	// TODO: This will probably only work for secp256k1 due to
	// optimizations.

	// Y = +-sqrt(x^3 + B)
	x3 := new(big.Int).Mul(x, x)
	x3.Mul(x3, x)
	x3.Add(x3, curve.Params().B)

	// now calculate sqrt mod p of x2 + B
	// This code used to do a full sqrt based on tonelli/shanks,
	// but this was replaced by the algorithms referenced in
	// https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294
	y := new(big.Int).Exp(x3, curve.QPlus1Div4(), curve.Params().P)

	if ybit != isOdd(y) {
		y.Sub(curve.Params().P, y)
	}
	if ybit != isOdd(y) {
		return nil, fmt.Errorf("ybit doesn't match oddness")
	}
	return y, nil
}

const (
	pubkeyCompressed   byte = 0x2 // y_bit + x coord
	pubkeyUncompressed byte = 0x4 // x coord + y coord
	pubkeyHybrid       byte = 0x6 // y_bit + x coord + y coord
)

// IsCompressedPubKey returns true the the passed serialized public key has
// been encoded in compressed format, and false otherwise.
func IsCompressedPubKey(pubKey []byte) bool {
	// The public key is only compressed if it is the correct length and
	// the format (first byte) is one of the compressed pubkey values.
	return len(pubKey) == PubKeyBytesLenCompressed &&
		(pubKey[0]&^byte(0x1) == pubkeyCompressed)
}

// ParsePubKey parses a public key for a koblitz curve from a bytestring into a
// ecdsa.Publickey, verifying that it is valid. It supports compressed,
// uncompressed and hybrid signature formats.
func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err error) {
	pubkey := PublicKey{}
	pubkey.Curve = curve

	if len(pubKeyStr) == 0 {
		return nil, errors.New("pubkey string is empty")
	}

	format := pubKeyStr[0]
	ybit := (format & 0x1) == 0x1
	format &= ^byte(0x1)

	switch len(pubKeyStr) {
	case PubKeyBytesLenUncompressed:
		if format != pubkeyUncompressed && format != pubkeyHybrid {
			return nil, fmt.Errorf("invalid magic in pubkey str: "+
				"%d", pubKeyStr[0])
		}

		pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])
		pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])
		// hybrid keys have extra information, make use of it.
		if format == pubkeyHybrid && ybit != isOdd(pubkey.Y) {
			return nil, fmt.Errorf("ybit doesn't match oddness")
		}
	case PubKeyBytesLenCompressed:
		// format is 0x2 | solution, <X coordinate>
		// solution determines which solution of the curve we use.
		/// y^2 = x^3 + Curve.B
		if format != pubkeyCompressed {
			return nil, fmt.Errorf("invalid magic in compressed "+
				"pubkey string: %d", pubKeyStr[0])
		}
		pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])
		pubkey.Y, err = decompressPoint(curve, pubkey.X, ybit)
		if err != nil {
			return nil, err
		}
	default: // wrong!
		return nil, fmt.Errorf("invalid pub key length %d",
			len(pubKeyStr))
	}

	if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 {
		return nil, fmt.Errorf("pubkey X parameter is >= to P")
	}
	if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 {
		return nil, fmt.Errorf("pubkey Y parameter is >= to P")
	}
	if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) {
		return nil, fmt.Errorf("pubkey isn't on secp256k1 curve")
	}
	return &pubkey, nil
}

// PublicKey is an ecdsa.PublicKey with additional functions to
// serialize in uncompressed, compressed, and hybrid formats.
type PublicKey ecdsa.PublicKey

// ToECDSA returns the public key as a *ecdsa.PublicKey.
func (p *PublicKey) ToECDSA() *ecdsa.PublicKey {
	return (*ecdsa.PublicKey)(p)
}

// SerializeUncompressed serializes a public key in a 65-byte uncompressed
// format.
func (p *PublicKey) SerializeUncompressed() []byte {
	b := make([]byte, 0, PubKeyBytesLenUncompressed)
	b = append(b, pubkeyUncompressed)
	b = paddedAppend(32, b, p.X.Bytes())
	return paddedAppend(32, b, p.Y.Bytes())
}

// SerializeCompressed serializes a public key in a 33-byte compressed format.
func (p *PublicKey) SerializeCompressed() []byte {
	b := make([]byte, 0, PubKeyBytesLenCompressed)
	format := pubkeyCompressed
	if isOdd(p.Y) {
		format |= 0x1
	}
	b = append(b, format)
	return paddedAppend(32, b, p.X.Bytes())
}

// SerializeHybrid serializes a public key in a 65-byte hybrid format.
func (p *PublicKey) SerializeHybrid() []byte {
	b := make([]byte, 0, PubKeyBytesLenHybrid)
	format := pubkeyHybrid
	if isOdd(p.Y) {
		format |= 0x1
	}
	b = append(b, format)
	b = paddedAppend(32, b, p.X.Bytes())
	return paddedAppend(32, b, p.Y.Bytes())
}

// IsEqual compares this PublicKey instance to the one passed, returning true if
// both PublicKeys are equivalent. A PublicKey is equivalent to another, if they
// both have the same X and Y coordinate.
func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bool {
	return p.X.Cmp(otherPubKey.X) == 0 &&
		p.Y.Cmp(otherPubKey.Y) == 0
}

// paddedAppend appends the src byte slice to dst, returning the new slice.
// If the length of the source is smaller than the passed size, leading zero
// bytes are appended to the dst slice before appending src.
func paddedAppend(size uint, dst, src []byte) []byte {
	for i := 0; i < int(size)-len(src); i++ {
		dst = append(dst, 0)
	}
	return append(dst, src...)
}


text:
FOUNDATION_EXPORT double LTHPasscodeViewControllerVersionNumber;
FOUNDATION_EXPORT const unsigned char LTHPasscodeViewControllerVersionString[];


text:
I implement specific mappings for FSM.

!! Collaborators

DCNavigator


text:
.. image:: https://readthedocs.org/projects/clamm/badge/?version=latest
.. image:: clam.png
.. inclusion-marker-do-not-remove

#####
ClaMM
#####

*the classical music manager you never knew you needed, until now...*

``clamm`` is a python command line program for managing (and growing) a library of classical music.

* efficiently maps the tags of classical music audio files to sane structures.
* provides tools for working with raw audio streams of (you guessed it!) classical music
* generate playlists using iTunes-like combination logic.

Installation
************

Most (if not all) of the software listed below can be installed using common package managers like brew, apt, pacman, yum, ...

``clamm`` functionality is broken into two main categories, Managing and Adding.

The dependencies for organizing and building a library are

1. ffmpeg_ for audio stream conversion and other low-level audio utilities

2. flac_ for ``metaflac`` which enables tagging FLAC files

The dependencies for adding to a library require macOS first of all. Also,

1. shairport-sync_ for capturing raw PCM data from iTunes

2. osascript_ for controlling iTunes

FAQ
***

Aren't there libraries that do this already?
''''''''''''''''''''''''''''''''''''''''''''

There are already several good music library tools on the market. The best I am aware of is probably is beets_. ``beets`` has great support for interfacing with the open-source tag database musicbrainz_ as well a host of library management functionality and a rich plugin ecosphere. Indeed, ``clamm`` aspires to be like ``beets`` when it grows up.

I tried beets and still have a use for it, but it didn't have the support for classical music tags I wanted. In fairness, beets relies heavily on musicbrainz, and musicbrainz reflects all other audio file tag schemas in skewing toward popular music.

.. _beets: http://beets.io/
.. _musicbrainz: https://musicbrainz.org/ database
.. _ffmpeg: https://github.com/FFmpeg/FFmpeg
.. _flac: https://xiph.org/flac/
.. _shairport-sync: https://github.com/mikebrady/shairport-sync
.. _osascript: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/osascript.1.html


text:
/* vim: set expandtab ts=4 sw=4: */
/*
 * You may redistribute this program and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef DeterminentRandomSeed_H
#define DeterminentRandomSeed_H

#include "crypto/random/seed/RandomSeed.h"
#include "memory/Allocator.h"
#include "util/Linker.h"
Linker_require("crypto/random/test/DeterminentRandomSeed.c")

struct RandomSeed* DeterminentRandomSeed_new(struct Allocator* alloc);

#endif


text:
var numcols = 10;
var numrows = 20;
var boxSize = 30;
var pickColorMode = false;
var currentColor;
var defaultColor;

var setWidth = numcols * boxSize;
var setHeight = numrows * boxSize;

var allBoxes = [];
var canv;

// Color picker
var sliderRed;
var sliderGreen;
var sliderBlue;
var numRed;
var numGreen;
var numBlue;

var buttonPick;
var buttonDefault;
var buttonSetDef;

// Color pallete
var pallet1 = [];
var pallet2 = [];

// Pallete buttons
var palletOpen;
var palletSave;
var palletCopy;

var inPalletCopy = false;
var outputDiv;

// Stroke
var strokeW_slider; // Slider
var strokeW_num;
var strokeW;
var strokeR; // Number
var strokeG;
var strokeB;
var strokeC; // Color

// cols & rows
var colnum;
var rownum;
var colrowbutton;

// Divers
var bgbutton;
var resetbutton;
var copybutton;

// Save
var saveButton;
var openButton;
var exportButton;

// More
var moreDiv;
var extraDiv;
var moreLink;

var doStroke = true;

var previewColor;
var sliderSize;
var numSize;
var debug;

// Import / export
var jsettings;

function setup() {

	canv = createCanvas(setWidth + 1, setHeight + 1);
	canv.parent('canvasDiv');
	canv.attribute("oncontextmenu", "return false;");

	doCOM();

	for (var j = 0; j < numrows; j++) {
		for(var i = 0; i < numcols; i++) {
			allBoxes.push(new aBox(i, j));
		}
	}

	strokeC = color(255,255,255);
	noStroke();
}

function draw() {
  background(255);

  if (pickColorMode) {
	  cursor(CROSS);
  } else {
	  cursor(ARROW);
  }

  var index = -1;
  if (mouseX >= 0 && mouseX < width && mouseY >= 0 && mouseY < height) {
	var i = mouseX / boxSize;
	var j = mouseY / boxSize;
	var index = floor(j) * numcols + floor(i);
	debug.elt.textContent = index;
  }

  for (var i = 0; i < allBoxes.length; i++) {
		allBoxes[i].draw(i == index && ! pickColorMode);
  }

  if (doStroke) {
	  stroke(strokeC);
	  for (var i = 0; i < allBoxes.length; i++) {
			allBoxes[i].drawLine(i == index && ! pickColorMode);
	  }
	  for (var i = 0; i <= numcols; i++) {
		  line(i * boxSize, 0, i * boxSize, height);
	  }
	  for (var i = 0; i <= numrows; i++) {
		  line(0, i * boxSize, width, i * boxSize);
	  }
	  noStroke();
  }

}


text:
from rdflib import BNode, Literal, URIRef, RDF
from rdflib.resource import Resource
from rdflib.term import Identifier

import base64
import random
from datetime import datetime

__all__ = ["create_id", "value2object", "tag_datastore", "getList"]

def create_id():
    return base64.encodestring(str(random.random() * datetime.now().toordinal()).encode('utf8')).decode('utf8').rstrip(
        '=\n')

def value2object(value):
    """
    Suitable for a triple takes a value and returns a Literal, URIRef or BNode
    suitable for a triple"""
    if isinstance(value, Resource):
        return value.identifier

    if isinstance(value, (Identifier, BNode, URIRef)):
        return value

    return Literal(value)

def tag_datastore(fn):
    def f(self,*args,**kw):
        result = fn(self,*args,**kw)
        if result:
            #print self, result
            result.datastore = self
        return result
    return f

# helper function, might be somewhere in rdflib I need to look for it there
def getList(sub, pred=None, db=None):
    """Attempts to return a list from sub (subject that is)
    passed in if it is a Collection or a Container (Bag,Seq or Alt)"""
    if not db:
        db = sub.graph
    if isinstance(sub, Resource):
        sub = sub.identifier
    if pred:
        base = db.value(sub, pred, any=True)
    else:
        # if there was no predicate assume a base node was passed in
        base = sub
    if not isinstance(base, BNode):
        # Doesn't look like a list or a collection, just return
        # multiple values (or an error?)
        val = [o for o in db.objects(sub, pred)]
        return val
    members = []
    first = db.value(base, RDF.first)
    # OK let's work at returning a list if there is an RDF.first
    if first:
        while first:
            members.append(first)
            base = db.value(base, RDF.rest)
            first = db.value(base, RDF.first)
        return members
    # OK let's work at returning a Collection (Seq,Bag or Alt)
    # if was no RDF.first

    i = 1
    # first = db.value(base, RDF._1) # _1 ???
    first = db.value(base, RDF.first)
    if not first:
        raise AttributeError(
            "Not a list, or collection but another type of BNode")
    while first:
        members.append(first)
        i += 1
        first = db.value(base, RDF['_%d' % i])
    return members


text:
package com.exilant.exility.core;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

/***
 * NOT USED. Ideas was to use date-time as time stamp
 *
 */
@Deprecated
public class TimeStampValue extends DateValue {
	private String milliSeconds;

	TimeStampValue(Date dateValue) {
		this.value = dateValue;
	}

	/**
	 * Lets try with milliseconds but getTime() excludes nanoseconds. Anant on
	 * 23 Otc 2013.
	 *
	 * @param str
	 *            Note: This constructor can throw NumberFormatException in case
	 *            str either null or not a valid number.
	 */
	TimeStampValue(String str) {
		this.milliSeconds = str;
		this.value = DateUtility.parseDateTime(str);
	}

	/**
	 * Lets try with milliseconds but getTime() excludes nanoseconds. TimeStamp
	 * also extends Date so we can assign it for java.util.Date value
	 *
	 * @param TimeStamp
	 */
	TimeStampValue(Timestamp dateValue) {
		this.value = dateValue;
		// If In Database this column is null then JDBC returns TimeStamp as
		// null.
		if (null == dateValue) {
			Spit.out("ERROR:  null is not a valid TimeStamp. You may get null related issues in your transactions.");
			return;
		}
		this.milliSeconds = dateValue.toString();
	}

	@Override
	Date getTimeStampValue() {
		return this.value;
	}

	@Override
	DataValueType getValueType() {
		return DataValueType.TIMESTAMP;
	}

	/**
	 * Don't format timeSatmp type values?Once its formated then application has
	 * maintain date formats, timeZones etc with respect to DB server.. Send
	 * timeStamp as milliseconds to client. Client should not change it. Anant
	 * on 24 Oct 2013.
	 */
	@Override
	protected String format() {
		if (null == this.value) {
			this.textValue = Value.NULL_VALUE;
		}

		// return this.textValue = DateUtility.formatDateTime(this.value);
		return String.valueOf(this.milliSeconds);
	}

	@Override
	String getQuotedValue() {
		return Chars.DATE_QUOTE + this.toString() + Chars.DATE_QUOTE;
	}

	@Override
	public void addToPrepearedStatement(PreparedStatement statement, int idx)
			throws SQLException {
		if (this.isNull()) {
			statement.setNull(idx, java.sql.Types.TIMESTAMP);
			return;
		}
		statement.setTimestamp(idx, Timestamp.valueOf(this.milliSeconds));
	}

}


text:
package org.apache.hadoop.yarn.sls.web;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType;
import org.apache.hadoop.yarn.sls.SLSRunner;
import org.apache.hadoop.yarn.sls.scheduler.FairSchedulerMetrics;
import org.apache.hadoop.yarn.sls.scheduler.SchedulerMetrics;
import org.apache.hadoop.yarn.sls.scheduler.SchedulerWrapper;

import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;

@Private
@Unstable
public class SLSWebApp extends HttpServlet {
  private static final long serialVersionUID = 1905162041950251407L;
  private transient Server server;
  private transient SchedulerWrapper wrapper;
  private transient MetricRegistry metrics;
  private transient SchedulerMetrics schedulerMetrics;
  // metrics objects
  private transient Gauge jvmFreeMemoryGauge;
  private transient Gauge jvmMaxMemoryGauge;
  private transient Gauge jvmTotalMemoryGauge;
  private transient Gauge numRunningAppsGauge;
  private transient Gauge numRunningContainersGauge;
  private transient Gauge allocatedMemoryGauge;
  private transient Gauge allocatedVCoresGauge;
  private transient Gauge availableMemoryGauge;
  private transient Gauge availableVCoresGauge;
  private transient Histogram allocateTimecostHistogram;
  private transient Histogram commitSuccessTimecostHistogram;
  private transient Histogram commitFailureTimecostHistogram;
  private transient Histogram handleTimecostHistogram;
  private transient Map<SchedulerEventType, Histogram>
     handleOperTimecostHistogramMap;
  private transient Map<String, Counter> queueAllocatedMemoryCounterMap;
  private transient Map<String, Counter> queueAllocatedVCoresCounterMap;
  private int port;
  private int ajaxUpdateTimeMS = 1000;
  // html page templates
  private String simulateInfoTemplate;
  private String simulateTemplate;
  private String trackTemplate;

  private transient Counter schedulerCommitSuccessCounter;
  private transient Counter schedulerCommitFailureCounter;
  private Long lastTrackingTime;
  private Long lastSchedulerCommitSuccessCount;
  private Long lastSchedulerCommitFailureCount;

  {
    // load templates
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
      simulateInfoTemplate = IOUtils.toString(
          cl.getResourceAsStream("html/simulate.info.html.template"));
      simulateTemplate = IOUtils.toString(
          cl.getResourceAsStream("html/simulate.html.template"));
      trackTemplate = IOUtils.toString(
          cl.getResourceAsStream("html/track.html.template"));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private void readObject(ObjectInputStream in) throws IOException,
      ClassNotFoundException {
    in.defaultReadObject();
    handleOperTimecostHistogramMap = new HashMap<>();
    queueAllocatedMemoryCounterMap = new HashMap<>();
    queueAllocatedVCoresCounterMap = new HashMap<>();
  }

  public SLSWebApp(SchedulerWrapper wrapper, int metricsAddressPort) {
    this.wrapper = wrapper;
    handleOperTimecostHistogramMap = new HashMap<>();
    queueAllocatedMemoryCounterMap = new HashMap<>();
    queueAllocatedVCoresCounterMap = new HashMap<>();
    schedulerMetrics = wrapper.getSchedulerMetrics();
    metrics = schedulerMetrics.getMetrics();
    port = metricsAddressPort;
  }

  public void start() throws Exception {
    final ResourceHandler staticHandler = new ResourceHandler();
    staticHandler.setMimeTypes(new MimeTypes());
    String webRootDir = getClass().getClassLoader().getResource("html").
        toExternalForm();
    staticHandler.setResourceBase(webRootDir);

    Handler handler = new AbstractHandler() {
      @Override
      public void handle(String target, Request baseRequest,
                         HttpServletRequest request,
                         HttpServletResponse response)
          throws IOException, ServletException {
        try{
          // timeunit
          int timeunit = 1000;   // second, divide millionsecond / 1000
          String timeunitLabel = "second";
          if (request.getParameter("u")!= null &&
                  request.getParameter("u").equalsIgnoreCase("m")) {
            timeunit = 1000 * 60;
            timeunitLabel = "minute";
          }

          // http request
          if (target.equals("/")) {
            printPageIndex(request, response);
          } else if (target.equals("/simulate")) {
            printPageSimulate(request, response, timeunit, timeunitLabel);
          } else if (target.equals("/track")) {
            printPageTrack(request, response, timeunit, timeunitLabel);
          } else
            // js/css request
            if (target.startsWith("/js") || target.startsWith("/css")) {
              response.setCharacterEncoding("utf-8");
              staticHandler.handle(target, baseRequest, request, response);
            } else
              // json request
              if (target.equals("/simulateMetrics")) {
                printJsonMetrics(request, response);
              } else if (target.equals("/trackMetrics")) {
                printJsonTrack(request, response);
              }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    };

    server = new Server(port);
    server.setHandler(handler);

    server.start();
  }

  public void stop() throws Exception {
    if (server != null) {
      server.stop();
    }
  }

  /**
   * index html page, show simulation info
   * path ""
   * @param request http request
   * @param response http response
   * @throws java.io.IOException
   */
  private void printPageIndex(HttpServletRequest request,
                              HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    String simulateInfo;
    if (SLSRunner.getSimulateInfoMap().isEmpty()) {
      String empty = "
" +
              "No information available
";
      simulateInfo = MessageFormat.format(simulateInfoTemplate, empty);
    } else {
      StringBuilder info = new StringBuilder();
      for (Map.Entry<String, Object> entry :
              SLSRunner.getSimulateInfoMap().entrySet()) {
        info.append("
");
        info.append("").append(entry.getKey()).append("	");
        info.append("").append(entry.getValue())
                .append("	");
        info.append("
");
      }
      simulateInfo =
              MessageFormat.format(simulateInfoTemplate, info.toString());
    }
    response.getWriter().println(simulateInfo);

    ((Request) request).setHandled(true);
  }

  /**
   * simulate html page, show several real-runtime chart
   * path "/simulate"
   * use d3.js
   * @param request http request
   * @param response http response
   * @throws java.io.IOException
   */
  private void printPageSimulate(HttpServletRequest request,
                                 HttpServletResponse response, int timeunit,
                                 String timeunitLabel)
          throws IOException {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    // queues {0}
    Set<String> queues = wrapper.getTracker().getQueueSet();
    StringBuilder queueInfo = new StringBuilder();

    int i = 0;
    for (String queue : queues) {
      queueInfo.append("legends[4][").append(i).append("] = 'queue.")
              .append(queue).append(".allocated.memory';");
      queueInfo.append("legends[5][").append(i).append("] = 'queue.")
              .append(queue).append(".allocated.vcores';");
      i ++;
    }

    // time unit label {1}
    // time unit {2}
    // ajax update time interval {3}
    String simulateInfo = MessageFormat.format(simulateTemplate,
            queueInfo.toString(), timeunitLabel, "" + timeunit,
            "" + ajaxUpdateTimeMS);
    response.getWriter().println(simulateInfo);

    ((Request) request).setHandled(true);
  }

  /**
   * html page for tracking one queue or job
   * use d3.js
   * @param request http request
   * @param response http response
   * @throws java.io.IOException
   */
  private void printPageTrack(HttpServletRequest request,
                               HttpServletResponse response, int timeunit,
                               String timeunitLabel)
          throws IOException {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    // tracked queues {0}
    StringBuilder trackedQueueInfo = new StringBuilder();
    Set<String> trackedQueues = wrapper.getTracker().getQueueSet();
    for(String queue : trackedQueues) {
      trackedQueueInfo.append("<option value='Queue ").append(queue)
              .append("'>").append(queue).append("</option>");
    }

    // tracked apps {1}
    StringBuilder trackedAppInfo = new StringBuilder();
    Set<String> trackedApps = wrapper.getTracker().getTrackedAppSet();
    for(String job : trackedApps) {
      trackedAppInfo.append("<option value='Job ").append(job)
              .append("'>").append(job).append("</option>");
    }

    // timeunit label {2}
    // time unit {3}
    // ajax update time {4}
    // final html
    String trackInfo = MessageFormat.format(trackTemplate,
            trackedQueueInfo.toString(), trackedAppInfo.toString(),
            timeunitLabel, "" + timeunit, "" + ajaxUpdateTimeMS);
    response.getWriter().println(trackInfo);

    ((Request) request).setHandled(true);
  }

  /**
   * package metrics information in a json and return
   * @param request http request
   * @param response http response
   * @throws java.io.IOException
   */
  private void printJsonMetrics(HttpServletRequest request,
                                HttpServletResponse response)
          throws IOException {
    response.setContentType("text/json");
    response.setStatus(HttpServletResponse.SC_OK);

    response.getWriter().println(generateRealTimeTrackingMetrics());
    ((Request) request).setHandled(true);
  }

  public String generateRealTimeTrackingMetrics() {
    // JVM
    double jvmFreeMemoryGB, jvmMaxMemoryGB, jvmTotalMemoryGB;
    if (jvmFreeMemoryGauge == null &&
            metrics.getGauges().containsKey("variable.jvm.free.memory")) {
      jvmFreeMemoryGauge = metrics.getGauges().get("variable.jvm.free.memory");
    }
    if (jvmMaxMemoryGauge == null &&
            metrics.getGauges().containsKey("variable.jvm.max.memory")) {
      jvmMaxMemoryGauge = metrics.getGauges().get("variable.jvm.max.memory");
    }
    if (jvmTotalMemoryGauge == null &&
            metrics.getGauges().containsKey("variable.jvm.total.memory")) {
      jvmTotalMemoryGauge = metrics.getGauges()
              .get("variable.jvm.total.memory");
    }
    jvmFreeMemoryGB = jvmFreeMemoryGauge == null ? 0 :
            Double.parseDouble(jvmFreeMemoryGauge.getValue().toString())
                    /1024/1024/1024;
    jvmMaxMemoryGB = jvmMaxMemoryGauge == null ? 0 :
            Double.parseDouble(jvmMaxMemoryGauge.getValue().toString())
                    /1024/1024/1024;
    jvmTotalMemoryGB = jvmTotalMemoryGauge == null ? 0 :
            Double.parseDouble(jvmTotalMemoryGauge.getValue().toString())
                    /1024/1024/1024;

    // number of running applications/containers
    String numRunningApps, numRunningContainers;
    if (numRunningAppsGauge == null &&
            metrics.getGauges().containsKey("variable.running.application")) {
      numRunningAppsGauge =
              metrics.getGauges().get("variable.running.application");
    }
    if (numRunningContainersGauge == null &&
            metrics.getGauges().containsKey("variable.running.container")) {
      numRunningContainersGauge =
              metrics.getGauges().get("variable.running.container");
    }
    numRunningApps = numRunningAppsGauge == null ? "0" :
            numRunningAppsGauge.getValue().toString();
    numRunningContainers = numRunningContainersGauge == null ? "0" :
            numRunningContainersGauge.getValue().toString();

    // cluster available/allocate resource
    double allocatedMemoryGB, allocatedVCoresGB,
            availableMemoryGB, availableVCoresGB;
    if (allocatedMemoryGauge == null &&
            metrics.getGauges()
                    .containsKey("variable.cluster.allocated.memory")) {
      allocatedMemoryGauge = metrics.getGauges()
              .get("variable.cluster.allocated.memory");
    }
    if (allocatedVCoresGauge == null &&
            metrics.getGauges()
                    .containsKey("variable.cluster.allocated.vcores")) {
      allocatedVCoresGauge = metrics.getGauges()
              .get("variable.cluster.allocated.vcores");
    }
    if (availableMemoryGauge == null &&
            metrics.getGauges()
                    .containsKey("variable.cluster.available.memory")) {
      availableMemoryGauge = metrics.getGauges()
              .get("variable.cluster.available.memory");
    }
    if (availableVCoresGauge == null &&
            metrics.getGauges()
                    .containsKey("variable.cluster.available.vcores")) {
      availableVCoresGauge = metrics.getGauges()
              .get("variable.cluster.available.vcores");
    }
    allocatedMemoryGB = allocatedMemoryGauge == null ? 0 :
            Double.parseDouble(allocatedMemoryGauge.getValue().toString())/1024;
    allocatedVCoresGB = allocatedVCoresGauge == null ? 0 :
            Double.parseDouble(allocatedVCoresGauge.getValue().toString());
    availableMemoryGB = availableMemoryGauge == null ? 0 :
            Double.parseDouble(availableMemoryGauge.getValue().toString())/1024;
    availableVCoresGB = availableVCoresGauge == null ? 0 :
            Double.parseDouble(availableVCoresGauge.getValue().toString());

    // scheduler operation
    double allocateTimecost, commitSuccessTimecost, commitFailureTimecost,
        handleTimecost;
    if (allocateTimecostHistogram == null &&
            metrics.getHistograms().containsKey(
                    "sampler.scheduler.operation.allocate.timecost")) {
      allocateTimecostHistogram = metrics.getHistograms()
              .get("sampler.scheduler.operation.allocate.timecost");
    }
    if (commitSuccessTimecostHistogram == null &&
        metrics.getHistograms().containsKey(
            "sampler.scheduler.operation.commit.success.timecost")) {
      commitSuccessTimecostHistogram = metrics.getHistograms()
          .get("sampler.scheduler.operation.commit.success.timecost");
    }
    if (commitFailureTimecostHistogram == null &&
        metrics.getHistograms().containsKey(
            "sampler.scheduler.operation.commit.failure.timecost")) {
      commitFailureTimecostHistogram = metrics.getHistograms()
          .get("sampler.scheduler.operation.commit.failure.timecost");
    }
    if (handleTimecostHistogram == null &&
            metrics.getHistograms().containsKey(
                    "sampler.scheduler.operation.handle.timecost")) {
      handleTimecostHistogram = metrics.getHistograms()
              .get("sampler.scheduler.operation.handle.timecost");
    }
    allocateTimecost = allocateTimecostHistogram == null ? 0.0 :
            allocateTimecostHistogram.getSnapshot().getMean()/1000000;
    commitSuccessTimecost = commitSuccessTimecostHistogram == null ? 0.0 :
            commitSuccessTimecostHistogram.getSnapshot().getMean()/1000000;
    commitFailureTimecost = commitFailureTimecostHistogram == null ? 0.0 :
            commitFailureTimecostHistogram.getSnapshot().getMean()/1000000;
    handleTimecost = handleTimecostHistogram == null ? 0.0 :
            handleTimecostHistogram.getSnapshot().getMean()/1000000;
    // various handle operation
    Map<SchedulerEventType, Double> handleOperTimecostMap =
            new HashMap<SchedulerEventType, Double>();
    for (SchedulerEventType e : SchedulerEventType.values()) {
      String key = "sampler.scheduler.operation.handle." + e + ".timecost";
      if (! handleOperTimecostHistogramMap.containsKey(e) &&
              metrics.getHistograms().containsKey(key)) {
        handleOperTimecostHistogramMap.put(e, metrics.getHistograms().get(key));
      }
      double timecost = handleOperTimecostHistogramMap.containsKey(e) ?
          handleOperTimecostHistogramMap.get(e).getSnapshot().getMean()/1000000
              : 0;
      handleOperTimecostMap.put(e, timecost);
    }

    // allocated resource for each queue
    Map<String, Double> queueAllocatedMemoryMap = new HashMap<String, Double>();
    Map<String, Long> queueAllocatedVCoresMap = new HashMap<String, Long>();
    for (String queue : wrapper.getTracker().getQueueSet()) {
      // memory
      String key = "counter.queue." + queue + ".allocated.memory";
      if (! queueAllocatedMemoryCounterMap.containsKey(queue) &&
              metrics.getCounters().containsKey(key)) {
        queueAllocatedMemoryCounterMap.put(queue,
                metrics.getCounters().get(key));
      }
      double queueAllocatedMemoryGB =
              queueAllocatedMemoryCounterMap.containsKey(queue) ?
                  queueAllocatedMemoryCounterMap.get(queue).getCount()/1024.0
                      : 0;
      queueAllocatedMemoryMap.put(queue, queueAllocatedMemoryGB);
      // vCores
      key = "counter.queue." + queue + ".allocated.cores";
      if (! queueAllocatedVCoresCounterMap.containsKey(queue) &&
              metrics.getCounters().containsKey(key)) {
        queueAllocatedVCoresCounterMap.put(
                queue, metrics.getCounters().get(key));
      }
      long queueAllocatedVCores =
              queueAllocatedVCoresCounterMap.containsKey(queue) ?
                      queueAllocatedVCoresCounterMap.get(queue).getCount(): 0;
      queueAllocatedVCoresMap.put(queue, queueAllocatedVCores);
    }

    // calculate commit throughput, unit is number/second
    if (schedulerCommitSuccessCounter == null && metrics.getCounters()
        .containsKey("counter.scheduler.operation.commit.success")) {
      schedulerCommitSuccessCounter = metrics.getCounters()
          .get("counter.scheduler.operation.commit.success");
    }
    if (schedulerCommitFailureCounter == null && metrics.getCounters()
        .containsKey("counter.scheduler.operation.commit.failure")) {
      schedulerCommitFailureCounter = metrics.getCounters()
          .get("counter.scheduler.operation.commit.failure");
    }
    long schedulerCommitSuccessThroughput = 0;
    long schedulerCommitFailureThroughput = 0;
    if (schedulerCommitSuccessCounter != null
        && schedulerCommitFailureCounter != null) {
      long currentTrackingTime = System.currentTimeMillis();
      long currentSchedulerCommitSucessCount =
          schedulerCommitSuccessCounter.getCount();
      long currentSchedulerCommitFailureCount =
          schedulerCommitFailureCounter.getCount();
      if (lastTrackingTime != null) {
        double intervalSeconds =
            (double) (currentTrackingTime - lastTrackingTime) / 1000;
        schedulerCommitSuccessThroughput = Math.round(
            (currentSchedulerCommitSucessCount
                - lastSchedulerCommitSuccessCount) / intervalSeconds);
        schedulerCommitFailureThroughput = Math.round(
            (currentSchedulerCommitFailureCount
                - lastSchedulerCommitFailureCount) / intervalSeconds);
      }
      lastTrackingTime = currentTrackingTime;
      lastSchedulerCommitSuccessCount = currentSchedulerCommitSucessCount;
      lastSchedulerCommitFailureCount = currentSchedulerCommitFailureCount;
    }

    // package results
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    sb.append("\"time\":" ).append(System.currentTimeMillis())
            .append(",\"jvm.free.memory\":").append(jvmFreeMemoryGB)
            .append(",\"jvm.max.memory\":").append(jvmMaxMemoryGB)
            .append(",\"jvm.total.memory\":").append(jvmTotalMemoryGB)
            .append(",\"running.applications\":").append(numRunningApps)
            .append(",\"running.containers\":").append(numRunningContainers)
            .append(",\"cluster.allocated.memory\":").append(allocatedMemoryGB)
            .append(",\"cluster.allocated.vcores\":").append(allocatedVCoresGB)
            .append(",\"cluster.available.memory\":").append(availableMemoryGB)
            .append(",\"cluster.available.vcores\":").append(availableVCoresGB);

    for (String queue : wrapper.getTracker().getQueueSet()) {
      sb.append(",\"queue.").append(queue).append(".allocated.memory\":")
              .append(queueAllocatedMemoryMap.get(queue));
      sb.append(",\"queue.").append(queue).append(".allocated.vcores\":")
              .append(queueAllocatedVCoresMap.get(queue));
    }
    // scheduler allocate & handle
    sb.append(",\"scheduler.allocate.timecost\":").append(allocateTimecost);
    sb.append(",\"scheduler.commit.success.timecost\":")
        .append(commitSuccessTimecost);
    sb.append(",\"scheduler.commit.failure.timecost\":")
        .append(commitFailureTimecost);
    sb.append(",\"scheduler.commit.success.throughput\":")
        .append(schedulerCommitSuccessThroughput);
    sb.append(",\"scheduler.commit.failure.throughput\":")
        .append(schedulerCommitFailureThroughput);
    sb.append(",\"scheduler.handle.timecost\":").append(handleTimecost);
    for (SchedulerEventType e : SchedulerEventType.values()) {
      sb.append(",\"scheduler.handle-").append(e).append(".timecost\":")
              .append(handleOperTimecostMap.get(e));
    }
    sb.append("}");
    return sb.toString();
  }

  /**
   * package metrics information for one tracked queue/app
   * only support FairScheduler currently
   * @throws java.io.IOException
   */
  private void printJsonTrack(HttpServletRequest request,
                              HttpServletResponse response) throws IOException {
    response.setContentType("text/json");
    response.setStatus(HttpServletResponse.SC_OK);

    StringBuilder sb = new StringBuilder();
    if(schedulerMetrics instanceof FairSchedulerMetrics) {
      String para = request.getParameter("t");
      if (para.startsWith("Job ")) {
        String appId = para.substring("Job ".length());

        sb.append("{");
        sb.append("\"time\": ").append(System.currentTimeMillis()).append(",");
        sb.append("\"appId\": \"").append(appId).append("\"");
        for(String metric : this.schedulerMetrics.getAppTrackedMetrics()) {
          String key = "variable.app." + appId + "." + metric;
          sb.append(",\"").append(metric).append("\": ");
          if (metrics.getGauges().containsKey(key)) {
            double memoryGB =
                    Double.parseDouble(
                            metrics.getGauges().get(key).getValue().toString())
                            / 1024;
            sb.append(memoryGB);
          } else {
            sb.append(-1);
          }
        }
        sb.append("}");

      } else if(para.startsWith("Queue ")) {
        String queueName = para.substring("Queue ".length());
        sb.append("{");
        sb.append("\"time\": ").append(System.currentTimeMillis()).append(",");
        sb.append("\"queueName\": \"").append(queueName).append("\"");
        for(String metric : this.schedulerMetrics.getQueueTrackedMetrics()) {
          String key = "variable.queue." + queueName + "." + metric;
          sb.append(",\"").append(metric).append("\": ");
          if (metrics.getGauges().containsKey(key)) {
            double memoryGB =
                    Double.parseDouble(
                            metrics.getGauges().get(key).getValue().toString())
                            / 1024;
            sb.append(memoryGB);
          } else {
            sb.append(-1);
          }
        }
        sb.append("}");
      }
    }
    String output = sb.toString();
    if (output.isEmpty()) {
      output = "[]";
    }
    response.getWriter().println(output);
    // package result
    ((Request) request).setHandled(true);
  }
}


text:
import {
  Directive,
  DoCheck,
  Inject,
  Input,
  KeyValueChanges,
  KeyValueDiffers,
  Optional,
  Renderer2,
  Type,
} from '@angular/core';

import {
  DynamicComponentInjector,
  DynamicComponentInjectorToken,
} from '../component-injector';

export interface AttributesMap {
  [key: string]: string;
}

interface AttributeActions {
  set: AttributesMap;
  remove: string[];
}

@Directive({
  selector: '[ndcDynamicAttributes],[ngComponentOutletNdcDynamicAttributes]',
  exportAs: 'ndcDynamicAttributes',
})
export class DynamicAttributesDirective implements DoCheck {
  @Input()
  ndcDynamicAttributes?: AttributesMap | null;
  @Input()
  ngComponentOutletNdcDynamicAttributes?: AttributesMap | null;

  private attrsDiffer = this.differs.find({}).create<string, string>();
  private lastCompType?: Type<unknown>;
  private lastAttrActions?: AttributeActions;

  private get _attributes() {
    return (
      this.ndcDynamicAttributes ||
      this.ngComponentOutletNdcDynamicAttributes ||
      {}
    );
  }

  private get nativeElement() {
    return this.componentInjector?.componentRef?.location.nativeElement;
  }

  private get compType() {
    return this.componentInjector?.componentRef?.componentType;
  }

  private get isCompChanged() {
    if (this.lastCompType !== this.compType) {
      this.lastCompType = this.compType;
      return true;
    }
    return false;
  }

  constructor(
    private renderer: Renderer2,
    private differs: KeyValueDiffers,
    @Inject(DynamicComponentInjectorToken)
    @Optional()
    private componentInjector?: DynamicComponentInjector,
  ) {}

  ngDoCheck(): void {
    const isCompChanged = this.isCompChanged;
    const changes = this.attrsDiffer.diff(this._attributes);

    if (changes) {
      this.lastAttrActions = this.changesToAttrActions(changes);
    }

    if (changes || (isCompChanged && this.lastAttrActions)) {
      this.updateAttributes(this.lastAttrActions);
    }
  }

  setAttribute(name: string, value: string, namespace?: string) {
    if (this.nativeElement) {
      this.renderer.setAttribute(this.nativeElement, name, value, namespace);
    }
  }

  removeAttribute(name: string, namespace?: string) {
    if (this.nativeElement) {
      this.renderer.removeAttribute(this.nativeElement, name, namespace);
    }
  }

  private updateAttributes(actions?: AttributeActions) {
    if (!this.compType || !actions) {
      return;
    }

    Object.keys(actions.set).forEach((key) =>
      this.setAttribute(key, actions.set[key]),
    );

    actions.remove.forEach((key) => this.removeAttribute(key));
  }

  private changesToAttrActions(
    changes: KeyValueChanges<string, string>,
  ): AttributeActions {
    const attrActions: AttributeActions = {
      set: {},
      remove: [],
    };

    changes.forEachAddedItem((r) => (attrActions.set[r.key] = r.currentValue!));
    changes.forEachChangedItem(
      (r) => (attrActions.set[r.key] = r.currentValue!),
    );
    changes.forEachRemovedItem((r) => attrActions.remove.push(r.key));

    return attrActions;
  }
}


text:
module.exports = function (grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            options: {
                separator: ''
            },
            library: {
                src: [
                    'src/angularFilterPack/angularFilterPack.prefix',
                    'src/angularFilterPack/angularFilterPack.js',
                    'src/angularFilterPack/directives/**/*.js',
                    'src/angularFilterPack/filters/**/*.js',
                    'src/angularFilterPack/services/**/*.js',
                    'src/angularFilterPack/angularFilterPack.suffix'
                ],
                dest: 'dist/angular-filter-pack.js'
            }
        },
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
            },
            jid: {
                files: {
                    'dist/angular-filter-pack.min.js': ['<%= concat.library.dest %>']
                }
            }
        },
        jshint: {
            beforeConcat: {
                src: ['gruntfile.js', 'angularFilterPack/**/*.js']
            },
            afterConcat: {
                src: [
                    '<%= concat.library.dest %>'
                ]
            },
            options: {
                // options here to override JSHint defaults
                globals: {
                    jQuery: true,
                    console: true,
                    module: true,
                    document: true,
                    angular: true
                },
                globalstrict: false
            }
        },
        watch: {
            options: {
                livereload: true
            },
            files: [
                'Gruntfile.js',
                'src/**/*'
            ],
            tasks: ['default']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.registerTask('default', ['jshint:beforeConcat', 'concat', 'jshint:afterConcat', 'uglify']);
    grunt.registerTask('livereload', ['default', 'watch']);

};


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

	<diskStore path="java.io.tmpdir/invest/ehcache" />

	<!-- DefaultCache setting. -->
	<defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
		overflowToDisk="true" maxEntriesLocalDisk="100000" />
    <cache name="queryCache"
           maxElementsInMemory="10000"
           overflowToDisk="true"
           eternal="true"
           timeToLiveSeconds="0"
           timeToIdleSeconds="0"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600"/>
    <!-- <cache name="org.apache.shiro.realm.text.PropertiesRealm-0-accounts"
           maxElementsInMemory="1000"
           eternal="true"
           overflowToDisk="true"/> -->

</ehcache>