text:
package com.yahoo.ycsb.db.arangodb;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.arangodb.ArangoCursor;
import com.arangodb.ArangoDB;
import com.arangodb.ArangoDBException;
import com.arangodb.Protocol;
import com.arangodb.entity.BaseDocument;
import com.arangodb.model.DocumentCreateOptions;
import com.arangodb.model.TransactionOptions;
import com.arangodb.util.MapBuilder;
import com.arangodb.velocypack.VPackBuilder;
import com.arangodb.velocypack.VPackSlice;
import com.arangodb.velocypack.ValueType;
import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import com.yahoo.ycsb.Status;
import com.yahoo.ycsb.StringByteIterator;

/**
 * ArangoDB binding for YCSB framework using the ArangoDB Inc. driver
 *

 * See the README.md for configuration information.
 *

 *
 * @see ArangoDB Inc.
 *      driver
 */
public class ArangoDBClient extends DB {

  private static Logger logger = LoggerFactory.getLogger(ArangoDBClient.class);

  /**
   * Count the number of times initialized to teardown on the last
   * {@link #cleanup()}.
   */
  private static final AtomicInteger INIT_COUNT = new AtomicInteger(0);

  /** ArangoDB Driver related, Singleton. */
  private ArangoDB arangoDB;
  private String databaseName = "ycsb";
  private String collectionName;
  private Boolean dropDBBeforeRun;
  private Boolean waitForSync = false;
  private Boolean transactionUpdate = false;

  /**
   * Initialize any state for this DB. Called once per DB instance; there is
   * one DB instance per client thread.
   *
   * Actually, one client process will share one DB instance here.(Coincide to
   * mongoDB driver)
   */
  @Override
  public void init() throws DBException {
    synchronized (ArangoDBClient.class) {
      Properties props = getProperties();

      collectionName = props.getProperty("table", "usertable");

      // Set the DB address
      String ip = props.getProperty("arangodb.ip", "localhost");
      String portStr = props.getProperty("arangodb.port", "8529");
      int port = Integer.parseInt(portStr);

      // Set network protocol
      String protocolStr = props.getProperty("arangodb.protocol", "VST");
      Protocol protocol = Protocol.valueOf(protocolStr);

      // If clear db before run
      String dropDBBeforeRunStr = props.getProperty("arangodb.dropDBBeforeRun", "false");
      dropDBBeforeRun = Boolean.parseBoolean(dropDBBeforeRunStr);

      // Set the sync mode
      String waitForSyncStr = props.getProperty("arangodb.waitForSync", "false");
      waitForSync = Boolean.parseBoolean(waitForSyncStr);

      // Set if transaction for update
      String transactionUpdateStr = props.getProperty("arangodb.transactionUpdate", "false");
      transactionUpdate = Boolean.parseBoolean(transactionUpdateStr);

      // Init ArangoDB connection
      try {
        arangoDB = new ArangoDB.Builder().host(ip).port(port).useProtocol(protocol).build();
      } catch (Exception e) {
        logger.error("Failed to initialize ArangoDB", e);
        System.exit(-1);
      }

      if(INIT_COUNT.getAndIncrement() == 0) {
        // Init the database
        if (dropDBBeforeRun) {
          // Try delete first
          try {
            arangoDB.db(databaseName).drop();
          } catch (ArangoDBException e) {
            logger.info("Fail to delete DB: {}", databaseName);
          }
        }
        try {
          arangoDB.createDatabase(databaseName);
          logger.info("Database created: " + databaseName);
        } catch (ArangoDBException e) {
          logger.error("Failed to create database: {} with ex: {}", databaseName, e.toString());
        }
        try {
          arangoDB.db(databaseName).createCollection(collectionName);
          logger.info("Collection created: " + collectionName);
        } catch (ArangoDBException e) {
          logger.error("Failed to create collection: {} with ex: {}", collectionName, e.toString());
        }
        logger.info("ArangoDB client connection created to {}:{}", ip, port);

        // Log the configuration
        logger.info("Arango Configuration: dropDBBeforeRun: {}; address: {}:{}; databaseName: {};"
                    + " waitForSync: {}; transactionUpdate: {};",
                    dropDBBeforeRun, ip, port, databaseName, waitForSync, transactionUpdate);
      }
    }
  }

  /**
   * Cleanup any state for this DB. Called once per DB instance; there is one
   * DB instance per client thread.
   *
   * Actually, one client process will share one DB instance here.(Coincide to
   * mongoDB driver)
   */
  @Override
  public void cleanup() throws DBException {
    if (INIT_COUNT.decrementAndGet() == 0) {
      arangoDB.shutdown();
      arangoDB = null;
      logger.info("Local cleaned up.");
    }
  }

  /**
   * Insert a record in the database. Any field/value pairs in the specified
   * values HashMap will be written into the record with the specified record
   * key.
   *
   * @param table
   *      The name of the table
   * @param key
   *      The record key of the record to insert.
   * @param values
   *      A HashMap of field/value pairs to insert in the record
   * @return Zero on success, a non-zero error code on error. See the
   *     {@link DB} class's description for a discussion of error codes.
   */
  @Override
  public Status insert(String table, String key, Map<String, ByteIterator> values) {
    try {
      BaseDocument toInsert = new BaseDocument(key);
      for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
        toInsert.addAttribute(entry.getKey(), byteIteratorToString(entry.getValue()));
      }
      DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(waitForSync);
      arangoDB.db(databaseName).collection(table).insertDocument(toInsert, options);
      return Status.OK;
    } catch (ArangoDBException e) {
      logger.error("Exception while trying insert {} {} with ex {}", table, key, e.toString());
    }
    return Status.ERROR;
  }

  /**
   * Read a record from the database. Each field/value pair from the result
   * will be stored in a HashMap.
   *
   * @param table
   *      The name of the table
   * @param key
   *      The record key of the record to read.
   * @param fields
   *      The list of fields to read, or null for all of them
   * @param result
   *      A HashMap of field/value pairs for the result
   * @return Zero on success, a non-zero error code on error or "not found".
   */
  @Override
  public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
    try {
      VPackSlice document = arangoDB.db(databaseName).collection(table).getDocument(key, VPackSlice.class, null);
      if (!this.fillMap(result, document, fields)) {
        return Status.ERROR;
      }
      return Status.OK;
    } catch (ArangoDBException e) {
      logger.error("Exception while trying read {} {} with ex {}", table, key, e.toString());
    }
    return Status.ERROR;
  }

  /**
   * Update a record in the database. Any field/value pairs in the specified
   * values HashMap will be written into the record with the specified record
   * key, overwriting any existing values with the same field name.
   *
   * @param table
   *      The name of the table
   * @param key
   *      The record key of the record to write.
   * @param values
   *      A HashMap of field/value pairs to update in the record
   * @return Zero on success, a non-zero error code on error. See this class's
   *     description for a discussion of error codes.
   */
  @Override
  public Status update(String table, String key, Map<String, ByteIterator> values) {
    try {
      if (!transactionUpdate) {
        BaseDocument updateDoc = new BaseDocument();
        for (Entry<String, ByteIterator> field : values.entrySet()) {
          updateDoc.addAttribute(field.getKey(), byteIteratorToString(field.getValue()));
        }
        arangoDB.db(databaseName).collection(table).updateDocument(key, updateDoc);
        return Status.OK;
      } else {
        // id for documentHandle
        String transactionAction = "function (id) {"
               // use internal database functions
            + "var db = require('internal').db;"
              // collection.update(document, data, overwrite, keepNull, waitForSync)
            + String.format("db._update(id, %s, true, false, %s);}",
                mapToJson(values), Boolean.toString(waitForSync).toLowerCase());
        TransactionOptions options = new TransactionOptions();
        options.writeCollections(table);
        options.params(createDocumentHandle(table, key));
        arangoDB.db(databaseName).transaction(transactionAction, Void.class, options);
        return Status.OK;
      }
    } catch (ArangoDBException e) {
      logger.error("Exception while trying update {} {} with ex {}", table, key, e.toString());
    }
    return Status.ERROR;
  }

  /**
   * Delete a record from the database.
   *
   * @param table
   *      The name of the table
   * @param key
   *      The record key of the record to delete.
   * @return Zero on success, a non-zero error code on error. See the
   *     {@link DB} class's description for a discussion of error codes.
   */
  @Override
  public Status delete(String table, String key) {
    try {
      arangoDB.db(databaseName).collection(table).deleteDocument(key);
      return Status.OK;
    } catch (ArangoDBException e) {
      logger.error("Exception while trying delete {} {} with ex {}", table, key, e.toString());
    }
    return Status.ERROR;
  }

  /**
   * Perform a range scan for a set of records in the database. Each
   * field/value pair from the result will be stored in a HashMap.
   *
   * @param table
   *      The name of the table
   * @param startkey
   *      The record key of the first record to read.
   * @param recordcount
   *      The number of records to read
   * @param fields
   *      The list of fields to read, or null for all of them
   * @param result
   *      A Vector of HashMaps, where each HashMap is a set field/value
   *      pairs for one record
   * @return Zero on success, a non-zero error code on error. See the
   *     {@link DB} class's description for a discussion of error codes.
   */
  @Override
  public Status scan(String table, String startkey, int recordcount, Set<String> fields,
      Vector<HashMap<String, ByteIterator>> result) {
    ArangoCursor<VPackSlice> cursor = null;
    try {
      String aqlQuery = String.format(
          "FOR target IN %s FILTER target._key >= @key SORT target._key ASC LIMIT %d RETURN %s ", table,
          recordcount, constructReturnForAQL(fields, "target"));

      Map<String, Object> bindVars = new MapBuilder().put("key", startkey).get();
      cursor = arangoDB.db(databaseName).query(aqlQuery, bindVars, null, VPackSlice.class);
      while (cursor.hasNext()) {
        VPackSlice aDocument = cursor.next();
        HashMap<String, ByteIterator> aMap = new HashMap<String, ByteIterator>(aDocument.size());
        if (!this.fillMap(aMap, aDocument)) {
          return Status.ERROR;
        }
        result.add(aMap);
      }
      return Status.OK;
    } catch (Exception e) {
      logger.error("Exception while trying scan {} {} {} with ex {}", table, startkey, recordcount, e.toString());
    } finally {
      if (cursor != null) {
        try {
          cursor.close();
        } catch (IOException e) {
          logger.error("Fail to close cursor", e);
        }
      }
    }
    return Status.ERROR;
  }

  private String createDocumentHandle(String collection, String documentKey) throws ArangoDBException {
    validateCollectionName(collection);
    return collection + "/" + documentKey;
  }

  private void validateCollectionName(String name) throws ArangoDBException {
    if (name.indexOf('/') != -1) {
      throw new ArangoDBException("does not allow '/' in name.");
    }
  }

  private String constructReturnForAQL(Set<String> fields, String targetName) {
    // Construct the AQL query string.
    String resultDes = targetName;
    if (fields != null && fields.size() != 0) {
      StringBuilder builder = new StringBuilder("{");
      for (String field : fields) {
        builder.append(String.format("\n\"%s\" : %s.%s,", field, targetName, field));
      }
      //Replace last ',' to newline.
      builder.setCharAt(builder.length() - 1, '\n');
      builder.append("}");
      resultDes = builder.toString();
    }
    return resultDes;
  }

  private boolean fillMap(Map<String, ByteIterator> resultMap, VPackSlice document) {
    return fillMap(resultMap, document, null);
  }

  /**
   * Fills the map with the properties from the BaseDocument.
   *
   * @param resultMap
   *      The map to fill/
   * @param document
   *      The record to read from
   * @param fields
   *      The list of fields to read, or null for all of them
   * @return isSuccess
   */
  private boolean fillMap(Map<String, ByteIterator> resultMap, VPackSlice document, Set<String> fields) {
    if (fields == null || fields.size() == 0) {
      for (Iterator<Entry<String, VPackSlice>> iterator = document.objectIterator(); iterator.hasNext();) {
        Entry<String, VPackSlice> next = iterator.next();
        VPackSlice value = next.getValue();
        if (value.isString()) {
          resultMap.put(next.getKey(), stringToByteIterator(value.getAsString()));
        } else if (!value.isCustom()) {
          logger.error("Error! Not the format expected! Actually is {}",
              value.getClass().getName());
          return false;
        }
      }
    } else {
      for (String field : fields) {
        VPackSlice value = document.get(field);
        if (value.isString()) {
          resultMap.put(field, stringToByteIterator(value.getAsString()));
        } else if (!value.isCustom()) {
          logger.error("Error! Not the format expected! Actually is {}",
              value.getClass().getName());
          return false;
        }
      }
    }
    return true;
  }

  private String byteIteratorToString(ByteIterator byteIter) {
    return new String(byteIter.toArray());
  }

  private ByteIterator stringToByteIterator(String content) {
    return new StringByteIterator(content);
  }

  private String mapToJson(Map<String, ByteIterator> values) {
    VPackBuilder builder = new VPackBuilder().add(ValueType.OBJECT);
    for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
      builder.add(entry.getKey(), byteIteratorToString(entry.getValue()));
    }
    builder.close();
    return arangoDB.util().deserialize(builder.slice(), String.class);
  }

}


text:
package mobi.omegacentauri.ptimer;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.MergeCursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * After a ringtone has been saved, this activity lets you pick a contact
 * and assign the ringtone to that contact.
 */
public class ChooseContactActivity
    extends ListActivity
    implements TextWatcher
{
    private TextView mFilter;
    private SimpleCursorAdapter mAdapter;
    private Uri mRingtoneUri;

    public ChooseContactActivity() {
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setTitle(R.string.choose_contact_title);

        Intent intent = getIntent();
        mRingtoneUri = intent.getData();

        // Inflate our UI from its XML layout description.
        setContentView(R.layout.choose_contact);

        try {
            mAdapter = new SimpleCursorAdapter(
                this,
                // Use a template that displays a text view
                R.layout.contact_row,
                // Give the cursor to the list adatper
                createCursor(""),
                // Map from database columns...
                new String[] {
                    People.CUSTOM_RINGTONE,
                    People.STARRED,
                    People.DISPLAY_NAME },
                // To widget ids in the row layout...
                new int[] {
                    R.id.row_ringtone,
                    R.id.row_starred,
                    R.id.row_display_name });

            mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
                    public boolean setViewValue(View view,
                                                Cursor cursor,
                                                int columnIndex) {
                        String name = cursor.getColumnName(columnIndex);
                        String value = cursor.getString(columnIndex);
                        if (name.equals(People.CUSTOM_RINGTONE)) {
                            if (value != null && value.length() > 0) {
                                view.setVisibility(View.VISIBLE);
                            } else  {
                                view.setVisibility(View.INVISIBLE);
                            }
                            return true;
                        }
                        if (name.equals(People.STARRED)) {
                            if (value != null && value.equals("1")) {
                                view.setVisibility(View.VISIBLE);
                            } else  {
                                view.setVisibility(View.INVISIBLE);
                            }
                            return true;
                        }

                        return false;
                    }
                });

            setListAdapter(mAdapter);

            // On click, assign ringtone to contact
            getListView().setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView parent,
                                            View view,
                                            int position,
                                            long id) {
                        assignRingtoneToContact();
                    }
                });

        } catch (SecurityException e) {
            // No permission to retrieve contacts?
            Log.e("Ringdroid", e.toString());
        }

        mFilter = (TextView) findViewById(R.id.search_filter);
        if (mFilter != null) {
            mFilter.addTextChangedListener(this);
        }
    }

    private boolean isEclairOrLater() {
	return Build.VERSION.SDK_INT >= 5;
    }

    private Uri getContactContentUri() {
	if (isEclairOrLater()) {
	    // ContactsContract.Contacts.CONTENT_URI
	    return Uri.parse("content://com.android.contacts/contacts");
	} else {
	    return Contacts.People.CONTENT_URI;
	}
    }

    private void assignRingtoneToContact() {
        Cursor c = mAdapter.getCursor();
        int dataIndex = c.getColumnIndexOrThrow(People._ID);
        String contactId = c.getString(dataIndex);

        dataIndex = c.getColumnIndexOrThrow(People.DISPLAY_NAME);
        String displayName = c.getString(dataIndex);

        Uri uri = Uri.withAppendedPath(getContactContentUri(), contactId);

        ContentValues values = new ContentValues();
        values.put(People.CUSTOM_RINGTONE, mRingtoneUri.toString());
        getContentResolver().update(uri, values, null, null);

        String message =
            getResources().getText(R.string.success_contact_ringtone) +
            " " +
            displayName;

        Toast.makeText(this, message, Toast.LENGTH_SHORT)
            .show();
        finish();
        return;
    }

    private Cursor createCursor(String filter) {
        String selection;
        if (filter != null && filter.length() > 0) {
            selection = "(DISPLAY_NAME LIKE \"%" + filter + "%\")";
        } else {
            selection = null;
        }
        Cursor cursor = managedQuery(
            getContactContentUri(),
            new String[] {
                People._ID,
                People.CUSTOM_RINGTONE,
                People.DISPLAY_NAME,
                People.LAST_TIME_CONTACTED,
                People.STARRED,
                People.TIMES_CONTACTED },
            selection,
            null,
            "STARRED DESC, " +
	    "TIMES_CONTACTED DESC, " +
	    "LAST_TIME_CONTACTED DESC, " +
	    "DISPLAY_NAME ASC");

        Log.i("Ringdroid", cursor.getCount() + " contacts");

        return cursor;
    }

    public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after) {
    }

    public void onTextChanged(CharSequence s,
                              int start, int before, int count) {
    }

    public void afterTextChanged(Editable s) {
        String filterStr = mFilter.getText().toString();
        mAdapter.changeCursor(createCursor(filterStr));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.terasology.utilities.tree;

import org.junit.jupiter.api.Test;

import java.util.Collection;
import java.util.Iterator;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

public class SpaceTreeTest {
    @Test
    public void test2DTreeErrors() {
        SpaceTree<Object> tree = new SpaceTree<>(2);

        try {
            tree.add(null, new Object());
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }

        try {
            tree.add(new float[1], new Object());
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }

        try {
            tree.add(new float[3], new Object());
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }

        try {
            tree.add(new float[2], null);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }

        try {
            tree.remove(null);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }

        try {
            tree.remove(new float[1]);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }

        try {
            tree.remove(new float[3]);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException exp) {
            // Expected
        }
    }

    @Test
    public void test2DTreeValues() {
        SpaceTree<Object> tree = new SpaceTree<>(2);

        assertNull(tree.remove(new float[2]));

        Object obj1 = new Object();
        Object obj2 = new Object();

        assertNull(tree.add(new float[2], obj1));
        assertSame(obj1, tree.add(new float[2], obj2));
        assertSame(obj2, tree.remove(new float[2]));

        assertNull(tree.remove(new float[2]));
    }

    @Test
    public void test3DTreeBasicProximity() {
        SpaceTree<Object> tree = new SpaceTree<>(3);

        Object obj1 = new Object();
        Object obj2 = new Object();

        float[] location1 = {0f, 0f, 0f};
        float[] location2 = {10f, 10f, 10f};

        tree.add(location1, obj1);
        tree.add(location2, obj2);

        assertSame(obj1, tree.findNearest(new float[]{3f, 3f, 3f}).value);
        assertSame(obj2, tree.findNearest(new float[]{100f, 100f, 0f}).value);

        float[] location3 = {5f, 5f, 5f};
        Object obj3 = new Object();
        tree.add(location3, obj3);

        assertSame(obj3, tree.findNearest(new float[]{3f, 3f, 3f}).value);
        assertSame(obj2, tree.findNearest(new float[]{100f, 100f, 0f}).value);
    }

    @Test
    public void test3DProximityTest() {
        SpaceTree<Object> tree = new SpaceTree<>(3);

        Object[] objects = {new Object(), new Object(), new Object(), new Object(), new Object(), new Object()};
        float[][] locations = {{0f, 0f, 0f}, {0f, 0f, 1f}, {0f, 0f, 2f}, {0f, 0f, 3f}, {0f, 0f, 4f}, {0f, 0f, 5f}};

        for (int i = 0; i < objects.length; i++) {
            tree.add(locations[i], objects[i]);
        }

        float delta = 0.0000001f;

        for (int i = 0; i < objects.length; i++) {
            DimensionalMap.Entry<Object> nearest = tree.findNearest(locations[i]);
            assertSame(objects[i], nearest.value);
            assertEquals(0f, nearest.distance, delta);
        }

        DimensionalMap.Entry<Object> nearestOne = tree.findNearest(new float[]{0f, 0f, -1f});
        assertSame(objects[0], nearestOne.value);
        assertEquals(1f, nearestOne.distance, delta);

        DimensionalMap.Entry<Object> nearestRoot = tree.findNearest(new float[]{0f, 1f, 6f});
        assertSame(objects[5], nearestRoot.value);
        assertEquals((float) Math.sqrt(2), nearestRoot.distance, delta);

        assertNull(tree.findNearest(new float[]{0f, 0f, -1f}, 0.5f));

        Collection<DimensionalMap.Entry<Object>> nearestTwo = tree.findNearest(new float[]{0f, 0f, 0f}, 2);

        assertEquals(2, nearestTwo.size());
        Iterator<DimensionalMap.Entry<Object>> nearestTwoIterator = nearestTwo.iterator();
        DimensionalMap.Entry<Object> firstNearest = nearestTwoIterator.next();
        DimensionalMap.Entry<Object> secondNearest = nearestTwoIterator.next();

        assertSame(objects[0], firstNearest.value);
        assertSame(objects[1], secondNearest.value);
        assertEquals(0, firstNearest.distance, delta);
        assertEquals(1, secondNearest.distance, delta);

        Collection<DimensionalMap.Entry<Object>> nearestThree = tree.findNearest(new float[]{0f, 0f, 5f}, 3, 1f);

        assertEquals(2, nearestThree.size());

        Iterator<DimensionalMap.Entry<Object>> nearestThreeIterator = nearestThree.iterator();
        firstNearest = nearestThreeIterator.next();
        secondNearest = nearestThreeIterator.next();

        assertSame(objects[5], firstNearest.value);
        assertSame(objects[4], secondNearest.value);
        assertEquals(0, firstNearest.distance, delta);
        assertEquals(1, secondNearest.distance, delta);
    }

    @Test
    public void testSearchDuplicationByDistance() {
        SpaceTree<Object> tree = new SpaceTree<>(3);

        Object[] objects = {new Object(), new Object(), new Object(), new Object(), new Object(), new Object()};
        float[][] locations = {{0f, 0f, 0f}, {0f, 0f, 1f}, {0f, 0f, 2f}, {0f, 0f, 3f}, {0f, 0f, 4f}, {0f, 0f, 5f}};

        for (int i = 0; i < objects.length; i++) {
            tree.add(locations[i], objects[i]);
        }

        float delta = 0.0000001f;

        Collection<DimensionalMap.Entry<Object>> nearest = tree.findNearest(locations[2], 3);
        assertEquals(3, nearest.size());

        Iterator<DimensionalMap.Entry<Object>> nearestIterator = nearest.iterator();

        DimensionalMap.Entry<Object> firstNearest = nearestIterator.next();
        DimensionalMap.Entry<Object> secondNearest = nearestIterator.next();
        DimensionalMap.Entry<Object> thirdNearest = nearestIterator.next();

        assertSame(objects[2], firstNearest.value);
        assertTrue(objects[1] == secondNearest.value || objects[3] == secondNearest.value);
        assertTrue(objects[1] == thirdNearest.value || objects[3] == thirdNearest.value);
        assertNotSame(secondNearest.value, thirdNearest.value);

        assertEquals(0, firstNearest.distance, delta);
        assertEquals(1, secondNearest.distance, delta);
        assertEquals(1, thirdNearest.distance, delta);
    }

}


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

Standard Lucene Query Node Builders.

## Standard Lucene Query Node Builders

 The package org.apache.lucene.queryparser.flexible.standard.builders contains all the builders needed to build a Lucene Query object from a query node tree. These builders expect the query node tree was already processed by the [](xref:Lucene.Net.QueryParsers.Flexible.Standard.Processors.StandardQueryNodeProcessorPipeline).

 [](xref:Lucene.Net.QueryParsers.Flexible.Standard.Builders.StandardQueryTreeBuilder) is a builder that already contains a defined map that maps each QueryNode object with its respective builder.


text:
react menu component. port from https://github.com/kissyteam/menu

[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![gemnasium deps][gemnasium-image]][gemnasium-url]
[![node version][node-image]][node-url]
[![npm download][download-image]][download-url]
[![Sauce Test Status](https://saucelabs.com/buildstatus/rc-menu)](https://saucelabs.com/u/rc-menu)

[![Sauce Test Status](https://saucelabs.com/browser-matrix/rc-menu.svg)](https://saucelabs.com/u/rc-menu)

[npm-image]: http://img.shields.io/npm/v/rc-menu.svg?style=flat-square
[npm-url]: http://npmjs.org/package/rc-menu
[travis-image]: https://img.shields.io/travis/react-component/menu.svg?style=flat-square
[travis-url]: https://travis-ci.org/react-component/menu
[coveralls-image]: https://img.shields.io/coveralls/react-component/menu.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/react-component/menu?branch=master
[gemnasium-image]: http://img.shields.io/gemnasium/react-component/menu.svg?style=flat-square
[gemnasium-url]: https://gemnasium.com/react-component/menu
[node-image]: https://img.shields.io/badge/node.js-%3E=_0.10-green.svg?style=flat-square
[node-url]: http://nodejs.org/download/
[download-image]: https://img.shields.io/npm/dm/rc-menu.svg?style=flat-square
[download-url]: https://npmjs.org/package/rc-menu

## Screenshot

![alt](https://tfsimg.alipay.com/images/T19vReXg0oXXXXXXXX.png)

## Usage

```js
import Menu, {SubMenu, MenuItem} = require('rc-menu');
ReactDOM.render(<Menu>
  <MenuItem>1</MenuItem>
  <SubMenu title="2">
  <MenuItem>2-1</MenuItem>
  </SubMenu>
</Menu>, container);
```

## install

[![rc-menu](https://nodei.co/npm/rc-menu.png)](https://npmjs.org/package/rc-menu)

## API

### Menu props

        name
        type
        default
        description

          className
          String

          additional css class of root dom node

          mode
          String
          vertical
          one of ["vertical","horizontal","inline"]

            activeKey
            Object

            initial and current active menu item's key.

            defaultActiveFirst
            Boolean
            false
            whether active first menu item when show if activeKey is not set or invalid

            multiple
            Boolean
            false
            whether allow multiple select

            selectedKeys
            String[]
            []
            selected keys of items

            defaultSelectedKeys
            String[]
            []
            initial selected keys of items

            openKeys
            String[]
            []
            open keys of SubMenuItem

            defaultOpenKeys
            String[]
            []
            initial open keys of SubMenuItem

            onSelect
            function({key:String, item:ReactComponent, domEvent:Event, selectedKeys:String[]})

            called when select a menu item

            onClick
            function({key:String, item:ReactComponent, domEvent:Event, keyPath: String[]})

            called when click a menu item

            onOpen
            function({openKeys:String[]})

            called when open a sub menu

            onClose
            function({openKeys:String[]})

            called when close a sub menu

            onDeselect
            function({key:String, item:ReactComponent, domEvent:Event, selectedKeys:String[]})

            called when deselect a menu item. only called when allow multiple

            openSubMenuOnMouseEnter
            bool
            true
            whether enable top items to open on mouse enter

            closeSubMenuOnMouseEnter
            bool
            true
            whether enable close submenu on mouse leave

            openAnimation
            {enter:function,leave:function}|String

            animate when sub menu open or close. see rc-animate for object type.

            openTransition
            String

            css transitionName when sub menu open or close

### Menu.Item props

        name
        type
        default
        description

          className
          String

          additional css class of root dom node

            disabled
            Boolean
            false
            no effect for click or keydown for this item

            key
            Object

            corresponding to activeKey

### Menu.SubMenu props

        name
        type
        default
        description

          className
          String

          additional css class of root dom node

          title
          String/ReactElement

          sub menu's content

            key
            Object

            corresponding to activeKey

            disabled
            Boolean
            false
            no effect for click or keydown for this item

### Menu.Divider props

none

### Menu.ItemGroup props

        name
        type
        default
        description

            title
            String|React.Element

            title of item group

            children
            React.Element[]

            MenuItems belonged to this group

## Development

```
npm install
npm start
```

## Example

http://localhost:8001/examples/index.md

online example: http://react-component.github.io/menu/examples/

## Test Case

http://localhost:8010/tests/runner.html?coverage

## Coverage

http://localhost:8010/node_modules/rc-server/node_modules/node-jscover/lib/front-end/jscoverage.html?w=http://localhost:8010/tests/runner.html?coverage

## License

rc-menu is released under the MIT license.


text:
package models;

import java.io.FileWriter;
import java.io.IOException;
import java.security.Timestamp;

public class log {
	public log(int failure, int error) {
		super();
		this.failure = failure;
		this.error = error;
	}

	public log() {
			super();
	}
	public int failure = 0;
	public int error = 0;

	public static void writeLog(String str) {
		FileWriter writer = null;
		try{
		     writer = new FileWriter("Log.csv", true);
		     writer.write(str,0,str.length());
		}catch(IOException ex){
		    ex.printStackTrace();
		}finally{
		  if(writer != null){
		     try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  }
		}
	}

	public static void writeLogMutation(String str) {
		FileWriter writer = null;
		try{
		     writer = new FileWriter("LogMutation.csv", true);
		     writer.write(str,0,str.length());
		}catch(IOException ex){
		    ex.printStackTrace();
		}finally{
		  if(writer != null){
		     try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  }
		}
	}

	public static long getCurrentTimeStamp() {
		java.util.Date date= new java.util.Date();
		return date.getTime();
	}
}


text:
<#
    To download and execute:
    [net.servicePointManager]::Expect100Continue = $true;
    [net.servicePointManager]::SecurityProtocol = [net.SecurityProtocolType]::Tls12;
    iwr "https://raw.githubusercontent.com/jagilber/powershellScripts/master/temp/desktop-heap.ps1" -outFile "$pwd\desktop-heap.ps1";.\desktop-heap.ps1
#>
$registryPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems"

$Name = "Windows"

# The critical bit is:
#
# SharedSection=1024,20480,768
# The first number (1024) is the system heap size.
# The second number (20480) is the size for interactive sessions.
# The third number (768) is the size of non-interactive (services) sessions. Note how the third number is 26x smaller than the second.
#    Changing this to: SharedSection=1024,20480,2048
#    Increased the limit of background service processes running from 113 to 270, almost perfectly scaling with the heap size.
#    Pick a value that reflects the maximum number of service processes that you expect to be deployed on the system.
#    Do not make this value larger than necessary, and no larger than 8192, as each service in your system will consume more of a precious resource.
#

$value = "%SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,20480,2048 Windows=On SubSystemType=Windows ServerDll=basesrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=sxssrv,4 ProfileControl=Off MaxRequestThreads=16"

if (!(Test-Path $registryPath)) {
    New-Item -Path $registryPath -Force | Out-Null
    New-ItemProperty -Path $registryPath -Name $name -Value $value -PropertyType ExpandString -Force | Out-Null
}
else {
    New-ItemProperty -Path $registryPath -Name $name -Value $value -PropertyType ExpandString -Force | Out-Null
}

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems"


text:
namespace webapps {

// A POD struct which holds booleans for creating and comparing against
// a (move-only) InstallableTask.
struct TaskParams {
  bool valid_manifest = false;
  bool has_worker = false;
  bool valid_primary_icon = false;
  bool valid_splash_icon = false;
};

// Constructs an InstallableTask, with the supplied bools stored in it.
InstallableTask CreateTask(const TaskParams& params) {
  InstallableTask task;
  task.params.valid_manifest = params.valid_manifest;
  task.params.has_worker = params.has_worker;
  task.params.valid_primary_icon = params.valid_primary_icon;
  task.params.valid_splash_icon = params.valid_splash_icon;
  return task;
}

bool IsEqual(const TaskParams& params, const InstallableTask& task) {
  return task.params.valid_manifest == params.valid_manifest &&
         task.params.has_worker == params.has_worker &&
         task.params.valid_primary_icon == params.valid_primary_icon &&
         task.params.valid_splash_icon == params.valid_splash_icon;
}

class InstallableTaskQueueUnitTest : public testing::Test {};

TEST_F(InstallableTaskQueueUnitTest, PausingMakesNextTaskAvailable) {
  InstallableTaskQueue task_queue;
  TaskParams task1 = {false, false, false, false};
  TaskParams task2 = {true, true, true, true};

  EXPECT_FALSE(task_queue.HasCurrent());
  EXPECT_FALSE(task_queue.HasPaused());

  task_queue.Add(CreateTask(task1));
  task_queue.Add(CreateTask(task2));

  EXPECT_TRUE(task_queue.HasCurrent());
  EXPECT_FALSE(task_queue.HasPaused());
  EXPECT_TRUE(IsEqual(task1, task_queue.Current()));

  // There is another task in the main queue, so it becomes current.
  task_queue.PauseCurrent();
  EXPECT_TRUE(task_queue.HasCurrent());
  EXPECT_TRUE(task_queue.HasPaused());
  EXPECT_TRUE(IsEqual(task2, task_queue.Current()));

  task_queue.ResetWithError(InstallableStatusCode::NO_ERROR_DETECTED);
  EXPECT_FALSE(task_queue.HasCurrent());
  EXPECT_FALSE(task_queue.HasPaused());
}

TEST_F(InstallableTaskQueueUnitTest, PausedTaskCanBeRetrieved) {
  InstallableTaskQueue task_queue;
  TaskParams task1 = {false, false, false, false};
  TaskParams task2 = {true, true, true, true};

  task_queue.Add(CreateTask(task1));
  task_queue.Add(CreateTask(task2));

  EXPECT_TRUE(IsEqual(task1, task_queue.Current()));
  task_queue.PauseCurrent();
  EXPECT_TRUE(task_queue.HasCurrent());
  EXPECT_TRUE(task_queue.HasPaused());
  EXPECT_TRUE(IsEqual(task2, task_queue.Current()));
  task_queue.UnpauseAll();

  // We've unpaused "1", but "2" is still current.
  EXPECT_TRUE(task_queue.HasCurrent());
  EXPECT_FALSE(task_queue.HasPaused());
  EXPECT_TRUE(IsEqual(task2, task_queue.Current()));
  task_queue.Next();
  EXPECT_TRUE(task_queue.HasCurrent());
  EXPECT_TRUE(IsEqual(task1, task_queue.Current()));

  task_queue.ResetWithError(InstallableStatusCode::NO_ERROR_DETECTED);
  EXPECT_FALSE(task_queue.HasCurrent());
  EXPECT_FALSE(task_queue.HasPaused());
}

TEST_F(InstallableTaskQueueUnitTest, NextDiscardsTask) {
  InstallableTaskQueue task_queue;
  TaskParams task1 = {false, false, false, false};
  TaskParams task2 = {true, true, true, true};

  task_queue.Add(CreateTask(task1));
  task_queue.Add(CreateTask(task2));

  EXPECT_TRUE(IsEqual(task1, task_queue.Current()));
  task_queue.Next();
  EXPECT_TRUE(IsEqual(task2, task_queue.Current()));
  // Next() does not pause "1"; it just drops it, so there is nothing to
  // unpause.
  task_queue.UnpauseAll();
  // "2" is still current.
  EXPECT_TRUE(IsEqual(task2, task_queue.Current()));
  // Unpausing does not retrieve "1"; it's gone forever.
  task_queue.Next();
  EXPECT_FALSE(task_queue.HasCurrent());
}

}  // namespace webapps


text:
macro(_add_unittests _TEST_TARGET _SOURCES _INCLUDE_DIRECTORIES _LINK_LIBRARIES)
    set(_TEST_FLAGS "${CMAKE_D_FLAGS_DEBUG_INIT}")
    separate_arguments(_TEST_FLAGS)

    set(_TEST_MAIN "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/unittest.d")
    if(NOT EXISTS ${_TEST_MAIN})
        file(WRITE ${_TEST_MAIN} "// Generated by UseDUnittest.cmake\nint main() { return 0; }")
    endif()

    #if(_INCLUDE_DIRECTORIES)
        set(_TEST_INCLUDE_DIRECTORIES )
        foreach(_INCLUDE_DIRECTORY ${_INCLUDE_DIRECTORIES})
            if(_INCLUDE_DIRECTORY) # since commented out if doesn't work for some reason
                list(APPEND _TEST_INCLUDE_DIRECTORIES "${CMAKE_INCLUDE_FLAG_D}${_INCLUDE_DIRECTORY}")
            endif()
        endforeach()
    #endif()

    #if(_LINK_LIBRARIES)
        set(_TEST_LINK_LIBRARIES )
        foreach(_LINK_LIBRARY ${_LINK_LIBRARIES})
            if(_LINK_LIBRARY) # since commented out if doesn't work for some reason
                list(APPEND _TEST_LINK_LIBRARIES "${CMAKE_LINK_LIBRARY_FLAG}${_LINK_LIBRARY}")
            endif()
        endforeach()
    #endif()

    set(_TEST_SOURCES )
    foreach(_SOURCE ${_SOURCES})
        list(APPEND _TEST_LINK_LIBRARIES "${CMAKE_CURRENT_SOURCE_DIR}/${_SOURCE}")
    endforeach()

    if(CMAKE_LIBRARY_OUTPUT_DIRECTORY)
        set(_TEST_LIBRARY_PATH "${CMAKE_LIBRARY_PATH_FLAG}${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
    endif()

    add_test(NAME build_${_TEST_TARGET}
        COMMAND ${CMAKE_D_COMPILER} ${_TEST_FLAGS} ${_TEST_INCLUDE_DIRECTORIES} ${_TEST_LIBRARY_PATH} ${_TEST_LINK_LIBRARIES} -of${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${_TEST_TARGET} ${_TEST_SOURCES} -unittest ${_TEST_MAIN})

    add_test(NAME ${_TEST_TARGET}
        COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${_TEST_TARGET})
    set_tests_properties(${_TEST_TARGET} PROPERTIES ENVIRONMENT "LD_LIBRARY_PATH=${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
endmacro()

macro(add_unittests_for_target _TARGET)
    set(_TEST_TARGET "test_${_TARGET}")

    get_target_property(_TARGET_TEST_SOURCES ${_TARGET} SOURCES)
    if(_TARGET_TEST_SOURCES)
        get_target_property(_TARGET_INCLUDE_DIRECTORIES ${_TARGET} INCLUDE_DIRECTORIES)
        get_target_property(_TARGET_LINK_LIBRARIES ${_TARGET} LINK_LIBRARIES)

        _add_unittests(${_TEST_TARGET} "${_TARGET_TEST_SOURCES}" "${_TARGET_INCLUDE_DIRECTORIES}" "${_TARGET_LINK_LIBRARIES}")
    else()
        message(SEND_ERROR "cannot add unittests for target ${TARGET }with no source files")
    endif()
endmacro()

macro(add_unittests _SOURCE)
    set(_TEST_TARGET "test_${_SOURCE}")

    get_directory_property(_INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES)
    get_directory_property(_LINK_LIBRARIES LINK_LIBRARIES)

    _add_unittests(${_TEST_TARGET} "${_SOURCE}" "${_INCLUDE_DIRECTORIES}" "${_LINK_LIBRARIES}")
endmacro()


text:
package com.loopj.android.http.sample;

import android.os.Bundle;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.ResponseHandlerInterface;
import com.loopj.android.http.SyncHttpClient;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;

public class SynchronousClientSample extends GetSample {
    private static final String LOG_TAG = "SyncSample";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAsyncHttpClient(new SyncHttpClient());
    }

    @Override
    public int getSampleTitle() {
        return R.string.title_synchronous;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    @Override
    public boolean isRequestHeadersAllowed() {
        return true;
    }

    @Override
    public String getDefaultURL() {
        return "https://httpbin.org/delay/6";
    }

    @Override
    public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) {
        if (client instanceof SyncHttpClient) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(LOG_TAG, "Before Request");
                    client.get(SynchronousClientSample.this, URL, headers, null, responseHandler);
                    Log.d(LOG_TAG, "After Request");
                }
            }).start();
        } else {
            Log.e(LOG_TAG, "Error, not using SyncHttpClient");
        }
        /**
         * SyncHttpClient does not return RequestHandle,
         * it executes each request directly,
         * therefore those requests are not in cancelable threads
         * */
        return null;
    }

    @Override
    public ResponseHandlerInterface getResponseHandler() {
        return new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        clearOutputs();
                    }
                });
            }

            @Override
            public void onSuccess(final int statusCode, final Header[] headers, final byte[] response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        debugHeaders(LOG_TAG, headers);
                        debugStatusCode(LOG_TAG, statusCode);
                        debugResponse(LOG_TAG, new String(response));
                    }
                });
            }

            @Override
            public void onFailure(final int statusCode, final Header[] headers, final byte[] errorResponse, final Throwable e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        debugHeaders(LOG_TAG, headers);
                        debugStatusCode(LOG_TAG, statusCode);
                        debugThrowable(LOG_TAG, e);
                        if (errorResponse != null) {
                            debugResponse(LOG_TAG, new String(errorResponse));
                        }
                    }
                });
            }
        };
    }
}


text:
package us.dot.its.jpo.ode.plugin.j2735.oss;

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

import java.math.BigDecimal;
import java.util.Map;

import org.junit.Ignore;
import org.junit.Test;

import us.dot.its.jpo.ode.j2735.dsrc.AntennaOffsetSet;
import us.dot.its.jpo.ode.j2735.dsrc.GNSSstatus;
import us.dot.its.jpo.ode.j2735.dsrc.Offset_B09;
import us.dot.its.jpo.ode.j2735.dsrc.Offset_B10;
import us.dot.its.jpo.ode.j2735.dsrc.Offset_B12;
import us.dot.its.jpo.ode.j2735.dsrc.RTCMheader;
import us.dot.its.jpo.ode.plugin.j2735.J2735GNSSstatus;
import us.dot.its.jpo.ode.plugin.j2735.J2735RTCMheader;

/**
 * -- Summary --
 * JUnit test class for OssRTCMheader
 *
 * Verifies correct conversion from generic RTCMheader to compliant-J2735RTCMheader
 *
 * This is a trivial test class. GNSStatus element is tested by OssGNSSstatusTest and AntennaOffsetSet is tested
 * by OssAntennaOffsetSetTest. This class tests a known GNSSstatus and AntennaOffsetSet pair is successfully created
 *
 * -- Documentation --
 * Data Frame: DF_RTCMheader
 * Use: The DF_RTCMheader data frame is a collection of data values used to convey RTCM information between users.
 * It is not required or used when sending RTCM data from a corrections source to end users (from a base station
 * to devices deployed in the field which are called rovers).
 * ASN.1 Representation:
 *    RTCMheader ::= SEQUENCE {
 *       status GNSSstatus,
 *       offsetSet AntennaOffsetSet
 *       }
 */
public class OssRTCMheaderTest {

    /**
     * Test that a known RTCM header with known GNSS status "isHealthy"
     */
    @Test
    public void shouldCreateRTCMheaderWithKnownGNSSstatus() {

        String elementTested = "isHealthy";

        byte[] testInputBytes = new byte[1];
        testInputBytes[0] = 0b01000000;

        GNSSstatus testGNSSstatus = new GNSSstatus(testInputBytes);

        Offset_B12 testXOffset = new Offset_B12(0);
        Offset_B09 testYOffset = new Offset_B09(0);
        Offset_B10 testZOffset = new Offset_B10(0);

        AntennaOffsetSet testAntennaOffsetSet = new AntennaOffsetSet(
                testXOffset,
                testYOffset,
                testZOffset);

        RTCMheader testHeader = new RTCMheader();
        testHeader.offsetSet = testAntennaOffsetSet;
        testHeader.status = testGNSSstatus;

        J2735RTCMheader actualHeader = OssRTCMheader.genericRTCMheader(testHeader);

        for (Map.Entry<String, Boolean> curVal : actualHeader.status.entrySet()) {
            if(curVal.getKey() == elementTested) {
                assertTrue("Expected " + curVal.getKey() + " to be true", curVal.getValue());
            } else {
                assertFalse("Expected " + curVal.getKey() + " to be false", curVal.getValue());
            }
        }

    }

    /**
     * Test that a known RTCM header with a known antenna offset set with x offset value (0.11)
     */
    @Test
    public void shouldCreateRTCMheaderWithKnownAntennaOffsetSet() {

        Integer testInput = 11;
        BigDecimal expectedValue = BigDecimal.valueOf(0.11);

        byte[] testInputBytes = new byte[1];
        testInputBytes[0] = 0b00000000;

        GNSSstatus testGNSSstatus = new GNSSstatus(testInputBytes);

        Offset_B12 testXOffset = new Offset_B12(testInput);
        Offset_B09 testYOffset = new Offset_B09(0);
        Offset_B10 testZOffset = new Offset_B10(0);

        AntennaOffsetSet testAntennaOffsetSet = new AntennaOffsetSet(
                testXOffset,
                testYOffset,
                testZOffset);

        RTCMheader testHeader = new RTCMheader();
        testHeader.offsetSet = testAntennaOffsetSet;
        testHeader.status = testGNSSstatus;

        BigDecimal actualValue = OssRTCMheader.genericRTCMheader(testHeader).offsetSet.getAntOffsetX();

        assertEquals(expectedValue, actualValue);
    }

}


text:
class Projects::Ci::DailyBuildGroupReportResultsController < Projects::ApplicationController
  include Gitlab::Utils::StrongMemoize

  MAX_ITEMS = 1000
  REPORT_WINDOW = 90.days

  before_action :validate_feature_flag!
  before_action :authorize_read_build_report_results!
  before_action :validate_param_type!

  def index
    respond_to do |format|
      format.csv { send_data(render_csv(report_results), type: 'text/csv; charset=utf-8') }
      format.json { render json: render_json(report_results) }
    end
  end

  private

  def validate_feature_flag!
    render_404 unless Feature.enabled?(:ci_download_daily_code_coverage, project, default_enabled: true)
  end

  def validate_param_type!
    respond_422 unless allowed_param_types.include?(param_type)
  end

  def render_csv(collection)
    CsvBuilders::SingleBatch.new(
      collection,
      {
        date: 'date',
        group_name: 'group_name',
        param_type => -> (record) { record.data[param_type] }
      }
    ).render
  end

  def render_json(collection)
    Ci::DailyBuildGroupReportResultSerializer.new.represent(collection, param_type: param_type)
  end

  def report_results
    Ci::DailyBuildGroupReportResultsFinder.new(finder_params).execute
  end

  def finder_params
    {
      current_user: current_user,
      project: project,
      ref_path: params.require(:ref_path),
      start_date: start_date,
      end_date: end_date,
      limit: MAX_ITEMS
    }
  end

  def start_date
    strong_memoize(:start_date) do
      start_date = Date.parse(params.require(:start_date))

      # The start_date cannot be older than `end_date - 90 days`
      [start_date, end_date - REPORT_WINDOW].max
    end
  end

  def end_date
    strong_memoize(:end_date) do
      Date.parse(params.require(:end_date))
    end
  end

  def allowed_param_types
    Ci::DailyBuildGroupReportResult::PARAM_TYPES
  end

  def param_type
    params.require(:param_type)
  end
end


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.beigesoft.android"
    android:versionCode="2"
    android:versionName="1.1" >

  <uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="28" />

  <application
    android:allowBackup="false"
    android:icon="@drawable/ic_launcher"
    android:label="@string/tree_chooser"
    android:theme="@style/AppTheme" >
  </application>

</manifest>


text:
import Api from './Api'
import Information from './Information'
import Method from './Method'
import style from './style.styl'

export default Api
export { Information, Method }


text:
function y = norm_lpdf(x,mu,sigma)
%NORM_LPDF Normal log-probability density function (lpdf).
%
%   Y = NORM_LPDF(X,MU,SIGMA) Returns the log of the normal pdf with
%   mean, MU, and standard deviation, SIGMA, at the values in X.
%
%   The size of Y is the common size of the input arguments. A scalar input
%   functions as a constant matrix of the same size as the other inputs.
%
%   Default values for MU and SIGMA are 0 and 1 respectively.

% Copyright (c) 1998-2004 Aki Vehtari

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

if nargin < 3,
  sigma = 1;
end

if nargin < 2;
  mu = 0;
end

if nargin < 1,
  error('Requires at least one input argument.');
end

y = -0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BonusTask
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>() { 5, 4, 2, 4, 5};
            //int x = 0;
            //foreach (var item in list)
            //{
            //    x ^= item;
            //}
            //Console.WriteLine(x);

            foreach (var item in FindOddNumbers(list))
            {
                Console.WriteLine(item);
            }
        }

        static IEnumerable<int> FindOddNumbers(List<int> numbers)
        {
            List<int> clone = new List<int>();
            int currNumb;

            while(clone.Count > 1)
            {
                currNumb = clone[0];
                clone.Remove(currNumb);

                if(!clone.Remove(currNumb))
                {
                    Console.WriteLine(currNumb);
                    yield return currNumb;
                }
            }

            if(clone.Count > 0)
            {
                Console.WriteLine(clone[0]);

                yield return clone[0];
            }
            else
            {
                Console.WriteLine(-1);
                yield return -1;
            }
        }
    }
}


text:
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.python;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesSupport;
import com.google.devtools.build.lib.analysis.SingleRunfilesSupplier;
import com.google.devtools.build.lib.analysis.SourceManifestAction;
import com.google.devtools.build.lib.analysis.SourceManifestAction.ManifestType;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.actions.AbstractFileWriteAction;
import com.google.devtools.build.lib.analysis.actions.DeterministicWriter;
import com.google.devtools.build.lib.analysis.starlark.StarlarkRuleContext;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.rules.cpp.CcInfo;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.PathFragment;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import net.starlark.java.annot.Param;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkValue;

/** Bridge to allow builtins bzl code to call Java code. */
@StarlarkBuiltin(name = "py_builtins", documented = false)
public abstract class PyBuiltins implements StarlarkValue {
  public static final String NAME = "py_builtins";

  private final Runfiles.EmptyFilesSupplier emptyFilesSupplier;

  protected PyBuiltins(Runfiles.EmptyFilesSupplier emptyFilesSupplier) {
    this.emptyFilesSupplier = emptyFilesSupplier;
  }

  @StarlarkMethod(
      name = "is_singleton_depset",
      doc = "Efficiently checks if the depset is a singleton.",
      parameters = {
        @Param(
            name = "value",
            positional = true,
            named = false,
            defaultValue = "unbound",
            doc = "depset to check for being a singleton")
      })
  public boolean isSingletonDepset(Depset depset) {
    return depset.getSet().isSingleton();
  }

  @StarlarkMethod(
      name = "regex_match",
      doc = "Return true if subject matches pattern; pattern is implicitly anchored with ^ and $",
      parameters = {
        @Param(name = "subject", positional = true, named = false, defaultValue = "unbound"),
        @Param(name = "pattern", positional = true, named = false, defaultValue = "unbound"),
      })
  public boolean regexMatch(String subject, String pattern) {
    return subject.matches(pattern);
  }

  @StarlarkMethod(
      name = "new_py_cc_link_params_provider",
      doc = "Creates a PyCcLinkParamsProvder.",
      parameters = {
        @Param(
            name = "cc_info",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "The CcInfo whose linking context to propagate; other information is discarded"),
      },
      useStarlarkThread = false)
  public PyCcLinkParamsProvider newPyCcLinkParamsProvider(CcInfo ccInfo) {
    return new PyCcLinkParamsProvider(ccInfo);
  }

  // TODO(b/69113360): Remove once par-generation is moved out of the py_binary rule itself.
  @StarlarkMethod(
      name = "new_runfiles_supplier",
      doc = "Create a RunfilesSupplier, which can be passed to ctx.actions.run.input_manifests.",
      parameters = {
        @Param(name = "ctx", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "runfiles_dir", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "runfiles", positional = false, named = true, defaultValue = "unbound"),
      })
  public Object addEnv(StarlarkRuleContext ruleContext, String runfilesStr, Runfiles runfiles)
      throws EvalException {
    return new SingleRunfilesSupplier(
        PathFragment.create(runfilesStr),
        runfiles,
        /*manifest=*/ null,
        /*repoMappingManifest=*/ null,
        ruleContext.getConfiguration().buildRunfileLinks(),
        ruleContext.getConfiguration().runfilesEnabled());
  }

  // TODO(rlevasseur): Remove once Starlark exposes this directly, see
  // https://github.com/bazelbuild/bazel/issues/15164
  @StarlarkMethod(
      name = "get_action_input_manifest_mappings",
      doc =
          "Get the set of runfiles passed to the action. These are the runfiles from "
              + "the `input_manifests`, `tools`, and `executable` args of ctx.actions.run."
              + "The return value is "
              + "dict[str runfiles_dir, dict[str runfiles_relative_path, optional File]], "
              + "which is a dict that maps the runfile directories to a dict of the path->File "
              + "entries within each runfiles directory. A File value will be None when the "
              + "path came from runfiles.empty_filesnames. If the passed in action doesn't "
              + "support fetching its runfiles mapping, None is returned.",
      parameters = {
        @Param(name = "action", positional = true, named = true, defaultValue = "unbound"),
      })
  public Object getActionRunfilesArtifacts(Object actionUnchecked) {
    if (!(actionUnchecked instanceof ActionExecutionMetadata)) {
      // There's many action implementations, and the Starlark caller can't check if they're
      // passing a valid one ahead of time. So return None instead of failing and crashing.
      return Starlark.NONE;
    }
    ActionExecutionMetadata action = (ActionExecutionMetadata) actionUnchecked;

    Dict.Builder<String, Dict<String, StarlarkValue>> inputManifest = Dict.builder();
    for (var outerEntry : action.getRunfilesSupplier().getMappings().entrySet()) {
      Dict.Builder<String, StarlarkValue> runfilesMap = Dict.builder();
      for (var innerEntry : outerEntry.getValue().entrySet()) {
        Artifact value = innerEntry.getValue();
        // NOTE: value may be null. This happens for Runfiles.empty_filenames entries.
        runfilesMap.put(innerEntry.getKey().getPathString(), value == null ? Starlark.NONE : value);
      }
      inputManifest.put(outerEntry.getKey().getPathString(), runfilesMap.buildImmutable());
    }
    return inputManifest.buildImmutable();
  }

  // TODO(bazel-team): Remove this once rules are switched to using execpath semanatics for the
  // $(location) function. See https://github.com/bazelbuild/bazel/issues/15294
  @StarlarkMethod(
      name = "expand_location_and_make_variables",
      doc =
          "Expands $(location) and makevar references. Note that $(location) performs "
              + "rootpath (runfiles-relative) expansion, not execpath expansion.",
      parameters = {
        @Param(
            name = "ctx",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "Rule context"),
        @Param(
            name = "attribute_name",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "Name of attribute being expanded; only used for error reporting."),
        @Param(
            name = "expression",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "The expression to expand."),
        @Param(
            name = "targets",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "List of additional targets to allow in expansions"),
      })
  public Object expandLocationAndMakeVariables(
      StarlarkRuleContext ruleContext, String attributeName, String expression, Sequence<?> targets)
      throws EvalException {
    ImmutableMap.Builder<Label, ImmutableCollection<Artifact>> builder = ImmutableMap.builder();

    for (TransitiveInfoCollection current :
        Sequence.cast(targets, TransitiveInfoCollection.class, "targets")) {

      ImmutableList<Artifact> artifacts;
      // This logic is basically a copy of how LocationExpander.java treats the data attribute.
      var filesToRun = current.getProvider(FilesToRunProvider.class);
      if (filesToRun == null) {
        artifacts = current.getProvider(FileProvider.class).getFilesToBuild().toList();
      } else {
        Artifact executable = filesToRun == null ? null : filesToRun.getExecutable();
        if (executable == null) {
          artifacts = filesToRun.getFilesToRun().toList();
        } else {
          artifacts = ImmutableList.of(executable);
        }
      }
      builder.put(AliasProvider.getDependencyLabel(current), artifacts);
    }

    return ruleContext
        .getRuleContext()
        .getExpander(builder.buildOrThrow())
        .withDataLocations() // Enables $(location) expansion.
        .expand(attributeName, expression);
  }

  // TODO(b/232136319): Remove this once the --experimental_build_transitive_python_runfiles
  // flag is flipped and removed.
  @StarlarkMethod(
      name = "new_empty_runfiles_with_middleman",
      doc = "Create an empty runfiles object with the current ctx's middleman attached.",
      parameters = {
        @Param(name = "ctx", positional = false, named = true, defaultValue = "unbound"),
        @Param(
            name = "runfiles_for_runfiles_support",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc =
                "Runfiles used to create RunfilesSupport; they are not added to the "
                    + "returned runfiles object."),
        @Param(
            name = "executable_for_runfiles_support",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc =
                "File; used to create RunfilesSupport; they are not added to the "
                    + "returned runfiles object."),
      })
  public Object newEmptyRunfilesWithMiddleman(
      StarlarkRuleContext starlarkCtx, Runfiles runfiles, Artifact executable)
      throws EvalException {
    // NOTE: The RunfilesSupport created here must exactly match the one done as part of Starlark
    // rule processing, otherwise action output conflicts occur. See
    // https://github.com/bazelbuild/bazel/blob/1940c5d68136ce2079efa8ff74d4e5fdf63ee3e6/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleConfiguredTargetUtil.java#L642-L651
    RunfilesSupport runfilesSupport =
        RunfilesSupport.withExecutable(starlarkCtx.getRuleContext(), runfiles, executable);
    return new Runfiles.Builder(
            starlarkCtx.getWorkspaceName(), starlarkCtx.getConfiguration().legacyExternalRunfiles())
        .addLegacyExtraMiddleman(runfilesSupport.getRunfilesMiddleman())
        .build();
  }

  @StarlarkMethod(
      name = "merge_runfiles_with_generated_inits_empty_files_supplier",
      doc =
          "Create a runfiles that generates missing __init__.py files using Java and "
              + "the internal EmptyFilesProvider interface",
      parameters = {
        @Param(name = "ctx", positional = false, named = true, defaultValue = "unbound"),
        @Param(
            name = "runfiles",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "Runfiles to merge into the result; must be non-empty"),
      })
  public Object mergeRunfilesWithGeneratedInitsEmptyFilesSupplier(
      StarlarkRuleContext starlarkCtx, Runfiles runfiles) throws EvalException {
    if (runfiles.isEmpty()) {
      // The Runfiles merge functions have an optimization to detect an empty runfiles and return a
      // singleton. Unfortunately, this optimization considers an empty runfiles with
      // a emptyFilesSupplier as empty, so then drops it when returning the singleton. To work
      // around this, require that there is *something* in the runfiles.
      throw Starlark.errorf("input runfiles cannot be empty");
    }
    return new Runfiles.Builder(
            starlarkCtx.getWorkspaceName(), starlarkCtx.getConfiguration().legacyExternalRunfiles())
        .setEmptyFilesSupplier(emptyFilesSupplier)
        .merge(runfiles)
        .build();
  }

  @StarlarkMethod(
      name = "declare_constant_metadata_file",
      doc = "Declare a file that always reports it is unchanged.",
      parameters = {
        @Param(name = "ctx", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "name", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "root", positional = false, named = true, defaultValue = "unbound"),
      })
  public Object declareConstantMetadataFile(
      StarlarkRuleContext ctx, String name, Object rootUnchecked) {
    ArtifactRoot root = (ArtifactRoot) rootUnchecked;
    return ctx.getRuleContext()
        .getAnalysisEnvironment()
        .getConstantMetadataArtifact(
            ctx.getRuleContext().getPackageDirectory().getRelative(PathFragment.create(name)),
            root);
  }

  @StarlarkMethod(
      name = "create_sources_only_manifest",
      doc = "Create a manifest of the files in runfiles",
      parameters = {
        @Param(name = "ctx", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "runfiles", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "output", positional = false, named = true, defaultValue = "unbound")
      })
  public void createRunfilesManifest(
      StarlarkRuleContext starlarkCtx, Runfiles runfiles, Artifact output) {
    var ruleContext = starlarkCtx.getRuleContext();
    ruleContext
        .getAnalysisEnvironment()
        .registerAction(
            new SourceManifestAction(
                ManifestType.SOURCES_ONLY,
                ruleContext.getActionOwner(),
                output,
                runfiles,
                /*repoMappingManifest=*/ null,
                ruleContext.getConfiguration().remotableSourceManifestActions()));
  }

  @StarlarkMethod(
      name = "copy_without_caching",
      doc = "Copy one file to another, but with action caching disabled.",
      parameters = {
        @Param(name = "ctx", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "read_from", positional = false, named = true, defaultValue = "unbound"),
        @Param(name = "write_to", positional = false, named = true, defaultValue = "unbound"),
      })
  public Object copyWithoutCaching(StarlarkRuleContext ctx, Artifact readFrom, Artifact writeTo)
      throws InterruptedException {
    var ruleContext = ctx.getRuleContext();
    ruleContext.registerAction(
        new CopyWithoutCachingAction(ruleContext.getActionOwner(), readFrom, writeTo));
    return Starlark.NONE;
  }

  @Immutable
  static final class CopyWithoutCachingAction extends AbstractFileWriteAction {
    private static final String GUID = "67513fa7-3824-493b-aeab-95a8b778ea07";

    CopyWithoutCachingAction(ActionOwner owner, Artifact readFrom, Artifact writeTo) {
      super(
          owner,
          NestedSetBuilder.create(Order.STABLE_ORDER, readFrom),
          writeTo,
          /* makeExecutable=*/ false);
    }

    @Override
    public DeterministicWriter newDeterministicWriter(ActionExecutionContext ctx) {
      return out -> ctx.getInputPath(getPrimaryInput()).getInputStream().transferTo(out);
    }

    @Override
    public boolean executeUnconditionally() {
      return true;
    }

    @Override
    public boolean isVolatile() {
      return true;
    }

    // NOTE: This method is effectively unused because executeUnconditionally=true.
    @Override
    protected void computeKey(
        ActionKeyContext actionKeyContext,
        @Nullable Artifact.ArtifactExpander artifactExpander,
        Fingerprint fp) {
      fp.addString(GUID);
      fp.addPath(getPrimaryInput().getPath());
      fp.addPath(getPrimaryOutput().getPath());
    }

    @Override
    public String describeKey() {
      StringBuilder message = new StringBuilder();
      message
          .append("executeUnconditionally: ")
          .append(executeUnconditionally())
          .append("\nGUID: ")
          .append(GUID)
          .append("\nreadFrom: ")
          .append(getPrimaryInput().getExecPathString())
          .append("\nwriteTo: ")
          .append(getPrimaryOutput().getExecPathString())
          .append('\n');

      return message.toString();
    }

    @Override
    protected String getRawProgressMessage() {
      return String.format(
          "Copying %s to %s (uncachable action)",
          getPrimaryInput().getExecPathString(), getPrimaryOutput().getExecPathString());
    }

    @Override
    public String getMnemonic() {
      return "PyCopyWithoutCaching";
    }
  }

  // TODO(b/253059598): Remove support for this; https://github.com/bazelbuild/bazel/issues/16455
  @StarlarkMethod(
      name = "are_action_listeners_enabled",
      doc =
          "Tells if any action listeners are enabled. This is to prevent registering "
              + "extra actions unless necessary",
      parameters = {
        @Param(
            name = "ctx",
            positional = true,
            named = false,
            defaultValue = "unbound",
            doc = "Rule context"),
      })
  public boolean areActionListenersEnabled(StarlarkRuleContext starlarkCtx) {
    return !starlarkCtx.getRuleContext().getConfiguration().getActionListeners().isEmpty();
  }

  // TODO(b/253059598): Remove support for this; https://github.com/bazelbuild/bazel/issues/16455
  @StarlarkMethod(
      name = "add_py_extra_pseudo_action",
      doc = "Adds an extra pseudo action for (deprecated) extra actions support",
      parameters = {
        @Param(
            name = "ctx",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "Rule context"),
        @Param(
            name = "dependency_transitive_python_sources",
            positional = false,
            named = true,
            defaultValue = "unbound",
            doc = "Depset of Artifacts from PyInfo.transitive_sources from the deps attribute"),
      })
  public void addPyExtraActionPseudoAction(
      StarlarkRuleContext starlarkCtx, Depset uncheckedDependencyTransitivePythonSources)
      throws EvalException {
    NestedSet<Artifact> dependencyTransitivePythonSources =
        Depset.cast(
            uncheckedDependencyTransitivePythonSources,
            Artifact.class,
            "dependency_transitive_python_sources");
    PyCommon.registerPyExtraActionPseudoAction(
        starlarkCtx.getRuleContext(), dependencyTransitivePythonSources);
  }
}


text:
module Sass
  # A namespace for nodes in the Sass parse tree.
  #
  # The Sass parse tree has three states: dynamic, static Sass, and static CSS.
  #
  # When it's first parsed, a Sass document is in the dynamic state.
  # It has nodes for mixin definitions and `@for` loops and so forth,
  # in addition to nodes for CSS rules and properties.
  # Nodes that only appear in this state are called **dynamic nodes**.
  #
  # {Tree::Visitors::Perform} creates a static Sass tree, which is different.
  # It still has nodes for CSS rules and properties
  # but it doesn't have any dynamic-generation-related nodes.
  # The nodes in this state are in the same structure as the Sass document:
  # rules and properties are nested beneath one another.
  # Nodes that can be in this state or in the dynamic state
  # are called **static nodes**.
  #
  # {Tree::Visitors::Cssize} is then used to create a static CSS tree.
  # This is like a static Sass tree,
  # but the structure exactly mirrors that of the generated CSS.
  # Rules and properties can't be nested beneath one another in this state.
  #
  # Finally, {Tree::Visitors::ToCss} can be called on a static CSS tree
  # to get the actual CSS code as a string.
  module Tree
    # The abstract superclass of all parse-tree nodes.
    class Node
      include Enumerable

      # The child nodes of this node.
      #
      # @return [Array<Tree::Node>]
      attr_accessor :children

      # Whether or not this node has child nodes.
      # This may be true even when \{#children} is empty,
      # in which case this node has an empty block (e.g. `{}`).
      #
      # @return [Boolean]
      attr_accessor :has_children

      # The line of the document on which this node appeared.
      #
      # @return [Fixnum]
      attr_accessor :line

      # The name of the document on which this node appeared.
      #
      # @return [String]
      attr_writer :filename

      # The options hash for the node.
      # See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
      #
      # @return [{Symbol => Object}]
      attr_reader :options

      def initialize
        @children = []
      end

      # Sets the options hash for the node and all its children.
      #
      # @param options [{Symbol => Object}] The options
      # @see #options
      def options=(options)
        Sass::Tree::Visitors::SetOptions.visit(self, options)
      end

      # @private
      def children=(children)
        self.has_children ||= !children.empty?
        @children = children
      end

      # The name of the document on which this node appeared.
      #
      # @return [String]
      def filename
        @filename || (@options && @options[:filename])
      end

      # Appends a child to the node.
      #
      # @param child [Tree::Node, Array<Tree::Node>] The child node or nodes
      # @raise [Sass::SyntaxError] if `child` is invalid
      def <<(child)
        return if child.nil?
        if child.is_a?(Array)
          child.each {|c| self << c}
        else
          self.has_children = true
          @children << child
        end
      end

      # Compares this node and another object (only other {Tree::Node}s will be equal).
      # This does a structural comparison;
      # if the contents of the nodes and all the child nodes are equivalent,
      # then the nodes are as well.
      #
      # Only static nodes need to override this.
      #
      # @param other [Object] The object to compare with
      # @return [Boolean] Whether or not this node and the other object
      #   are the same
      # @see Sass::Tree
      def ==(other)
        self.class == other.class && other.children == children
      end

      # True if \{#to\_s} will return `nil`;
      # that is, if the node shouldn't be rendered.
      # Should only be called in a static tree.
      #
      # @return [Boolean]
      def invisible?; false; end

      # The output style. See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
      #
      # @return [Symbol]
      def style
        @options[:style]
      end

      # Computes the CSS corresponding to this static CSS tree.
      #
      # @return [String, nil] The resulting CSS
      # @see Sass::Tree
      def to_s
        Sass::Tree::Visitors::ToCss.visit(self)
      end

      # Converts a static CSS tree (e.g. the output of \{Tree::Visitors::Cssize})
      # into another static CSS tree,
      # with the given extensions applied to all relevant {RuleNode}s.
      #
      # @todo Link this to the reference documentation on `@extend`
      #   when such a thing exists.
      #
      # @param extends [Sass::Util::SubsetMap{Selector::Simple => Selector::Sequence}]
      #   The extensions to perform on this tree
      # @return [Tree::Node] The resulting tree of static CSS nodes.
      # @raise [Sass::SyntaxError] Only if there's a programmer error
      #   and this is not a static CSS tree
      def do_extend(extends)
        node = dup
        node.children = children.map {|c| c.do_extend(extends)}
        node
      rescue Sass::SyntaxError => e
        e.modify_backtrace(:filename => filename, :line => line)
        raise e
      end

      # Iterates through each node in the tree rooted at this node
      # in a pre-order walk.
      #
      # @yield node
      # @yieldparam node [Node] a node in the tree
      def each(&block)
        yield self
        children.each {|c| c.each(&block)}
      end

      # Converts a node to Sass code that will generate it.
      #
      # @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
      # @return [String] The Sass code corresponding to the node
      def to_sass(options = {})
        Sass::Tree::Visitors::Convert.visit(self, options, :sass)
      end

      # Converts a node to SCSS code that will generate it.
      #
      # @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
      # @return [String] The Sass code corresponding to the node
      def to_scss(options = {})
        Sass::Tree::Visitors::Convert.visit(self, options, :scss)
      end

      # Return a deep clone of this node.
      # The child nodes are cloned, but options are not.
      #
      # @return [Node]
      def deep_copy
        Sass::Tree::Visitors::DeepCopy.visit(self)
      end

      protected

      # @see Sass::Shared.balance
      # @raise [Sass::SyntaxError] if the brackets aren't balanced
      def balance(*args)
        res = Sass::Shared.balance(*args)
        return res if res
        raise Sass::SyntaxError.new("Unbalanced brackets.", :line => line)
      end
    end
  end
end


text:
SparseMatrix assembleStiffnessMatrix(
    const Eigen::MatrixXd &vertices,
    const Eigen::MatrixXi &triangles) {
	SparseMatrix         A(vertices.rows(), vertices.rows());
	std::vector<Triplet> triplets;
	const int            numberOfElements = triangles.rows();

	for (int i = 0; i < numberOfElements; ++i) {
		auto &indexSet = triangles.row(i);

		const auto &a = vertices.row(indexSet(0));
		const auto &b = vertices.row(indexSet(1));
		const auto &c = vertices.row(indexSet(2));

		Eigen::Matrix3d stiffnessMatrix;
		computeStiffnessMatrix(stiffnessMatrix, a, b, c);

		for (int n = 0; n < 3; ++n) {
			for (int m = 0; m < 3; ++m) {
				auto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));
				triplets.push_back(triplet);
			}
		}
	}

	A.setFromTriplets(triplets.begin(), triplets.end());

	return A;
}
//----------------AssembleMatrixEnd----------------


text:
#ifndef FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_
# error This file must be included from Elf.h
#endif

namespace folly {
namespace symbolizer {

template <class Fn>
const ElfW(Shdr)* ElfFile::iterateSections(Fn fn) const {
  const ElfW(Shdr)* ptr = &at<ElfW(Shdr)>(elfHeader().e_shoff);
  for (size_t i = 0; i < elfHeader().e_shnum; i++, ptr++) {
    if (fn(*ptr)) {
      return ptr;
    }
  }

  return nullptr;
}

template <class Fn>
const ElfW(Shdr)* ElfFile::iterateSectionsWithType(uint32_t type, Fn fn)
  const {
  return iterateSections(
      [&](const ElfW(Shdr)& sh) {
        return sh.sh_type == type && fn(sh);
      });
}

template <class Fn>
const char* ElfFile::iterateStrings(const ElfW(Shdr)& stringTable, Fn fn)
  const {
  validateStringTable(stringTable);

  const char* start = file_ + stringTable.sh_offset;
  const char* end = start + stringTable.sh_size;

  const char* ptr = start;
  while (ptr != end && !fn(ptr)) {
    ptr += strlen(ptr) + 1;
  }

  return ptr != end ? ptr : nullptr;
}

template <class Fn>
const ElfW(Sym)* ElfFile::iterateSymbols(const ElfW(Shdr)& section, Fn fn)
  const {
  FOLLY_SAFE_CHECK(section.sh_entsize == sizeof(ElfW(Sym)),
                   "invalid entry size in symbol table");

  const ElfW(Sym)* sym = &at<ElfW(Sym)>(section.sh_offset);
  const ElfW(Sym)* end = sym + (section.sh_size / section.sh_entsize);

  while (sym < end) {
    if (fn(*sym)) {
      return sym;
    }

    ++sym;
  }

  return nullptr;
}

template <class Fn>
const ElfW(Sym)* ElfFile::iterateSymbolsWithType(const ElfW(Shdr)& section,
                                                 uint32_t type, Fn fn) const {
  // N.B. st_info has the same representation on 32- and 64-bit platforms
  return iterateSymbols(section, [&](const ElfW(Sym)& sym) -> bool {
    return ELF32_ST_TYPE(sym.st_info) == type && fn(sym);
  });
}

}  // namespace symbolizer
}  // namespace folly


text:
Dashboard

Here you have a quick overview of some features

xHey there! Welcome to the professional and flexible admin template "Grape". I hope you enjoy your stay and please make sure, that you visit the other pages.

                            Write an Article

                            User Manager

                            Control Monitor

                            Check the Mails

                            Statistics

                            Manage Console

                            Notes

                            Manage Images

Create a Blogpost

            <form id="validate-form" class="block-content form" action="dashboard.html" method="post">

                    Title
                    <input type="text" name="title" class="required">

                    Category
                    <select name="category" id="category">
                        <option>Lorem Ipsum</option>
                        <option>Consetetur Sadipscing</option>
                        <option>Eirmod Tempor</option>
                    </select>

                    Post
                    <textarea id="post" name="post" class="required" rows="5" cols="40"></textarea>

Cancel

<input type="submit" class="button" value="Create Post">

            </form>

What you should do

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Visit the Block List page to see the other types of block lists.

Overview-List

You have 12 new support tickets.

8262 Total Visits

521 Today Visits

257 Comments

42 Support Tickets