text:
package ru.stqa.pft.addressbook.appmanager;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;

import java.util.List;

/**
 * Created by RomanovaD on 22.05.2017.
 */
public class ContactHelper extends HelperBase {

    public ContactHelper(WebDriver wd) {
        super(wd);
    }

    public void submitContactCreation() {
        click(By.xpath("//div[@id='content']/form/input[21]"));
    }

    public void fillContactForm(ContactData contactData, boolean creation) {
        type(By.name("firstname"), contactData.getFirstname());
        type(By.name("lastname"), contactData.getLastname());
        type(By.name("address"), contactData.getAddress());
        type(By.name("home"), contactData.getHomePhone());
        type(By.name("mobile"), contactData.getMobilePhone());
        type(By.name("work"), contactData.getWorkPhone());
        type(By.name("email"), contactData.getMail());
        attach(By.name("photo"), contactData.getPhoto());
        if (creation) {
            if (contactData.getGroups().size() > 0) {
                Assert.assertTrue(contactData.getGroups().size() == 1);
                new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroups().iterator().next().getName());
            }

        } else {
            Assert.assertFalse(isElementPresent(By.name("new_group")));
        }
    }

    public void initContactCreation() {
        click(By.linkText("add new"));
    }

    public void selectContactById(int id) {
        wd.findElement(By.cssSelector(String.format("input[id='%s']", id))).click();
    }

    public void deleteSelectedContacts() {
        click(By.xpath(".//*[@id='content']/form[2]/div[2]/input"));
        wd.switchTo().alert().accept();
    }

    public void returnToHomePage() {
        click(By.linkText("home"));
    }

    public void initContactModificationById(int id) {
        wd.findElement(By.cssSelector(String.format("a[href='edit.php?id=%s']", id))).click();
    }

    public void submitContactModification() {
        click(By.name("update"));
    }

    public void create(ContactData contact) {
        initContactCreation();
        fillContactForm(contact, true);
        submitContactCreation();
        contactCache = null;
        returnToHomePage();
    }

    public void modify(ContactData contact) {
        initContactModificationById(contact.getId());
        fillContactForm(contact, false);
        submitContactModification();
        contactCache = null;
        returnToHomePage();
    }

    public void addToGroup(ContactData contact, GroupData group) {
        selectContactById(contact.getId());
        selectGroupById(group.getId());
        submitSelectedGroup();
        contactCache = null;
        returnToHomePage();
        selectGroupWithContactsByValue(String.valueOf(group.getId()));
    }

    public void removeFromGroup(ContactData contact, GroupData group) {
        selectGroupWithContactsByValue(String.valueOf(group.getId()));
        selectContactById(contact.getId());
        submitRemoveFromGroup();
        contactCache = null;
        returnToHomePage();
        selectGroupWithContactsByValue("");
    }

    private void submitRemoveFromGroup() {
        wd.findElement(By.name("remove")).click();
    }

    private void selectGroupWithContactsByValue(String value) {
        new Select(wd.findElement(By.name("group"))).selectByValue(value);
    }

    private void submitSelectedGroup() {
        wd.findElement(By.name("add")).click();

    }

    private void selectGroupById(int id) {
        new Select(wd.findElement(By.name("to_group"))).selectByValue(String.valueOf(id));
    }

    public void delete(ContactData contact) {
        selectContactById(contact.getId());
        deleteSelectedContacts();
        contactCache = null;
        returnToHomePage();

    }

    public boolean isThereAContact() {
        return isElementPresent(By.name("selected[]"));
    }

    public int count() {
        return wd.findElements(By.name("selected[]")).size();
    }

    private Contacts contactCache = null;

    public Contacts all() {
        if (contactCache != null) {
            return new Contacts(contactCache);
        }
        contactCache = new Contacts();
        List<WebElement> elements = wd.findElements(By.xpath(".//*[@id='maintable']/tbody/tr[@name='entry']"));
        for (WebElement element : elements) {
            int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("id"));
            String firstname = element.findElement(By.xpath(".//td[3]")).getText();
            String lastname = element.findElement(By.xpath(".//td[2]")).getText();
            String allPhones = element.findElement(By.xpath(".//td[6]")).getText();
            String allMails = element.findElement(By.xpath(".//td[5]")).getText();
            String address = element.findElement(By.xpath(".//td[4]")).getText();
            //String allAddresses = element.findElement(By.xpath(".//td[4]")).getText();
            //String[] phones = element.findElement(By.xpath(".//td[6]")).getText().split("\n");
            //contactCache.add(new ContactData().withId(id).withName(firstname).withSurname(lastname)
                    //.withAllAddresses(allAddresses).withAllMails(allMails).withAllPhones(allPhones));
            contactCache.add(new ContactData().withId(id).withName(firstname).withSurname(lastname)
                    .withAddress(address).withAllMails(allMails).withAllPhones(allPhones));
        }
        return new Contacts(contactCache);
    }

    public ContactData infoFromEditForm(ContactData contact) {
        initContactModificationById(contact.getId());
        String firstname = wd.findElement(By.name("firstname")).getAttribute("value");
        String latname = wd.findElement(By.name("lastname")).getAttribute("value");
        String home = wd.findElement(By.name("home")).getAttribute("value");
        String mobile = wd.findElement(By.name("mobile")).getAttribute("value");
        String work = wd.findElement(By.name("work")).getAttribute("value");
        String email = wd.findElement(By.name("email")).getAttribute("value");
        String email2 = wd.findElement(By.name("email2")).getAttribute("value");
        String email3 = wd.findElement(By.name("email3")).getAttribute("value");
        String address = wd.findElement(By.name("address")).getText();
        wd.navigate().back();
        return new ContactData().withId(contact.getId()).withName(contact.getFirstname()).withSurname(contact.getLastname())
                .withHomePhone(home).withMobilePhone(mobile).withWorkPhone(work)
                .withMail(email).withMail2(email2).withMail3(email3).withAllAddresses(address);

    }

}


text:
<package>
  <name>dumbo_ft_sensor_frequency_check</name>
  <version>0.0.1</version>
  <description>
    Node for checking sampling frequency of dumbo's force torque sensors
  </description>
  <maintainer email="fevb@kth.se">Francisco Vina</maintainer>
  <license>BSD</license>

  <url>http://wiki.ros.org/dumbo_ft_sensor_frequency_check</url>

  <author email="fevb@kth.se">Francisco Vina</author>
  <maintainer email="fevb@kth.se">Francisco Vina</maintainer>

  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>roscpp</build_depend>
  <build_depend>dumbo_force_torque_sensor</build_depend>

  <run_depend>roscpp</run_depend>
  <run_depend>dumbo_force_torque_sensor</run_depend>

</package>

redpajama_set_name: RedPajamaGithub


text:
namespace cobalt {
namespace loader {
namespace image {

namespace {
// Sanity check max size of data buffer.
uint32 kMaxBufferSizeBytes = 4 * 1024 * 1024L;
}  // namespace

ImageDataDecoder::ImageDataDecoder(
    render_tree::ResourceProvider* resource_provider,
    const base::DebuggerHooks& debugger_hooks)
    : resource_provider_(resource_provider),
      debugger_hooks_(debugger_hooks),
      state_(kWaitingForHeader) {
  CalculatePixelFormat();
}

void ImageDataDecoder::DecodeChunk(const uint8* data, size_t size) {
  TRACE_EVENT0("cobalt::loader::image_decoder",
               "ImageDataDecoder::DecodeChunk");
  size_t offset = 0;
  while (offset < size) {
    if (state_ == kError) {
      // Previous chunk causes an error, so there is nothing to do in here.
      return;
    }

    const uint8* input_bytes;
    size_t input_size;

    if (data_buffer_.empty()) {
      // Nothing in |data_buffer_|, so no data append needs to be performed.
      input_bytes = data + offset;
      input_size = size - offset;
      offset += input_size;
    } else {
      DCHECK_GE(kMaxBufferSizeBytes, data_buffer_.size());
      size_t fill_buffer_size =
          std::min(kMaxBufferSizeBytes - data_buffer_.size(), size - offset);

      // Append new data to data_buffer
      data_buffer_.insert(data_buffer_.end(), data + offset,
                          data + offset + fill_buffer_size);

      input_bytes = &data_buffer_[0];
      input_size = data_buffer_.size();
      offset += fill_buffer_size;
    }

    size_t decoded_size = DecodeChunkInternal(input_bytes, input_size);
    if (decoded_size == 0 && offset < size) {
      LOG(ERROR) << "Unable to make progress decoding image.";
      state_ = kError;
      return;
    }

    size_t undecoded_size = input_size - decoded_size;
    if (undecoded_size == 0) {
      // Remove all elements from the data_buffer.
      data_buffer_.clear();
    } else {
      if (data_buffer_.empty()) {
        if (undecoded_size > kMaxBufferSizeBytes) {
          LOG(ERROR) << "Max buffer size too small: " << undecoded_size
                     << "bytes required!";
          state_ = kError;
          return;
        }

        // |data_buffer_| is empty, so assign the undecoded data to it.
        data_buffer_.reserve(undecoded_size);
        data_buffer_.assign(data + offset - undecoded_size, data + offset);
      } else if (decoded_size != 0) {
        // |data_buffer_| is not empty, so erase the decoded data from it.
        data_buffer_.erase(
            data_buffer_.begin(),
            data_buffer_.begin() + static_cast<ptrdiff_t>(decoded_size));
      }
    }
  }
}

scoped_refptr<Image> ImageDataDecoder::FinishAndMaybeReturnImage() {
  TRACE_EVENT0("cobalt::loader::image_decoder",
               "ImageDataDecoder::FinishAndMaybeReturnImage");

  return FinishInternal();
}

std::unique_ptr<render_tree::ImageData> ImageDataDecoder::AllocateImageData(
    const math::Size& size, bool has_alpha) {
  DCHECK(resource_provider_->AlphaFormatSupported(
      render_tree::kAlphaFormatOpaque));
  DCHECK(resource_provider_->AlphaFormatSupported(
      render_tree::kAlphaFormatPremultiplied));
  auto image_data = resource_provider_->AllocateImageData(
      size, pixel_format(),
      has_alpha ? render_tree::kAlphaFormatPremultiplied
                : render_tree::kAlphaFormatOpaque);
  DLOG_IF(ERROR, !image_data) << "Failed to allocate image data ("
                              << size.width() << "x" << size.height() << ").";
  return image_data;
}

scoped_refptr<Image> ImageDataDecoder::CreateStaticImage(
    std::unique_ptr<render_tree::ImageData> image_data) {
  DCHECK(image_data);
  return new StaticImage(
      resource_provider()->CreateImage(std::move(image_data)));
}

void ImageDataDecoder::CalculatePixelFormat() {
  pixel_format_ = render_tree::kPixelFormatRGBA8;
  if (!resource_provider_->PixelFormatSupported(pixel_format_)) {
    pixel_format_ = render_tree::kPixelFormatBGRA8;
  }

  DCHECK(resource_provider_->PixelFormatSupported(pixel_format_));
}

}  // namespace image
}  // namespace loader
}  // namespace cobalt


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*=============================================================================
**
**
**
** Purpose: IEnumConnections interface definition.
**
**
=============================================================================*/

using System;

namespace System.Runtime.InteropServices.ComTypes
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]

    public struct CONNECTDATA
    {
        [MarshalAs(UnmanagedType.Interface)]
        public Object pUnk;
        public int dwCookie;
    }

    [Guid("B196B287-BAB4-101A-B69C-00AA00341D07")]
    [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface IEnumConnections
    {
        [PreserveSig]
        int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] CONNECTDATA[] rgelt, IntPtr pceltFetched);
        [PreserveSig]
        int Skip(int celt);
        void Reset();
        void Clone(out IEnumConnections ppenum);
    }
}


text:
package org.waveprotocol.box.server.waveserver;

import com.google.common.base.Preconditions;
import com.google.common.collect.*;
import com.google.inject.Inject;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.typesafe.config.Config;
import org.apache.commons.codec.binary.Hex;
import org.waveprotocol.box.server.common.CoreWaveletOperationSerializer;
import org.waveprotocol.wave.crypto.*;
import org.waveprotocol.wave.federation.FederationErrorProto.FederationError;
import org.waveprotocol.wave.federation.FederationErrors;
import org.waveprotocol.wave.federation.Proto.ProtocolSignature;
import org.waveprotocol.wave.federation.Proto.ProtocolSignedDelta;
import org.waveprotocol.wave.federation.Proto.ProtocolSignerInfo;
import org.waveprotocol.wave.federation.Proto.ProtocolWaveletDelta;
import org.waveprotocol.wave.federation.WaveletFederationProvider;
import org.waveprotocol.wave.federation.WaveletFederationProvider.DeltaSignerInfoResponseListener;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.version.HashedVersion;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.util.logging.Log;

import java.util.List;
import java.util.Map;

/**
 * Default implementation of {@link CertificateManager}.
 */
public class CertificateManagerImpl implements CertificateManager {

  private static final Log LOG = Log.get(CertificateManagerImpl.class);

  private final SignatureHandler waveSigner;
  private final ImmutableSet<String> localDomains;
  private final WaveSignatureVerifier verifier;
  private final CertPathStore certPathStore;
  private final boolean disableVerfication;

  /**
   * Map of signer ids to requests for the signer info for those ids.  Each signer id is mapped to
   * a multimap: a domain mapped to a list of callbacks for that domain, called when the signer info
   * is available for the signer id.  It is arranged by domain to facilitate the optimisation where
   * exactly 1 signer request is sent per domain.
   */
  private final Map<ByteString, Multimap<String, SignerInfoPrefetchResultListener>>
      signerInfoRequests;

  @Inject
  public CertificateManagerImpl(Config config, SignatureHandler signer,
    WaveSignatureVerifier verifier, CertPathStore certPathStore) {
    this.disableVerfication = config.getBoolean("federation.waveserver_disable_verification");
    this.waveSigner = signer;
    // for now, we just support a single signer
    this.localDomains = ImmutableSet.of(signer.getDomain());
    this.verifier = verifier;
    this.certPathStore = certPathStore;
    this.signerInfoRequests = Maps.newHashMap();

    if (disableVerfication) {
      LOG.warning("** SIGNATURE VERIFICATION DISABLED ** "
          + "see configuration federation.waveserver_disable_verification");
    }
  }

  @Override
  public ImmutableSet<String> getLocalDomains() {
    return localDomains;
  }

  @Override
  public SignatureHandler getLocalSigner() {
    return waveSigner;
  }

  @Override
  public ProtocolSignedDelta signDelta(ByteStringMessage<ProtocolWaveletDelta> delta) {
    // TODO: support extended address paths. For now, there will be exactly
    // one signature, and we don't support federated groups.
    Preconditions.checkState(delta.getMessage().getAddressPathCount() == 0);

    ProtocolSignedDelta.Builder signedDelta = ProtocolSignedDelta.newBuilder();

    signedDelta.setDelta(delta.getByteString());
    signedDelta.addAllSignature(waveSigner.sign(delta));
    return signedDelta.build();
  }

  @Override
  public ByteStringMessage<ProtocolWaveletDelta> verifyDelta(ProtocolSignedDelta signedDelta)
      throws SignatureException, UnknownSignerException {
    ByteStringMessage<ProtocolWaveletDelta> delta;
    try {
      delta = ByteStringMessage.parseProtocolWaveletDelta(signedDelta.getDelta());
    } catch (InvalidProtocolBufferException e) {
      throw new IllegalArgumentException("signed delta does not contain valid delta", e);
    }

    if (disableVerfication) {
      return delta;
    }

    List<String> domains = getParticipantDomains(delta.getMessage());

    if (domains.size() != signedDelta.getSignatureCount()) {
      throw new SignatureException("found " + domains.size() + " domains in " +
          "extended address path, but " + signedDelta.getSignatureCount() +
          " signatures.");
    }

    for (int i = 0; i < domains.size(); i++) {
      String domain = domains.get(i);
      ProtocolSignature signature = signedDelta.getSignature(i);
      verifySingleSignature(delta, signature, domain);
    }

    return delta;
  }

  /**
   * Verifies a single signature.
   * @param delta the payload that we're verifying the signature on.
   * @param signature the signature on the payload
   * @param domain the authority (domain name) that should have signed the
   *   payload.
   * @throws SignatureException if the signature doesn't verify.
   */
  private void verifySingleSignature(ByteStringMessage<ProtocolWaveletDelta> delta,
      ProtocolSignature signature, String domain)
      throws SignatureException, UnknownSignerException {
    verifier.verify(delta.getByteString().toByteArray(), signature, domain);
  }

  /**
   * Returns the domains of all the addresses in the extended address path.
   */
  private List<String> getParticipantDomains(ProtocolWaveletDelta delta) {
    Iterable<String> addresses = getExtendedAddressPath(delta);
    return getDeDupedDomains(addresses);
  }

  /**
   * Extracts the domains from user addresses, and removes duplicates.
   */
  private List<String> getDeDupedDomains(Iterable<String> addresses) {
    List<String> domains = Lists.newArrayList();
    for (String address : addresses) {
      String participantDomain = new ParticipantId(address).getDomain();
      if (!domains.contains(participantDomain)) {
        domains.add(participantDomain);
      }
    }
    return domains;
  }

  /**
   * Returns the extended address path, i.e., the addresses in the delta's
   * address path, plus the author of the delta.
   */
  private Iterable<String> getExtendedAddressPath(ProtocolWaveletDelta delta) {
    return Iterables.concat(delta.getAddressPathList(),
        ImmutableList.of(delta.getAuthor()));
  }

  @Override
  public synchronized void storeSignerInfo(ProtocolSignerInfo signerInfo)
      throws SignatureException {
    verifier.verifySignerInfo(new SignerInfo(signerInfo));
    certPathStore.putSignerInfo(signerInfo);
  }

  @Override
  public synchronized ProtocolSignerInfo retrieveSignerInfo(ByteString signerId) {
    SignerInfo signerInfo;
    try {
      signerInfo = certPathStore.getSignerInfo(signerId.toByteArray());
      // null is acceptable for retrieveSignerInfo.  The user of the certificate manager should call
      // prefetchDeltaSignerInfo for the mechanism to actually populate the certificate manager.
      return signerInfo == null ? null : signerInfo.toProtoBuf();
    } catch (SignatureException e) {
      /*
       * TODO: This may result in the server endlessly requesting the signer info from the
       * remote server, a more graceful failure needs to be implemented.
       */
      LOG.severe("Failed to retreive signer info for "
          + new String(Hex.encodeHex(signerId.toByteArray())), e);
      return null;
    }
  }

  @Override
  public synchronized void prefetchDeltaSignerInfo(WaveletFederationProvider provider,
      ByteString signerId, WaveletName waveletName, HashedVersion deltaEndVersion,
      SignerInfoPrefetchResultListener callback) {
    ProtocolSignerInfo signerInfo = retrieveSignerInfo(signerId);

    if (signerInfo != null) {
      callback.onSuccess(signerInfo);
    } else {
      enqueueSignerInfoRequest(provider, signerId, waveletName, deltaEndVersion, callback);
    }
  }

  /**
   * Enqueue a signer info request for a signed delta on a given domain.
   */
  private synchronized void enqueueSignerInfoRequest(final WaveletFederationProvider provider,
      final ByteString signerId, final WaveletName waveletName,
      HashedVersion deltaEndVersion, SignerInfoPrefetchResultListener callback) {
    final String domain = waveletName.waveletId.getDomain();
    Multimap<String, SignerInfoPrefetchResultListener> domainCallbacks =
        signerInfoRequests.get(signerId);

    if (domainCallbacks == null) {
      domainCallbacks = ArrayListMultimap.create();
      signerInfoRequests.put(signerId, domainCallbacks);
    }

    // The thing is, we need to add multiple callbacks for the same domain, but we only want to
    // have one outstanding request per domain
    domainCallbacks.put(domain, callback);

    if (domainCallbacks.get(domain).size() == 1) {
        provider.getDeltaSignerInfo(signerId, waveletName,
            (deltaEndVersion == null)
                ? null : CoreWaveletOperationSerializer.serialize(deltaEndVersion),
            new DeltaSignerInfoResponseListener() {
              @Override public void onFailure(FederationError error) {
                LOG.warning("getDeltaSignerInfo failed: " + error);
                // Fail all requests on this domain
                dequeueSignerInfoRequestForDomain(signerId, error, domain);
              }

              @Override public void onSuccess(ProtocolSignerInfo signerInfo) {
                try {
                  storeSignerInfo(signerInfo);
                  dequeueSignerInfoRequest(signerId, null);
                } catch (SignatureException e) {
                  LOG.warning("Failed to verify signer info", e);
                  dequeueSignerInfoRequest(signerId, FederationErrors.badRequest(e.toString()));
                }
              }});
    }
  }

  /**
   * Dequeue all signer info requests for a given signer id.
   *
   * @param signerId to dequeue requests for
   * @param error if there was an error, null for success
   */
  private synchronized void dequeueSignerInfoRequest(ByteString signerId, FederationError error) {
    List<String> domains = ImmutableList.copyOf(signerInfoRequests.get(signerId).keySet());
    for (String domain : domains) {
      dequeueSignerInfoRequestForDomain(signerId, error, domain);
    }
  }

  /**
   * Dequeue all signer info requests for a given signer id and a specific domain.
   *
   * @param signerId to dequeue requests for
   * @param error if there was an error, null for success
   * @param domain to dequeue the signer requests for
   */
  private synchronized void dequeueSignerInfoRequestForDomain(ByteString signerId,
      FederationError error, String domain) {
    Multimap<String, SignerInfoPrefetchResultListener> domainListeners =
        signerInfoRequests.get(signerId);
    if (domainListeners == null) {
      LOG.info("There are no domain listeners for signer " + signerId + " domain "+ domain);
      return;
    } else {
      LOG.info("Dequeuing " + domainListeners.size() + " listeners for domain " + domain);
    }

    for (SignerInfoPrefetchResultListener listener : domainListeners.get(domain)) {
      if (error == null) {
        listener.onSuccess(retrieveSignerInfo(signerId));
      } else {
        listener.onFailure(error);
      }
    }

    domainListeners.removeAll(domain);
    if (domainListeners.isEmpty()) {
      // No listeners for any domains, delete the signer id for the overall map
      signerInfoRequests.remove(signerId);
    }
  }
}


text:
using namespace std;

int ReadInteger(ifstream InputStream)
{
    int FileInteger = 0;
    InputStream >> FileInteger;
    return FileInteger;
}

void WriteInteger(ofstream OutputStream, int InputInteger)
{
    OutputStream << InputInteger;
}

int main()
{
    ifstream InputFile("Input.txt", ios_base::in);
    ofstream OutputFile("Output.txt", ios_base::out);
    if (!InputFile) return 0;
    if (!OutputFile) return 0;
    while (!InputFile.eof())
    {
        WriteInteger(OutputFile, ReadInteger(InputFile));
    }
    InputFile.close();
    OutputFile.close();
    return 0;
}


text:
class UnitTestReverseTest : public WsjcppUnitTestBase {
    public:
        UnitTestReverseTest();
        virtual bool doBeforeTest() override;
        virtual void executeTest() override;
        virtual bool doAfterTest() override;
};

#endif // UNIT_TEST_REVERSE_TEST_H


text:
<?php

namespace GarantPark\Selectel\Exceptions;

use Exception;

class LocalFileNotAvailableException extends Exception
{
}


text:
from __future__ import absolute_import, unicode_literals

from .base import Check  # NOQA
from .manager import CheckManager
from .github import GitHubContextCheck

manager = CheckManager()
manager.add('github', GitHubContextCheck)

get = manager.get


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical" >

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/default_padding"
    android:layout_marginLeft="@dimen/list_entry_padding_horizontal"
    android:layout_marginRight="@dimen/list_entry_padding_horizontal"
    android:orientation="horizontal">

    <TextView
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="wrap_content"
      android:text="@string/wallet_history_currency_spinner_label"
      android:textStyle="bold" />
    <Spinner
      android:id="@+id/wallet_history_currency_spinner"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="wrap_content"
      android:layout_marginBottom="@dimen/list_entry_padding_vertical"
      android:focusable="true"
    />
  </LinearLayout>
  <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:foreground="@drawable/fragment_shadow_horizontal_light"
    android:foregroundGravity="top|fill_horizontal" >
    <ExpandableListView
      android:id="@+id/wallet_history_expandable_list"
      android:layout_height="match_parent"
      android:layout_width="match_parent"/>

  </FrameLayout>

</LinearLayout>


text:
current_dir=`dirname "$0"`
current_dir=`cd "$current_dir"; pwd`
root_dir=${current_dir}/../../../../../
workload_config=${root_dir}/conf/workloads/micro/sort.conf
. "${root_dir}/bin/functions/load_bench_config.sh"

enter_bench ScalaSparkSort ${workload_config} ${current_dir}
show_bannar start

rmr_hdfs $OUTPUT_HDFS || true

SIZE=`dir_size $INPUT_HDFS`
START_TIME=`timestamp`
run_spark_job com.intel.hibench.sparkbench.micro.ScalaSort $INPUT_HDFS $OUTPUT_HDFS
END_TIME=`timestamp`

gen_report ${START_TIME} ${END_TIME} ${SIZE}
show_bannar finish
leave_bench


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>Spark NLP 4.2.2 ScalaDoc  - com.johnsnowlabs.nlp.annotators.resolution.util.StringFunctions</title>
          <meta name="description" content="Spark NLP 4.2.2 ScalaDoc - com.johnsnowlabs.nlp.annotators.resolution.util.StringFunctions" />
          <meta name="keywords" content="Spark NLP 4.2.2 ScalaDoc com.johnsnowlabs.nlp.annotators.resolution.util.StringFunctions" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        Spark NLP 4.2.2 ScalaDoc
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

        root

Definition Classes

root

        

        package

        com

Definition Classes

root

        

        package

        johnsnowlabs

Definition Classes

com

        

        package

        nlp

Definition Classes

johnsnowlabs

        

        package

        annotators

Definition Classes

nlp

        

        package

        resolution

Definition Classes

annotators

        

        package

        util

Definition Classes

resolution

                        StringFunctions

                        StructFeature_HadoopFix

t

com.johnsnowlabs.nlp.annotators.resolution.util

StringFunctions

        

        trait

        StringFunctions extends AnyRef

            Linear Supertypes

AnyRef, Any

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

StringFunctions

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        finalize(): Unit

Attributes

protected[lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        def

        label2path(label: String): String

Convenience function to use when naming folders after a string that eventually does not comply with filesystem requirements

Convenience function to use when naming folders after a string that eventually does not comply with filesystem requirements

label

string with special characters to transform into lowercase letters and numbers

returns

lowercase letters and numbers replacing special characters with _

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

                @native()

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
<TITLE>Review for Edtv (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Edtv (1999)

reviewed by
Akiva Gottlieb

EDtv ***

rated PG-13
starring Matthew McConaughey, Jenna Elfman, Ellen DeGeneres, Woody
Harrelson, Martin Landau, Sally Kirkland, Rob Reiner, Dennis Hopper,
Elizabeth Hurley, Clint Howard, Adam Goldberg
written by Lowell Ganz and Babaloo Mandel
based on the screenplay for LOUIS 19, LE ROI DES ONDES by Emile
Gaudreault and Sylvie Bouchard
directed by Ron Howard

Would you ever want a camera crew following you around 24 hours a day,
filming everything you do? If you gave any thought at all to it, my
guess is you'd say no. But Ed Kearney (Matthew McConaughey) in Ron
Howard's comedy EDtv doesn't give that much thought to anything.

Ed is a thirtysomething video store clerk who gets pushed into the
national spotlight when he agrees to star in a show called TrueTV, in
which a film crew would follow him around 24 hours a day. His brother,
Ray (Woody Harrelson, who could pass for McConaughey's brother in real
life), loves the idea because he can get free publicity for his new
gym. Ray's girlfriend Shari (a very good Jenna Elfman) finds out that
Ray is cheating on her when Ed and his cameras go to visit him, and
she realizes that it was Ed she wanted all along. But camera-shy Shari
can't stand all the attention she's getting and comes across as a
bitch on the show (according to 71% of USA Today readers).  Along with
Ed, we also find out hidden secrets about his family. And when Shari
ditches Ed and the cameras and moves away, the dimwitted Ed realizes
that the show has turned his life into a claustrophobic mess. One show
executive (Ellen DeGeneres) decides then to give the show some
excitement by sending out a woman (Elizabeth Hurley) to seduce Ed. By
then, Ed is a national phenomenon, and a few thousand people wait
outside the woman's apartment to cheer Ed on. When the night turns
into a mess, Ed finally confronts head studio executive (Rob Reiner)
and demands to be set free. But then the executive reminds him of the
contract he signed that says that he can be filmed for as long as the
studio would like to film him. Then the film takes a funny satirical
twist as Ed tries to get his simple life back to normal.

EDtv is not nearly as significant as the film that it will be compared
to time and time again, THE TRUMAN SHOW. In the few times that I saw
THE TRUMAN SHOW, I actually dismissed it as another overrated
Hollywood attempt at greatness.  But EDtv actually made me see what
made THE TRUMAN SHOW so special. It had a social significance and
portrayed Truman's world so satirically well. I'm not saying, though,
that EDtv is a bad movie. Infact, I may have enjoyed it more than THE
TRUMAN SHOW. It is funny, smart and entertaining, and it doesn't leave
as many unanswered questions as THE TRUMAN SHOW. But sometimes the
film gets lost, often forgetting what it's there to do. To prove (like
THE TRUMAN SHOW) that television, above all, is just a bunch of crap.

a review by Akiva Gottlieb, The Teenage Movie Critic
akiva@excite.com
http://www.angelfire.com/mo/film
watch me on TBS' "Dinner And A Movie" May 21, 8:05pm EST

Get your free, private email at http://mail.excite.com/

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text: Contains 'ndjson' files created during the projection and simplification


text:
+++
title= "RLSL (Rust -> SPIR-V compiler) Progress report"
date        = 2018-02-09
+++

# Disclaimer
The code for RLSL can be found [here](https://github.com/MaikKlein/rlsl). It is **not** ready to be used at all, the build tools haven't been written yet. I encourage you **not** to build it. Also the code is still in a relatively bad shape.

# What is RLSL?

This is a [follow up post](https://maikklein.github.io/shading-language-part1/). RLSL is a Rust to SPIR-V compiler. SPIR-V is the shading language for Vulkan, similar to other shading languages like GLSL, HLSL but more low level. OpenGL, DX9/11/12, Vulkan, Metal are all graphic APIs that are able to use the GPU to draw pixels on the screen. Those APIs have certain stages that can be controlled by the developer by using the correct shading language.
![](https://i.imgur.com/jCuAYVl.png)

In this blog post, I will only cover the vertex and fragment shader.

Shaders are usually written in GLSL, HLSL and while those languages are relatively nice, they have some downsides. One downside is that you can not share code between files. Because of that game engines like Unity, Unreal Engine, CryEngine, Godot have developed their own shading language stack on top of an existing shading language. This is especially important if you are targeting multiple graphics backends, like OpenGL, DX.

In case of SPIR-V there already exists a [tool](https://github.com/KhronosGroup/SPIRV-Cross) for translating SPIR-V to GLSL/HLSL/MSL. SPIR-V is low level enough to be compiled from a higher level language like Rust.

RLSL should make it much easier to get started with shader development.

# Why Rust as a shading language?

There are a few reasons:

* Libraries: Code can actually be shared
* Package manager: RLSL integrates with cargo and therefor libraries can also be managed by cargo.`RUSTC=rlsl cargo build` will compile the cargo project with RLSL.
* Generics/Traits: RLSL allows generics and traits everywhere except in entry points. I'll go into that later.
* Tooling support: Existing tools still work. (Racer, Rustfmt, Rls etc)
* Possibly better shader compile times: A common approach for current shader languages found in game engines is to copy/paste common shader code behind the scenes. In SPIR-V it is possible to create a big shader module that contains multiple shaders. *This property will be lost if the resulting SPIR-V is cross compiled to a different shading langauge*.
* Integrates with Rust: Structures defined in Rust can be shared between Rust and RLSL, but RLSL should still be usable in other languages.
* Testing: RLSL is a subset of Rust. If your code compiles in RLSL, it will also compile in Rust. This means that you can run your shader code on the CPU.

# Showcase
{{ iframe(src="PersonalAdventurousInganue") }}
[Link to gif](https://gfycat.com/PersonalAdventurousInganue)

```Rust
#![feature(custom_attribute)]
extern crate rlsl_math;
use rlsl_math::{Vec4, Vertex};

#[spirv(fragment)]
fn frag(color: Vec4<f32>) -> Vec4<f32> {
    color
}

#[spirv(vertex)]
fn vertex(vertex: &mut Vertex, pos: Vec4<f32>, color: Vec4<f32>) -> Vec4<f32> {
    vertex.position = pos;
    color
}
```

I recompile the RLSL code after every change, which produces a new `.spv` file. This is a modified version of the triangle example from [ash](https://github.com/MaikKlein/ash). Essentially I just recreate the graphics pipeline if the `.spv` file changes.

And this is how the `.spv` file looks in text form.
```C
; SPIR-V
; Version: 1.2
; Generator: Google rspirv; 0
; Bound: 29
; Schema: 0
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %2 "frag" %9 %12
               OpEntryPoint Vertex %5 "vertex" %9 %10 %12
               OpExecutionMode %2 OriginUpperLeft
               OpExecutionMode %5 OriginUpperLeft
               OpMemberName %Vertex 0 "position"
               OpMemberName %Vertex 1 "point_size"
               OpName %Vertex "Vertex"
               OpDecorate %9 Location 0
               OpDecorate %10 Location 1
               OpDecorate %12 Location 0
               OpMemberDecorate %Vertex 0 BuiltIn Position
               OpMemberDecorate %Vertex 1 BuiltIn PointSize
      %float = OpTypeFloat 32
    %v4float = OpTypeVector %float 4
%_ptr_Input_v4float = OpTypePointer Input %v4float
          %9 = OpVariable %_ptr_Input_v4float Input
         %10 = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
         %12 = OpVariable %_ptr_Output_v4float Output
       %void = OpTypeVoid
         %14 = OpTypeFunction %void
     %Vertex = OpTypeStruct %v4float %float
%_ptr_Output_Vertex = OpTypePointer Output %Vertex
         %20 = OpVariable %_ptr_Output_Vertex Output
%_ptr_Function_v4float = OpTypePointer Function %v4float
       %uint = OpTypeInt 32 0
     %uint_0 = OpConstant %uint 0
          %2 = OpFunction %void None %14
         %15 = OpLabel
               OpBranch %16
         %16 = OpLabel
         %17 = OpLoad %v4float %9
               OpStore %12 %17
               OpReturn
               OpFunctionEnd
          %5 = OpFunction %void None %14
         %21 = OpLabel
               OpBranch %22
         %22 = OpLabel
         %23 = OpLoad %v4float %9
         %27 = OpAccessChain %_ptr_Output_v4float %20 %uint_0
               OpStore %27 %23
         %28 = OpLoad %v4float %10
               OpStore %12 %28
               OpReturn
               OpFunctionEnd

```
# Entry points

```Rust
#[spirv(vertex)]
fn vertex(vertex: &mut Vertex, pos: Vec4<f32>, color: Vec4<f32>) -> Vec4<f32> {
    vertex.position = pos;
    color
}
```

```Rust
vertex: &mut Vertex
```
This is the first argument in a vertex shader. This gives you mutable access to various PerVertex variables like  `gl_Position`, `gl_Pointsize` etc.

```Rust
pos: Vec4<f32>, color: Vec4<f32>
```
The next two arguments are the input to the vertex shader. In the future I will also allow user defined structs. In Vulkan you can only pass SPIR-V primitives into the vertex shader. I will work around this problem by 'unrolling' the type into primitive types.

```Rust
struct Input{
    pos: Vec4<f32>,
    uv: Vec4<f32>,
}
```
will be unrolled into two variables `pos: Vec4<f32>, color: Vec4<f32>`.

```Rust
-> Vec4<f32>
```
The return type is the output of the vertex shader. Currently in RLSL you can only output one type, but this can be a composition of types.

This is the resulting GLSL of the cross compiled `.spv` file with `spirv-cross`. *RLSL currently doesn't generate debug information for global variables*

```C
// vertex shader
#version 450

layout(location = 0) in vec4 _9;
layout(location = 1) in vec4 _10;
layout(location = 0) out vec4 _12;

void main()
{
    gl_Position = _9;
    _12 = _10;
}
```

```C
// fragment shader
#version 450

layout(location = 0) in vec4 _8;
layout(location = 0) out vec4 _10;

void main()
{
    _10 = _8;
}
```
Entry points are not allowed to contain any generics, but functions inside the body are allowed to be generic.

```Rust
fn some_generic_fn<V1: Vector, V2: Vector>(vertex: &mut Vertex,
                                           pos: V1,
                                           color: V2) -> Vec4<f32>{
    ...
}

#[spirv(vertex)]
fn vertex(vertex: &mut Vertex, pos: Vec4<f32>, color: Vec4<f32>) -> Vec4<f32> {
    some_generic_fn(vertex, pos, color)
}

#[spirv(vertex)]
fn vertex2(vertex: &mut Vertex, pos: Vec2<f32>, color: Vec4<f32>) -> Vec4<f32> {
    some_generic_fn(vertex, pos, color)
}
```

It should be easy to create multiple entry points that share the same logic. This is especially useful for instancing where usually only the entry point changes.

Entry points are roughly equivalent to the main function in Rust. The difference is that there can be multiple entry points, and that there are different types of entry points like the vertex and fragment shader.

Currently I just look at every function that has the `#[spirv(vertex)]` or `#[spirv(fragment)]` attribute and I include it in the `.spv` file. In the future I want entry points to be defined outside of the `main.rs` file and I also need a way to specify which entry points should be included in the `.spv` file.

Also you might have noticed that I don't explicitly specify the location of the input / output variables. This is all done behind the scene. This information is inside the `.spv` file, but I will also make this information available in an easier to parse format and I will also create the necessary library to retrieve this information.

Some pseudo API

```Rust
let reflection: Reflection = parse("reflection.toml");
let data: &EntryPoint = reflection.get(some_entry_point).expect("Entry point not found");
data.path() // path to .spv file
data.inputs() // Input information
data.output() // Output information
data.constants() // Constant information
reflection.entry_point_iter() // iterator over every entry point
...
```

If necessary I might also introduce an API to set this information explicitly.

# RLSL is a subset of Rust

RLSL is a subset of Rust. If it compiles in RLSL it should compile in Rust, but not the other way around. SPIR-V has many limitations like  no pointers inside structs. This means a lot of iterators won't work in RLSL.

One interesting design decision is that currently no shader primitives are inside the std library. RLSL ships with the std but only with a reduced version. All the necessary types and functions are defined in an external library called `rlsl_math`.

```Rust
#[spirv(Vec4)]
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec4<T> {
    pub x: T,
    pub y: T,
    pub z: T,
    pub w: T,
}
```

This is currently how a `Vec4<T>` is defined in `rlsl_math`.The `#[spirv(Vec4)]` attribute tells RLSL that this should map to the builtin `vec4` type in SPIR-V. Remember that `rlsl_math` is an external library, that means other math libraries like cgmath or nalgebra should be able to replace `rlsl_math` (maybe not completely). I will probably split common functionality into a separate crate.

# Optimizations

Currently RLSL takes the following steps. `Rust -> HIR -> MIR -> SPIR-V`. There are a few optimizations implemented for MIR, but a lot of things are missing. [spirv-opt](https://github.com/KhronosGroup/SPIRV-Tools#optimizer) can be used to further optimize the `.spv` file.

I am still hoping for a `SPIR-V <-> LLIR` compiler for better optimizations. If nothing pops up within a year or two, I'll probably start one on my own. I don't expect this to be much harder than a `MIR -> SPIR-V` compiler.

`SPIR-V` is an intermediary format, which means it gets compiled by the driver. Considering the fact that most GPU vendors are competitors, I would expect at least some optimizations.

Currently the SPIR-V produced by RLSL is comparable to the SPIR-V produced by [glslang](https://github.com/KhronosGroup/glslang)

# Compilation
In the future you will be able to install RLSL with `cargo install rlsl`. To compile a project you just have to replace rustc with rlsl `RUSTC=rlsl cargo build`. Currently RLSL is completely unoptimized, but the hello triangle example compiles in 0.11s. At the moment RLSL is completely single threaded but that will soon change.

Although I don't expect compile times to be an issue, considering that the amount of shader code should not be that high.

To give you some estimation of the amount of shader code in a commercial engine (Unreal Engine 4)
```Markdown
 Language            Files        Lines         Code     Comments       Blanks
-------------------------------------------------------------------------------
 ...
 C++                 13503      5973298      4361179       586000      1026119
 C++ Header           3294       707450       513044        95156        99250
 Usf                   186        41230        27758         5396         8076
 ...
-------------------------------------------------------------------------------
 Total               70491     21705869     15499494      3410894      2795481
-------------------------------------------------------------------------------
```
`Usf` is the shading language in Unreal Engine 4, which I think is based on HLSL.

Currently RLSL is still tied to LLVM. If RLSL compiles a library it essentially falls back to rustc which then produces an `.rlib` file. This file includes the MIR which will be used to generate the SPIR-V. I am still hoping for [gh38913](https://github.com/rust-lang/rust/issues/38913) but it should be easy to do this on my own.

# Future

I wish I could work on this project full time, but at the current rate I think that RLSL should at least be installable and semi usable for small projects by the end of the year. At the same time I will open up the project for contributions.

If you are interested in using RLSL in the future, I would love to know your requirements.


text:
function varargout = start(varargin)
% START MATLAB code for start.fig
%      START, by itself, creates a new START or raises the existing
%      singleton*.
%
%      H = START returns the handle to a new START or the handle to
%      the existing singleton*.
%
%      START('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in START.M with the given input arguments.
%
%      START('Property','Value',...) creates a new START or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before start_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to start_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help start

% Last Modified by GUIDE v2.5 10-Mar-2017 21:26:23

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @start_OpeningFcn, ...
    'gui_OutputFcn',  @start_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before start is made visible.
function start_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to start (see VARARGIN)

% Choose default command line output for start
handles.output = hObject;
maximumNrOfStructures = 50;
handles.selected_structures = zeros(maximumNrOfStructures,1);
handles.defaultdatapath = fullfile('.');
handles.slice = -1;

% add to path
addpath(fullfile('dicom_import'),...
    fullfile('feature_extraction'),...
    fullfile('utils'),...
    fullfile('visualization'));

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes start wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = start_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox1

% --- Executes on button press in checkbox2.
function checkbox2_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox2

% --- Executes on button press in Up_button.
function Up_button_Callback(hObject, eventdata, handles)

% show the hourglass during computation
oldpointer = get(handles.figure1, 'pointer');
set(handles.figure1, 'pointer', 'watch')
drawnow;

handles.slice = handles.slice + 1;
% Update handles structure
guidata(hObject, handles)
handles.slice = plotDoseAndCT( hObject, eventdata, handles);
% Update handles structure
guidata(hObject, handles)

% set back an arrow
set(handles.figure1, 'pointer', oldpointer)

% --- Executes on button press in Down_button.
function Down_button_Callback(hObject, eventdata, handles)

% show the hourglass during computation
oldpointer = get(handles.figure1, 'pointer');
set(handles.figure1, 'pointer', 'watch')
drawnow;

handles.slice = handles.slice - 1;
% Update handles structure
guidata(hObject, handles)
handles.slice = plotDoseAndCT( hObject, eventdata, handles );
% Update handles structure
guidata(hObject, handles)

% set back an arrow
set(handles.figure1, 'pointer', oldpointer)

% % --- Executes on button press in Plot_button.
% function Plot_button_Callback(hObject, eventdata, handles)
%
% % show the hourglass during computation
% oldpointer = get(handles.figure1, 'pointer');
% set(handles.figure1, 'pointer', 'watch')
% drawnow;
%
% % Update handles structure
% guidata(hObject, handles)
% axes(handles.axes1);
% handles.slice = plotDoseAndCT( hObject, eventdata, handles );
% guidata(hObject, handles)
%
% % set back an arrow
% set(handles.figure1, 'pointer', oldpointer)

% --- Executes on button press in LoadTPSdata_button.
function LoadTPSdata_button_Callback(hObject, eventdata, handles)

% show the hourglass during computation
oldpointer = get(handles.figure1, 'pointer');
set(handles.figure1, 'pointer', 'watch')
drawnow;

[filename, directory] = uigetfile([handles.defaultdatapath 'mat'],...
    'Choose tps_data.mat file...');
if ischar(filename) && ischar(directory)
    load(fullfile(directory, filename));
    %load([directory '\' filename]);
    handles.output_directory = directory;
    handles.s_fieldnames = fieldnames(tps_data.structures);
    setPatName(handles);
    handles.tps_data = tps_data;
    guidata(hObject, handles);
    enablecheckboxes(hObject, eventdata, handles)
    handles.slice = plotDoseAndCT( hObject, eventdata, handles );
end

% set back an arrow
set(handles.figure1, 'pointer', oldpointer)

function setPatName(handles)
[~, deepestFolder] = fileparts(handles.output_directory(1:end-1));
set(handles.patname_text, 'String', deepestFolder);

% --- Executes on button press in structure32_checkbox.
function checkbox53_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(51, hObject, eventdata, handles);

function enablecheckboxes(hObject, eventdata, handles)
% set checkbox names
for loopIndex = 1:numel(handles.s_fieldnames)
    set(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'String', handles.s_fieldnames{loopIndex})
    set(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'Visible', 'on')
end

function checkboxmanager( number, hObject, eventdata, handles)
if get(hObject,'Value') == 1
    handles.selected_structures(number) = 1;
    r = randi([0 1]);
    g = randi([0 1]);
    b = randi([0 1]);
    set(hObject, 'ForegroundColor', [r g b]);
    if (r*g*b == 1 || (r == 1 && g == 1 && b == 0) || (r == 0 && g == 1 && b == 0) || (r == 0 && g == 1 && b == 1))
        set(hObject, 'BackgroundColor', [0 0 0]);
    end
else
    handles.selected_structures(number) = 0;
    set(hObject, 'ForegroundColor', [0 0 0]);
    set(hObject, 'BackgroundColor', [1 1 1]);
end
% Update handles structure
guidata(hObject, handles)

% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1

% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function slice = plotDoseAndCT(hObject, eventdata, handles)
struct_sel = lookForEnabledCheckboxes2(hObject, eventdata, handles);
if sum(struct_sel) == 0
    colors = [0 0 0];
else
    colors = getCheckboxColors(hObject, eventdata, handles);
end
% if handles.slice ~= -1
%     shift = (handles.tps_data.ct.zVec(handles.slice)-handles.tps_data.dose.zVec(handles.slice))/(handles.tps_data.ct.zVec(1)-handles.tps_data.ct.zVec(2)); % I NEED MORE ELEGANT SOLUTION!!!
% else
%     shift = 0;
% end
% plot ct
if isfield(handles.tps_data, 'ct')
    slice = plot_ct(handles.tps_data, handles.s_fieldnames(struct_sel == 1), handles.slice, colors, handles.axes1);
    handles.slice = slice;
end
% plot dose
if isfield(handles.tps_data, 'dose')
    slice = plot_dose(handles.tps_data, handles.s_fieldnames(struct_sel == 1), handles.slice, colors, handles.axes2);
    handles.slice = slice;
end
% plot 3rd axes
if isfield(handles.tps_data, 'dose')
        cla(handles.axes3) % clear axes before plotting
        %drawnow
        contents = get(handles.visualization_popupmenu, 'Value');
        switch contents
            case 1
                struct_sel = find(struct_sel == 1);
                for j=1:length(struct_sel)
                    linecolor = get(eval(['handles.structure' ...
                        num2str(struct_sel(j)) '_checkbox']), 'ForegroundColor');
                    %title = handles.s_fieldnames{struct_sel(j)};
                    % dvh = calc_dvh(handles.tps_data.dose.cube.*handles.tps_data.structures.(handles.s_fieldnames{struct_sel(j)}).indicator_mask);
                    hold( handles.axes3, 'on');
                    struct_cube = handles.tps_data.dose.cube.*handles.tps_data.structures.(handles.s_fieldnames{struct_sel(j)}).indicator_mask;
                    plot_dvh(struct_cube, linecolor, '', handles.axes3);
                end
                hold( handles.axes3, 'off');
            case 2
                plot_structure_dose(handles.tps_data, handles.s_fieldnames(struct_sel == 1), handles.slice, colors, handles.axes3);
            case 3
                plot_structure_gradient(handles.tps_data, handles.s_fieldnames(struct_sel == 1), handles.slice, colors, handles.axes3);
        end
end
guidata(hObject, handles)

function setTestResult(handles,flag)
if flag
    set(handles.analysisresult_text,'String', 'Test passed!');
    set(handles.analysisresult_text,'ForegroundColor', [0 0.5 0]);
else
    set(handles.analysisresult_text,'String', 'Test failed!');
    set(handles.analysisresult_text,'ForegroundColor', [1 0 0]);
end

function index = lookForEnabledCheckboxes(hObject, eventdata, handles)
% set checkbox names
for loopIndex = 1:numel(handles.s_fieldnames)
    value = get(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'Value');
    if value
        index = loopIndex;
    end
end

function index = lookForEnabledCheckboxes2(hObject, eventdata, handles)
% set checkbox names
index = zeros(numel(handles.s_fieldnames),1);
for loopIndex = 1:numel(handles.s_fieldnames)
    value = get(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'Value');
    if value
        index(loopIndex) = 1;
    end
end

function colors = getCheckboxColors(hObject, eventdata, handles)
% set checkbox names
%colors = zeros(numel(handles.s_fieldnames)-1,3);
index = 1;
for loopIndex = 1:numel(handles.s_fieldnames)
    value = get(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'Value');
    if value
        colors(index,:) = get(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'ForegroundColor');
        index = index+1;
    end
end

function clearCheckboxes(hObject, eventdata, handles)
% set checkbox names
for loopIndex = 1:numel(handles.s_fieldnames)
    set(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'Value', 0);
    set(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'ForegroundColor', [0 0 0]);
    set(eval(['handles.structure' num2str(loopIndex) '_checkbox']), 'BackgroundColor', [1 1 1]);
end
handles.selected_structures = handles.selected_structures * 0;
guidata(hObject, handles);

% --- Executes on button press in next_button.
function next_button_Callback(hObject, eventdata, handles)
% hObject    handle to next_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(hObject, handles);
uiresume(gcbf);

% --- Executes on selection change in visualization_popupmenu.
function visualization_popupmenu_Callback(hObject, eventdata, handles)
% hObject    handle to visualization_popupmenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns visualization_popupmenu contents as cell array
%        contents{get(hObject,'Value')} returns selected item from visualization_popupmenu

% --- Executes during object creation, after setting all properties.
function visualization_popupmenu_CreateFcn(hObject, eventdata, handles)
% hObject    handle to visualization_popupmenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes when selected object is changed in uipanel3.
function uipanel3_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanel3
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
%disp(get(get(handles.uipanel3,'SelectedObject'),'String'));

% --- Executes on button press in reset_button.
function reset_button_Callback(hObject, eventdata, handles)
% hObject    handle to reset_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
OrigDlgH = ancestor(hObject, 'figure');
delete(OrigDlgH);
start();

% --- Executes on button press in calcFeatures.
function calcFeatures_Callback(hObject, eventdata, handles)
organ = handles.organ.String(handles.organ.Value, :);
if get(handles.batch_tick, 'Value') == 0
    % show the hourglass during computation
    oldpointer = get(handles.figure1, 'pointer');
    set(handles.figure1, 'pointer', 'watch')
    drawnow;

    if isfield(handles, 'tps_data')
        features = calc_features(handles.tps_data, organ);
        features_table = cell2table(features(2:end, :));
        features_table.Properties.VariableNames = features(1, :);
        writetable(features_table, fullfile(handles.output_directory, 'features.csv'));
    else
        errordlg('Load tps.mat file first!','tps.mat error');
    end

    set(handles.figure1, 'pointer', oldpointer);
    drawnow;
else
    h = warndlg('DicomToolboxMatlab will load features from the csv files if found in patients'' directories. If you want to calculate all features from scratch, delete the csv files first!');
    uiwait(h);
    input_dir = uigetdir(handles.defaultdatapath, 'Choose Input Directory...');
    showGUI = true;
    recalcFeatures = false;
    calc_features_batch( input_dir, organ, recalcFeatures, showGUI);
end

% --- Executes on button press in select_all_button.
function select_all_button_Callback(hObject, eventdata, handles)
% hObject    handle to select_all_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in select_none_button.
function select_none_button_Callback(hObject, eventdata, handles)
% hObject    handle to select_none_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in newloader_button.
function newloader_button_Callback(hObject, eventdata, handles)
% hObject    handle to newloader_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if get(handles.batch_tick, 'Value') == 0
    dicom_import_gui
else
    dicom_import_batch_gui
end

% --- Executes on button press in batch_tick.
function batch_tick_Callback(hObject, eventdata, handles)
% hObject    handle to batch_tick (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of batch_tick

% --- Executes on button press in structure1_checkbox.
function structure1_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure1_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure1_checkbox
checkboxmanager(1, hObject, eventdata, handles);

% --- Executes on button press in structure2_checkbox.
function structure2_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure2_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure2_checkbox
checkboxmanager(2, hObject, eventdata, handles);

% --- Executes on button press in structure3_checkbox.
function structure3_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure3_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure3_checkbox
checkboxmanager(3, hObject, eventdata, handles);

% --- Executes on button press in structure4_checkbox.
function structure4_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure4_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure4_checkbox
checkboxmanager(4, hObject, eventdata, handles);

% --- Executes on button press in structure5_checkbox.
function structure5_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure5_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure5_checkbox
checkboxmanager(5, hObject, eventdata, handles);

% --- Executes on button press in structure6_checkbox.
function structure6_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure6_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure6_checkbox
checkboxmanager(6, hObject, eventdata, handles);

% --- Executes on button press in structure7_checkbox.
function structure7_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure7_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure7_checkbox
checkboxmanager(7, hObject, eventdata, handles);

% --- Executes on button press in structure8_checkbox.
function structure8_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure8_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure8_checkbox
checkboxmanager(8, hObject, eventdata, handles);

% --- Executes on button press in structure9_checkbox.
function structure9_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure9_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure9_checkbox
checkboxmanager(9, hObject, eventdata, handles);

% --- Executes on button press in structure10_checkbox.
function structure10_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure10_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure10_checkbox
checkboxmanager(10, hObject, eventdata, handles);

% --- Executes on button press in structure11_checkbox.
function structure11_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure11_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure11_checkbox
checkboxmanager(11, hObject, eventdata, handles);

% --- Executes on button press in structure12_checkbox.
function structure12_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure12_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure12_checkbox
checkboxmanager(12, hObject, eventdata, handles);

% --- Executes on button press in structure13_checkbox.
function structure13_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure13_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure13_checkbox
checkboxmanager(13, hObject, eventdata, handles);

% --- Executes on button press in structure14_checkbox.
function structure14_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure14_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure14_checkbox
checkboxmanager(14, hObject, eventdata, handles);

% --- Executes on button press in structure15_checkbox.
function structure15_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure15_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure15_checkbox
checkboxmanager(15, hObject, eventdata, handles);

% --- Executes on button press in structure16_checkbox.
function structure16_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure16_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure16_checkbox
checkboxmanager(16, hObject, eventdata, handles);

% --- Executes on button press in structure17_checkbox.
function structure17_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure17_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure17_checkbox
checkboxmanager(17, hObject, eventdata, handles);

% --- Executes on button press in structure18_checkbox.
function structure18_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure18_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure18_checkbox
checkboxmanager(18, hObject, eventdata, handles);

% --- Executes on button press in structure19_checkbox.
function structure19_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure19_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure19_checkbox
checkboxmanager(19, hObject, eventdata, handles);

% --- Executes on button press in structure20_checkbox.
function structure20_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure20_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure20_checkbox
checkboxmanager(20, hObject, eventdata, handles);

% --- Executes on button press in structure21_checkbox.
function structure21_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure21_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure21_checkbox
checkboxmanager(21, hObject, eventdata, handles);

% --- Executes on button press in structure22_checkbox.
function structure22_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure22_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure22_checkbox
checkboxmanager(22, hObject, eventdata, handles);

% --- Executes on button press in structure23_checkbox.
function structure23_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure23_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure23_checkbox
checkboxmanager(23, hObject, eventdata, handles);

% --- Executes on button press in structure24_checkbox.
function structure24_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure24_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure24_checkbox
checkboxmanager(24, hObject, eventdata, handles);

% --- Executes on button press in structure25_checkbox.
function structure25_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure25_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure25_checkbox
checkboxmanager(25, hObject, eventdata, handles);

% --- Executes on button press in structure26_checkbox.
function structure26_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure26_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure26_checkbox
checkboxmanager(26, hObject, eventdata, handles);

% --- Executes on button press in structure27_checkbox.
function structure27_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure27_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure27_checkbox
checkboxmanager(27, hObject, eventdata, handles);

% --- Executes on button press in structure28_checkbox.
function structure28_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure28_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure28_checkbox
checkboxmanager(28, hObject, eventdata, handles);

% --- Executes on button press in structure29_checkbox.
function structure29_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure29_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure29_checkbox
checkboxmanager(29, hObject, eventdata, handles);

% --- Executes on button press in structure30_checkbox.
function structure30_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure30_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure30_checkbox
checkboxmanager(30, hObject, eventdata, handles);

% --- Executes on button press in structure31_checkbox.
function structure31_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure31_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure31_checkbox
checkboxmanager(31, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure32_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(32, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure33_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(33, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure34_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(34, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure35_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(35, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure36_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(36, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure37_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(37, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure38_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(38, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure39_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(39, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure40_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(40, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure41_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(41, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure42_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(42, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure43_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(43, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure44_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(44, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure45_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(45, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure46_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(46, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure47_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(47, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure48_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(48, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure49_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(49, hObject, eventdata, handles);

% --- Executes on button press in structure32_checkbox.
function structure50_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to structure32_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of structure32_checkbox
checkboxmanager(50, hObject, eventdata, handles);

% --- Executes on selection change in organ.
function organ_Callback(hObject, eventdata, handles)
% hObject    handle to organ (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns organ contents as cell array
%        contents{get(hObject,'Value')} returns selected item from organ

% --- Executes during object creation, after setting all properties.
function organ_CreateFcn(hObject, eventdata, handles)
% hObject    handle to organ (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


text:
\begin{tikzpicture}[auto]
\tikzstyle{astnode}     = [ rectangle, draw, text width=8em
                          , minimum height=2em, text centered
                          ]
\tikzstyle{attribute}   = [ circle, draw, xshift=4em
                          , minimum height=1.5em
                          , black!70,thick ]
\tikzstyle{synth}       = [ -triangle 60, black!70 ]
\tikzstyle{level 1}     = [ sibling distance=50mm ]
\tikzstyle{attrlab}     = [ near start, left, yshift=0.5em
                          , black!70 ]
\node [astnode] (Statement-Assign) {:=}
  child
  {
    node [astnode] (Variable-Local-i4) {Local i4}
  }
  child
  {
    node [astnode] (Call-primSubInt) {Call primSubInt}
      child
      {
        node [astnode] (Variable-Value-1) {Variable Value}
          child
          {
            node [astnode] (Variable-Local-x78) {Local x78}
          }
      }
      child
      {
        node [astnode] (Variable-Value-2) {Variable Value}
          child
          {
            node [astnode] (Subs) {[1]}
              child
              {
                node [astnode] (Param-p1) {Param p1}
              }
          }
      }
  };

\node [circle, xshift=4em, right of=Statement-Assign] (Statement-Assign-attr) {};

%Left subtree
\node [attribute, right of=Variable-Local-i4] (Variable-Local-i4-attr) {$\tau$};
\draw [synth] (Variable-Local-i4-attr) -- node [attrlab] {$GrWord^*$} (Statement-Assign-attr.south);

\node [attribute, right of=Call-primSubInt] (Call-primSubInt-attr) {$\tau$};
\draw [synth] (Call-primSubInt-attr) -- node [attrlab, xshift=-2em] {$GrWord$} (Statement-Assign-attr.south);

\node [attribute, right of=Variable-Value-1] (Variable-Value-1-attr) {$\tau$};
\draw [synth] (Variable-Value-1-attr) -- node [attrlab] {$GrWord$} (Call-primSubInt-attr.south);

\node [attribute, right of=Variable-Local-x78] (Variable-Local-attr) {$\tau$};
\draw [synth] (Variable-Local-attr) -- node [attrlab] {$GrWord^*$} (Variable-Value-1-attr.south);

\node [attribute, right of=Variable-Value-2] (Variable-Value-2-attr) {$\tau$};
\draw [synth] (Variable-Value-2-attr) -- node [attrlab, xshift=-2em] {$GrWord$} (Call-primSubInt-attr.south);

\node [attribute, right of=Subs] (Subs-attr) {$\tau$};
\draw [synth] (Subs-attr) -- node [attrlab] {$GrWord^*$} (Variable-Value-2-attr.south);

\node [attribute, right of=Param-p1] (Param-p1-attr) {$\tau$};
\draw [synth] (Param-p1-attr) -- node [attrlab] {$GrWord$} (Subs-attr.south);
%\node [astnode, below of=Subs-1] (Param-p1) {Param p1};
\end{tikzpicture}


text:
var bt = require('./lib/bing-translate.js').init({
    client_id: 'your_client_id',
    client_secret: 'your_client_secret'
  });

bt.translate('This hotel is located close to the centre of Paris.', 'en', 'ro', function(err, res){
  console.log(err, res);
});


text:
package at.tugraz.sss.serv.datatype.par;

import at.tugraz.sss.serv.datatype.par.SSServPar;
import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.serv.datatype.*;
import java.sql.*;

public class SSCircleIsEntitySharedPar extends SSServPar{

  public SSUri forUser  = null;
  public SSUri entity   = null;

  public String getForUser(){
    return SSStrU.removeTrailingSlash(forUser);
  }

  public void setForUser(final String forUser) throws SSErr{
    this.entity = SSUri.get(forUser);
  }

  public String getEntity(){
    return SSStrU.removeTrailingSlash(entity);
  }

  public void setEntity(final String entity) throws SSErr{
    this.entity = SSUri.get(entity);
  }

  public SSCircleIsEntitySharedPar(){/* Do nothing because of only JSON Jackson needs this */ }

  public SSCircleIsEntitySharedPar(
    final SSServPar servPar,
    final SSUri         user,
    final SSUri         forUser,
    final SSUri         entity){

    super(SSVarNames.circleIsEntityShared, null, user, servPar.sqlCon);

    this.forUser             = forUser;
    this.entity              = entity;
  }
}


text:
HttpSimpleRequesterPost::HttpSimpleRequesterPost(boost::function<void(int, int, const std::string&)> _onCall,
							boost::function<void(int, int, const std::string&, const std::string&)> _onCallPost,
							boost::function<void(int)> _onFinished,
							CallContextPtr _context,
							const std::string &_call_url,
							const std::string &_postdata,
							boost::function<void(CallContextPtr, const std::string&)> _onCalledOk,
							boost::function<void(CallContextPtr)> _onCalledFail):

		HttpOutRequestDisp::Requester(_onCall, _onCallPost, _onFinished),
		m_context(_context),
		m_call_url(_call_url),
		m_postdata(_postdata),
		m_onCalledOk(_onCalledOk),
		m_onCalledFail(_onCalledFail) {

}

void HttpSimpleRequesterPost::onCallDone (int _callid, bool _success, const std::string &_resp) {

	if (!_success) {
		m_onCalledFail(m_context);
		m_isfinished = true;
		///finished();
	}
	else {
		m_onCalledOk(m_context, _resp);
		m_isfinished = true;
		//finished();
	}
}

void HttpSimpleRequesterPost::start() {

	callPost(0, m_call_url, m_postdata);
}


text:
module UI
  def self.Font(font)
    case font
      when UI::Font
        self
      when Hash
        name = (font[:name] or raise ":name expected")
        size = (font[:size] or raise ":size expected")
        trait = (font[:trait] or :normal)
        extension = (font[:extension] or :ttf)
        UI::Font.new(name, size, trait, extension)
      when Array
        raise "Expected Array of 2 or 3 or 4 elements" if font.size < 2 or font.size > 4
        UI::Font.new(*font)
      else
        raise "Expected UI::Font or Hash or Array"
    end
  end

  class Font
    attr_reader :proxy

    def italic?
      trait == :italic or trait == :bold_italic
    end

    def bold?
      trait == :bold or trait == :bold_italic
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.Languages.Core.Text;
using Microsoft.R.Core.AST;
using Microsoft.R.Core.AST.Expressions;
using Microsoft.R.Core.AST.Functions;
using Microsoft.R.Core.AST.Scopes;
using Microsoft.R.Core.AST.Statements;
using Microsoft.R.Core.Parser;
using Microsoft.UnitTests.Core.XUnit;

namespace Microsoft.R.Core.Test.AST {
    [ExcludeFromCodeCoverage]
    public class AstShiftTest {
        [Test]
        [Category.R.Ast]
        public void AstShiftTest1() {
            AstRoot ast = RParser.Parse(new TextStream(" a()"));
            IScope scope = ast.Children[0].Should().BeAssignableTo<IScope>().Which;

            scope.Children[0].Start.Should().Be(1);
            ast.Shift(1);
            scope.Children[0].Start.Should().Be(2);
        }

        [Test]
        [Category.R.Ast]
        public void AstShiftTest2() {
            AstRoot ast = RParser.Parse(new TextStream(" a()"));
            var scope = ast.Children[0].Should().BeAssignableTo<IScope>().Which;
            scope.Children[0].Start.Should().Be(1);

            var expression = scope.Children[0].Should().BeAssignableTo<IStatement>()
                .Which.Children[0].Should().BeAssignableTo<IExpression>()
                .Which;

            expression.Children[0].Start.Should().Be(1);
            var func = expression.Children[0].Should().BeAssignableTo<IFunction>()
                .Which;

            func.OpenBrace.Start.Should().Be(2);

            ast.ShiftStartingFrom(2, 1);

            func.OpenBrace.Start.Should().Be(3);
        }
    }
}


text:
#include "bfd.h"
#include "sysdep.h"

#define TARGET_SYM 		i386pe_vec
#define TARGET_NAME 		"pe-i386"
#define COFF_WITH_PE
#define PCRELOFFSET 		TRUE
#define TARGET_UNDERSCORE 	'_'
#define COFF_LONG_SECTION_NAMES
#define COFF_SUPPORT_GNU_LINKONCE
#define COFF_LONG_FILENAMES

#define COFF_SECTION_ALIGNMENT_ENTRIES \
{ COFF_SECTION_NAME_EXACT_MATCH (".bss"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 4 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".data"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 4 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".rdata"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 4 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".text"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 4 }, \
{ COFF_SECTION_NAME_PARTIAL_MATCH (".idata"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".pdata"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_PARTIAL_MATCH (".debug"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 0 }, \
{ COFF_SECTION_NAME_PARTIAL_MATCH (".gnu.linkonce.wi."), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 0 }

#include "coff-i386.c"