text:
<?php
/**
 * Created by EdwardData
 * BlackCube Technologies
 * Date: 2/17/15
 * Time: 3:46 PM
 *
 */

namespace Bitxone\MainBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * RetailersStatuses
 *
 * @ORM\Table(name="retailers")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Retailers
{
	function __construct()
	{
		$this->orders = new ArrayCollection();
		$this->shippingCodes = new ArrayCollection();
	}

	/**
	* @var integer
	*
	* @ORM\Column(name="id", type="integer", nullable=false)
	* @ORM\Id
	* @ORM\GeneratedValue(strategy="IDENTITY")
	*/
	private $id;

	/**
	* @var string
	*
	* @ORM\Column(name="guid", type="string", length=255, nullable=false)
	*/
	private $guid;

	/**
	* @var string
	*
	* @ORM\Column(name="retailer_name", type="string", length=255, nullable=false)
	*/
	private $retailerName;

	/**
	* @var string
	*
	* @ORM\Column(name="remote_folder_name", type="string", length=255, nullable=false)
	*/
	private $remoteFolderName;

	/**
	* @var string
	*
	* @ORM\Column(name="icon_name", type="string", length=255, nullable=true)
	*/
	private $iconName;

	/**
	* @var string
	*
	* @ORM\Column(name="css_color", type="string", length=255, nullable=true)
	*/
	private $cssColor;

	/**
	* @var integer
	* @ORM\OneToOne(targetEntity="Bitxone\MainBundle\Entity\RetailersStatuses")
    * @ORM\JoinColumn(name="status_id", referencedColumnName="id", nullable=true)
	*/
	private $statusId = 1;

	/**
	* @var \DateTime
	*
	* @ORM\Column(name="created_at", type="datetime", nullable=false)
	*/
	private $createdAt;

	/**
	* @var \DateTime
	*
	* @ORM\Column(name="updated_at", type="datetime", nullable=true)
	*/
	private $updatedAt;

	/**
	* @var integer
    * @ORM\OneToOne(targetEntity="Bitxone\MainBundle\Entity\ShipmentTypes")
	* @ORM\JoinColumn(name="shipment_type_id", referencedColumnName="id", nullable=true)
	*/
	private $shipmentTypeId = 1;

	/**
	* @var string
	*
	* @ORM\Column(name="erp_custom_code", type="string", length=255, nullable=true)
	*/
	private $erpCustomCode;

	/**
	* @var string
	*
	* @ORM\Column(name="sales_person", type="string", length=255, nullable=true)
	*/
	private $salesPerson;

	/**
	  * @ORM\OneToMany(targetEntity="Bitxone\MainBundle\Entity\Orders", mappedBy="retailer_id")
	  * @ORM\JoinColumns({
	  *   @ORM\JoinColumn(name="retailer_id", referencedColumnName="id")
	  * })
	  */
	protected $orders;

	/**
	  * @ORM\OneToMany(targetEntity="Bitxone\MainBundle\Entity\ShippingCodes", mappedBy="retailerId")
	  * @ORM\JoinColumns({
	  *   @ORM\JoinColumn(name="retailer_id", referencedColumnName="id")
	  * })
	  */
	protected $shippingCodes;

	/**
	 * @return int
	 */
	public function getId()
	{
		return $this->id;
	}

	/**
	 * @param int $id
	 */
	public function setId( $id )
	{
		$this->id = $id;
	}

	/**
	 * @return string
	 */
	public function getGuid()
	{
		return $this->guid;
	}

	/**
	 * @param string $guid
	 */
	public function setGuid( $guid )
	{
		$this->guid = $guid;
	}

	/**
	 * @return string
	 */
	public function getRetailerName()
	{
		return $this->retailerName;
	}

	/**
	 * @param string $retailerName
	 */
	public function setRetailerName( $retailerName )
	{
		$this->retailerName = $retailerName;
	}

	/**
	 * @return string
	 */
	public function getRemoteFolderName()
	{
		return $this->remoteFolderName;
	}

	/**
	 * @param string $remoteFolderName
	 */
	public function setRemoteFolderName( $remoteFolderName )
	{
		$this->remoteFolderName = $remoteFolderName;
	}

	/**
	 * @return string
	 */
	public function getIconName()
	{
		return $this->iconName;
	}

	/**
	 * @param string $iconName
	 */
	public function setIconName( $iconName )
	{
		$this->iconName = $iconName;
	}

	/**
	 * @return string
	 */
	public function getCssColor()
	{
		return $this->cssColor;
	}

	/**
	 * @param string $cssColor
	 */
	public function setCssColor( $cssColor )
	{
		$this->cssColor = $cssColor;
	}

	/**
	 * @return mixed
	 */
	public function getStatusId()
	{
		return $this->statusId;
	}

	/**
	 * @param mixed $statusId
	 */
	public function setStatusId( $statusId )
	{
		$this->statusId = $statusId;
	}

	/**
	 * @return \DateTime
	 */
	public function getCreatedAt()
	{
		return $this->createdAt;
	}

	/**
	 * @param \DateTime $createdAt
	 */
	public function setCreatedAt( $createdAt )
	{
		$this->createdAt = $createdAt;
	}

	/**
	 * @return \DateTime
	 */
	public function getUpdatedAt()
	{
		return $this->updatedAt;
	}

	/**
	 * @param \DateTime $updatedAt
	 */
	public function setUpdatedAt( $updatedAt )
	{
		$this->updatedAt = $updatedAt;
	}

	/**
	 * @return mixed
	 */
	public function getShipmentTypeId()
	{
		return $this->shipmentTypeId;
	}

	/**
	 * @param mixed $shipmentTypeId
	 */
	public function setShipmentTypeId( $shipmentTypeId )
	{
		$this->shipmentTypeId = $shipmentTypeId;
	}

	/**
	 * @return string
	 */
	public function getErpCustomCode()
	{
		return $this->erpCustomCode;
	}

	/**
	 * @param string $erpCustomCode
	 */
	public function setErpCustomCode( $erpCustomCode )
	{
		$this->erpCustomCode = $erpCustomCode;
	}

	/**
	 * @return string
	 */
	public function getSalesPerson()
	{
		return $this->salesPerson;
	}

	/**
	 * @param string $salesPerson
	 */
	public function setSalesPerson( $salesPerson )
	{
		$this->salesPerson = $salesPerson;
	}

	/**
	* @ORM\PrePersist
	*/
	public function setPrePersistGuid()
	{
		$this->setGuid( \uuid_create() );
	}

	/**
	* @ORM\PrePersist
	*/
	public function setPrePersistCreatedAt()
	{
		$this->setCreatedAt(new \DateTime());
	}

	/**
	* @ORM\PreUpdate
	*/
	public function setPreUpdateUpdatedAt()
	{
		$this->setUpdatedAt(new \DateTime());
	}

	public function __toString()
	{
		return $this->getRetailerName();
	}

	/**
	 * @return mixed
	 */
	public function getOrders()
	{
		return $this->orders;
	}

	/**
	 * @param mixed $orders
	 */
	public function setOrders( $orders )
	{
		$this->orders = $orders;
	}

	/**
	 * @return mixed
	 */
	public function getShippingCodes()
	{
		return $this->shippingCodes;
	}

	/**
	 * @param mixed $shippingCodes
	 */
	public function setShippingCodes( $shippingCodes )
	{
		$this->shippingCodes = $shippingCodes;
	}

}


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt

package com.google.appinventor.blockseditor.youngandroid;

import com.google.appinventor.blockseditor.jsonp.AsyncJsonpRequestHandler;
import com.google.appinventor.blockseditor.jsonp.HttpServer;
import com.google.appinventor.blockseditor.jsonp.HttpServerEventListener;
import com.google.appinventor.blockseditor.jsonp.Util;
import com.google.appinventor.common.youngandroid.YaHttpServerConstants;

import org.json.JSONException;

import openblocks.yacodeblocks.AndroidController;
import openblocks.yacodeblocks.ExternalController;
import openblocks.yacodeblocks.FeedbackReporter;
import openblocks.yacodeblocks.IWorkspaceController;
import openblocks.yacodeblocks.LoadException;
import openblocks.yacodeblocks.NoProjectException;
import openblocks.yacodeblocks.SaveException;
import openblocks.yacodeblocks.WorkspaceController;
import openblocks.yacodeblocks.WorkspaceControllerHolder;
import openblocks.yacodeblocks.YailGenerationException;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Young Android HTTP Server. Wraps an HTTP server around the codeblocks
 * executable so that it can communicate with the ODE server. This program is
 * executed via JavaWebStart on the client machine.
 *
 * @author sharon@google.com (Sharon Perl)
 */
public class YaHttpServerMain {

  /**
   * Interface for translating a string URI into a {@link URLConnection}.
   * Injected into {@link YaCodeblocksController} to allow testing mocks.
   */
  public interface ServerConnection {
    HttpURLConnection getConnection(String path) throws MalformedURLException, IOException;
  }

  // All access to workspaceController blocks state should be locked from
  // workspaceControllerLock. Note that we don't currently use
  // workspaceController itself as a synchronization object because
  // some of its methods that we call are themselves synchronized.
  // TODO(sharon): revisit this if we remove the synchronization on
  // WorkspaceController methods.
  private static final Object workspaceControllerLock = new Object();

  private static final String EMPTY_PROPERTIES_ERROR_MESSAGE =
      "Project was unexepectedly empty and "
          + "failed to load.  Please try reloading Blocks Editor.";

  protected final HttpServer server;
  private YaCodeblocksController yaController;
  private YaCodeblocksAndroidController yaAndroidController = null;

  // This gives access to methods in the workspace controller.
  private final WorkspaceController workspaceController;

  private final ServerConnection conn;

  // Keep track of the codeblocks source path and the yail path of the current form.
  private String codeblocksSourcePath;
  private String yailPath;

  public YaHttpServerMain(final HttpServer server, String baseUrl, String path,
      WorkspaceController wc, ServerConnection conn) {
    this.server = server;
    this.workspaceController = wc;
    this.conn = conn;
    this.yaController = new YaCodeblocksController(conn, baseUrl);

    codeblocksSourcePath = "";
    yailPath = "";

    final String phoneAppUrl = baseUrl + path + YaHttpServerConstants.STARTER_PHONEAPP_APK;
    // handle case where phoneAppUrl is malformed or null
    try {
      String phoneAppFile = downloadPhoneAppFromServer(phoneAppUrl);
      this.yaAndroidController = new YaCodeblocksAndroidController(phoneAppFile);
    } catch (MalformedURLException e) {
      reportDownloadError(e.getMessage());
    } catch (FileNotFoundException e) {
      reportDownloadError(e.getMessage());
    } catch (IOException e) {
      reportDownloadError(e.getMessage());
    }

    final String savePortUrl = baseUrl + path + YaHttpServerConstants.CODEBLOCKS_SAVE_PORT;
    server.addHttpServerEventListener(new HttpServerEventListener() {
      @Override
      public void onPortSelected(HttpServer subject, int port) {
        int secret = savePort(savePortUrl, port);
        server.setSecret(secret);
      }
      @Override
      public void onConnectivityStatusChange(HttpServer subject, boolean status) {
        /*
         * TODO(sharon): in some OS/browser combos this seems to happen
         * frequently even though we haven't really lost connection to the
         * browser. At some point we might want to report these in a status bar,
         * but for now we do nothing.
         */
      }
    });

    addHandlers();
  }

  private void reportDownloadError(String exceptionMessage) {
    FeedbackReporter.showErrorMessage(
        "We could not download the starter application from the server in order to install it " +
        "on the
device. This may prevent the \"Connect to Device\" button from working." +
        "
This error can occur if you have tried to start the blocks editor with a previously " +
        "downloaded
\".jnlp\" file.
" +
        "
Make sure that you start the blocks editor by clicking the \"Open the Blocks " +
        "Editor\" button in
the designer and using the \".jnlp\" file that is downloaded by " +
        "that action.
Do not try to start the blocks editor with a previously downloaded " +
        "\".jnlp\" file.
");
    System.out.println("Failed to get application from server and start controller: " +
        exceptionMessage);
  }

  private void addHandlers() {
    server.setHandler(YaHttpServerConstants.GENERATE_YAIL, new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        return Boolean.toString(generateYail());
      }
    });

    server.setHandler(YaHttpServerConstants.LOAD_FORM, new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        String formPropertiesPath = parameters.get(YaHttpServerConstants.FORM_PROPERTIES_PATH);
        String assetsPath = parameters.get(YaHttpServerConstants.ASSET_PATH);
        String projectName = parameters.get(YaHttpServerConstants.PROJECT_NAME);
        return Boolean.toString(loadForm(formPropertiesPath, assetsPath, projectName));
      }
    });

    server.setHandler(YaHttpServerConstants.RELOAD_PROPERTIES,
        new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        return Boolean.toString(reloadProperties());
      }
    });

    server.setHandler(YaHttpServerConstants.CLEAR_CODEBLOCKS, new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        return Boolean.toString(clearCodeblocks());
      }
    });

    server.setHandler(YaHttpServerConstants.SAVE_CODEBLOCKS_SOURCE, new AsyncJsonpRequestHandler(
        server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        return Boolean.toString(saveCodeblocksSource());
      }
    });

    server.setHandler(YaHttpServerConstants.SYNC_PROPERTY, new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        String componentName = parameters.get(YaHttpServerConstants.COMPONENT_NAME);
        String componentType = parameters.get(YaHttpServerConstants.COMPONENT_TYPE);
        String propertyName = parameters.get(YaHttpServerConstants.PROPERTY_NAME);
        String propertyValue = parameters.get(YaHttpServerConstants.PROPERTY_VALUE);
        return Boolean.toString(syncProperty(componentName, componentType, propertyName,
            propertyValue));
      }
    });

    server.setHandler(YaHttpServerConstants.ADD_ASSET,
        new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        String assetPath = parameters.get(YaHttpServerConstants.ASSET_PATH);
        return Boolean.toString(addAsset(assetPath));
      }
    });

    server.setHandler(YaHttpServerConstants.INSTALL_APPLICATION,
        new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        String apkFilePath = parameters.get(YaHttpServerConstants.APK_FILE_PATH);
        String appName = parameters.get(YaHttpServerConstants.APP_NAME);
        String packageName = parameters.get(YaHttpServerConstants.PACKAGE_NAME);
        return Boolean.toString(installApplication(apkFilePath, appName, packageName));
      }
    });

    server.setHandler(YaHttpServerConstants.IS_PHONE_CONNECTED,
        new AsyncJsonpRequestHandler(server) {
      @Override
      public String getResponseValueAsync(Map<String, String> parameters) throws Throwable {
        return Boolean.toString(isPhoneConnected());
      }
    });
  }

  /**
   * Downloads the phone application apk from the server and saves it into
   * a temporary file.  phoneAppFile will get set to the location where the
   * apk is placed on the local file system.
   *
   * @param  phoneAppUrl URL on server to tell it to download the phone application apk.
   * @return the location of the temp file containing the apk.
   * @throws MalformedURLException (which we don't expect)
   * @throws FileNotFoundException (which we don't expect)
   * @throws IOException (which we also do not expect, but might happen somehow)
   */
  public static String downloadPhoneAppFromServer(String phoneAppUrl)
      throws FileNotFoundException, IOException, MalformedURLException {
    System.out.println("Trying to download phone app apk");
    String phoneAppFile = Util.downloadFile(phoneAppUrl, "phoneApp.apk");
    System.out.println("Phone app apk saved into temp file: " + phoneAppFile);
    return phoneAppFile;
  }

  /**
   * Returns {@code true} if the call to persist the source succeeds in
   * {@link WorkspaceController}, {@code false} if a runtime exception occurs.
   */
  private boolean saveCodeblocksSource() {
    System.out.println("Got call to save codeblocks source.");

    synchronized (workspaceControllerLock) {
      try {
        workspaceController.persistCodeblocksSourceFile(true /* wait for save to complete */);
        return true;
      } catch (SaveException e) {
        FeedbackReporter.showErrorMessage("Blocks Editor source file failed to save.");
        e.printStackTrace();
        return false;
      }
    }
  }

  private boolean clearCodeblocks() {
    codeblocksSourcePath = "";
    yailPath = "";
    yaController.setFormPropertiesPath("");

    synchronized (workspaceControllerLock) {
      System.out.println("Clearing codeblocks.");
      workspaceController.loadFreshWorkspace("", null);
    }
    return true;
  }

  private boolean reloadProperties() {
    System.out.println("Reloading properties");
    try {
      String formProperties = yaController.getFormPropertiesForProject();
      if (formProperties == null) {
        return false;
      }
      synchronized (workspaceControllerLock) {
        if (formProperties.length() > 0) {
          workspaceController.loadProperties(formProperties);
        } else {
          FeedbackReporter.showSystemErrorMessage(EMPTY_PROPERTIES_ERROR_MESSAGE);
          workspaceController.loadFreshWorkspace("", null);
          return false;
        }
      }
    } catch (LoadException e) {
      System.out.println(e.getMessage());
      return false;
    } catch (NoProjectException e) {
      FeedbackReporter.showErrorMessage(e.getMessage());
      return false;
    } catch (IOException e) {
      FeedbackReporter.showSystemErrorMessage("Failed to reload properties: " +
          e.getMessage());
      return false;
    }
    return true;
  }

  private boolean generateYail() {
    /*
     * TODO(user): Get the qualified project name here so that it can be
     * put in the YAIL without parsing it from the path.
     */
    /* This synchronize prevents a save of the .blk file while yail generation is
     * going on, but it doesn't prevent the user from fiddling with the blocks.
     */
    synchronized (workspaceControllerLock) {
      try {
        // We generate YAIL in order to show problems (like empty sockets) to the user.
        // We don't actually send the YAIL to the server.
        workspaceController.wrapProjectYailForAPK(yailPath);
        return true;
      } catch (YailGenerationException e) {
        FeedbackReporter.showErrorMessage(e.getMessage());
        return false;
      } catch (NoProjectException e) {
        FeedbackReporter.showErrorMessage(e.getMessage());
        return false;
      } catch (JSONException e) {
        FeedbackReporter.showErrorMessage(e.getMessage());
        return false;
      } catch (IOException e) {
        FeedbackReporter.showSystemErrorMessage("Failed in Packaging for Phone" + e.getMessage());
        return false;
      }
    }
  }

  private boolean loadForm(String formPropertiesPath,
      String assetsFilePath, String projectName) {
    System.out.println("==== Loading form, project is " + projectName);
    if (formPropertiesPath.equals("") || !formPropertiesPath.endsWith(".scm")) {
      return false;
    }
    String rootName = formPropertiesPath.substring(0, formPropertiesPath.length() - 4);
    codeblocksSourcePath = rootName + ".blk";
    yailPath = rootName + ".yail";
    yaController.setFormPropertiesPath(formPropertiesPath);

    String codeblocksSource;
    String formProperties;
    Map<String, String> assetFiles;
    try {
      codeblocksSource = yaController.getContentsFromServer(codeblocksSourcePath);
      formProperties = yaController.getContentsFromServer(formPropertiesPath);
      assetFiles = yaController.downloadZipFromServer(assetsFilePath);
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    try {
      synchronized (workspaceControllerLock) {
        if (formProperties.length() > 0) {
          workspaceController.loadSourceAndProperties(codeblocksSourcePath, codeblocksSource,
              formProperties, assetFiles, projectName);
        } else {
          System.out.println("Both source files are empty. Clearing workspace");
          workspaceController.loadFreshWorkspace("", null);
          FeedbackReporter.showSystemErrorMessage(EMPTY_PROPERTIES_ERROR_MESSAGE);
          return false;
        }
      }
    } catch (LoadException e) {
      System.out.println(e.getMessage());
      return false;
    }
    return true;
  }

  private ExternalController getExternalController() {
    return yaController;
  }

  private AndroidController getAndroidController() {
    return yaAndroidController;
  }

  private int savePort(String savePortUrl, int port) {
    try {
      // Send the port back to the ODE server using the savePortUrl.
      HttpURLConnection httpUrlConn = conn.getConnection(savePortUrl);
      // Write the port as the data for the POST request.
      httpUrlConn.setDoOutput(true);
      httpUrlConn.setRequestMethod("POST");
      httpUrlConn.addRequestProperty("Content-Type", "text/plain; charset=utf-8");
      httpUrlConn.connect();
      OutputStreamWriter writer = new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8");
      writer.write(Integer.toString(port));
      writer.close();
      String encoding = httpUrlConn.getContentEncoding();
      if (encoding == null) {
        encoding = "UTF-8";
      }
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          httpUrlConn.getInputStream(), encoding));
      try {
        String line = reader.readLine();
        int secret = Integer.parseInt(line);
        return secret;
      } finally {
        reader.close();
      }
    } catch (IOException e) {
      if (HttpServer.LOG_TO_SYSTEM_OUT) {
        e.printStackTrace(System.out);
      }
    }
    return 0;
  }

  private boolean syncProperty(String componentName, String componentType, String propertyName,
      String propertyValue) {
    System.out.println("Got call to sync the " + componentName + "." + propertyName + " property.");

    synchronized (workspaceControllerLock) {
      return workspaceController.syncProperty(componentName, componentType, propertyName,
          propertyValue);
    }
  }

  // TODO(sharon): assets downloaded via addAsset will end up in /tmp/<assetname>
  // while those downloaded when the project is downloaded will end up in
  // /tmp/assets/<assetname>. Do we care?
  private boolean addAsset(String assetPath) {
    try {
      String localAssetPath =
          yaController.downloadContentFromServer(assetPath);
      System.out.println("Asset downloaded from server to: " + localAssetPath);
      return workspaceController.getPhoneCommManager().addAsset(assetPath, localAssetPath);
    } catch (IOException e) {
      e.printStackTrace();
      // ignore for now.
      return false;
    }
  }

  private boolean installApplication(String apkFilePath, String appName, String packageName) {
    System.out.println("Got call to install the application: " + appName);
    try {
      String localApkPath = yaController.downloadContentFromServer(apkFilePath);
      System.out.println("Apk downloaded from server to: " + localApkPath);
      return workspaceController.getPhoneCommManager()
          .installApplication(localApkPath, appName, packageName);
    } catch (IOException e) {
      // TODO(kerr) handle this exception
      e.printStackTrace();
      return false;
    }
  }

  private boolean isPhoneConnected() {
    return workspaceController.getPhoneCommManager().connectedToPhone();
  }

  /**
   * Start an HTTP server so the ODE client can talk to us.
   * Command-line arguments:
   *

   *
the base URL of the WebStartFileServlet in the ODE server
   *
the path within the WebStartFileServlet to use when sending our port
   *     and when retrieving the phone app apk
   *
boolean indicating whether this is a production server
   *

   *
   * @throws IOException if running the HTTP server throws it
   */
  public static void main(String[] args) throws IOException {
    String baseUrl = args[0];
    String path = args[1];
    HttpServer server = new HttpServer();

    // Give the WorkspaceControllerHolder a factory that will create a WorkspaceController.
    // This ensures that only one workspace controller will be created and that it will be the
    // appropriate implementation: WorkspaceController.
    IWorkspaceController.Factory factory = new IWorkspaceController.Factory() {
      @Override
      public IWorkspaceController create() {
        return new WorkspaceController();
      }
    };
    WorkspaceControllerHolder.setFactory(factory, false);  // not headless
    WorkspaceController workspaceController = (WorkspaceController) WorkspaceControllerHolder.get();

    YaHttpServerMain main =
        new YaHttpServerMain(server, baseUrl, path, workspaceController,
            new ServerConnection() {
              @Override
              public HttpURLConnection getConnection(String path) throws MalformedURLException,
                  IOException {
                URLConnection urlConnection = new URL(path).openConnection();
                if (!(urlConnection instanceof HttpURLConnection)) {
                  throw new MalformedURLException("Not an http URL: " + path);
                } else {
                  return (HttpURLConnection) urlConnection;
                }
              }
            });
    AndroidController androidController = main.getAndroidController();
    workspaceController.startCodeblocks(main.getExternalController(), androidController);
    System.out.flush();

    /*
     * Now, we start up the HTTP server. If any calls come in while the fresh
     * workspace is loading they will get scheduled to run immediately after the
     * workspace is loaded.
     */
    server.runHttpServer();
    if (androidController != null) {
      androidController.androidCleanUpBeforeExit();
    }

    /*
     * When this process is started via JavaWebStart on Linux, it exits without
     * calling System.exit here. However, on the Mac, there are two threads
     * related to JavaWebStart that are not daemon threads: the "Javaws Secure
     * Thread" and the "CacheMemoryCleanUpThread", both in the
     * "javawsSecurityThreadGroup" thread group. These non-daemon threads
     * prevent the process from exiting unless we explicitly call System.exit
     * here.
     */
    try {
      synchronized (workspaceControllerLock) {
        workspaceController.persistCodeblocksSourceFile(true /* wait for save to complete */);
      }
    } catch (SaveException e) {
      e.printStackTrace();
    } finally {
      System.exit(0);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Module.Interface;
using Model.Enum;

namespace Model.Module
{
    public class Friend : People
    {
        public List<Message> Messages { get; set; }

        public bool IsOnline { get; set; }

        public string Id { get; set; }

        public Friend()
            : base()
        {
            this.Messages = new List<Message>();
            this.Id = Guid.NewGuid().ToString();
            this.IsOnline = false;
        }

        public override void Translated()
        {
            base.Translated();
            foreach (var obj in this.Messages)
            {
                obj.Translated();
            }
            lock (this.Messages)
            {
                this.Messages = new List<Message>();
            }
        }

    }
}


text:
import { CompileNgModuleMetadata } from '../compile_metadata';
import { CompilerConfig } from '../config';
import { CompileMetadataResolver } from '../metadata_resolver';
import { NgModuleCompiler } from '../ng_module_compiler';
import { OutputEmitter } from '../output/abstract_emitter';
import { StyleCompiler } from '../style_compiler';
import { SummaryResolver } from '../summary_resolver';
import { TemplateParser } from '../template_parser/template_parser';
import { ViewCompiler } from '../view_compiler/view_compiler';
import { AotCompilerHost } from './compiler_host';
import { GeneratedFile } from './generated_file';
import { StaticReflector } from './static_reflector';
import { StaticSymbol } from './static_symbol';
import { StaticSymbolResolver } from './static_symbol_resolver';
export declare class AotCompiler {
    private _config;
    private _host;
    private _reflector;
    private _metadataResolver;
    private _templateParser;
    private _styleCompiler;
    private _viewCompiler;
    private _ngModuleCompiler;
    private _outputEmitter;
    private _summaryResolver;
    private _localeId;
    private _translationFormat;
    private _enableSummariesForJit;
    private _symbolResolver;
    constructor(_config: CompilerConfig, _host: AotCompilerHost, _reflector: StaticReflector, _metadataResolver: CompileMetadataResolver, _templateParser: TemplateParser, _styleCompiler: StyleCompiler, _viewCompiler: ViewCompiler, _ngModuleCompiler: NgModuleCompiler, _outputEmitter: OutputEmitter, _summaryResolver: SummaryResolver<StaticSymbol>, _localeId: string | null, _translationFormat: string | null, _enableSummariesForJit: boolean | null, _symbolResolver: StaticSymbolResolver);
    clearCache(): void;
    analyzeModulesSync(rootFiles: string[]): NgAnalyzedModules;
    analyzeModulesAsync(rootFiles: string[]): Promise<NgAnalyzedModules>;
    emitAllStubs(analyzeResult: NgAnalyzedModules): GeneratedFile[];
    emitAllImpls(analyzeResult: NgAnalyzedModules): GeneratedFile[];
    private _compileStubFile(srcFileUrl, directives, ngModules);
    private _compileImplFile(srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables);
    private _createSummary(srcFileUrl, directives, pipes, ngModules, injectables, ngFactoryCtx);
    private _compileModule(outputCtx, ngModuleType);
    private _compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
    private _compileComponent(outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix);
    private _createOutputContext(genFilePath);
    private _codegenStyles(srcFileUrl, compMeta, stylesheetMetadata, fileSuffix);
    private _codegenSourceModule(srcFileUrl, ctx);
}
export interface NgAnalyzedModules {
    ngModules: CompileNgModuleMetadata[];
    ngModuleByPipeOrDirective: Map<StaticSymbol, CompileNgModuleMetadata>;
    files: Array<{
        srcUrl: string;
        directives: StaticSymbol[];
        pipes: StaticSymbol[];
        ngModules: StaticSymbol[];
        injectables: StaticSymbol[];
    }>;
    symbolsMissingModule?: StaticSymbol[];
}
export interface NgAnalyzeModulesHost {
    isSourceFile(filePath: string): boolean;
}
export declare function analyzeNgModules(programStaticSymbols: StaticSymbol[], host: NgAnalyzeModulesHost, metadataResolver: CompileMetadataResolver): NgAnalyzedModules;
export declare function analyzeAndValidateNgModules(programStaticSymbols: StaticSymbol[], host: NgAnalyzeModulesHost, metadataResolver: CompileMetadataResolver): NgAnalyzedModules;
export declare function extractProgramSymbols(staticSymbolResolver: StaticSymbolResolver, files: string[], host: NgAnalyzeModulesHost): StaticSymbol[];


text:
package jpsplus

const (
	MapWidth = 100
	MapHeight
	TileWidth = 100
	TileHeight
)

const (
	COST_STRAIGHT = 1000
	COST_DIAGONAL = 1414
	CloseSetMax   = 500
)

type LocJPS struct {
	row int
	col int
}

func newLocJPS(row int, col int) *LocJPS {
	l := new(LocJPS)
	l.row = row
	l.col = col
	return l
}

type Node struct {
	row       int
	col       int
	givenCost int
	finalCost int
	parent    *Node
	direction int
	heapIndex int
}

func newNode(r int, c int) *Node {
	node := new(Node)
	node.row = r
	node.col = c
	return node
}

func (this *Node) equal(n *Node) bool {
	return this.row == n.row && this.col == n.col
}

type nodeList map[int]*Node

func newNodeList() nodeList {
	return make(nodeList)
}

func (n nodeList) insert(node *Node) {
	n[node.row*MapWidth+node.col] = node
}

func (n nodeList) lookup(row int, col int) (node *Node, ok bool) {
	node, ok = n[row*MapWidth+col]
	return
}

func (n nodeList) remove(row int, col int) {
	delete(n, row*MapWidth+col)
}

func (n nodeList) len() int {
	return len(n)
}

type JPSPlus struct {
	startNode *Node
	goalNode  *Node
	fastStack *PriorityQueue
	openSet   nodeList
	closeSet  nodeList
}

func NewJPSPlus(sRow int, sCol int, gRow int, gCol int) *JPSPlus {
	j := new(JPSPlus)
	j.startNode = newNode(sRow, sCol)
	j.goalNode = newNode(gRow, gCol)
	j.fastStack = newPriorityQueue()
	j.closeSet = newNodeList()
	j.openSet = newNodeList()
	j.closeSet.insert(j.startNode)

	return j
}

func (this *JumpMap) GetPath(sRow int, sCol int, gRow int, gCol int) (path map[int]*LocJPS, isFind bool) {
	jps := NewJPSPlus(sRow, sCol, gRow, gCol)
	if this.SearchLoop(jps) {
		path = jps.FinalizePath()
		isFind = true
	}
	return
}

func logicToTile(x int, y int) (r int, c int) {
	r = y / TileHeight
	c = x / TileWidth
	return
}

func tileToLogic(r int, c int) (x int, y int) {
	y = r * TileHeight
	x = c * TileWidth
	return
}

func (this *JumpMap) SearchLoop(jps *JPSPlus) bool {
	jumpNode := this[jps.startNode.row][jps.startNode.col]
	JPSPlusExplore_AllDirections(jps.startNode, jumpNode, jps)
	for 0 != jps.fastStack.Len() && jps.closeSet.len() < CloseSetMax {
		cur := jps.fastStack.PopNode()
		jps.openSet.remove(cur.row, cur.col)
		if cur.equal(jps.goalNode) {
			jps.goalNode.parent = cur.parent
			return true
		} else {
			jps.closeSet.insert(cur)
			jump := this[cur.row][cur.col]
			exploreDirections[(jump.blocked*8)+cur.direction](cur, jump, jps)
		}
	}
	return false
}

func (j *JPSPlus) FinalizePath() map[int]*LocJPS {
	jump := make(map[int]*LocJPS)
	for i, cur := 0, j.goalNode; nil != cur; cur, i = cur.parent, i+1 {
		jump[i] = newLocJPS(cur.row, cur.col)
	}
	return jump
}

func MacroExploreDown(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchDown(currentNode, jump.distant[Down])
}

func MacroExploreDownRight(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchDownRight(currentNode, jump.distant[DownRight])

}

func MacroExploreRight(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchRight(currentNode, jump.distant[Right])

}

func MacroExploreUpRight(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchUpRight(currentNode, jump.distant[UpRight])

}

func MacroExploreUp(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchUp(currentNode, jump.distant[Up])

}

func MacroExploreUpLeft(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchUpLeft(currentNode, jump.distant[UpLeft])

}

func MacroExploreLeft(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchLeft(currentNode, jump.distant[Left])

}

func MacroExploreDownLeft(currentNode *Node, jump *Jump, jpsPlus *JPSPlus) {
	jpsPlus.SearchDownLeft(currentNode, jump.distant[DownLeft])

}

func JPSPlusExplore_Null(currentNode *Node, jump *Jump, jps *JPSPlus) {
}

func JPSPlusExplore_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_DR(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDownRight(currentNode, jump, jps)
}

func JPSPlusExplore_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_UR(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUpRight(currentNode, jump, jps)
}

func JPSPlusExplore_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_UL(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUpLeft(currentNode, jump, jps)
}

func JPSPlusExplore_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_DL(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDownLeft(currentNode, jump, jps)
}

func JPSPlusExplore_D_DR(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
}

func JPSPlusExplore_DR_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_R_UR(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
}

func JPSPlusExplore_UR_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_U_UL(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
}

func JPSPlusExplore_UL_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_L_DL(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
}

func JPSPlusExplore_DL_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_D_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_R_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_U_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_L_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_D_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_R_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_D_DR_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_DR_R_UR(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
}

func JPSPlusExplore_R_UR_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_UR_U_UL(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
}

func JPSPlusExplore_U_UL_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_UL_L_DL(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
}

func JPSPlusExplore_L_DL_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_DL_D_DR(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
}

func JPSPlusExplore_D_R_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_R_U_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_U_L_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_L_D_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_R_DR_D_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_R_D_DL_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_U_UR_R_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_U_R_DR_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_L_UL_U_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_L_U_UR_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_D_DL_L_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_D_L_UL_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_R_DR_D_DL_L(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
}

func JPSPlusExplore_U_UR_R_DR_D(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
	MacroExploreDown(currentNode, jump, jps)
}

func JPSPlusExplore_L_UL_U_UR_R(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
}

func JPSPlusExplore_D_DL_L_UL_U(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
}

func JPSPlusExplore_AllDirections(currentNode *Node, jump *Jump, jps *JPSPlus) {
	MacroExploreDown(currentNode, jump, jps)
	MacroExploreDownLeft(currentNode, jump, jps)
	MacroExploreLeft(currentNode, jump, jps)
	MacroExploreUpLeft(currentNode, jump, jps)
	MacroExploreUp(currentNode, jump, jps)
	MacroExploreUpRight(currentNode, jump, jps)
	MacroExploreRight(currentNode, jump, jps)
	MacroExploreDownRight(currentNode, jump, jps)
}

func (j *JPSPlus) SearchDown(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if col == j.goalNode.col && row < j.goalNode.row {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		if (row + absJumpDistance) >= j.goalNode.row {
			diff := j.goalNode.row - row
			givenCost := currentNode.givenCost + fixed_point_shift(diff)
			newSuccessor := j.goalNode
			j.PushNewNode(newSuccessor, currentNode, Down, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newRow := row + jumpDistance
		givenCost := currentNode.givenCost + fixed_point_shift(jumpDistance)
		newSuccessor := newNode(newRow, col)
		j.PushNewNode(newSuccessor, currentNode, Down, givenCost)
	}
}

func (j *JPSPlus) SearchDownRight(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if row < j.goalNode.row && col < j.goalNode.col {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		diffRow := j.goalNode.row - row
		diffCol := j.goalNode.col - col
		smallerDiff := diffRow
		if diffCol < smallerDiff {
			smallerDiff = diffCol
		}

		if smallerDiff <= absJumpDistance {
			newRow := row + smallerDiff
			newCol := col + smallerDiff
			givenCost := currentNode.givenCost + COST_DIAGONAL*smallerDiff
			newSuccessor := newNode(newRow, newCol)
			j.PushNewNode(newSuccessor, currentNode, DownRight, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newRow := row + jumpDistance
		newCol := col + jumpDistance
		givenCost := currentNode.givenCost + COST_DIAGONAL*jumpDistance
		newSuccessor := newNode(newRow, newCol)
		j.PushNewNode(newSuccessor, currentNode, DownRight, givenCost)
	}
}

func (j *JPSPlus) SearchRight(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if row == j.goalNode.row && col < j.goalNode.col {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		if (col + absJumpDistance) >= j.goalNode.col {
			diff := j.goalNode.col - col
			givenCost := currentNode.givenCost + fixed_point_shift(diff)
			newSuccessor := j.goalNode
			j.PushNewNode(newSuccessor, currentNode, Right, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newCol := col + jumpDistance
		givenCost := currentNode.givenCost + fixed_point_shift(jumpDistance)
		newSuccessor := newNode(row, newCol)
		j.PushNewNode(newSuccessor, currentNode, Right, givenCost)
	}
}

func (j *JPSPlus) SearchUpRight(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if row > j.goalNode.row && col < j.goalNode.col {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		diffRow := row - j.goalNode.row
		diffCol := j.goalNode.col - col
		smallerDiff := diffRow
		if diffCol < smallerDiff {
			smallerDiff = diffCol
		}

		if smallerDiff <= absJumpDistance {
			newRow := row - smallerDiff
			newCol := col + smallerDiff
			givenCost := currentNode.givenCost + COST_DIAGONAL*smallerDiff
			newSuccessor := newNode(newRow, newCol)
			j.PushNewNode(newSuccessor, currentNode, UpRight, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newRow := row - jumpDistance
		newCol := col + jumpDistance
		givenCost := currentNode.givenCost + COST_DIAGONAL*jumpDistance
		newSuccessor := newNode(newRow, newCol)
		j.PushNewNode(newSuccessor, currentNode, UpRight, givenCost)
	}
}

func (j *JPSPlus) SearchUp(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if col == j.goalNode.col && row > j.goalNode.row {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		if (row - absJumpDistance) <= j.goalNode.row {
			diff := row - j.goalNode.row
			givenCost := currentNode.givenCost + fixed_point_shift(diff)
			newSuccessor := j.goalNode
			j.PushNewNode(newSuccessor, currentNode, Up, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newRow := row - jumpDistance
		givenCost := currentNode.givenCost + fixed_point_shift(jumpDistance)
		newSuccessor := newNode(newRow, col)
		j.PushNewNode(newSuccessor, currentNode, Up, givenCost)
	}
}

func (j *JPSPlus) SearchUpLeft(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if row > j.goalNode.row && col > j.goalNode.col {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		diffRow := row - j.goalNode.row
		diffCol := col - j.goalNode.col
		smallerDiff := diffRow
		if diffCol < smallerDiff {
			smallerDiff = diffCol
		}

		if smallerDiff <= absJumpDistance {
			newRow := row - smallerDiff
			newCol := col - smallerDiff
			givenCost := currentNode.givenCost + COST_DIAGONAL*smallerDiff
			newSuccessor := newNode(newRow, newCol)
			j.PushNewNode(newSuccessor, currentNode, UpLeft, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newRow := row - jumpDistance
		newCol := col - jumpDistance
		givenCost := currentNode.givenCost + COST_DIAGONAL*jumpDistance
		newSuccessor := newNode(newRow, newCol)
		j.PushNewNode(newSuccessor, currentNode, UpLeft, givenCost)
	}
}

func (j *JPSPlus) SearchLeft(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if row == j.goalNode.row && col > j.goalNode.col {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		if (col - absJumpDistance) <= j.goalNode.col {
			diff := col - j.goalNode.col
			givenCost := currentNode.givenCost + fixed_point_shift(diff)
			newSuccessor := j.goalNode
			j.PushNewNode(newSuccessor, currentNode, Left, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newCol := col - jumpDistance
		givenCost := currentNode.givenCost + fixed_point_shift(jumpDistance)
		newSuccessor := newNode(row, newCol)
		j.PushNewNode(newSuccessor, currentNode, Left, givenCost)
	}
}

func (j *JPSPlus) SearchDownLeft(currentNode *Node, jumpDistance int) {
	row := currentNode.row
	col := currentNode.col

	if row < j.goalNode.row && col > j.goalNode.col {
		absJumpDistance := jumpDistance
		if absJumpDistance < 0 {
			absJumpDistance = -absJumpDistance
		}

		diffRow := j.goalNode.row - row
		diffCol := col - j.goalNode.col
		smallerDiff := diffRow
		if diffCol < smallerDiff {
			smallerDiff = diffCol
		}

		if smallerDiff <= absJumpDistance {
			newRow := row + smallerDiff
			newCol := col - smallerDiff
			givenCost := currentNode.givenCost + COST_DIAGONAL*smallerDiff
			newSuccessor := newNode(newRow, newCol)
			j.PushNewNode(newSuccessor, currentNode, DownLeft, givenCost)
			return
		}
	}

	if jumpDistance > 0 {
		newRow := row + jumpDistance
		newCol := col - jumpDistance
		givenCost := currentNode.givenCost + COST_DIAGONAL*jumpDistance
		newSuccessor := newNode(newRow, newCol)
		j.PushNewNode(newSuccessor, currentNode, DownLeft, givenCost)
	}
}

func (j *JPSPlus) PushNewNode(newJump *Node, cur *Node, parentDirection int, givenCost int) {
	_, ok := j.closeSet.lookup(newJump.row, newJump.col)
	if !ok {
		old, ok := j.openSet.lookup(newJump.row, newJump.col)
		if ok {
			if old.givenCost > givenCost {
				old.givenCost = givenCost
				old.parent = cur
				old.finalCost = givenCost + heuristicDistance(newJump, j.goalNode)
			}
		} else {
			newJump.parent = cur
			newJump.direction = parentDirection
			newJump.givenCost = givenCost
			newJump.finalCost = givenCost + heuristicDistance(newJump, j.goalNode)
			j.openSet.insert(newJump)
			j.fastStack.PushNode(newJump)
		}
	}
}

func heuristicDistance(cur *Node, stop *Node) int {
	row := abs(cur.row - stop.row)
	col := abs(cur.col - stop.col)
	h_dia := min(row, col)
	h_str := abs(row - col)
	return COST_DIAGONAL*h_dia + COST_STRAIGHT*h_str
}

func abs(i int) int {
	if i < 0 {
		return -i
	} else {
		return i
	}
}

func min(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}

func fixed_point_shift(x int) int {
	return x * COST_STRAIGHT
}


text:
/*
 /  Author: Sam Rushing <rushing@nightmare.com>
 /  Hacked for Unix by AMK
 /  $Id: mmapmodule.c,v 1.1.1.1 2006/05/30 06:06:40 hhzhou Exp $

 / mmapmodule.cpp -- map a view of a file into memory
 /
 / todo: need permission flags, perhaps a 'chsize' analog
 /   not all functions check range yet!!!
 /
 /
 / Note: This module currently only deals with 32-bit file
 /   sizes.
 /
 / This version of mmapmodule.c has been changed significantly
 / from the original mmapfile.c on which it was based.
 / The original version of mmapfile is maintained by Sam at
 / ftp://squirl.nightmare.com/pub/python/python-ext.
*/

#include <Python.h>

#ifndef MS_WINDOWS
#define UNIX
#endif

#ifdef MS_WINDOWS
#include <windows.h>
static int
my_getpagesize(void)
{
	SYSTEM_INFO si;
	GetSystemInfo(&si);
	return si.dwPageSize;
}
#endif

#ifdef UNIX
#include <sys/mman.h>
#include <sys/stat.h>

#if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
static int
my_getpagesize(void)
{
	return sysconf(_SC_PAGESIZE);
}
#else
#define my_getpagesize getpagesize
#endif

#endif /* UNIX */

#include <string.h>
#include <sys/types.h>

static PyObject *mmap_module_error;

typedef enum
{
	ACCESS_DEFAULT,
	ACCESS_READ,
	ACCESS_WRITE,
	ACCESS_COPY
} access_mode;

typedef struct {
	PyObject_HEAD
	char *	data;
	size_t	size;
	size_t	pos;

#ifdef MS_WINDOWS
	HANDLE	map_handle;
	HANDLE	file_handle;
	char *	tagname;
#endif

#ifdef UNIX
        int fd;
#endif

        access_mode access;
} mmap_object;

static void
mmap_object_dealloc(mmap_object *m_obj)
{
#ifdef MS_WINDOWS
	if (m_obj->data != NULL)
		UnmapViewOfFile (m_obj->data);
	if (m_obj->map_handle != INVALID_HANDLE_VALUE)
		CloseHandle (m_obj->map_handle);
	if (m_obj->file_handle != INVALID_HANDLE_VALUE)
		CloseHandle (m_obj->file_handle);
	if (m_obj->tagname)
		PyMem_Free(m_obj->tagname);
#endif /* MS_WINDOWS */

#ifdef UNIX
	if (m_obj->data!=NULL) {
		msync(m_obj->data, m_obj->size, MS_SYNC);
		munmap(m_obj->data, m_obj->size);
	}
#endif /* UNIX */

	PyObject_Del(m_obj);
}

static PyObject *
mmap_close_method(mmap_object *self, PyObject *args)
{
        if (!PyArg_ParseTuple(args, ":close"))
		return NULL;
#ifdef MS_WINDOWS
	/* For each resource we maintain, we need to check
	   the value is valid, and if so, free the resource
	   and set the member value to an invalid value so
	   the dealloc does not attempt to resource clearing
	   again.
	   TODO - should we check for errors in the close operations???
	*/
	if (self->data != NULL) {
		UnmapViewOfFile (self->data);
		self->data = NULL;
	}
	if (self->map_handle != INVALID_HANDLE_VALUE) {
		CloseHandle (self->map_handle);
		self->map_handle = INVALID_HANDLE_VALUE;
	}
	if (self->file_handle != INVALID_HANDLE_VALUE) {
		CloseHandle (self->file_handle);
		self->file_handle = INVALID_HANDLE_VALUE;
	}
#endif /* MS_WINDOWS */

#ifdef UNIX
	if (self->data != NULL) {
		munmap(self->data, self->size);
		self->data = NULL;
	}
#endif

	Py_INCREF (Py_None);
	return (Py_None);
}

#ifdef MS_WINDOWS
#define CHECK_VALID(err)						\
do {									\
    if (self->map_handle == INVALID_HANDLE_VALUE) {						\
	PyErr_SetString (PyExc_ValueError, "mmap closed or invalid");	\
	return err;							\
    }									\
} while (0)
#endif /* MS_WINDOWS */

#ifdef UNIX
#define CHECK_VALID(err)						\
do {									\
    if (self->data == NULL) {						\
	PyErr_SetString (PyExc_ValueError, "mmap closed or invalid");	\
	return err;							\
	}								\
} while (0)
#endif /* UNIX */

static PyObject *
mmap_read_byte_method(mmap_object *self,
		      PyObject *args)
{
	CHECK_VALID(NULL);
        if (!PyArg_ParseTuple(args, ":read_byte"))
		return NULL;
	if (self->pos < self->size) {
	        char value = self->data[self->pos];
		self->pos += 1;
		return Py_BuildValue("c", value);
	} else {
		PyErr_SetString (PyExc_ValueError, "read byte out of range");
		return NULL;
	}
}

static PyObject *
mmap_read_line_method(mmap_object *self,
		      PyObject *args)
{
	char *start = self->data+self->pos;
	char *eof = self->data+self->size;
	char *eol;
	PyObject *result;

	CHECK_VALID(NULL);
        if (!PyArg_ParseTuple(args, ":readline"))
		return NULL;

	eol = memchr(start, '\n', self->size - self->pos);
	if (!eol)
		eol = eof;
	else
		++eol;		/* we're interested in the position after the
				   newline. */
	result = PyString_FromStringAndSize(start, (eol - start));
	self->pos += (eol - start);
	return (result);
}

static PyObject *
mmap_read_method(mmap_object *self,
		 PyObject *args)
{
	long num_bytes;
	PyObject *result;

	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple(args, "l:read", &num_bytes))
		return(NULL);

	/* silently 'adjust' out-of-range requests */
	if ((self->pos + num_bytes) > self->size) {
		num_bytes -= (self->pos+num_bytes) - self->size;
	}
	result = Py_BuildValue("s#", self->data+self->pos, num_bytes);
	self->pos += num_bytes;
	return (result);
}

static PyObject *
mmap_find_method(mmap_object *self,
		 PyObject *args)
{
	long start = self->pos;
	char *needle;
	int len;

	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "s#|l:find", &needle, &len, &start)) {
		return NULL;
	} else {
		char *p;
		char *e = self->data + self->size;

                if (start < 0)
			start += self->size;
                if (start < 0)
			start = 0;
                else if ((size_t)start > self->size)
			start = self->size;

		for (p = self->data + start; p + len <= e; ++p) {
			int i;
			for (i = 0; i < len && needle[i] == p[i]; ++i)
				/* nothing */;
			if (i == len) {
				return Py_BuildValue (
					"l",
					(long) (p - self->data));
			}
		}
		return Py_BuildValue ("l", (long) -1);
	}
}

static int
is_writeable(mmap_object *self)
{
	if (self->access != ACCESS_READ)
		return 1;
	PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
	return 0;
}

static int
is_resizeable(mmap_object *self)
{
	if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
		return 1;
	PyErr_Format(PyExc_TypeError,
		     "mmap can't resize a readonly or copy-on-write memory map.");
	return 0;
}

static PyObject *
mmap_write_method(mmap_object *self,
		  PyObject *args)
{
	int length;
	char *data;

	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "s#:write", &data, &length))
		return(NULL);

	if (!is_writeable(self))
		return NULL;

	if ((self->pos + length) > self->size) {
		PyErr_SetString (PyExc_ValueError, "data out of range");
		return NULL;
	}
	memcpy (self->data+self->pos, data, length);
	self->pos = self->pos+length;
	Py_INCREF (Py_None);
	return (Py_None);
}

static PyObject *
mmap_write_byte_method(mmap_object *self,
		       PyObject *args)
{
	char value;

	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "c:write_byte", &value))
		return(NULL);

	if (!is_writeable(self))
		return NULL;
	*(self->data+self->pos) = value;
	self->pos += 1;
	Py_INCREF (Py_None);
	return (Py_None);
}

static PyObject *
mmap_size_method(mmap_object *self,
		 PyObject *args)
{
	CHECK_VALID(NULL);
        if (!PyArg_ParseTuple(args, ":size"))
		return NULL;

#ifdef MS_WINDOWS
	if (self->file_handle != INVALID_HANDLE_VALUE) {
		return (Py_BuildValue (
			"l", (long)
			GetFileSize (self->file_handle, NULL)));
	} else {
		return (Py_BuildValue ("l", (long) self->size) );
	}
#endif /* MS_WINDOWS */

#ifdef UNIX
	{
		struct stat buf;
		if (-1 == fstat(self->fd, &buf)) {
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}
		return (Py_BuildValue ("l", (long) buf.st_size) );
	}
#endif /* UNIX */
}

/* This assumes that you want the entire file mapped,
 / and when recreating the map will make the new file
 / have the new size
 /
 / Is this really necessary?  This could easily be done
 / from python by just closing and re-opening with the
 / new size?
 */

static PyObject *
mmap_resize_method(mmap_object *self,
		   PyObject *args)
{
	unsigned long new_size;
	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "l:resize", &new_size) ||
	    !is_resizeable(self)) {
		return NULL;
#ifdef MS_WINDOWS
	} else {
		DWORD dwErrCode = 0;
		/* First, unmap the file view */
		UnmapViewOfFile (self->data);
		/* Close the mapping object */
		CloseHandle (self->map_handle);
		/* Move to the desired EOF position */
		SetFilePointer (self->file_handle,
				new_size, NULL, FILE_BEGIN);
		/* Change the size of the file */
		SetEndOfFile (self->file_handle);
		/* Create another mapping object and remap the file view */
		self->map_handle = CreateFileMapping (
			self->file_handle,
			NULL,
			PAGE_READWRITE,
			0,
			new_size,
			self->tagname);
		if (self->map_handle != NULL) {
			self->data = (char *) MapViewOfFile (self->map_handle,
							     FILE_MAP_WRITE,
							     0,
							     0,
							     0);
			if (self->data != NULL) {
				self->size = new_size;
				Py_INCREF (Py_None);
				return Py_None;
			} else {
				dwErrCode = GetLastError();
			}
		} else {
			dwErrCode = GetLastError();
		}
		PyErr_SetFromWindowsErr(dwErrCode);
		return (NULL);
#endif /* MS_WINDOWS */

#ifdef UNIX
#ifndef HAVE_MREMAP
	} else {
		PyErr_SetString(PyExc_SystemError,
				"mmap: resizing not available--no mremap()");
		return NULL;
#else
	} else {
		void *newmap;

		if (ftruncate(self->fd, new_size) == -1) {
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}

#ifdef MREMAP_MAYMOVE
		newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
#else
		newmap = mremap(self->data, self->size, new_size, 0);
#endif
		if (newmap == (void *)-1)
		{
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}
		self->data = newmap;
		self->size = new_size;
		Py_INCREF(Py_None);
		return Py_None;
#endif /* HAVE_MREMAP */
#endif /* UNIX */
	}
}

static PyObject *
mmap_tell_method(mmap_object *self, PyObject *args)
{
	CHECK_VALID(NULL);
        if (!PyArg_ParseTuple(args, ":tell"))
		return NULL;
	return (Py_BuildValue ("l", (long) self->pos) );
}

static PyObject *
mmap_flush_method(mmap_object *self, PyObject *args)
{
	size_t offset	= 0;
	size_t size = self->size;
	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "|ll:flush", &offset, &size)) {
		return NULL;
	} else if ((offset + size) > self->size) {
		PyErr_SetString (PyExc_ValueError,
				 "flush values out of range");
		return NULL;
	} else {
#ifdef MS_WINDOWS
		return (Py_BuildValue("l", (long)
                                      FlushViewOfFile(self->data+offset, size)));
#endif /* MS_WINDOWS */
#ifdef UNIX
		/* XXX semantics of return value? */
		/* XXX flags for msync? */
		if (-1 == msync(self->data + offset, size,
				MS_SYNC))
		{
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}
		return Py_BuildValue ("l", (long) 0);
#endif /* UNIX */
	}
}

static PyObject *
mmap_seek_method(mmap_object *self, PyObject *args)
{
	int dist;
	int how=0;
	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "i|i:seek", &dist, &how)) {
		return(NULL);
	} else {
		size_t where;
		switch (how) {
		case 0: /* relative to start */
			if (dist < 0)
				goto onoutofrange;
			where = dist;
			break;
		case 1: /* relative to current position */
			if ((int)self->pos + dist < 0)
				goto onoutofrange;
			where = self->pos + dist;
			break;
		case 2: /* relative to end */
			if ((int)self->size + dist < 0)
				goto onoutofrange;
			where = self->size + dist;
			break;
		default:
			PyErr_SetString (PyExc_ValueError,
					 "unknown seek type");
			return NULL;
		}
		if (where > self->size)
			goto onoutofrange;
		self->pos = where;
		Py_INCREF (Py_None);
		return (Py_None);
	}

  onoutofrange:
	PyErr_SetString (PyExc_ValueError, "seek out of range");
	return NULL;
}

static PyObject *
mmap_move_method(mmap_object *self, PyObject *args)
{
	unsigned long dest, src, count;
	CHECK_VALID(NULL);
	if (!PyArg_ParseTuple (args, "iii:move", &dest, &src, &count) ||
	    !is_writeable(self)) {
		return NULL;
	} else {
		/* bounds check the values */
		if (/* end of source after end of data?? */
			((src+count) > self->size)
			/* dest will fit? */
			|| (dest+count > self->size)) {
			PyErr_SetString (PyExc_ValueError,
					 "source or destination out of range");
			return NULL;
		} else {
			memmove (self->data+dest, self->data+src, count);
			Py_INCREF (Py_None);
			return Py_None;
		}
	}
}

static struct PyMethodDef mmap_object_methods[] = {
	{"close",	(PyCFunction) mmap_close_method,	METH_VARARGS},
	{"find",	(PyCFunction) mmap_find_method,		METH_VARARGS},
	{"flush",	(PyCFunction) mmap_flush_method,	METH_VARARGS},
	{"move",	(PyCFunction) mmap_move_method,		METH_VARARGS},
	{"read",	(PyCFunction) mmap_read_method,		METH_VARARGS},
	{"read_byte",	(PyCFunction) mmap_read_byte_method,  	METH_VARARGS},
	{"readline",	(PyCFunction) mmap_read_line_method,	METH_VARARGS},
	{"resize",	(PyCFunction) mmap_resize_method,	METH_VARARGS},
	{"seek",	(PyCFunction) mmap_seek_method,		METH_VARARGS},
	{"size",	(PyCFunction) mmap_size_method,		METH_VARARGS},
	{"tell",	(PyCFunction) mmap_tell_method,		METH_VARARGS},
	{"write",	(PyCFunction) mmap_write_method,	METH_VARARGS},
	{"write_byte",	(PyCFunction) mmap_write_byte_method,	METH_VARARGS},
	{NULL,	   NULL}       /* sentinel */
};

/* Functions for treating an mmap'ed file as a buffer */

static int
mmap_buffer_getreadbuf(mmap_object *self, int index, const void **ptr)
{
	CHECK_VALID(-1);
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"Accessing non-existent mmap segment");
		return -1;
	}
	*ptr = self->data;
	return self->size;
}

static int
mmap_buffer_getwritebuf(mmap_object *self, int index, const void **ptr)
{
	CHECK_VALID(-1);
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"Accessing non-existent mmap segment");
		return -1;
	}
	if (!is_writeable(self))
		return -1;
	*ptr = self->data;
	return self->size;
}

static int
mmap_buffer_getsegcount(mmap_object *self, int *lenp)
{
	CHECK_VALID(-1);
	if (lenp)
		*lenp = self->size;
	return 1;
}

static int
mmap_buffer_getcharbuffer(mmap_object *self, int index, const void **ptr)
{
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"accessing non-existent buffer segment");
		return -1;
	}
	*ptr = (const char *)self->data;
	return self->size;
}

static PyObject *
mmap_object_getattr(mmap_object *self, char *name)
{
	return Py_FindMethod (mmap_object_methods, (PyObject *)self, name);
}

static int
mmap_length(mmap_object *self)
{
	CHECK_VALID(-1);
	return self->size;
}

static PyObject *
mmap_item(mmap_object *self, int i)
{
	CHECK_VALID(NULL);
	if (i < 0 || (size_t)i >= self->size) {
		PyErr_SetString(PyExc_IndexError, "mmap index out of range");
		return NULL;
	}
	return PyString_FromStringAndSize(self->data + i, 1);
}

static PyObject *
mmap_slice(mmap_object *self, int ilow, int ihigh)
{
	CHECK_VALID(NULL);
	if (ilow < 0)
		ilow = 0;
	else if ((size_t)ilow > self->size)
		ilow = self->size;
	if (ihigh < 0)
		ihigh = 0;
	if (ihigh < ilow)
		ihigh = ilow;
	else if ((size_t)ihigh > self->size)
		ihigh = self->size;

	return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
}

static PyObject *
mmap_concat(mmap_object *self, PyObject *bb)
{
	CHECK_VALID(NULL);
	PyErr_SetString(PyExc_SystemError,
			"mmaps don't support concatenation");
	return NULL;
}

static PyObject *
mmap_repeat(mmap_object *self, int n)
{
	CHECK_VALID(NULL);
	PyErr_SetString(PyExc_SystemError,
			"mmaps don't support repeat operation");
	return NULL;
}

static int
mmap_ass_slice(mmap_object *self, int ilow, int ihigh, PyObject *v)
{
	const char *buf;

	CHECK_VALID(-1);
	if (ilow < 0)
		ilow = 0;
	else if ((size_t)ilow > self->size)
		ilow = self->size;
	if (ihigh < 0)
		ihigh = 0;
	if (ihigh < ilow)
		ihigh = ilow;
	else if ((size_t)ihigh > self->size)
		ihigh = self->size;

	if (v == NULL) {
		PyErr_SetString(PyExc_TypeError,
				"mmap object doesn't support slice deletion");
		return -1;
	}
	if (! (PyString_Check(v)) ) {
		PyErr_SetString(PyExc_IndexError,
				"mmap slice assignment must be a string");
		return -1;
	}
	if ( PyString_Size(v) != (ihigh - ilow) ) {
		PyErr_SetString(PyExc_IndexError,
				"mmap slice assignment is wrong size");
		return -1;
	}
	if (!is_writeable(self))
		return -1;
	buf = PyString_AsString(v);
	memcpy(self->data + ilow, buf, ihigh-ilow);
	return 0;
}

static int
mmap_ass_item(mmap_object *self, int i, PyObject *v)
{
	const char *buf;

	CHECK_VALID(-1);
	if (i < 0 || (size_t)i >= self->size) {
		PyErr_SetString(PyExc_IndexError, "mmap index out of range");
		return -1;
	}
	if (v == NULL) {
		PyErr_SetString(PyExc_TypeError,
				"mmap object doesn't support item deletion");
		return -1;
	}
	if (! (PyString_Check(v) && PyString_Size(v)==1) ) {
		PyErr_SetString(PyExc_IndexError,
				"mmap assignment must be single-character string");
		return -1;
	}
	if (!is_writeable(self))
		return -1;
	buf = PyString_AsString(v);
	self->data[i] = buf[0];
	return 0;
}

static PySequenceMethods mmap_as_sequence = {
	(inquiry)mmap_length,		       /*sq_length*/
	(binaryfunc)mmap_concat,	       /*sq_concat*/
	(intargfunc)mmap_repeat,	       /*sq_repeat*/
	(intargfunc)mmap_item,		       /*sq_item*/
	(intintargfunc)mmap_slice,	       /*sq_slice*/
	(intobjargproc)mmap_ass_item,	       /*sq_ass_item*/
	(intintobjargproc)mmap_ass_slice,      /*sq_ass_slice*/
};

static PyBufferProcs mmap_as_buffer = {
	(getreadbufferproc)mmap_buffer_getreadbuf,
	(getwritebufferproc)mmap_buffer_getwritebuf,
	(getsegcountproc)mmap_buffer_getsegcount,
	(getcharbufferproc)mmap_buffer_getcharbuffer,
};

static PyTypeObject mmap_object_type = {
	PyObject_HEAD_INIT(0) /* patched in module init */
	0,					/* ob_size */
	"mmap.mmap",				/* tp_name */
	sizeof(mmap_object),			/* tp_size */
	0,					/* tp_itemsize */
	/* methods */
	(destructor) mmap_object_dealloc,	/* tp_dealloc */
	0,					/* tp_print */
	(getattrfunc) mmap_object_getattr,	/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
	&mmap_as_sequence,			/*tp_as_sequence*/
	0,					/*tp_as_mapping*/
	0,					/*tp_hash*/
	0,					/*tp_call*/
	0,					/*tp_str*/
	0,					/*tp_getattro*/
	0,					/*tp_setattro*/
	&mmap_as_buffer,			/*tp_as_buffer*/
	Py_TPFLAGS_HAVE_GETCHARBUFFER,		/*tp_flags*/
	0,					/*tp_doc*/
};

/* extract the map size from the given PyObject

   The map size is restricted to [0, INT_MAX] because this is the current
   Python limitation on object sizes. Although the mmap object *could* handle
   a larger map size, there is no point because all the useful operations
   (len(), slicing(), sequence indexing) are limited by a C int.

   Returns -1 on error, with an appropriate Python exception raised. On
   success, the map size is returned. */
static int
_GetMapSize(PyObject *o)
{
	if (PyInt_Check(o)) {
		long i = PyInt_AsLong(o);
		if (PyErr_Occurred())
			return -1;
		if (i < 0)
			goto onnegoverflow;
		if (i > INT_MAX)
			goto onposoverflow;
		return (int)i;
	}
	else if (PyLong_Check(o)) {
		long i = PyLong_AsLong(o);
		if (PyErr_Occurred()) {
			/* yes negative overflow is mistaken for positive overflow
			   but not worth the trouble to check sign of 'i' */
			if (PyErr_ExceptionMatches(PyExc_OverflowError))
				goto onposoverflow;
			else
				return -1;
		}
		if (i < 0)
			goto onnegoverflow;
		if (i > INT_MAX)
			goto onposoverflow;
		return (int)i;
	}
	else {
		PyErr_SetString(PyExc_TypeError,
				"map size must be an integral value");
		return -1;
	}

  onnegoverflow:
	PyErr_SetString(PyExc_OverflowError,
			"memory mapped size must be positive");
	return -1;

  onposoverflow:
	PyErr_SetString(PyExc_OverflowError,
			"memory mapped size is too large (limited by C int)");
	return -1;
}

#ifdef UNIX
static PyObject *
new_mmap_object(PyObject *self, PyObject *args, PyObject *kwdict)
{
#ifdef HAVE_FSTAT
	struct stat st;
#endif
	mmap_object *m_obj;
	PyObject *map_size_obj = NULL;
	int map_size;
	int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
	access_mode access = ACCESS_DEFAULT;
	char *keywords[] = {"fileno", "length",
			    "flags", "prot",
			    "access", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iii", keywords,
					 &fd, &map_size_obj, &flags, &prot, &access))
		return NULL;
	map_size = _GetMapSize(map_size_obj);
	if (map_size < 0)
		return NULL;

	if ((access != ACCESS_DEFAULT) &&
	    ((flags != MAP_SHARED) || ( prot != (PROT_WRITE | PROT_READ))))
		return PyErr_Format(PyExc_ValueError,
				    "mmap can't specify both access and flags, prot.");
	switch(access) {
	case ACCESS_READ:
		flags = MAP_SHARED;
		prot = PROT_READ;
		break;
	case ACCESS_WRITE:
		flags = MAP_SHARED;
		prot = PROT_READ | PROT_WRITE;
		break;
	case ACCESS_COPY:
		flags = MAP_PRIVATE;
		prot = PROT_READ | PROT_WRITE;
		break;
	case ACCESS_DEFAULT:
		/* use the specified or default values of flags and prot */
		break;
	default:
		return PyErr_Format(PyExc_ValueError,
				    "mmap invalid access parameter.");
	}

#ifdef HAVE_FSTAT
#  ifdef __VMS
	/* on OpenVMS we must ensure that all bytes are written to the file */
	fsync(fd);
#  endif
	if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
	    (size_t)map_size > st.st_size) {
		PyErr_SetString(PyExc_ValueError,
				"mmap length is greater than file size");
		return NULL;
	}
#endif
	m_obj = PyObject_New (mmap_object, &mmap_object_type);
	if (m_obj == NULL) {return NULL;}
	m_obj->size = (size_t) map_size;
	m_obj->pos = (size_t) 0;
	m_obj->fd = dup(fd);
	if (m_obj->fd == -1) {
		Py_DECREF(m_obj);
		PyErr_SetFromErrno(mmap_module_error);
		return NULL;
	}
	m_obj->data = mmap(NULL, map_size,
			   prot, flags,
			   fd, 0);
	if (m_obj->data == (char *)-1) {
	        m_obj->data = NULL;
		Py_DECREF(m_obj);
		PyErr_SetFromErrno(mmap_module_error);
		return NULL;
	}
	m_obj->access = access;
	return (PyObject *)m_obj;
}
#endif /* UNIX */

#ifdef MS_WINDOWS
static PyObject *
new_mmap_object(PyObject *self, PyObject *args, PyObject *kwdict)
{
	mmap_object *m_obj;
	PyObject *map_size_obj = NULL;
	int map_size;
	char *tagname = "";
	DWORD dwErr = 0;
	int fileno;
	HANDLE fh = 0;
	access_mode   access = ACCESS_DEFAULT;
	DWORD flProtect, dwDesiredAccess;
	char *keywords[] = { "fileno", "length",
			     "tagname",
			     "access", NULL };

	if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|zi", keywords,
					 &fileno, &map_size_obj,
					 &tagname, &access)) {
		return NULL;
	}

	switch(access) {
	case ACCESS_READ:
		flProtect = PAGE_READONLY;
		dwDesiredAccess = FILE_MAP_READ;
		break;
	case ACCESS_DEFAULT:  case ACCESS_WRITE:
		flProtect = PAGE_READWRITE;
		dwDesiredAccess = FILE_MAP_WRITE;
		break;
	case ACCESS_COPY:
		flProtect = PAGE_WRITECOPY;
		dwDesiredAccess = FILE_MAP_COPY;
		break;
	default:
		return PyErr_Format(PyExc_ValueError,
				    "mmap invalid access parameter.");
	}

	map_size = _GetMapSize(map_size_obj);
	if (map_size < 0)
		return NULL;

	/* if an actual filename has been specified */
	if (fileno != 0) {
		fh = (HANDLE)_get_osfhandle(fileno);
		if (fh==(HANDLE)-1) {
			PyErr_SetFromErrno(mmap_module_error);
			return NULL;
		}
		/* Win9x appears to need us seeked to zero */
		lseek(fileno, 0, SEEK_SET);
	}

	m_obj = PyObject_New (mmap_object, &mmap_object_type);
	if (m_obj==NULL)
		return NULL;
	/* Set every field to an invalid marker, so we can safely
	   destruct the object in the face of failure */
	m_obj->data = NULL;
	m_obj->file_handle = INVALID_HANDLE_VALUE;
	m_obj->map_handle = INVALID_HANDLE_VALUE;
	m_obj->tagname = NULL;

	if (fh) {
		/* It is necessary to duplicate the handle, so the
		   Python code can close it on us */
		if (!DuplicateHandle(
			GetCurrentProcess(), /* source process handle */
			fh, /* handle to be duplicated */
			GetCurrentProcess(), /* target proc handle */
			(LPHANDLE)&m_obj->file_handle, /* result */
			0, /* access - ignored due to options value */
			FALSE, /* inherited by child processes? */
			DUPLICATE_SAME_ACCESS)) { /* options */
			dwErr = GetLastError();
			Py_DECREF(m_obj);
			PyErr_SetFromWindowsErr(dwErr);
			return NULL;
		}
		if (!map_size) {
			m_obj->size = GetFileSize (fh, NULL);
		} else {
			m_obj->size = map_size;
		}
	}
	else {
		m_obj->size = map_size;
	}

	/* set the initial position */
	m_obj->pos = (size_t) 0;

	/* set the tag name */
	if (tagname != NULL && *tagname != '\0') {
		m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
		if (m_obj->tagname == NULL) {
			PyErr_NoMemory();
			Py_DECREF(m_obj);
			return NULL;
		}
		strcpy(m_obj->tagname, tagname);
	}
	else
		m_obj->tagname = NULL;

	m_obj->access = access;
	m_obj->map_handle = CreateFileMapping (m_obj->file_handle,
					       NULL,
					       flProtect,
					       0,
					       m_obj->size,
					       m_obj->tagname);
	if (m_obj->map_handle != NULL) {
		m_obj->data = (char *) MapViewOfFile (m_obj->map_handle,
						      dwDesiredAccess,
						      0,
						      0,
						      0);
		if (m_obj->data != NULL) {
			return ((PyObject *) m_obj);
		} else {
			dwErr = GetLastError();
		}
	} else {
		dwErr = GetLastError();
	}
	Py_DECREF(m_obj);
	PyErr_SetFromWindowsErr(dwErr);
	return (NULL);
}
#endif /* MS_WINDOWS */

/* List of functions exported by this module */
static struct PyMethodDef mmap_functions[] = {
	{"mmap",	(PyCFunction) new_mmap_object,
	 METH_VARARGS|METH_KEYWORDS},
	{NULL,		NULL}	     /* Sentinel */
};

PyMODINIT_FUNC
	initmmap(void)
{
	PyObject *dict, *module;

	/* Patch the object type */
	mmap_object_type.ob_type = &PyType_Type;

	module = Py_InitModule ("mmap", mmap_functions);
	dict = PyModule_GetDict (module);
	mmap_module_error = PyExc_EnvironmentError;
	Py_INCREF(mmap_module_error);
	PyDict_SetItemString (dict, "error", mmap_module_error);
#ifdef PROT_EXEC
	PyDict_SetItemString (dict, "PROT_EXEC", PyInt_FromLong(PROT_EXEC) );
#endif
#ifdef PROT_READ
	PyDict_SetItemString (dict, "PROT_READ", PyInt_FromLong(PROT_READ) );
#endif
#ifdef PROT_WRITE
	PyDict_SetItemString (dict, "PROT_WRITE", PyInt_FromLong(PROT_WRITE) );
#endif

#ifdef MAP_SHARED
	PyDict_SetItemString (dict, "MAP_SHARED", PyInt_FromLong(MAP_SHARED) );
#endif
#ifdef MAP_PRIVATE
	PyDict_SetItemString (dict, "MAP_PRIVATE",
			      PyInt_FromLong(MAP_PRIVATE) );
#endif
#ifdef MAP_DENYWRITE
	PyDict_SetItemString (dict, "MAP_DENYWRITE",
			      PyInt_FromLong(MAP_DENYWRITE) );
#endif
#ifdef MAP_EXECUTABLE
	PyDict_SetItemString (dict, "MAP_EXECUTABLE",
			      PyInt_FromLong(MAP_EXECUTABLE) );
#endif
#ifdef MAP_ANON
	PyDict_SetItemString (dict, "MAP_ANON", PyInt_FromLong(MAP_ANON) );
	PyDict_SetItemString (dict, "MAP_ANONYMOUS",
			      PyInt_FromLong(MAP_ANON) );
#endif

	PyDict_SetItemString (dict, "PAGESIZE",
			      PyInt_FromLong( (long)my_getpagesize() ) );

	PyDict_SetItemString (dict, "ACCESS_READ",
			      PyInt_FromLong(ACCESS_READ));
	PyDict_SetItemString (dict, "ACCESS_WRITE",
			      PyInt_FromLong(ACCESS_WRITE));
	PyDict_SetItemString (dict, "ACCESS_COPY",
			      PyInt_FromLong(ACCESS_COPY));
}


text:
<?php
hocwp_article_before();
hocwp_post_thumbnail( array( 'width' => 200, 'height' => 120 ) );
hocwp_post_title_link();
hocwp_entry_meta();
hocwp_entry_summary( 250 );
hocwp_article_after();


text:
drop index ACT_RU_CASE_EXECUTION.ACT_IDX_CASE_EXEC_BUSKEY;

-- indexes for concurrency problems - https://app.camunda.com/jira/browse/CAM-1646 --
drop index ACT_RU_CASE_EXECUTION.ACT_IDX_CASE_EXEC_CASE;
drop index ACT_RU_CASE_EXECUTION.ACT_IDX_CASE_EXEC_PARENT;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_CASE_EXEC;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_CASE_INST;
drop index ACT_RU_TASK.ACT_IDX_TASK_CASE_EXEC;
drop index ACT_RU_TASK.ACT_IDX_TASK_CASE_DEF_ID;
drop index ACT_RU_CASE_SENTRY_PART.ACT_IDX_CASE_SENTRY_CASE_INST;
drop index ACT_RU_CASE_SENTRY_PART.ACT_IDX_CASE_SENTRY_CASE_EXEC;

alter table ACT_RU_CASE_EXECUTION
    drop constraint ACT_FK_CASE_EXE_CASE_INST;

alter table ACT_RU_CASE_EXECUTION
    drop constraint ACT_FK_CASE_EXE_PARENT;

alter table ACT_RU_CASE_EXECUTION
    drop constraint ACT_FK_CASE_EXE_CASE_DEF;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_CASE_EXE;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_CASE_INST;

alter table ACT_RU_TASK
    drop constraint ACT_FK_TASK_CASE_EXE;

alter table ACT_RU_TASK
    drop constraint ACT_FK_TASK_CASE_DEF;

alter table ACT_RU_CASE_SENTRY_PART
    drop constraint ACT_FK_CASE_SENTRY_CASE_INST;

alter table ACT_RU_CASE_SENTRY_PART
    drop constraint ACT_FK_CASE_SENTRY_CASE_EXEC;

if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RE_CASE_DEF') drop table ACT_RE_CASE_DEF;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_CASE_EXECUTION') drop table ACT_RU_CASE_EXECUTION;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_CASE_SENTRY_PART') drop table ACT_RU_CASE_SENTRY_PART;


text:
<?php

// myBundleictBundle:scholarship:edit.html.twig
return array (
);


text:
// Programar em C# #58 - Classe Queue

using System;
using System.Collections.Generic;

namespace Base {
    class ClasseQueue {
        private Queue<int> fila = new Queue<int>();
        private const int Multiplicador = 10;
        private int numero = 1;

        public void Run() {
            for (int indice = 1; indice <= 5; indice++) {
                fila.Enqueue(numero);
                numero *= Multiplicador;
            }

            ImprimirFila();

            Console.WriteLine($"\nA remover o número {fila.Dequeue()} da fila com o método Dequeue()!\n");

            ImprimirFila();

            Console.WriteLine($"\nO número que se encontra na parte superior da fila é o {fila.Peek()}!");
        }

        private void ImprimirFila() {
            foreach (var numero in fila)
                Console.WriteLine(numero);
        }
    }
}


text:
package org.jboss.hal.client.configuration.subsystem.infinispan;

import javax.inject.Inject;

import org.jboss.hal.core.mbui.table.TableButtonFactory;
import org.jboss.hal.meta.MetadataRegistry;
import org.jboss.hal.resources.Resources;

import static org.jboss.hal.client.configuration.subsystem.infinispan.CacheType.SCATTERED;

public class ScatteredCacheView extends CacheViewImpl<ScatteredCachePresenter>
        implements ScatteredCachePresenter.MyView {

    @Inject
    public ScatteredCacheView(MetadataRegistry metadataRegistry, TableButtonFactory tableButtonFactory,
            Resources resources) {
        init(SCATTERED, metadataRegistry, tableButtonFactory, resources);
    }
}


text:
#include "espressif/esp_common.h"
#include "freertos/portmacro.h"

#include "gpio.h"

void ICACHE_FLASH_ATTR gpio_config(GPIO_ConfigTypeDef *pGPIOConfig) {
  uint16 gpio_pin_mask = pGPIOConfig->GPIO_Pin;
  uint32 io_reg;
  uint8 io_num = 0;
  uint32 pin_reg;

  if (pGPIOConfig->GPIO_Mode == GPIO_Mode_Input) {
    GPIO_AS_INPUT(gpio_pin_mask);
  } else if (pGPIOConfig->GPIO_Mode == GPIO_Mode_Output) {
    GPIO_AS_OUTPUT(gpio_pin_mask);
  }

  do {
    if ((gpio_pin_mask >> io_num) & 0x1) {
      io_reg = GPIO_PIN_REG(io_num);

      if ((0x1 << io_num) &
          (GPIO_Pin_0 | GPIO_Pin_2 | GPIO_Pin_4 | GPIO_Pin_5)) {
        PIN_FUNC_SELECT(io_reg, 0);
      } else {
        PIN_FUNC_SELECT(io_reg, 3);
      }

      if (pGPIOConfig->GPIO_Pullup) {
        PIN_PULLUP_EN(io_reg);
      } else {
        PIN_PULLUP_DIS(io_reg);
      }

      if (pGPIOConfig->GPIO_Mode == GPIO_Mode_Out_OD) {
        portENTER_CRITICAL();

        pin_reg = GPIO_REG_READ(GPIO_PIN_ADDR(io_num));
        pin_reg &= (~GPIO_PIN_DRIVER_MASK);
        pin_reg |= (GPIO_PAD_DRIVER_ENABLE << GPIO_PIN_DRIVER_LSB);
        GPIO_REG_WRITE(GPIO_PIN_ADDR(io_num), pin_reg);

        portEXIT_CRITICAL();
      } else if (pGPIOConfig->GPIO_Mode == GPIO_Mode_Sigma_Delta) {
        portENTER_CRITICAL();

        pin_reg = GPIO_REG_READ(GPIO_PIN_ADDR(io_num));
        pin_reg &= (~GPIO_PIN_SOURCE_MASK);
        pin_reg |= (0x1 << GPIO_PIN_SOURCE_LSB);
        GPIO_REG_WRITE(GPIO_PIN_ADDR(io_num), pin_reg);
        GPIO_REG_WRITE(GPIO_SIGMA_DELTA_ADDRESS, SIGMA_DELTA_ENABLE);

        portEXIT_CRITICAL();
      }

      gpio_pin_intr_state_set(io_num, pGPIOConfig->GPIO_IntrType);
    }

    io_num++;
  } while (io_num < 16);
}

/*
 * Change GPIO pin output by setting, clearing, or disabling pins.
 * In general, it is expected that a bit will be set in at most one
 * of these masks.  If a bit is clear in all masks, the output state
 * remains unchanged.
 *
 * There is no particular ordering guaranteed; so if the order of
 * writes is significant, calling code should divide a single call
 * into multiple calls.
 */
void ICACHE_FLASH_ATTR gpio_output_conf(uint32 set_mask, uint32 clear_mask,
                                        uint32 enable_mask,
                                        uint32 disable_mask) {
  GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, set_mask);
  GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, clear_mask);
  GPIO_REG_WRITE(GPIO_ENABLE_W1TS_ADDRESS, enable_mask);
  GPIO_REG_WRITE(GPIO_ENABLE_W1TC_ADDRESS, disable_mask);
}

/*
 * Sample the value of GPIO input pins and returns a bitmask.
 */
uint32 ICACHE_FLASH_ATTR gpio_input_get(void) {
  return GPIO_REG_READ(GPIO_IN_ADDRESS);
}

/*
 * Register an application-specific interrupt handler for GPIO pin
 * interrupts.  Once the interrupt handler is called, it will not
 * be called again until after a call to gpio_intr_ack.  Any GPIO
 * interrupts that occur during the interim are masked.
 *
 * The application-specific handler is called with a mask of
 * pending GPIO interrupts.  After processing pin interrupts, the
 * application-specific handler may wish to use gpio_intr_pending
 * to check for any additional pending interrupts before it returns.
 */
void ICACHE_FLASH_ATTR gpio_intr_handler_register(void *fn) {
  _xt_isr_attach(ETS_GPIO_INUM, fn, NULL);
}

/*
  only highlevel and lowlevel intr can use for wakeup
*/
void ICACHE_FLASH_ATTR
gpio_pin_wakeup_enable(uint32 i, GPIO_INT_TYPE intr_state) {
  uint32 pin_reg;

  if ((intr_state == GPIO_PIN_INTR_LOLEVEL) ||
      (intr_state == GPIO_PIN_INTR_HILEVEL)) {
    portENTER_CRITICAL();

    pin_reg = GPIO_REG_READ(GPIO_PIN_ADDR(i));
    pin_reg &= (~GPIO_PIN_INT_TYPE_MASK);
    pin_reg |= (intr_state << GPIO_PIN_INT_TYPE_LSB);
    pin_reg |= GPIO_PIN_WAKEUP_ENABLE_SET(GPIO_WAKEUP_ENABLE);
    GPIO_REG_WRITE(GPIO_PIN_ADDR(i), pin_reg);

    portEXIT_CRITICAL();
  }
}

void ICACHE_FLASH_ATTR gpio_pin_wakeup_disable(void) {
  uint8 i;
  uint32 pin_reg;

  for (i = 0; i < GPIO_PIN_COUNT; i++) {
    pin_reg = GPIO_REG_READ(GPIO_PIN_ADDR(i));

    if (pin_reg & GPIO_PIN_WAKEUP_ENABLE_MASK) {
      pin_reg &= (~GPIO_PIN_INT_TYPE_MASK);
      pin_reg |= (GPIO_PIN_INTR_DISABLE << GPIO_PIN_INT_TYPE_LSB);
      pin_reg &= ~(GPIO_PIN_WAKEUP_ENABLE_SET(GPIO_WAKEUP_ENABLE));
      GPIO_REG_WRITE(GPIO_PIN_ADDR(i), pin_reg);
    }
  }
}

void ICACHE_FLASH_ATTR
gpio_pin_intr_state_set(uint32 i, GPIO_INT_TYPE intr_state) {
  uint32 pin_reg;

  portENTER_CRITICAL();

  pin_reg = GPIO_REG_READ(GPIO_PIN_ADDR(i));
  pin_reg &= (~GPIO_PIN_INT_TYPE_MASK);
  pin_reg |= (intr_state << GPIO_PIN_INT_TYPE_LSB);
  GPIO_REG_WRITE(GPIO_PIN_ADDR(i), pin_reg);

  portEXIT_CRITICAL();
}

void ICACHE_FLASH_ATTR gpio16_output_conf(void) {
  WRITE_PERI_REG(
      PAD_XPD_DCDC_CONF,
      (READ_PERI_REG(PAD_XPD_DCDC_CONF) & 0xffffffbc) |
          (uint32)0x1);  // mux configuration for XPD_DCDC to output rtc_gpio0

  WRITE_PERI_REG(RTC_GPIO_CONF,
                 (READ_PERI_REG(RTC_GPIO_CONF) & (uint32)0xfffffffe) |
                     (uint32)0x0);  // mux configuration for out enable

  WRITE_PERI_REG(RTC_GPIO_ENABLE,
                 (READ_PERI_REG(RTC_GPIO_ENABLE) & (uint32)0xfffffffe) |
                     (uint32)0x1);  // out enable
}

void ICACHE_FLASH_ATTR gpio16_output_set(uint8 value) {
  WRITE_PERI_REG(
      RTC_GPIO_OUT,
      (READ_PERI_REG(RTC_GPIO_OUT) & (uint32)0xfffffffe) | (uint32)(value & 1));
}

void ICACHE_FLASH_ATTR gpio16_input_conf(void) {
  WRITE_PERI_REG(PAD_XPD_DCDC_CONF,
                 (READ_PERI_REG(PAD_XPD_DCDC_CONF) & 0xffffffbc) |
                     (uint32)0x1);  // mux configuration for XPD_DCDC and
                                    // rtc_gpio0 connection

  WRITE_PERI_REG(RTC_GPIO_CONF,
                 (READ_PERI_REG(RTC_GPIO_CONF) & (uint32)0xfffffffe) |
                     (uint32)0x0);  // mux configuration for out enable

  WRITE_PERI_REG(
      RTC_GPIO_ENABLE,
      READ_PERI_REG(RTC_GPIO_ENABLE) & (uint32)0xfffffffe);  // out disable
}

uint8 ICACHE_FLASH_ATTR gpio16_input_get(void) {
  return (uint8)(READ_PERI_REG(RTC_GPIO_IN_DATA) & 1);
}


text:
/**
 *
 * @author Tristan Charuel <tristan.charuel@utt.fr>
 * @author Julien Egret <julien.egret@utt.fr>
 *
 * Package de l'interface graphique
 */

package gui;


text:
#ifndef MODULES_AUDIO_PROCESSING_AGC2_ADAPTIVE_MODE_LEVEL_ESTIMATOR_AGC_H_
#define MODULES_AUDIO_PROCESSING_AGC2_ADAPTIVE_MODE_LEVEL_ESTIMATOR_AGC_H_

#include <stddef.h>
#include <stdint.h>

#include "modules/audio_processing/agc/agc.h"
#include "modules/audio_processing/agc2/adaptive_mode_level_estimator.h"
#include "modules/audio_processing/agc2/saturation_protector.h"
#include "modules/audio_processing/agc2/vad_with_level.h"

namespace webrtc {
class AdaptiveModeLevelEstimatorAgc : public Agc {
 public:
  explicit AdaptiveModeLevelEstimatorAgc(ApmDataDumper* apm_data_dumper);

  // |audio| must be mono; in a multi-channel stream, provide the first (usually
  // left) channel.
  void Process(const int16_t* audio,
               size_t length,
               int sample_rate_hz) override;

  // Retrieves the difference between the target RMS level and the current
  // signal RMS level in dB. Returns true if an update is available and false
  // otherwise, in which case |error| should be ignored and no action taken.
  bool GetRmsErrorDb(int* error) override;
  void Reset() override;

  float voice_probability() const override;

 private:
  static constexpr int kTimeUntilConfidentMs = 700;
  static constexpr int kDefaultAgc2LevelHeadroomDbfs = -1;
  int32_t time_in_ms_since_last_estimate_ = 0;
  AdaptiveModeLevelEstimator level_estimator_;
  VadWithLevel agc2_vad_;
  float latest_voice_probability_ = 0.f;
};
}  // namespace webrtc

#endif  // MODULES_AUDIO_PROCESSING_AGC2_ADAPTIVE_MODE_LEVEL_ESTIMATOR_AGC_H_


text:
@interface WordMessages ()

@end

@implementation WordMessages

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)setWordObject:(id)theWord{
    self.word = theWord;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touched: %@", self.word.wordName);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [titleBar setTitle:self.word.wordName];
    NSLog(@"loading word name: %@", self.word.wordName);

    //setup firebase listener
    [self.word.wordListener observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
        NSLog(@"loading message: %@", snapshot.value);
        UITextView *aMessage = [[UITextView alloc] init];
        [aMessage setText:snapshot.value];
        aMessage.frame = CGRectMake(10, 0, 310, 50);
        [contentScroll addSubview:aMessage];
        [aMessage setFont:[UIFont fontWithName:@"Helvetica" size:20]];

        CGSize size = [aMessage sizeThatFits:CGSizeMake(320, FLT_MAX)];

        NSLog(@"Height of thing: %f", size.height);
        NSLog(@"Height so far: %d", messageHeightSoFar);

        [aMessage.layer setBorderColor:[[UIColor grayColor] CGColor]];
        [aMessage.layer setBorderWidth:1.0];
        [aMessage.layer setMasksToBounds:YES];

        [aMessage setFrame:CGRectMake(10, messageHeightSoFar, 300, size.height + 10)];
        [aMessage setEditable:NO];

        messageHeightSoFar += size.height;
        [contentScroll setContentSize:CGSizeMake(320, messageHeightSoFar)];
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end