text:
package org.apache.poi.util;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import org.apache.poi.poifs.dev.TestPOIFSDump;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class TestTempFile {
    private String previousTempDir;
    private File tempDir;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Before
    public void setUp() throws IOException {
        previousTempDir = System.getProperty(TempFile.JAVA_IO_TMPDIR);

        // use a separate tempdir for the tests to be able to check for leftover files
        tempDir = File.createTempFile("TestTempFile", ".tst");
        assertTrue(tempDir.delete());
        assertTrue(tempDir.mkdirs());
        System.setProperty(TempFile.JAVA_IO_TMPDIR, tempDir.getAbsolutePath());
    }

    @After
    public void tearDown() throws IOException {
        String[] files = tempDir.list();
        // can have the "poifiles" subdir
        if(files.length == 1) {
            assertEquals("Had: " + Arrays.toString(files), DefaultTempFileCreationStrategy.POIFILES, files[0]);
            files = new File(tempDir, files[0]).list();
            assertEquals("Had: " + Arrays.toString(files), 0, files.length);
        } else {
            assertEquals("Had: " + Arrays.toString(files), 0, files.length);
        }

        // remove the directory after the tests
        TestPOIFSDump.deleteDirectory(tempDir);

        if(previousTempDir == null) {
            System.clearProperty(TempFile.JAVA_IO_TMPDIR);
        } else {
            System.setProperty(TempFile.JAVA_IO_TMPDIR, previousTempDir);
        }

        // reset strategy to re-create the directory
        TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy());

        // check that we can still create a tempfile
        File testFile = TempFile.createTempFile("test", ".tst");
        assertTrue(testFile.exists());
        assertTrue(testFile.delete());
    }

    @Test
    public void testCreateTempFile() throws IOException
    {
        File tempFile = TempFile.createTempFile("test", ".txt");
        FileOutputStream fos = new FileOutputStream(tempFile);
        fos.write(1); //file can be written to
        fos.close();
        assertTrue("temp file exists", tempFile.exists());
        assertTrue("temp file is a file", tempFile.isFile());
        assertTrue("temp file's name should start with test",
                tempFile.getName().startsWith("test"));
        assertTrue("temp file's name should end with .txt",
                tempFile.getName().endsWith(".txt"));
        assertEquals("temp file is saved in poifiles directory",
                DefaultTempFileCreationStrategy.POIFILES, tempFile.getParentFile().getName());

        // Can't think of a good way to check whether a file is actually deleted since it would require the VM to stop.
        // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion"
        assertTrue("Unable to delete temp file", tempFile.delete());
    }

    @Test
    public void createTempFileWithDefaultSuffix() throws IOException {
        File tempFile = TempFile.createTempFile("test", null);
        assertTrue("temp file's name should end with .tmp",
                tempFile.getName().endsWith(".tmp"));
    }

    @Test
    public void testCreateTempDirectory() throws IOException
    {
        File tempDir = TempFile.createTempDirectory("testDir");
        assertTrue("testDir exists", tempDir.exists());
        assertTrue("testDir is a directory", tempDir.isDirectory());
        assertTrue("testDir's name starts with testDir",
                tempDir.getName().startsWith("testDir"));
        assertEquals("tempDir is saved in poifiles directory",
                DefaultTempFileCreationStrategy.POIFILES, tempDir.getParentFile().getName());

        // Can't think of a good way to check whether a directory is actually deleted since it would require the VM to stop.
        // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion"
        assertTrue("Unable to delete tempDir", tempDir.delete());
    }

    @Test
    public void testSetTempFileCreationStrategy() throws IOException {
        TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy());

        // Should be able to create two tempfiles with same prefix and suffix
        File file1 = TempFile.createTempFile("TestTempFile", ".tst");
        File file2 = TempFile.createTempFile("TestTempFile", ".tst");
        assertFalse(file1.equals(file2));
        assertNotNull(file2);
        assertTrue(file2.delete());
        assertNotNull(file1);
        assertTrue(file1.delete());

        thrown.expect(IllegalArgumentException.class);
        TempFile.setTempFileCreationStrategy(null);
    }
}


text:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.JScrollPane;

import java.util.ArrayList;
import java.util.Collections;

public class SuggestionsView extends JPanel implements IView {
   private JFrame frame;
   private JottoModel model;
   private JList suggestionsList;

   public SuggestionsView(JFrame aFrame, JottoModel aModel) {
      super();
      frame = aFrame;
      model = aModel;
      layoutView();
      registerControllers();
   } // Constructor

   // Lays the widget out in the view
   private void layoutView() {
      setOpaque(false);
   	Border emptyBorder = BorderFactory.createEmptyBorder(50, 10, 20, 20);
      TitledBorder titledBorder =
         BorderFactory.createTitledBorder(emptyBorder, "Words Suggested");
      titledBorder.setTitleFont(
      	 new Font(titledBorder.getTitleFont().getName(), Font.BOLD, 18));
      titledBorder.setTitleColor(Color.WHITE);
      setBorder(titledBorder);
      setLayout(new GridLayout(1, 1));

      // Lays the word suggestions list out in the view
      suggestionsList = new JList<String>(model.getSuggestionsListModel());
      JScrollPane scrollPane = new JScrollPane(suggestionsList);
      scrollPane.setPreferredSize(new Dimension(220, getHeight()));
      add(scrollPane);
   } // layoutView

   // Registers controllers for each widget
   private void registerControllers() {
      suggestionsList.addMouseListener(new MouseAdapter() {
      	 public void mouseClicked(MouseEvent e) {
            JList list = (JList) e.getSource();
            if (e.getClickCount() == 2) {
               int index = list.locationToIndex(e.getPoint());
               if (index >= 0) {
                    disableMenuItems();
               	  DefaultListModel<String> suggestionsListModel =
               	     model.getSuggestionsListModel();
               	  String guess =
               	     suggestionsListModel.getElementAt(index).toString();
               	  model.setGuess(guess);
               } // if
            } // if
      	 } // mouseClicked
      });
   } // registerControllers

   // Disables some menu items once the game starts
   // (i.e.: the player makes their first valid guess)
   private void disableMenuItems() {
      for (int i = 0; i < 4; i++) {
         frame.getJMenuBar().getMenu(1).getItem(i).setEnabled(false);
      } // for
   } // disableMenuItems

   // Updates the view using info from the model
   public void update() {
   	;
   } // update
}

redpajama_set_name: RedPajamaGithub


text:
import { run } from '@ember/runloop';
import { moduleForComponent, test } from 'ember-qunit';

moduleForComponent('uic-dropdown', 'Unit | Component | uic dropdown', {
  needs: [
    'component:uic-dropdown-container'
  ],
  unit: true
});

test('it renders', function(assert) {
  assert.expect(2);
  var component = this.subject();
  assert.equal(component._state, 'preRender');
  this.render();
  assert.equal(component._state, 'inDOM');
});

test('showDropdown', function(assert) {
  assert.expect(1);
  var component = this.subject();
  this.render();
  assert.equal(component.get('showDropdown'), false);
});

test('autoClose', function(assert) {
  assert.expect(1);
  var component = this.subject();
  this.render();
  assert.equal(component.get('autoClose'), true);
});

test('_hideDropdown() method', function(assert) {
  assert.expect(1);
  var component = this.subject();
  component.set('showDropdown', true);
  this.render();
  run(() => component._hideDropdown());
  assert.equal(component.get('showDropdown'), false);
});

test('click', function(assert) {
  assert.expect(2);
  var component = this.subject();
  component.set('showDropdown', false);
  this.render();

  run(() => component.click());
  assert.equal(component.get('showDropdown'), true);

  run(() => component.click());
  assert.equal(component.get('showDropdown'), false);
});

test('hideDropdown action', function(assert) {
  assert.expect(1);
  var component = this.subject();
  component.set('_hideDropdown', () => assert.ok(true));
  this.render();
  component.send('hideDropdown');
});


text:
<template name="notification_new_reply">

    {{author}}
    {{_ "has_replied_to_your_comment_on"}}
    {{postTitle}}

</template>


text:
package io.github.michaelfedora.fedorasmarket.database;

import com.google.inject.Inject;
import io.github.michaelfedora.fedorasmarket.PluginInfo;
import io.github.michaelfedora.fedorasmarket.database.table.*;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.service.sql.SqlService;

import java.sql.*;

/**
 * Created by Michael on 2/27/2016.
 */
public final class DatabaseManager {

    public static final String DB_ID = "jdbc:h2:./mods/FedorasData/market.db";
    public static final String DB_TABLE = "tbl" + PluginInfo.DATA_ROOT;

    /*
    Database layout:
    - Tablename: "type:name", contains it's own layout; e.x.
     - [tradeform:00000-0000-00-0001] {"name", <data>}
     - [modifier:<uuid>] {"name", <data>}
     - [depot:server] {<idx>, <item_data>}
     - [shop:1234-5678-91-01234] {<uuid>, <data>}
     - [tradereq:4444-4656-87-3535] {<idx>, <data>}
     */

    public static final TradeFormTable tradeForm = new TradeFormTable();
    public static final ModifierTable modifier = new ModifierTable();
    public static final DepotTable depot = new DepotTable();
    public static final ShopTable shop = new ShopTable();
    public static final TradeReqTable tradeReq = new TradeReqTable();
    public static final UserdataTable userdata = new UserdataTable();

    @Inject
    private static PluginContainer plugin;

    private DatabaseManager() { }

    private static SqlService SQL;
    public static javax.sql.DataSource getDataSource(String jdbcUrl) throws SQLException {
        if(SQL == null)
            SQL = Sponge.getServiceManager().provide(SqlService.class).orElseThrow(() -> new SQLException("Could not 'get' SqlService!"));

        return SQL.getDataSource(jdbcUrl);
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource(DB_ID).getConnection();
    }

    public static void makeIfNotExist(Connection conn, String id) throws SQLException {
        tradeForm.makeIfNotExist(conn, id);
        modifier.makeIfNotExist(conn, id);
        depot.makeIfNotExist(conn, id);
        shop.makeIfNotExist(conn, id);
        tradeReq.makeIfNotExist(conn, id);
        userdata.makeIfNotExist(conn, id);
    }

    public static void initialize() {

        try(Connection conn = getConnection()) {

            for (Player p : Sponge.getServer().getOnlinePlayers()) // not that this is necessary...
                makeIfNotExist(conn, p.getUniqueId().toString());

        } catch(SQLException e) {
            plugin.getLogger().error("SQL Error", e);
        }

        Sponge.getEventManager().registerListener(plugin, ClientConnectionEvent.Join.class, DatabaseManager::OnPlayerJoin);
    }

    private static void OnPlayerJoin(ClientConnectionEvent.Join event) {
        try(Connection conn = getConnection()) {
            makeIfNotExist(conn, event.getTargetEntity().getUniqueId().toString());
        } catch(SQLException e) {
            plugin.getLogger().error("SQL Error", e);
        }
    }
}


text:
var five = require('johnny-five');
var BeagleBone = require('beaglebone-io');

var board = new five.Board({
  io: new BeagleBone()
});

board.on('ready', function () {

//do awesome

});


text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

using Xceed.Wpf.AvalonDock.Layout;

using Metaseed.MetaShell.Services;
namespace Metaseed.MetaShell.Controls
{
    using ViewModels;
    public class LayoutInitializer : ILayoutUpdateStrategy
    {
        private enum InsertPosition
        {
            Start,
            End
        }
        private static LayoutAnchorablePane CreateAnchorablePane(LayoutRoot layout, Orientation orientation,
            string paneName, InsertPosition position)
        {
            var parent = layout.Descendents().OfType<LayoutPanel>().First(d => d.Orientation == orientation);

            //if (parent == null)
            //{
            //    switch (orientation)
            //    {
            //        case Orientation.Horizontal:
            //            var hpl = new LayoutPanel() { Orientation = Orientation.Horizontal };
            //            System.Diagnostics.Debug.Assert(layout.RootPanel.Orientation == Orientation.Vertical);
            //            layout.RootPanel.InsertChildAt(0, hpl);
            //            break;
            //        case Orientation.Vertical:
            //            //var hp = layout.Descendents().OfType<LayoutPanel>().FirstOrDefault(d => d.Orientation == Orientation.Horizontal);
            //            //if (hp == null)
            //            //{
            //            var hp = new LayoutPanel() { Orientation = Orientation.Horizontal };
            //            hp.InsertChildAt(0, new LayoutDocumentPaneGroup(new LayoutDocumentPane()));
            //            //}
            //            layout.RootPanel = new LayoutPanel(hp) { Orientation = Orientation.Vertical };
            //            parent = layout.RootPanel;
            //            break;
            //        default:
            //            break;
            //    }
            //}
            var toolsPane = new LayoutAnchorablePane { Name = paneName };
            if (position == InsertPosition.Start)
            {
                parent.InsertChildAt(0, toolsPane);
            }
            else
            {
                parent.Children.Add(toolsPane);
            }
            return toolsPane;
        }

        public bool BeforeInsertAnchorable(LayoutRoot layout, LayoutAnchorable anchorableToShow, ILayoutContainer destinationContainer)
        {
            //AD wants to add the anchorable into destinationContainer, just for test provide a new anchorable pane
            //if the pane is floating let the manager go ahead

            //var destPane = destinationContainer as LayoutAnchorablePane;
            if (destinationContainer != null && destinationContainer.FindParent<LayoutFloatingWindow>() != null)
                return false;

            var toolViewModel = anchorableToShow.Content as IToolViewModel;
            if (toolViewModel != null)
            {
                var preferredLocation = toolViewModel.PreferredLocation;
                string paneName = preferredLocation.ToString();
                var toolsPane = layout.Descendents().OfType<LayoutAnchorablePane>().FirstOrDefault(d => d.Name == paneName);
                if (toolsPane == null)
                {
                    switch (preferredLocation)
                    {
                        case ToolPaneLocation.Left:
                            toolsPane = CreateAnchorablePane(layout, Orientation.Horizontal, paneName, InsertPosition.Start);
                            break;
                        case ToolPaneLocation.Right:
                            toolsPane = CreateAnchorablePane(layout, Orientation.Horizontal, paneName, InsertPosition.End);
                            break;
                        case ToolPaneLocation.Bottom:
                            toolsPane = CreateAnchorablePane(layout, Orientation.Vertical, paneName, InsertPosition.End);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
                toolsPane.Children.Add(anchorableToShow);
                return true;
            }
            return false;
        }

        public void AfterInsertAnchorable(LayoutRoot layout, LayoutAnchorable anchorableShown)
        {
            // If this is the first anchorable added to this pane, then use the preferred size.
            var toolViewModel = anchorableShown.Content as IToolViewModel;
            if (toolViewModel != null && toolViewModel.IsVisible == true)
            {
                var anchorablePane = anchorableShown.Parent as LayoutAnchorablePane;
                if (anchorablePane != null && anchorablePane.ChildrenCount == 1)
                {
                    switch (toolViewModel.PreferredLocation)
                    {
                        case ToolPaneLocation.Left:
                        case ToolPaneLocation.Right:
                            anchorablePane.DockWidth = new GridLength(toolViewModel.PreferredWidth, GridUnitType.Pixel);
                            break;
                        case ToolPaneLocation.Bottom:
                            anchorablePane.DockHeight = new GridLength(toolViewModel.PreferredHeight, GridUnitType.Pixel);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }
        }

        public bool BeforeInsertDocument(LayoutRoot layout, LayoutDocument anchorableToShow, ILayoutContainer destinationContainer)
        {
            return false;
        }

        public void AfterInsertDocument(LayoutRoot layout, LayoutDocument anchorableShown)
        {

        }
    }
}


text:
using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;

// Get SubArch (vN).
int arm::getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  llvm::StringRef Arch = Triple.getArchName();
  return llvm::ARM::parseArchVersion(Arch);
}

// True if M-profile.
bool arm::isARMMProfile(const llvm::Triple &Triple) {
  llvm::StringRef Arch = Triple.getArchName();
  return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::M;
}

// Get Arch/CPU from args.
void arm::getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
                                llvm::StringRef &CPU, bool FromAs) {
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))
    CPU = A->getValue();
  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
    Arch = A->getValue();
  if (!FromAs)
    return;

  for (const Arg *A :
       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
    StringRef Value = A->getValue();
    if (Value.startswith("-mcpu="))
      CPU = Value.substr(6);
    if (Value.startswith("-march="))
      Arch = Value.substr(7);
  }
}

// Handle -mhwdiv=.
// FIXME: Use ARMTargetParser.
static void getARMHWDivFeatures(const Driver &D, const Arg *A,
                                const ArgList &Args, StringRef HWDiv,
                                std::vector<StringRef> &Features) {
  uint64_t HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
}

// Handle -mfpu=.
static unsigned getARMFPUFeatures(const Driver &D, const Arg *A,
                                  const ArgList &Args, StringRef FPU,
                                  std::vector<StringRef> &Features) {
  unsigned FPUID = llvm::ARM::parseFPU(FPU);
  if (!llvm::ARM::getFPUFeatures(FPUID, Features))
    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
  return FPUID;
}

// Decode ARM features from string like +[no]featureA+[no]featureB+...
static bool DecodeARMFeatures(const Driver &D, StringRef text,
                              StringRef CPU, llvm::ARM::ArchKind ArchKind,
                              std::vector<StringRef> &Features) {
  SmallVector<StringRef, 8> Split;
  text.split(Split, StringRef("+"), -1, false);

  for (StringRef Feature : Split) {
    if (!appendArchExtFeatures(CPU, ArchKind, Feature, Features))
      return false;
  }
  return true;
}

static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,
                                     std::vector<StringRef> &Features) {
  CPU = CPU.split("+").first;
  if (CPU != "generic") {
    llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
    uint64_t Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);
    llvm::ARM::getExtensionFeatures(Extension, Features);
  }
}

// Check if -march is valid by checking if it can be canonicalised and parsed.
// getARMArch is used here instead of just checking the -march value in order
// to handle -march=native correctly.
static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
                             llvm::StringRef ArchName, llvm::StringRef CPUName,
                             std::vector<StringRef> &Features,
                             const llvm::Triple &Triple) {
  std::pair<StringRef, StringRef> Split = ArchName.split("+");

  std::string MArch = arm::getARMArch(ArchName, Triple);
  llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(MArch);
  if (ArchKind == llvm::ARM::ArchKind::INVALID ||
      (Split.second.size() && !DecodeARMFeatures(
        D, Split.second, CPUName, ArchKind, Features)))
    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
}

// Check -mcpu=. Needs ArchName to handle -mcpu=generic.
static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
                            llvm::StringRef CPUName, llvm::StringRef ArchName,
                            std::vector<StringRef> &Features,
                            const llvm::Triple &Triple) {
  std::pair<StringRef, StringRef> Split = CPUName.split("+");

  std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  llvm::ARM::ArchKind ArchKind =
    arm::getLLVMArchKindForARM(CPU, ArchName, Triple);
  if (ArchKind == llvm::ARM::ArchKind::INVALID ||
      (Split.second.size() && !DecodeARMFeatures(
        D, Split.second, CPU, ArchKind, Features)))
    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
}

bool arm::useAAPCSForMachO(const llvm::Triple &T) {
  // The backend is hardwired to assume AAPCS for M-class processors, ensure
  // the frontend matches that.
  return T.getEnvironment() == llvm::Triple::EABI ||
         T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
}

// Select mode for reading thread pointer (-mtp=soft/cp15).
arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args) {
  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
    arm::ReadTPMode ThreadPointer =
        llvm::StringSwitch<arm::ReadTPMode>(A->getValue())
            .Case("cp15", ReadTPMode::Cp15)
            .Case("soft", ReadTPMode::Soft)
            .Default(ReadTPMode::Invalid);
    if (ThreadPointer != ReadTPMode::Invalid)
      return ThreadPointer;
    if (StringRef(A->getValue()).empty())
      D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
    else
      D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
    return ReadTPMode::Invalid;
  }
  return ReadTPMode::Soft;
}

arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  return arm::getARMFloatABI(TC.getDriver(), TC.getEffectiveTriple(), Args);
}

// Select the float ABI as determined by -msoft-float, -mhard-float, and
// -mfloat-abi=.
arm::FloatABI arm::getARMFloatABI(const Driver &D, const llvm::Triple &Triple,
                                  const ArgList &Args) {
  auto SubArch = getARMSubArchVersionNumber(Triple);
  arm::FloatABI ABI = FloatABI::Invalid;
  if (Arg *A =
          Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
                          options::OPT_mfloat_abi_EQ)) {
    if (A->getOption().matches(options::OPT_msoft_float)) {
      ABI = FloatABI::Soft;
    } else if (A->getOption().matches(options::OPT_mhard_float)) {
      ABI = FloatABI::Hard;
    } else {
      ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
                .Case("soft", FloatABI::Soft)
                .Case("softfp", FloatABI::SoftFP)
                .Case("hard", FloatABI::Hard)
                .Default(FloatABI::Invalid);
      if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
        D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
        ABI = FloatABI::Soft;
      }
    }

    // It is incorrect to select hard float ABI on MachO platforms if the ABI is
    // "apcs-gnu".
    if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
        ABI == FloatABI::Hard) {
      D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
                                                       << Triple.getArchName();
    }
  }

  // If unspecified, choose the default based on the platform.
  if (ABI == FloatABI::Invalid) {
    switch (Triple.getOS()) {
    case llvm::Triple::Darwin:
    case llvm::Triple::MacOSX:
    case llvm::Triple::IOS:
    case llvm::Triple::TvOS: {
      // Darwin defaults to "softfp" for v6 and v7.
      ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
      ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
      break;
    }
    case llvm::Triple::WatchOS:
      ABI = FloatABI::Hard;
      break;

    // FIXME: this is invalid for WindowsCE
    case llvm::Triple::Win32:
      ABI = FloatABI::Hard;
      break;

    case llvm::Triple::NetBSD:
      switch (Triple.getEnvironment()) {
      case llvm::Triple::EABIHF:
      case llvm::Triple::GNUEABIHF:
        ABI = FloatABI::Hard;
        break;
      default:
        ABI = FloatABI::Soft;
        break;
      }
      break;

    case llvm::Triple::FreeBSD:
      switch (Triple.getEnvironment()) {
      case llvm::Triple::GNUEABIHF:
        ABI = FloatABI::Hard;
        break;
      default:
        // FreeBSD defaults to soft float
        ABI = FloatABI::Soft;
        break;
      }
      break;

    case llvm::Triple::OpenBSD:
      ABI = FloatABI::SoftFP;
      break;

    default:
      switch (Triple.getEnvironment()) {
      case llvm::Triple::GNUEABIHF:
      case llvm::Triple::MuslEABIHF:
      case llvm::Triple::EABIHF:
        ABI = FloatABI::Hard;
        break;
      case llvm::Triple::GNUEABI:
      case llvm::Triple::MuslEABI:
      case llvm::Triple::EABI:
        // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
        ABI = FloatABI::SoftFP;
        break;
      case llvm::Triple::Android:
        ABI = (SubArch >= 7) ? FloatABI::SoftFP : FloatABI::Soft;
        break;
      default:
        // Assume "soft", but warn the user we are guessing.
        if (Triple.isOSBinFormatMachO() &&
            Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
          ABI = FloatABI::Hard;
        else
          ABI = FloatABI::Soft;

        if (Triple.getOS() != llvm::Triple::UnknownOS ||
            !Triple.isOSBinFormatMachO())
          D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
        break;
      }
    }
  }

  assert(ABI != FloatABI::Invalid && "must select an ABI");
  return ABI;
}

static bool hasIntegerMVE(const std::vector<StringRef> &F) {
  auto MVE = llvm::find(llvm::reverse(F), "+mve");
  auto NoMVE = llvm::find(llvm::reverse(F), "-mve");
  return MVE != F.rend() &&
         (NoMVE == F.rend() || std::distance(MVE, NoMVE) > 0);
}

void arm::getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
                               const ArgList &Args, ArgStringList &CmdArgs,
                               std::vector<StringRef> &Features, bool ForAS) {
  bool KernelOrKext =
      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
  arm::ReadTPMode ThreadPointer = arm::getReadTPMode(D, Args);
  const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  const Arg *WaHDiv = nullptr, *WaArch = nullptr;

  // This vector will accumulate features from the architecture
  // extension suffixes on -mcpu and -march (e.g. the 'bar' in
  // -mcpu=foo+bar). We want to apply those after the features derived
  // from the FPU, in case -mfpu generates a negative feature which
  // the +bar is supposed to override.
  std::vector<StringRef> ExtensionFeatures;

  if (!ForAS) {
    // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
    // yet (it uses the -mfloat-abi and -msoft-float options), and it is
    // stripped out by the ARM target. We should probably pass this a new
    // -target-option, which is handled by the -cc1/-cc1as invocation.
    //
    // FIXME2:  For consistency, it would be ideal if we set up the target
    // machine state the same when using the frontend or the assembler. We don't
    // currently do that for the assembler, we pass the options directly to the
    // backend and never even instantiate the frontend TargetInfo. If we did,
    // and used its handleTargetFeatures hook, then we could ensure the
    // assembler and the frontend behave the same.

    // Use software floating point operations?
    if (ABI == arm::FloatABI::Soft)
      Features.push_back("+soft-float");

    // Use software floating point argument passing?
    if (ABI != arm::FloatABI::Hard)
      Features.push_back("+soft-float-abi");
  } else {
    // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
    // to the assembler correctly.
    for (const Arg *A :
         Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
      StringRef Value = A->getValue();
      if (Value.startswith("-mfpu=")) {
        WaFPU = A;
      } else if (Value.startswith("-mcpu=")) {
        WaCPU = A;
      } else if (Value.startswith("-mhwdiv=")) {
        WaHDiv = A;
      } else if (Value.startswith("-march=")) {
        WaArch = A;
      }
    }
  }

  if (ThreadPointer == arm::ReadTPMode::Cp15)
    Features.push_back("+read-tp-hard");

  const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  StringRef ArchName;
  StringRef CPUName;

  // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  if (WaCPU) {
    if (CPUArg)
      D.Diag(clang::diag::warn_drv_unused_argument)
          << CPUArg->getAsString(Args);
    CPUName = StringRef(WaCPU->getValue()).substr(6);
    CPUArg = WaCPU;
  } else if (CPUArg)
    CPUName = CPUArg->getValue();

  // Check -march. ClangAs gives preference to -Wa,-march=.
  if (WaArch) {
    if (ArchArg)
      D.Diag(clang::diag::warn_drv_unused_argument)
          << ArchArg->getAsString(Args);
    ArchName = StringRef(WaArch->getValue()).substr(7);
    checkARMArchName(D, WaArch, Args, ArchName, CPUName,
                     ExtensionFeatures, Triple);
    // FIXME: Set Arch.
    D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  } else if (ArchArg) {
    ArchName = ArchArg->getValue();
    checkARMArchName(D, ArchArg, Args, ArchName, CPUName,
                     ExtensionFeatures, Triple);
  }

  // Add CPU features for generic CPUs
  if (CPUName == "native") {
    llvm::StringMap<bool> HostFeatures;
    if (llvm::sys::getHostCPUFeatures(HostFeatures))
      for (auto &F : HostFeatures)
        Features.push_back(
            Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  } else if (!CPUName.empty()) {
    // This sets the default features for the specified CPU. We certainly don't
    // want to override the features that have been explicitly specified on the
    // command line. Therefore, process them directly instead of appending them
    // at the end later.
    DecodeARMFeaturesFromCPU(D, CPUName, Features);
  }

  if (CPUArg)
    checkARMCPUName(D, CPUArg, Args, CPUName, ArchName,
                    ExtensionFeatures, Triple);
  // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  unsigned FPUID = llvm::ARM::FK_INVALID;
  const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  if (WaFPU) {
    if (FPUArg)
      D.Diag(clang::diag::warn_drv_unused_argument)
          << FPUArg->getAsString(Args);
    (void)getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
                            Features);
  } else if (FPUArg) {
    FPUID = getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  } else if (Triple.isAndroid() && getARMSubArchVersionNumber(Triple) >= 7) {
    const char *AndroidFPU = "neon";
    FPUID = llvm::ARM::parseFPU(AndroidFPU);
    if (!llvm::ARM::getFPUFeatures(FPUID, Features))
      D.Diag(clang::diag::err_drv_clang_unsupported)
          << std::string("-mfpu=") + AndroidFPU;
  }

  // Now we've finished accumulating features from arch, cpu and fpu,
  // we can append the ones for architecture extensions that we
  // collected separately.
  Features.insert(std::end(Features),
                  std::begin(ExtensionFeatures), std::end(ExtensionFeatures));

  // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  if (WaHDiv) {
    if (HDivArg)
      D.Diag(clang::diag::warn_drv_unused_argument)
          << HDivArg->getAsString(Args);
    getARMHWDivFeatures(D, WaHDiv, Args,
                        StringRef(WaHDiv->getValue()).substr(8), Features);
  } else if (HDivArg)
    getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);

  // Handle (arch-dependent) fp16fml/fullfp16 relationship.
  // Must happen before any features are disabled due to soft-float.
  // FIXME: this fp16fml option handling will be reimplemented after the
  // TargetParser rewrite.
  const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), "-fullfp16");
  const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), "+fp16fml");
  if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_4a) {
    const auto ItRFullFP16  = std::find(Features.rbegin(), Features.rend(), "+fullfp16");
    if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {
      // Only entangled feature that can be to the right of this +fullfp16 is -fp16fml.
      // Only append the +fp16fml if there is no -fp16fml after the +fullfp16.
      if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16)
        Features.push_back("+fp16fml");
    }
    else
      goto fp16_fml_fallthrough;
  }
  else {
fp16_fml_fallthrough:
    // In both of these cases, putting the 'other' feature on the end of the vector will
    // result in the same effect as placing it immediately after the current feature.
    if (ItRNoFullFP16 < ItRFP16FML)
      Features.push_back("-fp16fml");
    else if (ItRNoFullFP16 > ItRFP16FML)
      Features.push_back("+fullfp16");
  }

  // Setting -msoft-float/-mfloat-abi=soft effectively disables the FPU (GCC
  // ignores the -mfpu options in this case).
  // Note that the ABI can also be set implicitly by the target selected.
  if (ABI == arm::FloatABI::Soft) {
    llvm::ARM::getFPUFeatures(llvm::ARM::FK_NONE, Features);

    // Disable all features relating to hardware FP, not already disabled by the
    // above call.
    Features.insert(Features.end(),
                    {"-dotprod", "-fp16fml", "-mve", "-mve.fp", "-fpregs"});
  } else if (FPUID == llvm::ARM::FK_NONE) {
    // -mfpu=none is *very* similar to -mfloat-abi=soft, only that it should not
    // disable MVE-I.
    Features.insert(Features.end(), {"-dotprod", "-fp16fml", "-mve.fp"});
    if (!hasIntegerMVE(Features))
      Features.emplace_back("-fpregs");
  }

  // En/disable crc code generation.
  if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
    if (A->getOption().matches(options::OPT_mcrc))
      Features.push_back("+crc");
    else
      Features.push_back("-crc");
  }

  // For Arch >= ARMv8.0 && A profile:  crypto = sha2 + aes
  // FIXME: this needs reimplementation after the TargetParser rewrite
  auto CryptoIt = llvm::find_if(llvm::reverse(Features), [](const StringRef F) {
    return F.contains("crypto");
  });
  if (CryptoIt != Features.rend()) {
    if (CryptoIt->take_front() == "+") {
      StringRef ArchSuffix = arm::getLLVMArchSuffixForARM(
          arm::getARMTargetCPU(CPUName, ArchName, Triple), ArchName, Triple);
      if (llvm::ARM::parseArchVersion(ArchSuffix) >= 8 &&
          llvm::ARM::parseArchProfile(ArchSuffix) ==
              llvm::ARM::ProfileKind::A) {
        if (ArchName.find_lower("+nosha2") == StringRef::npos &&
            CPUName.find_lower("+nosha2") == StringRef::npos)
          Features.push_back("+sha2");
        if (ArchName.find_lower("+noaes") == StringRef::npos &&
            CPUName.find_lower("+noaes") == StringRef::npos)
          Features.push_back("+aes");
      } else {
        D.Diag(clang::diag::warn_target_unsupported_extension)
            << "crypto"
            << llvm::ARM::getArchName(llvm::ARM::parseArch(ArchSuffix));
        // With -fno-integrated-as -mfpu=crypto-neon-fp-armv8 some assemblers such as the GNU assembler
        // will permit the use of crypto instructions as the fpu will override the architecture.
        // We keep the crypto feature in this case to preserve compatibility.
        // In all other cases we remove the crypto feature.
        if (!Args.hasArg(options::OPT_fno_integrated_as))
          Features.push_back("-crypto");
      }
    }
  }

  // CMSE: Check for target 8M (for -mcmse to be applicable) is performed later.
  if (Args.getLastArg(options::OPT_mcmse))
    Features.push_back("+8msecext");

  // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  // neither options are specified, see if we are compiling for kernel/kext and
  // decide whether to pass "+long-calls" based on the OS and its version.
  if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
                               options::OPT_mno_long_calls)) {
    if (A->getOption().matches(options::OPT_mlong_calls))
      Features.push_back("+long-calls");
  } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
             !Triple.isWatchOS()) {
      Features.push_back("+long-calls");
  }

  // Generate execute-only output (no data access to code sections).
  // This only makes sense for the compiler, not for the assembler.
  if (!ForAS) {
    // Supported only on ARMv6T2 and ARMv7 and above.
    // Cannot be combined with -mno-movt or -mlong-calls
    if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {
      if (A->getOption().matches(options::OPT_mexecute_only)) {
        if (getARMSubArchVersionNumber(Triple) < 7 &&
            llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6T2)
              D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();
        else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))
          D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
        // Long calls create constant pool entries and have not yet been fixed up
        // to play nicely with execute-only. Hence, they cannot be used in
        // execute-only code for now
        else if (Arg *B = Args.getLastArg(options::OPT_mlong_calls, options::OPT_mno_long_calls)) {
          if (B->getOption().matches(options::OPT_mlong_calls))
            D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
        }
        Features.push_back("+execute-only");
      }
    }
  }

  // Kernel code has more strict alignment requirements.
  if (KernelOrKext)
    Features.push_back("+strict-align");
  else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
                                    options::OPT_munaligned_access)) {
    if (A->getOption().matches(options::OPT_munaligned_access)) {
      // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
      if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
        D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
      // v8M Baseline follows on from v6M, so doesn't support unaligned memory
      // access either.
      else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
        D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
    } else
      Features.push_back("+strict-align");
  } else {
    // Assume pre-ARMv6 doesn't support unaligned accesses.
    //
    // ARMv6 may or may not support unaligned accesses depending on the
    // SCTLR.U bit, which is architecture-specific. We assume ARMv6
    // Darwin and NetBSD targets support unaligned accesses, and others don't.
    //
    // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
    // which raises an alignment fault on unaligned accesses. Linux
    // defaults this bit to 0 and handles it as a system-wide (not
    // per-process) setting. It is therefore safe to assume that ARMv7+
    // Linux targets support unaligned accesses. The same goes for NaCl.
    //
    // The above behavior is consistent with GCC.
    int VersionNum = getARMSubArchVersionNumber(Triple);
    if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
      if (VersionNum < 6 ||
          Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
        Features.push_back("+strict-align");
    } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
      if (VersionNum < 7)
        Features.push_back("+strict-align");
    } else
      Features.push_back("+strict-align");
  }

  // llvm does not support reserving registers in general. There is support
  // for reserving r9 on ARM though (defined as a platform-specific register
  // in ARM EABI).
  if (Args.hasArg(options::OPT_ffixed_r9))
    Features.push_back("+reserve-r9");

  // The kext linker doesn't know how to deal with movw/movt.
  if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
    Features.push_back("+no-movt");

  if (Args.hasArg(options::OPT_mno_neg_immediates))
    Features.push_back("+no-neg-immediates");
}

const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  std::string MArch;
  if (!Arch.empty())
    MArch = std::string(Arch);
  else
    MArch = std::string(Triple.getArchName());
  MArch = StringRef(MArch).split("+").first.lower();

  // Handle -march=native.
  if (MArch == "native") {
    std::string CPU = std::string(llvm::sys::getHostCPUName());
    if (CPU != "generic") {
      // Translate the native cpu into the architecture suffix for that CPU.
      StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
      // If there is no valid architecture suffix for this CPU we don't know how
      // to handle it, so return no architecture.
      if (Suffix.empty())
        MArch = "";
      else
        MArch = std::string("arm") + Suffix.str();
    }
  }

  return MArch;
}

/// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  std::string MArch = getARMArch(Arch, Triple);
  // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  // here means an -march=native that we can't handle, so instead return no CPU.
  if (MArch.empty())
    return StringRef();

  // We need to return an empty string here on invalid MArch values as the
  // various places that call this function can't cope with a null result.
  return Triple.getARMCPUForArch(MArch);
}

/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
                                 const llvm::Triple &Triple) {
  // FIXME: Warn on inconsistent use of -mcpu and -march.
  // If we have -mcpu=, use that.
  if (!CPU.empty()) {
    std::string MCPU = StringRef(CPU).split("+").first.lower();
    // Handle -mcpu=native.
    if (MCPU == "native")
      return std::string(llvm::sys::getHostCPUName());
    else
      return MCPU;
  }

  return std::string(getARMCPUForMArch(Arch, Triple));
}

/// getLLVMArchSuffixForARM - Get the LLVM ArchKind value to use for a
/// particular CPU (or Arch, if CPU is generic). This is needed to
/// pass to functions like llvm::ARM::getDefaultFPU which need an
/// ArchKind as well as a CPU name.
llvm::ARM::ArchKind arm::getLLVMArchKindForARM(StringRef CPU, StringRef Arch,
                                               const llvm::Triple &Triple) {
  llvm::ARM::ArchKind ArchKind;
  if (CPU == "generic" || CPU.empty()) {
    std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
    ArchKind = llvm::ARM::parseArch(ARMArch);
    if (ArchKind == llvm::ARM::ArchKind::INVALID)
      // In case of generic Arch, i.e. "arm",
      // extract arch from default cpu of the Triple
      ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  } else {
    // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
    // armv7k triple if it's actually been specified via "-arch armv7k".
    ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
                          ? llvm::ARM::ArchKind::ARMV7K
                          : llvm::ARM::parseCPUArch(CPU);
  }
  return ArchKind;
}

/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
/// CPU  (or Arch, if CPU is generic).
// FIXME: This is redundant with -mcpu, why does LLVM use this.
StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
                                       const llvm::Triple &Triple) {
  llvm::ARM::ArchKind ArchKind = getLLVMArchKindForARM(CPU, Arch, Triple);
  if (ArchKind == llvm::ARM::ArchKind::INVALID)
    return "";
  return llvm::ARM::getSubArch(ArchKind);
}

void arm::appendBE8LinkFlag(const ArgList &Args, ArgStringList &CmdArgs,
                            const llvm::Triple &Triple) {
  if (Args.hasArg(options::OPT_r))
    return;

  // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  // to generate BE-8 executables.
  if (arm::getARMSubArchVersionNumber(Triple) >= 7 || arm::isARMMProfile(Triple))
    CmdArgs.push_back("--be8");
}


text:
// this file was created by SCC 2019 and is largely a derived work from the
// original java class/interface

package org.orekit.propagation.sampling;

import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.sampling.OrekitStepHandler;
import org.orekit.propagation.sampling.OrekitStepInterpolator;
import org.orekit.time.AbsoluteDate;

public class PythonOrekitStepHandler implements OrekitStepHandler {

    /** Part of JCC Python interface to object */
    private long pythonObject;

    /** Part of JCC Python interface to object */
    public void pythonExtension(long pythonObject)
    {
        this.pythonObject = pythonObject;
    }

    /** Part of JCC Python interface to object */
    public long pythonExtension()
    {
        return this.pythonObject;
    }

    /** Part of JCC Python interface to object */
    public void finalize()
            throws Throwable
    {
        pythonDecRef();
    }

    /** Part of JCC Python interface to object */
    public native void pythonDecRef();

    /**
     * Initialize step handler at the start of a propagation.
     * Extension point for Python.
     *

     * This method is called once at the start of the propagation. It
     * may be used by the step handler to initialize some internal data
     * if needed.
     *

     *

     * The default method does nothing
     *

     *
     * @param s0 initial state
     * @param t  target time for the integration
     */
    @Override
    public native void init(SpacecraftState s0, AbsoluteDate t);

    /**
     * Handle the current step.
     * Extension point for Python.
     *
     * @param interpolator interpolator set up for the current step
     * @param isLast       if true, this is the last integration step
     */
    @Override
    public native void handleStep(OrekitStepInterpolator interpolator, boolean isLast);
}


text:
import { material } from 'angular';
import { IScope } from 'angular';
import { StateParams, StateService } from '@uirouter/angularjs';

import { Template } from '../../Template';

import { Contract } from '../../../domain/Contract';
import { Developer } from '../../../domain/Developer';

import { ContractsService } from '../../../data/ContractsService';
import { SettingsService } from '../../../data/SettingsService';

import { ContractEditController } from './ContractEditController';
import { ContractDeleteController } from './ContractDeleteController';

const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];

export class ContractsListController {
    public loading: boolean;

    public selectedYear: number;
    public yearOptions: number[];
    public hasData: boolean;

    public contractsByMonth: {
        month: string;
        contracts: Contract[];
        sum: number;
        exceeds: boolean;
    }[];

    public constructor(
        private $scope: IScope,
        private $state: StateService,
        private $stateParams: StateParams,
        private $mdDialog: material.IDialogService,
        private contractsService: ContractsService,
        private settingsService: SettingsService,
        public developer: Developer
    ) {
        'ngInject';

        if (!developer) {
            $state.go('developers');
            return;
        }

        this.selectedYear = new Date().getFullYear();

        this.loadData();
        this.fillYearOptions();
    }

    public async openEditDialog(event: MouseEvent, contract: Contract) {
        event.stopPropagation();

        try {
            const { developer } = this;
            await this.$mdDialog.show({
                templateUrl: Template.getUrl('developers/contracts/ContractEdit'),
                targetEvent: event,
                controller: ContractEditController,
                controllerAs: 'ctrl',
                locals: { developer, contract }
            });

            this.loadData();
        } catch (ex) { }
    }

    public async openDeleteDialog(event: MouseEvent, contract: Contract) {
        event.stopPropagation();

        try {
            const { developer } = this;
            await this.$mdDialog.show({
                templateUrl: Template.getUrl('developers/contracts/ContractDelete'),
                targetEvent: event,
                controller: ContractDeleteController,
                controllerAs: 'ctrl',
                locals: { developer, contract }
            });

            this.loadData();
        } catch (ex) { }
    }

    public selectYear() {
        this.loadData();
    }

    private async loadData() {
        this.loading = true;

        try {
            const data = await this.contractsService.getAllByYear(this.developer, this.selectedYear);

            this.hasData = data.length > 0;
            this.contractsByMonth = MONTHS.map(month => (
                { month, contracts: [], sum: 0.0, exceeds: false }
            ));
            data.forEach(contract => {
                const index = new Date(contract.StartDate).getMonth();
                const batch = this.contractsByMonth[index];
                batch.contracts.push(contract);
                if (!contract.AcceptanceDate) {
                    batch.sum += contract.Amount;
                }
            });
            MONTHS.forEach((month, index) => {
                const batch = this.contractsByMonth[index];
                batch.exceeds = batch.sum > this.developer.CeilingAmount;
            });
        } finally {
            this.loading = false;
            this.$scope.$apply();
        }
    }

    private async fillYearOptions() {
        this.yearOptions = [];

        const { selectedYear, yearOptions } = this;

        try {
            const settings = await this.settingsService.get();
            const { YearFrom, YearTo } = settings;

            if (YearFrom > selectedYear) {
                yearOptions.push(selectedYear);
            }
            for (let year = YearFrom; year <= YearTo; year += 1) {
                yearOptions.push(year);
            }
            if (YearTo < selectedYear) {
                yearOptions.push(selectedYear);
            }
        } finally {
            this.$scope.$apply();
        }
    }
}


text:
require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
//import ReactAddons from 'react/addons';
import { findDOMNode } from 'react-dom';

var IMAGE_WIDTH = 320;    //240px, height = width
//获取图片元数据
var imageInfoList = require('../data/imgDescInfo.json');
//生成图片的url和位置
imageInfoList = (function (imageInfoArr){
    imageInfoArr.forEach(function(element) {
      element.imageUrl = require('../images/' + element.fileName);
      element.position = {left: 0, top: 0};
      element.rotate = 0;   //旋转角度
      //element.isFlipped = false;  //是否翻到背面了?
    }, this);

    return imageInfoArr;
}(imageInfoList));

class ImgFigure extends React.Component {
  constructor(props) {
    super(props);
    this.state ={
      figureInfo: props.imgInfo,
      isFlipped: false
    };
  }

  onClick() {
    if (this.props.center) {
      this.setState({
        isFlipped: !this.state.isFlipped
      });
    } else {
      this.props.gotoCenter();
    }
  }

  flip() {
    this.setState({
      isFlipped: !this.state.isFlipped
    })
  }

  render() {
    var styleValue = this.props.imgInfo.position;
    //旋转html元素的css写法: transform: rotate(20deg);
    //这里,通过style属性来设置旋转
    //为兼容老版本的浏览器,启用了-ms-transform, -webkit-transform, -moz-transform等属性,属性值都是rotate(??deg)
/*     ["-ms-", "-webkit-", "-moz-", ""].forEach(function(preStr){
      styleValue[preStr + "transform"] =  "rotate(" + this.props.imgInfo.rotate + "deg)";
    }, this);  */
    if (this.props.imgInfo.rotate)
      styleValue["transform"] = 'rotate(' + this.props.imgInfo.rotate + 'deg)';
    //style属性值包含transform子属性的话,css文件中针对同一元素的transform设定将被覆盖。

    //var figureClassName = "img-figure is-flipped";  //测试App.scss中实现的图片翻转效果是否出得来。测试成功。
    var figureClassName = 'img-figure';
    if (this.state.isFlipped) {
      figureClassName += ' ' + 'is-flipped';
    }

    return (
            /* .img-figure样式设定position=absolute,才能使得style属性中的left, top起效 */

{this.props.imgInfo.title}

{this.props.imgInfo.desc}

    );
  }
}

class AppComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imagesInfo: imageInfoList,
    };   //用(class...extends...)定义组件时,这是定义组件状态变量的写法。
    this.center_img_index = 8;    //居中图片的编号
  }

/*   getInitialState() {    //用React.createClass定义组件时,用getInitialState定义组件状态变量
    return {imagesInfo: imageInfoList};
  } */

  onClickImage(event) {

    event.preventDefault();
    event.stopPropagation();
  }

  render() {
    var controllerUnits = [];
    var imgFigures = [];
    //var stage = React.findDOMNode('.stage');    //此时,组件还未加载到网页上。是无法调用findDOMNode取到dom节点的。

    //console.log('AppComponent.render(), imageInfoList=', imageInfoList);
    imageInfoList.forEach(function(singleImageInfo, index){
      //singleImageInfo.left = index * 10;   /* 要使left, top属性起效,需要把position设定为absolute  */
      //singleImageInfo.top = index * 10;
      //singleImageInfo.position = calcRandomPosition(0, 0, stage.width, stage.height);   //需要在componentDidMount生命周期函数内来计算图片的位置
      //singleImageInfo.position = {left: 0, top: 0};
      var centerOrNot = index == this.center_img_index;
      imgFigures.push(<ImgFigure imgInfo={singleImageInfo} key={index} center={centerOrNot} gotoCenter={this.gotoCenter(index)}/>);
    }, this);

    return (

          {imgFigures}

          {controllerUnits}

    );
  }

  componentDidMount() {
    this.arrangeImagesInWidow(this.center_img_index);
  }

  arrangeImagesInWidow(center_img_index) {
    this.center_img_index = center_img_index;
    var stageDomNode = findDOMNode(this.refs.stage);

    var stageWidth = stageDomNode.scrollWidth;
    var stageHeight = stageDomNode.scrollHeight;
    //console.log('AppComponent.componentDidMount(), (stageWidth, stageHeight)=', stageWidth, stageHeight);

    this.arrangeImages(0, 0, stageWidth, stageHeight, center_img_index);
  }

  arrangeImages(x_low, y_low, x_high, y_high, center_img_index) {
/*     imageInfoList.forEach(function(singleImageInfo, index){
      singleImageInfo.position = this.calcRandomPosition(x_low, y_low, x_high, y_high);
      //imageInfoList[index].position = this.calcRandomPosition(x_low, y_low, x_high, y_high);
    }, this); */
    this.setImagesPostion(x_low, y_low, x_high, y_high, center_img_index);
    //console.log('AppComponent.arrangeImages(), imageInfoList=', imageInfoList);
    this.setState({
      imagesInfo: imageInfoList
    });
  }

  //设定所有图片的坐标位置
  // @param center_img_index: 处于中心位置的图片的下标(数组中的下标)
  setImagesPostion(x_low, y_low, x_high, y_high, center_img_index) {
    console.log("setImagePosition(), center_img_index=", center_img_index);
    var halfImageWidth = Math.floor(IMAGE_WIDTH / 2);
    //中心点
    var center_x = Math.floor(x_low + (x_high - x_low) / 2);
    var center_y = Math.floor(y_low + (y_high - y_low) / 2);

    //左侧区域
    var leftArea_x_low = x_low - halfImageWidth;
    var leftArea_x_high = center_x - halfImageWidth - IMAGE_WIDTH;
    var leftArea_y_low = y_low - halfImageWidth;
    var leftArea_y_high = y_high + halfImageWidth;

    //右侧区域
    var rightArea_x_low = center_x + halfImageWidth;
    var rightArea_x_high = x_high - halfImageWidth;
    var rightArea_y_low = y_low - halfImageWidth;
    var rightArea_y_high = y_high + halfImageWidth;

    //设定图片位置
    //中心图片
    imageInfoList[center_img_index].position = {
      left: center_x - halfImageWidth,
      top: center_y - halfImageWidth
    };
    imageInfoList[center_img_index].rotate = 0;

    //左侧图片
    for (var i = 0; i < imageInfoList.length / 2; i++) {
      if (i == center_img_index) continue;
      imageInfoList[i].position = this.calcRandomPosition(leftArea_x_low, leftArea_y_low, leftArea_x_high, leftArea_y_high);
      imageInfoList[i].rotate = this.randomRotateDeg();
    }
    //右侧图片
    for (var r = imageInfoList.length / 2; r < imageInfoList.length; r++) {
      if (r == center_img_index) continue;
      imageInfoList[r].position = this.calcRandomPosition(rightArea_x_low, rightArea_y_low, rightArea_x_high, rightArea_y_high);
      imageInfoList[r].rotate = this.randomRotateDeg();
    }

  }

  calcRandomPosition(x_low, y_low, x_high, y_high) {
    var x = Math.floor(Math.random() * (x_high - x_low) + x_low);
    var y = Math.floor(Math.random() * (y_high - y_low) + y_low);
    //console.log('calcRandomPosition(), (x, y)=', x, y);
    return {left: x, top: y};
  }

  randomRotateDeg() {
    var deg = Math.floor(Math.random() * 30);
    if (Math.random() < 0.5)
      return -deg;
    else
      return deg;
  }

  //把图片调到窗口中心
  gotoCenter(index) {
    //return function(index) {  //错误的写法,这要求调用闭包函数的时候传入参数。这里,是想把index作为执行环境变量,供闭包函数使用。
    return function() {
      //console.log("AppComponent.gotoCenter(), center_img_index=", index);
      this.arrangeImagesInWidow(index);
    }.bind(this);
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;


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="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/detail_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:text="@string/source_title" >
        </EditText>

        <CheckBox
            android:id="@+id/detail_serverenable"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/enabled_on_server" >
        </CheckBox>

        <CheckBox
            android:id="@+id/detail_localenable"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/enabled_locally" >
        </CheckBox>

        <TextView
            android:id="@+id/detail_sourcekey"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="2" >
        </TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/detail_save"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="save"
            android:text="@string/save" >
        </Button>

        <Button
            android:id="@+id/detail_emailkey"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="emailKey"
            android:text="@string/email_source_key" >
        </Button>

        <Button
            android:id="@+id/detail_messages"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="messages"
            android:text="@string/messages" >
        </Button>

        <Button
            android:id="@+id/detail_test"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="test"
            android:text="@string/test" >
        </Button>

        <Button
            android:id="@+id/detail_delete"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="delete"
            android:text="@string/delete" >
        </Button>
    </LinearLayout>

</LinearLayout>


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
SweetPortfolio::Application.initialize!


text:
from setuptools import setup

setup(
    name='yg.emanate',
    use_scm_version=True,
    description="Lightweight event system for Python",
    author="YouGov, plc",
    author_email='dev@yougov.com',
    url='https://github.com/yougov/yg.emanate',
    packages=[
        'yg.emanate',
    ],
    namespace_packages=['yg'],
    include_package_data=True,
    setup_requires=['setuptools_scm>=1.15'],
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
    ],
    test_suite='tests',
    python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
)


text:
package io.reactivex.netty.examples.http.loadbalancing;

import io.reactivex.netty.examples.ExamplesTestUtil;
import org.junit.Test;

import java.util.Queue;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

public class LoadBalancingTest {

    @Test(timeout = 60000)
    public void testLoadBalancing() throws Exception {
        Queue<String> output = ExamplesTestUtil.runClientInMockedEnvironment(HttpLoadBalancingClient.class);

        assertThat("Unexpected number of messages echoed", output, hasSize(5));

        assertThat("Unexpected status.", output.poll(), anyOf(containsString("HTTP/1.1 200 OK"),
                                                              containsString("HTTP/1.1 503 Service Unavailable")));
        assertThat("Unexpected status.", output.poll(), anyOf(containsString("HTTP/1.1 200 OK"),
                                                              containsString("HTTP/1.1 503 Service Unavailable")));
        assertThat("Unexpected status.", output.poll(), anyOf(containsString("HTTP/1.1 200 OK"),
                                                              containsString("HTTP/1.1 503 Service Unavailable")));
        assertThat("Unexpected status.", output.poll(), anyOf(containsString("HTTP/1.1 200 OK"),
                                                              containsString("HTTP/1.1 503 Service Unavailable")));
        assertThat("Unexpected status.", output.poll(), anyOf(containsString("HTTP/1.1 200 OK"),
                                                              containsString("HTTP/1.1 503 Service Unavailable")));

    }
}


text:
"""
This module implements a model checkpoint loader and writer.
"""
import os

import tensorflow as tf

from niftynet.engine.application_variables import global_vars_init_or_restore
from niftynet.engine.signal import \
    ITER_FINISHED, SESS_FINISHED, SESS_STARTED
from niftynet.io.misc_io import touch_folder

FILE_PREFIX = 'model.ckpt'

def make_model_name(model_dir):
    """
    Make the model checkpoint folder.
    the checkpoint file will be located at `model_dir/models/` folder,
    the filename will start with FILE_PREFIX.

    :param model_dir: niftynet model folder
    :return: a partial name of a checkpoint file `model_dir/model/FILE_PREFIX`
    """
    _model_dir = touch_folder(os.path.join(model_dir, 'models'))
    return os.path.join(_model_dir, FILE_PREFIX)

class ModelRestorer(object):
    """
    This class handles restoring the model at the beginning of a session.
    """

    def __init__(self,
                 model_dir,
                 initial_iter=0,
                 is_training_action=True,
                 vars_to_restore=None,
                 **_unused):
        self.initial_iter = initial_iter
        self.vars_to_restore = vars_to_restore
        self.file_name_prefix = make_model_name(model_dir)
        # randomly initialise or restoring model
        if is_training_action and initial_iter == 0:
            SESS_STARTED.connect(self.rand_init_model)
        else:
            SESS_STARTED.connect(self.restore_model)

    def rand_init_model(self, _sender, **_unused):
        """
        Randomly initialising all trainable variables defined in
        the default session.

        :param _sender:
        :param _unused:
        :return:
        """
        with tf.name_scope('Initialisation'):
            init_op = global_vars_init_or_restore()
        tf.get_default_session().run(init_op)
        tf.logging.info('Parameters from random initialisations ...')

    def restore_model(self, _sender, **_unused):
        """
        Loading checkpoint files as variable initialisations.

        :param _sender:
        :param _unused:
        :return:
        """
        checkpoint = '{}-{}'.format(self.file_name_prefix, self.initial_iter)
        to_restore = None  # tf.train.Saver's default value, restoring all

        if self.vars_to_restore:
            # partially restore (updating `to_restore` list)
            tf.logging.info("Finding variables to restore...")
            import re
            # Determine which vars to
            # restore using regex matching
            var_regex = re.compile(self.vars_to_restore)
            to_restore, to_randomise = [], []
            for restorable in tf.global_variables():
                if var_regex.search(restorable.name):
                    to_restore.append(restorable)
                else:
                    to_randomise.append(restorable)

            if not to_restore:
                tf.logging.fatal(
                    'vars_to_restore specified: %s, but nothing matched.',
                    self.vars_to_restore)
                assert to_restore, 'Nothing to restore (--vars_to_restore)'

            var_names = [  # getting first three item to print
                var_restore.name for var_restore in to_restore[:3]]
            tf.logging.info(
                'Restoring %s out of %s variables from %s: \n%s, ...',
                len(to_restore),
                len(tf.global_variables()),
                checkpoint, ',\n'.join(var_names))
            # Initialize vars to randomize
            init_op = tf.variables_initializer(to_randomise)
            tf.get_default_session().run(init_op)

        try:
            saver = tf.train.Saver(
                var_list=to_restore, save_relative_paths=True)
            saver.restore(tf.get_default_session(), checkpoint)
        except tf.errors.NotFoundError:
            tf.logging.fatal(
                'checkpoint %s not found or variables to restore do not '
                'match the current application graph', checkpoint)
            dir_name = os.path.dirname(checkpoint)
            if dir_name and not os.path.exists(dir_name):
                tf.logging.fatal(
                    "Model folder not found %s, please check"
                    "config parameter: model_dir", dir_name)
            raise

class ModelSaver(object):
    """
    This class handles iteration events to save the model as checkpoint files.
    """

    def __init__(self,
                 model_dir,
                 save_every_n=0,
                 max_checkpoints=1,
                 is_training_action=True,
                 **_unused):

        self.save_every_n = save_every_n
        self.max_checkpoints = max_checkpoints
        self.file_name_prefix = make_model_name(model_dir)
        self.saver = None

        # initialise the saver after the graph finalised
        SESS_STARTED.connect(self.init_saver)
        # save the training model at a positive frequency
        if self.save_every_n > 0:
            ITER_FINISHED.connect(self.save_model_interval)
        # always save the final training model before exiting
        if is_training_action:
            SESS_FINISHED.connect(self.save_model)

    def init_saver(self, _sender, **_unused):
        """
        Initialise a model saver.

        :param _sender:
        :param _unused:
        :return:
        """
        self.saver = tf.train.Saver(
            max_to_keep=self.max_checkpoints, save_relative_paths=True)

    def save_model(self, _sender, **msg):
        """
        Saving the model at the current iteration.

        :param _sender:
        :param msg: an iteration message instance
        :return:
        """
        iter_i = msg['iter_msg'].current_iter
        if iter_i >= 0:
            self._save_at(iter_i)

    def save_model_interval(self, _sender, **msg):
        """
        Saving the model according to the frequency of ``save_every_n``.

        :param _sender:
        :param msg: an iteration message instance
        :return:
        """
        if not msg['iter_msg'].is_training:
            return
        iter_i = msg['iter_msg'].current_iter
        if iter_i > 0 and iter_i % self.save_every_n == 0:
            self._save_at(iter_i)

    def _save_at(self, iter_i):
        """
        Saving the model at iter i and print a console log.

        : param iter_i: integer of the current iteration
        : return:
        """
        if not self.saver:
            return
        self.saver.save(sess=tf.get_default_session(),
                        save_path=self.file_name_prefix,
                        global_step=iter_i)
        tf.logging.info('iter %d saved: %s', iter_i, self.file_name_prefix)


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

namespace MiniNet.Channels
{
    public class StringEncoder : IChannelEncoder<string>
    {
        private readonly Encoding encoding;

        public StringEncoder(Encoding encoding)
        {
            this.encoding = encoding;
        }

        public void Process(IBuffer buffer, string message)
        {
            // var len = Encoding.UTF8.GetByteCount(message.ToString());
            // BitConverter2.GetBytes(len, _buffer, 0);
            buffer.SetString(buffer.Size, message, encoding);
            //System.Console.WriteLine("Encoded message: " + message);
        }

        public void Reset()
        {
        }
    }
}


text:
Verify Data

{{newProject.entriesImported}} entries were found in the initial data.

    <button class="btn" id="nonCriticalErrorsButton" data-ng-click="show.importErrors = !show.importErrors">
        {{showImportErrorsButtonLabel()}}</button>

{{newProject.importErrors}}


text:
HexGrid::HexGrid(QObject *parent, int width, int height)
	:QObject(parent), width(width), height(height), neighborSet()
{
	neighborSet.reserve(6);
	neighborSet.append(QPoint(0, 1));
	neighborSet.append(QPoint(1, 0));
	neighborSet.append(QPoint(1, 1));
	neighborSet.append(QPoint(0, -1));
	neighborSet.append(QPoint(-1, 0));
	neighborSet.append(QPoint(-1, -1));

	for (int i = 0; i < height; i++)
	{
		//the y axis is actually at a 60 degree angle to the x axis rather than going up and down
		//so as we move further away from the x axis, the leftmost column that we keep track of on
		//this square-like grid will increase, by one column for every 2 rows
		int leftCol = i / 2;

		for (int j = leftCol; j < leftCol + width; j++)
		{
			grid.insert(QPoint(j, i), GridEntry());
		}
	}
}

QVector<QPoint> HexGrid::getNeighbors(const QPoint &p) const
{
	QVector<QPoint> results;
	results.reserve(neighborSet.size());

	for (const QPoint &n : neighborSet)
	{
		QPoint testPoint = p + n;
		if (grid.contains(testPoint))
		{
			results.push_back(testPoint);
		}
	}
	return results;
}

bool HexGrid::isValidCell(const QPoint &p) const
{
	return grid.contains(p);
}

GridEntry& HexGrid::getEntry(const QPoint &p)
{
	return grid[p];
}

QList<QPoint> HexGrid::getCells(void)
{
	return grid.keys();
}

int HexGrid::manhattanDistance(const QPoint &p1, const QPoint &p2) const
{
	//algorithm: http://stackoverflow.com/questions/5084801/distance-between-tiles-in-a-hexagonal-field

	int dx = p2.x() - p1.x();
	int dy = p2.y() - p1.y();

	if (sign(dx) == sign(dy))
	{
		return qMax(qAbs(dx), qAbs(dy));
	}
	else
	{
		return qAbs(dx) + qAbs(dy);
	}
}

int HexGrid::getWidth(void) const
{
	return width;
}
int HexGrid::getHeight(void) const
{
	return height;
}

void HexGrid::resetSearched(void)
{
	for (auto it = grid.begin(); it != grid.end(); it++)
	{
		it.value().searched = false;
		it.value().queued = false;
		it.value().path = false;
		it.value().modified = true;
	}
}

void HexGrid::resetAll(void)
{
	for (auto it = grid.begin(); it != grid.end(); it++)
	{
		it.value().searched = false;
		it.value().queued = false;
		it.value().path = false;
		it.value().modified = true;
		it.value().type = GridEntry::Open;
	}
}

uint qHash(const QPoint &p)
{
	uint hx = qHash(p.x());
	uint hy = qHash(p.y());

	return hx ^ ((hy << 16) | (hy >> 16));
}


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');//favicon serving middleware with caching
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override')
var mongoose=require("mongoose");
var session = require('express-session')
var passport = require('passport');

//mongodb://localhost/database
var url="mongodb://localhost:27017/broadwayDb";
//mongodb://username:password@hostname:port/database

mongoose.connect(url);
var connection=mongoose.connection;

connection.on('connected', function(){
  console.log('Mongoose connected to ' + url);
});

connection.on("open",function () {
  console.log("Connection open on  " + url)
});

connection.on('error', function() {
  console.log("Sorry, there is no mongo db server running.")
});

process.on('SIGINT', function(){
  connection.close(function(){
    console.log('Mongoose disconnected through app termination');
    process.exit(0);
  });
});

var indexRoute = require('./routes/index');
var usersRoute = require('./routes/users');
var booksRoute = require('./routes/books');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));//The urlencoded method within body-parser tells body-parser to extract data from the <form> element and add them to the body property in the request object.
app.use(cookieParser());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

//this is configuration for session and passport
//require('./passportConfig')(passport);
 app.use(session({secret: 'bbbroooaadwaaay', saveUninitialized: true, resave: true}));
// app.use(passport.initialize());
// app.use(passport.session());

 //router define start here

app.use('/', indexRoute);
app.use('/users', usersRoute);
app.use('/books', booksRoute);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
package omaha

import (
	"encoding/xml"
	"fmt"
	"testing"

	"github.com/kylelemons/godebug/diff"
)

const (
	testAppID  = "{27BD862E-8AE8-4886-A055-F7F1A6460627}"
	testAppVer = "1.0.0"
)

var (
	nilRequest  *Request
	nilResponse *Response
)

func init() {
	nilRequest = NewRequest()
	nilRequest.AddApp(testAppID, testAppVer)
	nilResponse = NewResponse()
	nilResponse.AddApp(testAppID, AppOK)
}

func compareXML(a, b interface{}) error {
	aXml, err := xml.MarshalIndent(a, "", "\t")
	if err != nil {
		return err
	}

	bXml, err := xml.MarshalIndent(b, "", "\t")
	if err != nil {
		return err
	}

	if d := diff.Diff(string(aXml), string(bXml)); d != "" {
		err := fmt.Errorf("Unexpected XML:\n%s", d)
		return err
	}

	return nil
}

func TestHandleNilRequest(t *testing.T) {
	handler := OmahaHandler{UpdaterStub{}}
	response := NewResponse()
	handler.serveApp(response, nil, nilRequest, nilRequest.Apps[0])
	if err := compareXML(nilResponse, response); err != nil {
		t.Error(err)
	}
}