text:
package com.example.sony.cameraremote;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.sony.cameraremote.utils.SimpleLiveviewSlicer;
import com.example.sony.cameraremote.utils.SimpleLiveviewSlicer.Payload;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * SimpleLiveviewSurfaceView.
 */
public class SimpleLiveviewSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

    /** Remote APIインスタンス. */
    private SimpleRemoteApi mRemoteApi;
    /** View生成・破壊フラグ. */
    private boolean mWhileFetching;
    /** jpegデータ. */
    private final BlockingQueue<byte[]> mJpegQueue = new ArrayBlockingQueue<byte[]>(2);
    /** ミュート可否フラグ. */
    private final boolean mInMutableAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    /** ビューの内容描画用スレッド. */
    private Thread mDrawerThread;
    /** 横幅. */
    private int mPreviousWidth = 0;
    /** 縦幅. */
    private int mPreviousHeight = 0;
    /** フレームペイントインスタンス. */
    private final Paint mFramePaint;

    /**
     * Contractor.
     *
     * @param context コンテクスト
     */
    public SimpleLiveviewSurfaceView(final Context context) {
        super(context);
        getHolder().addCallback(this);
        mFramePaint = new Paint();
        mFramePaint.setDither(true);
    }

    /**
     * Contractor.
     *
     * @param context コンテクスト
     * @param attrs アトリビュート
     */
    public SimpleLiveviewSurfaceView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
        mFramePaint = new Paint();
        mFramePaint.setDither(true);
    }

    /**
     * Contractor.
     *
     * @param context コンテクスト
     * @param attrs アトリビュート
     * @param defStyle デフォルトスタイル
     */
    public SimpleLiveviewSurfaceView(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        getHolder().addCallback(this);
        mFramePaint = new Paint();
        mFramePaint.setDither(true);
    }

    @Override
    public void surfaceChanged(final SurfaceHolder holder, final int format, final int width, final int height) {
        // do nothing.
    }

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        // do nothing.
    }

    @Override
    public void surfaceDestroyed(final SurfaceHolder holder) {
        mWhileFetching = false;
    }

    /**
     * Bind a Remote API object to communicate with Camera device. Need to call
     * this method before calling start() method.
     *
     * @param remoteApi リモートAPIインスタンス
     */
    public void bindRemoteApi(final SimpleRemoteApi remoteApi) {
        mRemoteApi = remoteApi;
    }

    /**
     * Start retrieving and drawing liveview frame data by new threads.
     *
     * @return true if the starting is completed successfully, false otherwise.
     * @see SimpleLiveviewSurfaceView#bindRemoteApi(SimpleRemoteApi)
     */
    public boolean start() {
        if (mRemoteApi == null) {
            throw new IllegalStateException("RemoteApi is not set.");
        }
        if (mWhileFetching) {
            return false;
        }

        mWhileFetching = true;

        // A thread for retrieving liveview data from server.
        Thread mThread = new Thread() {
            @Override
            public void run() {
                SimpleLiveviewSlicer slicer = null;

                try {
                    // Prepare for connecting.
                    JSONObject replyJson = null;

                    replyJson = mRemoteApi.startLiveview();
                    if (!isErrorReply(replyJson)) {
                        JSONArray resultsObj = replyJson.getJSONArray("result");
                        String liveviewUrl = null;
                        if (1 <= resultsObj.length()) {
                            // Obtain liveview URL from the result.
                            liveviewUrl = resultsObj.getString(0);
                        }
                        if (liveviewUrl != null) {
                            // Create Slicer to open the stream and parse it.
                            slicer = new SimpleLiveviewSlicer();
                            slicer.open(liveviewUrl);
                        }
                    }

                    if (slicer == null) {
                        mWhileFetching = false;
                        return;
                    }

                    while (mWhileFetching) {
                        final Payload payload = slicer.nextPayload();
                        if (payload == null) { // never occurs
                            continue;
                        }

                        if (mJpegQueue.size() == 2) {
                            mJpegQueue.remove();
                        }
                        mJpegQueue.add(payload.getJpegData());
                    }
                } catch (IOException e) {
                  //Exceptionを受けるだけなので処理は行わない
                } catch (JSONException e) {
                  //Exceptionを受けるだけなので処理は行わない
                } finally {
                    // Finalize
                    try {
                        if (slicer != null) {
                            slicer.close();
                        }
                        mRemoteApi.stopLiveview();
                    } catch (IOException e) {
                      //Exceptionを受けるだけなので処理は行わない
                    }

                    if (mDrawerThread != null) {
                        mDrawerThread.interrupt();
                    }

                    mJpegQueue.clear();
                    mWhileFetching = false;
                }
            }
        };
        mThread.start();

        // A thread for drawing liveview frame fetched by above thread.
        mDrawerThread = new Thread() {
            @Override
            public void run() {
                Bitmap frameBitmap = null;

                BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
                factoryOptions.inSampleSize = 1;
                if (mInMutableAvailable) {
                    initInBitmap(factoryOptions);
                }

                while (mWhileFetching) {
                    try {
                        byte[] jpegData = mJpegQueue.take();
                        frameBitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, factoryOptions);
                    } catch (IllegalArgumentException e) {
                        if (mInMutableAvailable) {
                            clearInBitmap(factoryOptions);
                        }
                        continue;
                    } catch (InterruptedException e) {
                        break;
                    }

                    if (mInMutableAvailable) {
                        setInBitmap(factoryOptions, frameBitmap);
                    }
                    drawFrame(frameBitmap);
                }

                if (frameBitmap != null) {
                    frameBitmap.recycle();
                }
                mWhileFetching = false;
            }
        };
        mDrawerThread.start();
        return true;
    }

    /**
     * Request to stop retrieving and drawing liveview data.
     */
    public void stop() {
        mWhileFetching = false;
    }

    /**
     * Check to see whether start() is already called.
     *
     * @return true if start() is already called, false otherwise.
     */
    public boolean isStarted() {
        return mWhileFetching;
    }

    /**
     * Target API version.
     *
     * @param options オプション
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void initInBitmap(final BitmapFactory.Options options) {
        options.inBitmap = null;
        options.inMutable = true;
    }

    /**
     * Target API version.
     *
     * @param options オプション
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void clearInBitmap(final BitmapFactory.Options options) {
        if (options.inBitmap != null) {
            options.inBitmap.recycle();
            options.inBitmap = null;
        }
    }

    /**
     * Target API version.
     *
     * @param options オプション
     * @param bitmap ビットマップ
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setInBitmap(final BitmapFactory.Options options, final Bitmap bitmap) {
        options.inBitmap = bitmap;
    }

    /**
     * Draw frame bitmap onto a canvas.
     *
     * @param frame フレーム
     */
    private void drawFrame(final Bitmap frame) {
        if (frame.getWidth() != mPreviousWidth || frame.getHeight() != mPreviousHeight) {
            onDetectedFrameSizeChanged(frame.getWidth(), frame.getHeight());
            return;
        }
        Canvas canvas = getHolder().lockCanvas();
        if (canvas == null) {
            return;
        }
        int w = frame.getWidth();
        int h = frame.getHeight();
        Rect src = new Rect(0, 0, w, h);

        float by = Math.min((float) getWidth() / w, (float) getHeight() / h);
        int offsetX = (getWidth() - (int) (w * by)) / 2;
        int offsetY = (getHeight() - (int) (h * by)) / 2;
        Rect dst = new Rect(offsetX, offsetY, getWidth() - offsetX, getHeight() - offsetY);
        canvas.drawBitmap(frame, src, dst, mFramePaint);
        getHolder().unlockCanvasAndPost(canvas);
    }

    /**
     * Called when the width or height of liveview frame image is changed.
     *
     * @param width width
     * @param height height
     */
    private void onDetectedFrameSizeChanged(final int width, final int height) {
        mPreviousWidth = width;
        mPreviousHeight = height;
        drawBlackFrame();
        drawBlackFrame();
        drawBlackFrame(); // delete triple buffers
    }

    /**
     * Draw black screen.
     */
    private void drawBlackFrame() {
        Canvas canvas = getHolder().lockCanvas();
        if (canvas == null) {
            return;
        }

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL);

        canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), paint);
        getHolder().unlockCanvasAndPost(canvas);
    }

    /**
     * Parse JSON and returns a error code.
     *
     * @param replyJson 送信用JSON
     * @return hasError
     */
    private static boolean isErrorReply(final JSONObject replyJson) {
        boolean hasError = (replyJson != null && replyJson.has("error"));
        return hasError;
    }
}


text:
package com.google.api.ads.adwords.jaxws.v201406.cm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Returns a list of all mobile devices.
 *
 *             @return A list of mobile devices.
 *             @throws ApiException when there is at least one error with the request.
 *
 *
 *
Java class for getMobileDeviceCriterion element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="getMobileDeviceCriterion">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "getMobileDeviceCriterion")
public class ConstantDataServiceInterfacegetMobileDeviceCriterion {

}

redpajama_set_name: RedPajamaGithub


text:
ENV['MOCK_HEROKU'] = '1'

def start_heroku_app(params = {})
  Locomotive::Heroku.connection.post_app(params).body.tap do |data|
    name = data['name']
    Locomotive::Heroku.app_name = name

    ready = false
    until ready
      ready = Locomotive::Heroku.connection.request(:method => :put, :path => "/apps/#{name}/status").status == 201
    end

    Locomotive::Heroku.connection.post_addon(name, 'custom_domains:basic')
  end
end

def shutdown_heroku_app(name)
  Locomotive::Heroku.connection.delete_app(name) rescue nil
end

def with_app(params = {}, &block)
  begin
    data = start_heroku_app(params)
    @name = data['name']
    yield(data)
  ensure
    shutdown_heroku_app @name
  end
end


text:
package sbt

import sbt.internal.{
  Act,
  Aggregation,
  BuildStructure,
  BuildUnit,
  CommandExchange,
  CommandStrings,
  DefaultBackgroundJobService,
  EvaluateConfigurations,
  Inspect,
  IvyConsole,
  Load,
  LoadedBuildUnit,
  LogManager,
  Output,
  PluginsDebug,
  ProjectNavigation,
  Script,
  SessionSettings,
  SetResult,
  SettingCompletions
}
import sbt.internal.util.{
  AttributeKey,
  AttributeMap,
  ConsoleOut,
  GlobalLogging,
  LineRange,
  MainAppender,
  SimpleReader,
  Types
}
import sbt.util.{ Level, Logger, Show }

import sbt.internal.util.complete.{ DefaultParsers, Parser }
import sbt.internal.inc.ScalaInstance
import sbt.compiler.EvalImports
import Types.{ const, idFun }
import Aggregation.AnyKeys
import Project.LoadAction
import xsbti.compile.CompilerCache

import scala.annotation.tailrec
import sbt.io.IO
import sbt.io.syntax._
import StandardMain._

import java.io.{ File, IOException }
import java.net.URI
import java.util.Locale
import scala.util.control.NonFatal
import BasicCommandStrings.{ Shell, TemplateCommand }
import CommandStrings.BootCommand

/** This class is the entry point for sbt. */
final class xMain extends xsbti.AppMain {
  def run(configuration: xsbti.AppConfiguration): xsbti.MainResult = {
    import BasicCommands.early
    import BasicCommandStrings.runEarly
    import BuiltinCommands.defaults
    import sbt.internal.CommandStrings.{ BootCommand, DefaultsCommand, InitCommand }
    val state = initialState(
      configuration,
      Seq(defaults, early),
      runEarly(DefaultsCommand) :: runEarly(InitCommand) :: BootCommand :: Nil)
    runManaged(state)
  }
}

final class ScriptMain extends xsbti.AppMain {
  def run(configuration: xsbti.AppConfiguration): xsbti.MainResult = {
    import BasicCommandStrings.runEarly
    runManaged(
      initialState(
        configuration,
        BuiltinCommands.ScriptCommands,
        runEarly(Level.Error.toString) :: Script.Name :: Nil
      ))
  }
}

final class ConsoleMain extends xsbti.AppMain {
  def run(configuration: xsbti.AppConfiguration): xsbti.MainResult =
    runManaged(
      initialState(
        configuration,
        BuiltinCommands.ConsoleCommands,
        IvyConsole.Name :: Nil
      ))
}

object StandardMain {
  private[sbt] lazy val exchange = new CommandExchange()

  def runManaged(s: State): xsbti.MainResult = {
    val previous = TrapExit.installManager()
    try {
      try {
        MainLoop.runLogged(s)
      } finally DefaultBackgroundJobService.backgroundJobService.shutdown()
    } finally TrapExit.uninstallManager(previous)
  }

  /** The common interface to standard output, used for all built-in ConsoleLoggers. */
  val console: ConsoleOut =
    ConsoleOut.systemOutOverwrite(ConsoleOut.overwriteContaining("Resolving "))

  def initialGlobalLogging: GlobalLogging =
    GlobalLogging.initial(MainAppender.globalDefault(console),
                          File.createTempFile("sbt", ".log"),
                          console)

  def initialState(configuration: xsbti.AppConfiguration,
                   initialDefinitions: Seq[Command],
                   preCommands: Seq[String]): State = {
    import BasicCommandStrings.isEarlyCommand
    val userCommands = configuration.arguments.map(_.trim)
    val (earlyCommands, normalCommands) = (preCommands ++ userCommands).partition(isEarlyCommand)
    val commands = (earlyCommands ++ normalCommands).toList map { x =>
      Exec(x, None)
    }
    val initAttrs = BuiltinCommands.initialAttributes
    val s = State(
      configuration,
      initialDefinitions,
      Set.empty,
      None,
      commands,
      State.newHistory,
      initAttrs,
      initialGlobalLogging,
      None,
      State.Continue
    )
    s.initializeClassLoaderCache
  }
}

import DefaultParsers._
import sbt.internal.CommandStrings._
import BasicCommandStrings._
import BasicCommands._
import CommandUtil._
import TemplateCommandUtil.templateCommand

object BuiltinCommands {
  def initialAttributes = AttributeMap.empty

  def ConsoleCommands: Seq[Command] =
    Seq(ignore, exit, IvyConsole.command, setLogLevel, early, act, nop)

  def ScriptCommands: Seq[Command] =
    Seq(ignore, exit, Script.command, setLogLevel, early, act, nop)

  def DefaultCommands: Seq[Command] =
    Seq(
      ignore,
      help,
      completionsCommand,
      about,
      tasks,
      settingsCommand,
      loadProject,
      templateCommand,
      projects,
      project,
      reboot,
      read,
      history,
      set,
      sessionCommand,
      inspect,
      loadProjectImpl,
      loadFailed,
      Cross.crossBuild,
      Cross.switchVersion,
      PluginCross.pluginCross,
      PluginCross.pluginSwitch,
      Cross.crossRestoreSession,
      setOnFailure,
      clearOnFailure,
      stashOnFailure,
      popOnFailure,
      setLogLevel,
      plugin,
      plugins,
      writeSbtVersion,
      notifyUsersAboutShell,
      ifLast,
      multi,
      shell,
      oldshell,
      BasicCommands.client,
      continuous,
      eval,
      alias,
      append,
      last,
      lastGrep,
      export,
      boot,
      nop,
      call,
      exit,
      early,
      initialize,
      act
    ) ++ compatCommands

  def DefaultBootCommands: Seq[String] =
    WriteSbtVersion :: LoadProject :: NotifyUsersAboutShell :: s"$IfLast $Shell" :: Nil

  def boot = Command.make(BootCommand)(bootParser)

  def about = Command.command(AboutCommand, aboutBrief, aboutDetailed) { s =>
    s.log.info(aboutString(s)); s
  }

  def setLogLevel = Command.arb(const(logLevelParser), logLevelHelp)(LogManager.setGlobalLogLevel)
  private[this] def logLevelParser: Parser[Level.Value] =
    oneOf(Level.values.toSeq.map(v => v.toString ^^^ v))

  // This parser schedules the default boot commands unless overridden by an alias
  def bootParser(s: State) = {
    val orElse = () => DefaultBootCommands.toList ::: s
    delegateToAlias(BootCommand, success(orElse))(s)
  }

  def sbtName(s: State): String = s.configuration.provider.id.name
  def sbtVersion(s: State): String = s.configuration.provider.id.version
  def scalaVersion(s: State): String = s.configuration.provider.scalaProvider.version
  def aboutProject(s: State): String =
    if (Project.isProjectLoaded(s)) {
      val e = Project.extract(s)
      val version = e.getOpt(Keys.version) match { case None => ""; case Some(v) => " " + v }
      val current = "The current project is " + Reference.display(e.currentRef) + version + "\n"
      val sc = aboutScala(s, e)
      val built = if (sc.isEmpty) "" else "The current project is built against " + sc + "\n"
      current + built + aboutPlugins(e)
    } else "No project is currently loaded"

  def aboutPlugins(e: Extracted): String = {
    def list(b: BuildUnit) = b.plugins.detected.autoPlugins.map(_.value.label)
    val allPluginNames = e.structure.units.values.flatMap(u => list(u.unit)).toSeq.distinct
    if (allPluginNames.isEmpty) "" else allPluginNames.mkString("Available Plugins: ", ", ", "")
  }

  def aboutScala(s: State, e: Extracted): String = {
    val scalaVersion = e.getOpt(Keys.scalaVersion)
    val scalaHome = e.getOpt(Keys.scalaHome).flatMap(idFun)
    val instance =
      e.getOpt(Keys.scalaInstance).flatMap(_ => quiet(e.runTask(Keys.scalaInstance, s)._2))
    (scalaVersion, scalaHome, instance) match {
      case (sv, Some(home), Some(si)) =>
        "local Scala version " + selectScalaVersion(sv, si) + " at " + home.getAbsolutePath
      case (_, Some(home), None)  => "a local Scala build at " + home.getAbsolutePath
      case (sv, None, Some(si))   => "Scala " + selectScalaVersion(sv, si)
      case (Some(sv), None, None) => "Scala " + sv
      case (None, None, None)     => ""
    }
  }

  def aboutString(s: State): String = {
    val (name, ver, scalaVer, about) =
      (sbtName(s), sbtVersion(s), scalaVersion(s), aboutProject(s))
    """This is %s %s
			|%s
			|%s, %s plugins, and build definitions are using Scala %s
			|""".stripMargin.format(name, ver, about, name, name, scalaVer)
  }

  private[this] def selectScalaVersion(sv: Option[String], si: ScalaInstance): String =
    sv match {
      case Some(si.version) => si.version
      case _                => si.actualVersion
    }

  private[this] def quiet[T](t: => T): Option[T] = try { Some(t) } catch {
    case e: Exception => None
  }

  def settingsCommand: Command =
    showSettingLike(SettingsCommand,
                    settingsPreamble,
                    KeyRanks.MainSettingCutoff,
                    key => !isTask(key.manifest))

  def tasks: Command =
    showSettingLike(TasksCommand,
                    tasksPreamble,
                    KeyRanks.MainTaskCutoff,
                    key => isTask(key.manifest))

  def showSettingLike(command: String,
                      preamble: String,
                      cutoff: Int,
                      keep: AttributeKey[_] => Boolean): Command =
    Command(command, settingsBrief(command), settingsDetailed(command))(showSettingParser(keep)) {
      case (s: State, (verbosity: Int, selected: Option[String])) =>
        if (selected.isEmpty) System.out.println(preamble)
        val prominentOnly = verbosity <= 1
        val verboseFilter = if (prominentOnly) highPass(cutoff) else topNRanked(25 * verbosity)
        System.out.println(tasksHelp(s, keys => verboseFilter(keys filter keep), selected))
        System.out.println()
        if (prominentOnly) System.out.println(moreAvailableMessage(command, selected.isDefined))
        s
    }
  def showSettingParser(keepKeys: AttributeKey[_] => Boolean)(
      s: State): Parser[(Int, Option[String])] =
    verbosityParser ~ selectedParser(s, keepKeys).?
  def selectedParser(s: State, keepKeys: AttributeKey[_] => Boolean): Parser[String] =
    singleArgument(allTaskAndSettingKeys(s).filter(keepKeys).map(_.label).toSet)
  def verbosityParser: Parser[Int] =
    success(1) | ((Space ~ "-") ~> (
      'v'.id.+.map(_.size + 1) |
        ("V" ^^^ Int.MaxValue)
    ))
  def taskDetail(keys: Seq[AttributeKey[_]]): Seq[(String, String)] =
    sortByLabel(withDescription(keys)) flatMap taskStrings

  def allTaskAndSettingKeys(s: State): Seq[AttributeKey[_]] = {
    val extracted = Project.extract(s)
    import extracted._
    val index = structure.index
    index.keyIndex
      .keys(Some(currentRef))
      .toSeq
      .map { key =>
        try Some(index.keyMap(key))
        catch {
          case NonFatal(ex) =>
            s.log debug ex.getMessage
            None
        }
      }
      .collect { case Some(s) => s }
      .distinct
  }

  def sortByLabel(keys: Seq[AttributeKey[_]]): Seq[AttributeKey[_]] = keys.sortBy(_.label)
  def sortByRank(keys: Seq[AttributeKey[_]]): Seq[AttributeKey[_]] = keys.sortBy(_.rank)
  def withDescription(keys: Seq[AttributeKey[_]]): Seq[AttributeKey[_]] =
    keys.filter(_.description.isDefined)
  def isTask(mf: Manifest[_])(implicit taskMF: Manifest[Task[_]],
                              inputMF: Manifest[InputTask[_]]): Boolean =
    mf.runtimeClass == taskMF.runtimeClass || mf.runtimeClass == inputMF.runtimeClass
  def topNRanked(n: Int) = (keys: Seq[AttributeKey[_]]) => sortByRank(keys).take(n)
  def highPass(rankCutoff: Int) =
    (keys: Seq[AttributeKey[_]]) => sortByRank(keys).takeWhile(_.rank <= rankCutoff)

  def tasksHelp(s: State,
                filter: Seq[AttributeKey[_]] => Seq[AttributeKey[_]],
                arg: Option[String]): String = {
    val commandAndDescription = taskDetail(filter(allTaskAndSettingKeys(s)))
    arg match {
      case Some(selected) => detail(selected, commandAndDescription.toMap)
      case None           => aligned("  ", "   ", commandAndDescription) mkString ("\n", "\n", "")
    }
  }

  def taskStrings(key: AttributeKey[_]): Option[(String, String)] = key.description map { d =>
    (key.label, d)
  }

  def defaults = Command.command(DefaultsCommand) { s =>
    s.copy(definedCommands = DefaultCommands)
  }

  def initialize: Command = Command.command(InitCommand) { s =>
    /*"load-commands -base ~/.sbt/commands" :: */
    readLines(readable(sbtRCs(s))).toList ::: s
  }

  def eval: Command = Command.single(EvalCommand, Help.more(EvalCommand, evalDetailed)) {
    (s, arg) =>
      if (Project.isProjectLoaded(s)) loadedEval(s, arg) else rawEval(s, arg)
      s
  }

  private[this] def loadedEval(s: State, arg: String): Unit = {
    val extracted = Project extract s
    import extracted._
    val result =
      session.currentEval().eval(arg, srcName = "<eval>", imports = autoImports(extracted))
    s.log.info(s"ans: ${result.tpe} = ${result.getValue(currentLoader)}")
  }

  private[this] def rawEval(s: State, arg: String): Unit = {
    val app = s.configuration.provider
    val classpath = app.mainClasspath ++ app.scalaProvider.jars
    val result = Load
      .mkEval(classpath, s.baseDir, Nil)
      .eval(arg, srcName = "<eval>", imports = new EvalImports(Nil, ""))
    s.log.info(s"ans: ${result.tpe} = ${result.getValue(app.loader)}")
  }

  def sessionCommand: Command =
    Command.make(SessionCommand, sessionBrief, SessionSettings.Help)(SessionSettings.command)

  def reapply(newSession: SessionSettings, structure: BuildStructure, s: State): State = {
    s.log.info("Reapplying settings...")
    // For correct behavior, we also need to re-inject a settings logger, as we'll be re-evaluating settings
    val loggerInject = LogManager.settingsLogger(s)
    val withLogger = newSession.appendRaw(loggerInject :: Nil)
    val show = Project.showContextKey(newSession, structure)
    val newStructure = Load.reapply(withLogger.mergeSettings, structure)(show)
    Project.setProject(newSession, newStructure, s)
  }

  def set: Command = Command(SetCommand, setBrief, setDetailed)(setParser) {
    case (s, (all, arg)) =>
      val extracted = Project extract s
      import extracted._
      val dslVals = extracted.currentUnit.unit.definitions.dslDefinitions
      // TODO - This is possibly inefficient (or stupid).  We should try to only attach the
      // classloader + imports NEEDED to compile the set command, rather than
      // just ALL of them.
      val ims = (imports(extracted) ++ dslVals.imports.map(i => (i, -1)))
      val cl = dslVals.classloader(currentLoader)
      val settings = EvaluateConfigurations.evaluateSetting(
        session.currentEval(),
        "<set>",
        ims,
        arg,
        LineRange(0, 0)
      )(cl)
      val setResult =
        if (all) SettingCompletions.setAll(extracted, settings)
        else SettingCompletions.setThis(s, extracted, settings, arg)
      s.log.info(setResult.quietSummary)
      s.log.debug(setResult.verboseSummary)
      reapply(setResult.session, structure, s)
  }

  def setThis(
      s: State,
      extracted: Extracted,
      settings: Seq[Def.Setting[_]],
      arg: String
  ): SetResult =
    SettingCompletions.setThis(s, extracted, settings, arg)

  def inspect: Command = Command(InspectCommand, inspectBrief, inspectDetailed)(Inspect.parser) {
    case (s, (option, sk)) =>
      s.log.info(Inspect.output(s, option, sk))
      s
  }

  def lastGrep: Command =
    Command(LastGrepCommand, lastGrepBrief, lastGrepDetailed)(lastGrepParser) {
      case (s, (pattern, Some(sks))) =>
        val (str, _, display) = extractLast(s)
        Output.lastGrep(sks, str.streams(s), pattern, printLast(s))(display)
        keepLastLog(s)
      case (s, (pattern, None)) =>
        for (logFile <- lastLogFile(s)) yield Output.lastGrep(logFile, pattern, printLast(s))
        keepLastLog(s)
    }

  def extractLast(s: State): (BuildStructure, Select[ProjectRef], Show[Def.ScopedKey[_]]) = {
    val ext = Project.extract(s)
    (ext.structure, Select(ext.currentRef), ext.showKey)
  }

  def setParser = (s: State) => {
    val extracted = Project.extract(s)
    import extracted._
    token(Space ~> flag("every" ~ Space)) ~
      SettingCompletions.settingParser(structure.data, structure.index.keyMap, currentProject)
  }

  import Def.ScopedKey
  type KeysParser = Parser[Seq[ScopedKey[T]] forSome { type T }]

  val spacedAggregatedParser: State => KeysParser = (s: State) =>
    Act.requireSession(s, token(Space) ~> Act.aggregatedKeyParser(s))

  val aggregatedKeyValueParser: State => Parser[Option[AnyKeys]] = (s: State) =>
    spacedAggregatedParser(s).map(x => Act.keyValues(s)(x)).?

  val exportParser: State => Parser[() => State] = (s: State) =>
    Act.requireSession(s, token(Space) ~> exportParser0(s))

  private[sbt] def exportParser0(s: State): Parser[() => State] = {
    val extracted = Project extract s
    import extracted.{ showKey, structure }
    val keysParser = token(flag("--last" <~ Space)) ~ Act.aggregatedKeyParser(extracted)
    val show = Aggregation.ShowConfig(
      settingValues = true,
      taskValues = false,
      print = println(_),
      success = false
    )
    for {
      lastOnly_keys <- keysParser
      kvs = Act.keyValues(structure)(lastOnly_keys._2)
      f <- if (lastOnly_keys._1) success(() => s)
      else Aggregation.evaluatingParser(s, structure, show)(kvs)
    } yield
      () => {
        def export0(s: State): State = lastImpl(s, kvs, Some(ExportStream))
        val newS = try f()
        catch {
          case NonFatal(e) =>
            try export0(s)
            finally { throw e }
        }
        export0(newS)
      }
  }

  def lastGrepParser(s: State): Parser[(String, Option[AnyKeys])] =
    Act.requireSession(
      s,
      (token(Space) ~> token(NotSpace, "<pattern>")) ~ aggregatedKeyValueParser(s)
    )

  def last: Command = Command(LastCommand, lastBrief, lastDetailed)(aggregatedKeyValueParser) {
    case (s, Some(sks)) => lastImpl(s, sks, None)
    case (s, None) =>
      for (logFile <- lastLogFile(s)) yield Output.last(logFile, printLast(s))
      keepLastLog(s)
  }

  def export: Command =
    Command(ExportCommand, exportBrief, exportDetailed)(exportParser)((_, f) => f())

  private[this] def lastImpl(s: State, sks: AnyKeys, sid: Option[String]): State = {
    val (str, _, display) = extractLast(s)
    Output.last(sks, str.streams(s), printLast(s), sid)(display)
    keepLastLog(s)
  }

  /** Determines the log file that last* commands should operate on.  See also isLastOnly. */
  def lastLogFile(s: State): Option[File] = {
    val backing = s.globalLogging.backing
    if (isLastOnly(s)) backing.last else Some(backing.file)
  }

  /**
   * If false, shift the current log file to be the log file that 'last' will operate on.
   * If true, keep the previous log file as the one 'last' operates on because there is nothing useful in the current one.
   */
  def keepLastLog(s: State): State = if (isLastOnly(s)) s.keepLastLog else s

  /**
   * The last* commands need to determine whether to read from the current log file or the previous log file
   * and whether to keep the previous log file or not.  This is selected based on whether the previous command
   * was 'shell', which meant that the user directly entered the 'last' command.  If it wasn't directly entered,
   * the last* commands operate on any output since the last 'shell' command and do shift the log file.
   * Otherwise, the output since the previous 'shell' command is used and the log file is not shifted.
   */
  def isLastOnly(s: State): Boolean = s.history.previous.forall(_.commandLine == Shell)

  def printLast(s: State): Seq[String] => Unit = _ foreach println

  def autoImports(extracted: Extracted): EvalImports =
    new EvalImports(imports(extracted), "<auto-imports>")

  def imports(extracted: Extracted): Seq[(String, Int)] = {
    val curi = extracted.currentRef.build
    extracted.structure.units(curi).imports.map(s => (s, -1))
  }

  def listBuild(
      uri: URI,
      build: LoadedBuildUnit,
      current: Boolean,
      currentID: String,
      log: Logger
  ): Unit = {
    log.info(s"In $uri")
    def prefix(id: String) = if (currentID != id) "   " else if (current) " * " else "(*)"
    for (id <- build.defined.keys.toSeq.sorted) log.info("\t" + prefix(id) + id)
  }

  def act: Command = Command.customHelp(Act.actParser, actHelp)

  def actHelp: State => Help =
    s => CommandStrings.showHelp ++ CommandStrings.multiTaskHelp ++ keysHelp(s)

  def keysHelp(s: State): Help =
    if (Project.isProjectLoaded(s))
      Help.detailOnly(taskDetail(allTaskAndSettingKeys(s)))
    else
      Help.empty

  def plugins: Command = Command.command(PluginsCommand, pluginsBrief, pluginsDetailed) { s =>
    val helpString = PluginsDebug.helpAll(s)
    System.out.println(helpString)
    s
  }

  val pluginParser: State => Parser[AutoPlugin] = s => {
    val autoPlugins: Map[String, AutoPlugin] = PluginsDebug.autoPluginMap(s)
    token(Space) ~> Act.knownPluginParser(autoPlugins, "plugin")
  }

  def plugin: Command = Command(PluginCommand)(pluginParser) { (s, plugin) =>
    val helpString = PluginsDebug.help(plugin, s)
    System.out.println(helpString)
    s
  }

  def projects: Command =
    Command(ProjectsCommand, (ProjectsCommand, projectsBrief), projectsDetailed)(s =>
      projectsParser(s).?) {
      case (s, Some(modifyBuilds)) => transformExtraBuilds(s, modifyBuilds)
      case (s, None)               => showProjects(s); s
    }

  def showProjects(s: State): Unit = {
    val extracted = Project extract s
    import extracted._
    import currentRef.{ build => curi, project => cid }
    listBuild(curi, structure.units(curi), true, cid, s.log)
    for ((uri, build) <- structure.units if curi != uri) listBuild(uri, build, false, cid, s.log)
  }

  def transformExtraBuilds(s: State, f: List[URI] => List[URI]): State = {
    val original = Project.extraBuilds(s)
    val extraUpdated = Project.updateExtraBuilds(s, f)
    try doLoadProject(extraUpdated, LoadAction.Current)
    catch {
      case e: Exception =>
        s.log.error("Project loading failed: reverting to previous state.")
        Project.setExtraBuilds(s, original)
    }
  }

  def projectsParser(s: State): Parser[List[URI] => List[URI]] = {
    val addBase = token(Space ~> "add") ~> token(Space ~> basicUri, "<build URI>").+
    val removeBase = token(Space ~> "remove") ~> token(Space ~> Uri(Project.extraBuilds(s).toSet)).+
    addBase.map(toAdd => (xs: List[URI]) => (toAdd.toList ::: xs).distinct) |
      removeBase.map(toRemove => (xs: List[URI]) => xs.filterNot(toRemove.toSet))
  }

  def project: Command =
    Command.make(ProjectCommand, projectBrief, projectDetailed)(ProjectNavigation.command)

  def loadFailed: Command = Command(LoadFailed)(loadProjectParser)(doLoadFailed)

  @tailrec
  private[this] def doLoadFailed(s: State, loadArg: String): State = {
    val result = (SimpleReader.readLine(
      "Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? ") getOrElse Quit)
      .toLowerCase(Locale.ENGLISH)
    def matches(s: String) = !result.isEmpty && (s startsWith result)
    def retry = loadProjectCommand(LoadProject, loadArg) :: s.clearGlobalLog
    def ignoreMsg =
      if (Project.isProjectLoaded(s)) "using previously loaded project" else "no project loaded"

    result match {
      case ""                     => retry
      case _ if matches("retry")  => retry
      case _ if matches(Quit)     => s.exit(ok = false)
      case _ if matches("ignore") => s.log.warn(s"Ignoring load failure: $ignoreMsg."); s
      case _ if matches("last")   => LastCommand :: loadProjectCommand(LoadFailed, loadArg) :: s
      case _                      => println("Invalid response."); doLoadFailed(s, loadArg)
    }
  }

  def loadProjectCommands(arg: String): List[String] =
    StashOnFailure ::
      (OnFailure + " " + loadProjectCommand(LoadFailed, arg)) ::
      loadProjectCommand(LoadProjectImpl, arg) ::
      PopOnFailure ::
      State.FailureWall ::
      Nil

  def loadProject: Command =
    Command(LoadProject, LoadProjectBrief, LoadProjectDetailed)(loadProjectParser)((s, arg) =>
      loadProjectCommands(arg) ::: s)

  private[this] def loadProjectParser: State => Parser[String] =
    _ => matched(Project.loadActionParser)

  private[this] def loadProjectCommand(command: String, arg: String): String =
    s"$command $arg".trim

  def loadProjectImpl: Command =
    Command(LoadProjectImpl)(_ => Project.loadActionParser)(doLoadProject)

  def doLoadProject(s0: State, action: LoadAction.Value): State = {
    val (s1, base) = Project.loadAction(SessionVar.clear(s0), action)
    IO.createDirectory(base)
    val s = if (s1 has Keys.stateCompilerCache) s1 else registerCompilerCache(s1)

    val (eval, structure) =
      try Load.defaultLoad(s, base, s.log, Project.inPluginProject(s), Project.extraBuilds(s))
      catch {
        case ex: compiler.EvalException =>
          s0.log.debug(ex.getMessage)
          ex.getStackTrace map (ste => s"\tat $ste") foreach (s0.log.debug(_))
          ex.setStackTrace(Array.empty)
          throw ex
      }

    val session = Load.initialSession(structure, eval, s0)
    SessionSettings.checkSession(session, s)
    Project.setProject(session, structure, s)
  }

  def registerCompilerCache(s: State): State = {
    val maxCompilers = System.getProperty("sbt.resident.limit")
    val cache =
      if (maxCompilers == null)
        CompilerCache.fresh
      else {
        val num = try maxCompilers.toInt
        catch {
          case e: NumberFormatException =>
            throw new RuntimeException("Resident compiler limit must be an integer.", e)
        }
        if (num <= 0) CompilerCache.fresh else CompilerCache.createCacheFor(num)
      }
    s.put(Keys.stateCompilerCache, cache)
  }

  def shell: Command = Command.command(Shell, Help.more(Shell, ShellDetailed)) { s0 =>
    import sbt.internal.{ ConsolePromptEvent, ConsoleUnpromptEvent }
    val exchange = StandardMain.exchange
    val s1 = exchange run s0
    exchange publishEventMessage ConsolePromptEvent(s0)
    val exec: Exec = exchange.blockUntilNextExec
    val newState = s1
      .copy(onFailure = Some(Exec(Shell, None)),
            remainingCommands = exec +: Exec(Shell, None) +: s1.remainingCommands)
      .setInteractive(true)
    exchange publishEventMessage ConsoleUnpromptEvent(exec.source)
    if (exec.commandLine.trim.isEmpty) newState
    else newState.clearGlobalLog
  }

  private val sbtVersionRegex = """sbt\.version\s*=.*""".r
  private def isSbtVersionLine(s: String) = sbtVersionRegex.pattern matcher s matches ()

  private def isSbtProject(baseDir: File, projectDir: File) =
    projectDir.exists() || (baseDir * "*.sbt").get.nonEmpty

  private def writeSbtVersionUnconditionally(state: State) = {
    val baseDir = state.baseDir
    val sbtVersion = BuiltinCommands.sbtVersion(state)
    val projectDir = baseDir / "project"
    val buildProps = projectDir / "build.properties"

    val buildPropsLines = if (buildProps.canRead) IO.readLines(buildProps) else Nil

    val sbtVersionAbsent = buildPropsLines forall (!isSbtVersionLine(_))

    if (sbtVersionAbsent) {
      val warnMsg = s"No sbt.version set in project/build.properties, base directory: $baseDir"
      try {
        if (isSbtProject(baseDir, projectDir)) {
          val line = s"sbt.version=$sbtVersion"
          IO.writeLines(buildProps, line :: buildPropsLines)
          state.log info s"Updated file $buildProps: set sbt.version to $sbtVersion"
        } else
          state.log warn warnMsg
      } catch {
        case _: IOException => state.log warn warnMsg
      }
    }
  }

  private def intendsToInvokeNew(state: State) =
    state.remainingCommands exists (_.commandLine == TemplateCommand)

  private def writeSbtVersion(state: State) =
    if (!java.lang.Boolean.getBoolean("sbt.skip.version.write") && !intendsToInvokeNew(state))
      writeSbtVersionUnconditionally(state)

  private def WriteSbtVersion = "write-sbt-version"

  private def writeSbtVersion: Command =
    Command.command(WriteSbtVersion) { state =>
      writeSbtVersion(state); state
    }

  private def intendsToInvokeCompile(state: State) =
    state.remainingCommands exists (_.commandLine == Keys.compile.key.label)

  private def notifyUsersAboutShell(state: State): Unit = {
    val suppress = Project extract state getOpt Keys.suppressSbtShellNotification getOrElse false
    if (!suppress && intendsToInvokeCompile(state))
      state.log info "Executing in batch mode. For better performance use sbt's shell"
  }

  private def NotifyUsersAboutShell = "notify-users-about-shell"

  private def notifyUsersAboutShell: Command =
    Command.command(NotifyUsersAboutShell) { state =>
      notifyUsersAboutShell(state); state
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>CaduneTree: C:/Development/projects/CaduneTree/Source/CaduneTree/CTSerializer.h File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Namespaces

Classes

Files

C:/Development/projects/CaduneTree/Source/CaduneTree/CTSerializer.h File Reference
#include "CTPrerequisites.h"

#include <string>

#include <fstream>

Go to the source code of this file.

Namespaces

namespace  	CaduneTree

Classes

class  	CaduneTree::Serializer

 	Class used for import and export of parameters.  More...

Detailed Description

Definition in file CTSerializer.h.

<address style="text-align: right;">Generated on Sat Sep 8 18:06:03 2007 for CaduneTree by

 1.5.3 </address>


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

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

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

# Package apache-airflow-backport-providers-oracle

Release: 2020.10.29

**Table of contents**

- [Backport package](#backport-package)
- [Installation](#installation)
- [PIP requirements](#pip-requirements)
- [Provider class summary](#provider-classes-summary)
    - [Operators](#operators)
        - [Moved operators](#moved-operators)
    - [Transfer operators](#transfer-operators)
        - [Moved transfer operators](#moved-transfer-operators)
    - [Hooks](#hooks)
        - [Moved hooks](#moved-hooks)
- [Releases](#releases)
    - [Release 2020.10.29](#release-20201029)
    - [Release 2020.10.5](#release-2020105)
    - [Release 2020.6.24](#release-2020624)

## Backport package

This is a backport providers package for `oracle` provider. All classes for this provider package
are in `airflow.providers.oracle` python package.

**Only Python 3.6+ is supported for this backport package.**

While Airflow 1.10.* continues to support Python 2.7+ - you need to upgrade python to 3.6+ if you
want to use this backport package.

## Installation

You can install this package on top of an existing airflow 1.10.* installation via
`pip install apache-airflow-backport-providers-oracle`

## PIP requirements

| PIP package   | Version required   |
|:--------------|:-------------------|
| cx_Oracle     | >=5.1.2            |

# Provider classes summary

In Airflow 2.0, all operators, transfers, hooks, sensors, secrets for the `oracle` provider
are in the `airflow.providers.oracle` package. You can read more about the naming conventions used
in [Naming conventions for provider packages](https://github.com/apache/airflow/blob/master/CONTRIBUTING.rst#naming-conventions-for-provider-packages)

## Operators

### Moved operators

| Airflow 2.0 operators: `airflow.providers.oracle` package                                                                     | Airflow 1.10.* previous location (usually `airflow.contrib`)                                                                         |
|:------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------|
| [operators.oracle.OracleOperator](https://github.com/apache/airflow/blob/master/airflow/providers/oracle/operators/oracle.py) | [operators.oracle_operator.OracleOperator](https://github.com/apache/airflow/blob/v1-10-stable/airflow/operators/oracle_operator.py) |

## Transfer operators

### Moved transfer operators

| Airflow 2.0 transfers: `airflow.providers.oracle` package                                                                                | Airflow 1.10.* previous location (usually `airflow.contrib`)                                                                                |
|:----------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [transfers.oracle_to_oracle.OracleToOracleOperator](https://github.com/apache/airflow/blob/master/airflow/providers/oracle/transfers/oracle_to_oracle.py) | [contrib.operators.oracle_to_oracle_transfer.OracleToOracleTransfer](https://github.com/apache/airflow/blob/v1-10-stable/airflow/contrib/operators/oracle_to_oracle_transfer.py) |

## Hooks

### Moved hooks

| Airflow 2.0 hooks: `airflow.providers.oracle` package                                                             | Airflow 1.10.* previous location (usually `airflow.contrib`)                                                     |
|:------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------|
| [hooks.oracle.OracleHook](https://github.com/apache/airflow/blob/master/airflow/providers/oracle/hooks/oracle.py) | [hooks.oracle_hook.OracleHook](https://github.com/apache/airflow/blob/v1-10-stable/airflow/hooks/oracle_hook.py) |

## Releases

### Release 2020.10.29

| Commit                                                                                | Committed   | Subject                                                          |
|:-----------------------------------------------------------------------------------------------|:------------|:-----------------------------------------------------------------|
| [b680bbc0b](https://github.com/apache/airflow/commit/872b1566a11cb73297e657ff325161721b296574) | 2020-10-24  | Generated backport providers readmes/setup for 2020.10.29        |
| [349b0811c](https://github.com/apache/airflow/commit/349b0811c3022605426ba57d30936240a7c2848a) | 2020-10-20  | Add D200 pydocstyle check (#11688)                               |
| [16e712971](https://github.com/apache/airflow/commit/16e7129719f1c0940aef2a93bed81368e997a746) | 2020-10-13  | Added support for provider packages for Airflow 2.0 (#11487)     |
| [d305876be](https://github.com/apache/airflow/commit/d305876bee328287ff391a29cc1cd632468cc731) | 2020-10-12  | Remove redundant None provided as default to dict.get() (#11448) |
| [0a0e1af80](https://github.com/apache/airflow/commit/0a0e1af80038ef89974c3c8444461fe867945daa) | 2020-10-03  | Fix Broken Markdown links in Providers README TOC (#11249)       |

### Release 2020.10.5

| Commit                                                                                | Committed   | Subject                                                              |
|:-----------------------------------------------------------------------------------------------|:------------|:---------------------------------------------------------------------|
| [ca4238eb4](https://github.com/apache/airflow/commit/ca4238eb4d9a2aef70eb641343f59ee706d27d13) | 2020-10-02  | Fixed month in backport packages to October (#11242)                 |
| [5220e4c38](https://github.com/apache/airflow/commit/5220e4c3848a2d2c81c266ef939709df9ce581c5) | 2020-10-02  | Prepare Backport release 2020.09.07 (#11238)                         |
| [5093245d6](https://github.com/apache/airflow/commit/5093245d6f77a370fbd2f9e3df35ac6acf46a1c4) | 2020-09-30  | Strict type coverage for Oracle and Yandex provider  (#11198)        |
| [fdd9b6f65](https://github.com/apache/airflow/commit/fdd9b6f65b608c516b8a062b058972d9a45ec9e3) | 2020-08-25  | Enable Black on Providers Packages (#10543)                          |
| [3696c34c2](https://github.com/apache/airflow/commit/3696c34c28c6bc7b442deab999d9ecba24ed0e34) | 2020-08-24  | Fix typo in the word "release" (#10528)                              |
| [ee7ca128a](https://github.com/apache/airflow/commit/ee7ca128a17937313566f2badb6cc569c614db94) | 2020-08-22  | Fix broken Markdown refernces in Providers README (#10483)           |
| [7c206a82a](https://github.com/apache/airflow/commit/7c206a82a6f074abcc4898a005ecd2c84a920054) | 2020-08-22  | Replace assigment with Augmented assignment (#10468)                 |
| [cdec30125](https://github.com/apache/airflow/commit/cdec3012542b45d23a05f62d69110944ba542e2a) | 2020-08-07  | Add correct signature to all operators and sensors (#10205)          |
| [24c8e4c2d](https://github.com/apache/airflow/commit/24c8e4c2d6e359ecc2c7d6275dccc68de4a82832) | 2020-08-06  | Changes to all the constructors to remove the args argument (#10163) |
| [aeea71274](https://github.com/apache/airflow/commit/aeea71274d4527ff2351102e94aa38bda6099e7f) | 2020-08-02  | Remove `args` parameter from provider operator constructors (#10097) |
| [d0e7db402](https://github.com/apache/airflow/commit/d0e7db4024806af35e3c9a2cae460fdeedd4d2ec) | 2020-06-19  | Fixed release number for fresh release (#9408)                       |

### Release 2020.6.24

| Commit                                                                                | Committed   | Subject                                                                                |
|:-----------------------------------------------------------------------------------------------|:------------|:--------------------------------------------------------------------------------------------|
| [12af6a080](https://github.com/apache/airflow/commit/12af6a08009b8776e00d8a0aab92363eb8c4e8b1) | 2020-06-19  | Final cleanup for 2020.6.23rc1 release preparation (#9404)                                  |
| [c7e5bce57](https://github.com/apache/airflow/commit/c7e5bce57fe7f51cefce4f8a41ce408ac5675d13) | 2020-06-19  | Prepare backport release candidate for 2020.6.23rc1 (#9370)                                 |
| [f6bd817a3](https://github.com/apache/airflow/commit/f6bd817a3aac0a16430fc2e3d59c1f17a69a15ac) | 2020-06-16  | Introduce 'transfers' packages (#9320)                                                      |
| [0b0e4f7a4](https://github.com/apache/airflow/commit/0b0e4f7a4cceff3efe15161fb40b984782760a34) | 2020-05-26  | Preparing for RC3 release of backports (#9026)                                               |
| [00642a46d](https://github.com/apache/airflow/commit/00642a46d019870c4decb3d0e47c01d6a25cb88c) | 2020-05-26  | Fixed name of 20 remaining wrongly named operators. (#8994)                                 |
| [1d36b0303](https://github.com/apache/airflow/commit/1d36b0303b8632fce6de78ca4e782ae26ee06fea) | 2020-05-23  | Fix references in docs (#8984)                                                              |
| [375d1ca22](https://github.com/apache/airflow/commit/375d1ca229464617780623c61c6e8a1bf570c87f) | 2020-05-19  | Release candidate 2 for backport packages 2020.05.20 (#8898)                                |
| [12c5e5d8a](https://github.com/apache/airflow/commit/12c5e5d8ae25fa633efe63ccf4db389e2b796d79) | 2020-05-17  | Prepare release candidate for backport packages (#8891)                                     |
| [f3521fb0e](https://github.com/apache/airflow/commit/f3521fb0e36733d8bd356123e56a453fd37a6dca) | 2020-05-16  | Regenerate readme files for backport package release (#8886)                                |
| [92585ca4c](https://github.com/apache/airflow/commit/92585ca4cb375ac879f4ab331b3a063106eb7b92) | 2020-05-15  | Added automated release notes generation for backport operators (#8807)                     |
| [4bde99f13](https://github.com/apache/airflow/commit/4bde99f1323d72f6c84c1548079d5e98fc0a2a9a) | 2020-03-23  | Make airflow/providers pylint compatible (#7802)                                            |
| [97a429f9d](https://github.com/apache/airflow/commit/97a429f9d0cf740c5698060ad55f11e93cb57b55) | 2020-02-02  | [AIRFLOW-6714] Remove magic comments about UTF-8 (#7338)                                    |
| [057f3ae3a](https://github.com/apache/airflow/commit/057f3ae3a4afedf6d462ecf58b01dd6304d3e135) | 2020-01-29  | [AIRFLOW-6670][depends on AIRFLOW-6669] Move contrib operators to providers package (#7286) |
| [059eda05f](https://github.com/apache/airflow/commit/059eda05f82fefce4410f44f761f945a27d83daf) | 2020-01-21  | [AIRFLOW-6610] Move software classes to providers package (#7231)                           |


text:
var m = require('mithril');
var game = require('game').game;

function prefixInteger(num, length) {
  return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

function bold(x) {
  return '' + x + '';
}

function formatClockTime(ctrl, time) {
  var date = new Date(time);
  var minutes = prefixInteger(date.getUTCMinutes(), 2);
  var seconds = prefixInteger(date.getSeconds(), 2);
  if (ctrl.data.showTenths && time < 10000) {
    tenths = Math.floor(date.getMilliseconds() / 100);
    return bold(minutes) + ':' + bold(seconds) + '.' + bold(tenths) + '';
  } else if (time >= 3600000) {
    var hours = prefixInteger(date.getUTCHours(), 2);
    return bold(hours) + ':' + bold(minutes) + ':' + bold(seconds);
  } else {
    return bold(minutes) + ':' + bold(seconds);
  }
}

function showBar(ctrl, time) {
  return ctrl.data.showBar ? m('div.bar',
    m('span', {
      style: {
        width: Math.max(0, Math.min(100, (time / ctrl.data.barTime) * 100)) + '%'
      }
    })
  ) : null;
}

module.exports = {
  formatClockTime: formatClockTime,
  showBar: showBar
};


text:
from nbgrader.preprocessors import IncludeHeaderFooter
from nose.tools import assert_equal

from .base import TestBase

class TestIncludeHeaderFooter(TestBase):

    def setup(self):
        super(TestIncludeHeaderFooter, self).setup()
        self.preprocessor = IncludeHeaderFooter()

    def test_concatenate_nothing(self):
        """Are the cells the same if there is no header/footer?"""
        orig_nb = self.nbs["test.ipynb"]
        nb = self.preprocessor.preprocess(orig_nb, {})[0]
        assert_equal(nb, orig_nb)

    def test_concatenate_header(self):
        """Is the header prepended correctly?"""
        self.preprocessor.header = self.files["header.ipynb"]
        cells = self.nbs["header.ipynb"].cells[:]
        orig_nb = self.nbs["test.ipynb"]
        orig_cells = orig_nb.cells[:]
        nb = self.preprocessor.preprocess(orig_nb, {})[0]
        assert_equal(nb.cells, (cells + orig_cells))

    def test_concatenate_footer(self):
        """Is the footer appended correctly?"""
        self.preprocessor.footer = self.files["header.ipynb"]
        cells = self.nbs["header.ipynb"].cells[:]
        orig_nb = self.nbs["test.ipynb"]
        orig_cells = orig_nb.cells[:]
        nb = self.preprocessor.preprocess(orig_nb, {})[0]
        assert_equal(nb.cells, (orig_cells + cells))

    def test_concatenate_header_and_footer(self):
        """Are the header and footer appended correctly?"""
        self.preprocessor.header = self.files["header.ipynb"]
        self.preprocessor.footer = self.files["header.ipynb"]
        header_cells = self.nbs["header.ipynb"].cells[:]
        footer_cells = self.nbs["header.ipynb"].cells[:]
        orig_nb = self.nbs["test.ipynb"]
        orig_cells = orig_nb.cells[:]
        nb = self.preprocessor.preprocess(orig_nb, {})[0]
        assert_equal(nb.cells, (header_cells + orig_cells + footer_cells))


text:
module.exports = function() {
  console.log("hello world");
}

module.exports.hello2 = function() {
  console.log("hello world (2)");
}

module.exports.hello3 = function() {
  console.log("hello world (3)");
}


text:
#ifdef OSKAR_HAVE_CUDA
#include <cuda_runtime_api.h>
#endif

#include "mem/oskar_mem.h"
#include "mem/private_mem.h"
#include "utility/oskar_device.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

void oskar_mem_realloc(oskar_Mem* mem, size_t num_elements, int* status)
{
    if (*status || !mem) return;

    /* Check if the structure owns the memory it points to. */
    if (mem->owner == 0)
    {
        *status = OSKAR_ERR_MEMORY_NOT_ALLOCATED;
        return;
    }

    /* Get size of new and old memory blocks. */
    const size_t element_size = oskar_mem_element_size(mem->type);
    if (element_size == 0)
    {
        *status = OSKAR_ERR_BAD_DATA_TYPE;
        return;
    }
    const size_t new_size = num_elements * element_size;
    const size_t old_size = mem->num_elements * element_size;

    /* Do nothing if new size and old size are the same. */
    if (new_size == old_size) return;

    /* Check memory location. */
    if (mem->location == OSKAR_CPU)
    {
        /* Reallocate the memory. */
        void* mem_new = realloc(mem->data, new_size);
        if (!mem_new && (new_size > 0))
        {
            *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE;
            return;
        }

        /* Initialise the new memory if it's larger than the old block. */
        if (new_size > old_size)
        {
            memset((char*)mem_new + old_size, 0, new_size - old_size);
        }

        /* Set the new meta-data. */
        mem->data = (new_size > 0) ? mem_new : 0;
        mem->num_elements = num_elements;
    }
    else if (mem->location == OSKAR_GPU)
    {
#ifdef OSKAR_HAVE_CUDA
        /* Allocate and initialise a new block of memory. */
        void* mem_new = NULL;
        if (new_size > 0)
        {
            const int cuda_error = (int)cudaMalloc(&mem_new, new_size);
            if (cuda_error)
            {
                *status = cuda_error;
                return;
            }
            if (!mem_new)
            {
                *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE;
                return;
            }
        }

        /* Copy contents of old block to new block. */
        const size_t copy_size = (old_size > new_size) ? new_size : old_size;
        if (copy_size > 0)
        {
            const int cuda_error = (int)cudaMemcpy(mem_new,
                    mem->data, copy_size, cudaMemcpyDeviceToDevice);
            if (cuda_error)
            {
                *status = cuda_error;
            }
        }

        /* Free the old block. */
        const int cuda_error = (int)cudaFree(mem->data);
        if (cuda_error && !*status) *status = cuda_error;

        /* Set the new meta-data. */
        mem->data = mem_new;
        mem->num_elements = num_elements;
#else
        *status = OSKAR_ERR_CUDA_NOT_AVAILABLE;
#endif
    }
    else if (mem->location & OSKAR_CL)
    {
#ifdef OSKAR_HAVE_OPENCL
        /* Allocate and initialise a new block of memory. */
        cl_event event = 0;
        cl_int error = 0;
        cl_mem mem_new = 0;
        mem_new = clCreateBuffer(oskar_device_context_cl(),
                CL_MEM_READ_WRITE, new_size, NULL, &error);
        if (error != CL_SUCCESS)
        {
            *status = OSKAR_ERR_MEMORY_ALLOC_FAILURE;
            return;
        }

        /* Copy contents of old block to new block. */
        const size_t copy_size = (old_size > new_size) ? new_size : old_size;
        if (copy_size > 0)
        {
            error = clEnqueueCopyBuffer(oskar_device_queue_cl(), mem->buffer,
                    mem_new, 0, 0, copy_size, 0, NULL, &event);
            if (error != CL_SUCCESS)
            {
                *status = OSKAR_ERR_MEMORY_COPY_FAILURE;
            }
        }

        /* Free the old buffer. */
        if (mem->buffer)
        {
            clReleaseMemObject(mem->buffer);
        }

        /* Set the new meta-data. */
        mem->buffer = mem_new;
        mem->data = (void*) (mem->buffer);
        mem->num_elements = num_elements;
#else
        *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE;
#endif
    }
    else
    {
        *status = OSKAR_ERR_BAD_LOCATION;
    }
}

#ifdef __cplusplus
}
#endif


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.activiti.bpmn.converter;

import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

import org.activiti.bpmn.converter.util.BpmnXMLUtil;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.ThrowEvent;

/**
 * @author Tijs Rademakers
 */
public class ThrowEventXMLConverter extends BaseBpmnXMLConverter {

  public static String getXMLType() {
    return ELEMENT_EVENT_THROW;
  }

  public static Class<? extends BaseElement> getBpmnElementType() {
    return ThrowEvent.class;
  }

  @Override
  protected String getXMLElementName() {
    return ELEMENT_EVENT_THROW;
  }

  @Override
  protected BaseElement convertXMLToElement(XMLStreamReader xtr) throws Exception {
    ThrowEvent throwEvent = new ThrowEvent();
    BpmnXMLUtil.addXMLLocation(throwEvent, xtr);
    parseChildElements(getXMLElementName(), throwEvent, xtr);
    return throwEvent;
  }

  @Override
  protected void writeAdditionalAttributes(BaseElement element, XMLStreamWriter xtw) throws Exception {
  }

  @Override
  protected void writeExtensionChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
  }

  @Override
  protected void writeAdditionalChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
    ThrowEvent throwEvent = (ThrowEvent) element;
    writeEventDefinitions(throwEvent.getEventDefinitions(), xtw);
  }
}


text:
'use strict'

const fs = require('fs')
    , multer = require('multer')
    , passport = require('passport')

module.exports = (app) => {
    const user = app.controllers.controllerUsers  // Llama al controlador de los usuarios
        , auth = app.middlewares.auth  // Llamada del middleware para la validacion de las rutas
        , find = app.middlewares.find  // Llamada del middleware para la busqueda
        , validate = app.middlewares.validations  // Llama al middleware para las validaciones

    let storage = multer.diskStorage({
            destination: function (req, file, cb) {
                cb(null, 'public/images/imagesUsers/')  // URL donde se almacenan las imagenes
            },
            filename: function (req, file, cb) {
                cb(null, 'imageUser-' + Date.now() + '.' + file.originalname.split('.').pop())  // Renombra el archivo, despues lo mueve
            },
            onError: function (error, next) {
                console.log(`\n[routesUser.storage]: Ups hay un error => ${error}`)
                next(error)
            }
        })
    , upload = multer({ storage: storage })  // Usa el storage especificado con anterioridad

    app.all('/user/:id*', find.findUser)  // Middleware que busca un usuario y lo almacena en locals

    app.get('/users/new', [auth.isLogged, user.getViewUserNew])  // Formulario para un nuevo usuario via admin
    app.get('/user/:id/edit', [auth.isLogged, user.getViewUserEdit])  // Formulario para editar un usuario
    app.get('/user/contact', [auth.isLogged, user.getViewUsercontact])  // Formulario para completar Informacion de contacto

    app.get('/users/profile', (req, res) => {  // URL paraa ver el perfil del usuario
        res.render('./viewsUserPlus/users/view', {
            storedUser : req.user,
            user       : req.user,
            err        : req.flash('err'),  // Si hay mensajes de error, los almacena
            warning    : req.flash('warning'),  // Si hay mensajes de Precaucion
            info       : req.flash('info'),  // Si hay mensajes informativos, los almacena
            success    : req.flash('success')  // Si hay mensajes afirmativos, los almacena
        })  // Usa el usuario que esta logeado actualmente
    })

    app.get('/accounts/logout', (req, res) => {  // URL para eliminar y cerrar la sesion
        req.logout()  // Sale de la sesion actual
        req.session.destroy()  // Destruye la sesion que se genera todo En produccion, ya no sera necesario si se implementa bien deserializeUser
        res.redirect('/')  // Redirige al inicio
    })

    app.post('/user/:id/contact', [auth.isLogged, user.setContact])  // URL para completar informacion de contacto

// =====================================================================================================================
// AUTENTICACION LOCAL Y REDES SOCIALES POR 1a Vez =====================================================================
// =====================================================================================================================
    app.get('/accounts/signin', (req, res) => {  // Formualrio para iniciar sesion
        res.render('signin', {
            err     : req.flash('err'),  // Si hay mensajes de error, los almacena
            warning : req.flash('warning'),  // Si hay mensajes de Precaucion
            info    : req.flash('info'),  // Si hay mensajes informativos, los almacena
            success : req.flash('success')  // Si hay mensajes afirmativos, los almacena
        })
    })

    app.post('/accounts/signin', passport.authenticate('local-signin', {  // URL de callback
        successRedirect : '/',  // Redirecciona si el proceso es exitoso
        failureRedirect : '/accounts/signin',  // Redirecciona si el proceso falla
        failureFlash : true  // Permite enviar mensajes Flash
    }))

// Local ***************************************************************************************************************
    app.get('/accounts/signup', (req, res) => {  // Formulario para registro de usurio
        res.render('signup', {
            err     : req.flash('err'),  // Si hay mensajes de error, los almacena
            warning : req.flash('warning'),  // Si hay mensajes de Precaucion
            info    : req.flash('info'),  // Si hay mensajes informativos, los almacena
            success : req.flash('success')  // Si hay mensajes afirmativos, los almacena
        })
    })

    app.post('/accounts/signup', passport.authenticate('local-signup', {  // URL de callback
        successRedirect : '/',  // Redirecciona si el proceso es exitoso
        failureRedirect : '/accounts/signup',  // Redirecciona si el proceso falla
        failureFlash    : true  // Permite enviar mensajes Flash
    }))

// Facebook ************************************************************************************************************
    app.get('/auth/facebook', passport.authenticate('facebook', {
        scope : 'email'
    }))
    app.get('/auth/facebook/callback', passport.authenticate('facebook', {  // URL de callback
        successRedirect : '/',  // Redirecciona si el proceso es exitoso
        failureRedirect : '/accounts/signin',  // Redirecciona si el proceso falla
        failureFlash    : true  // Permite enviar mensajes Flash
    }))

// Twitter *************************************************************************************************************
    app.get('/auth/twitter', passport.authenticate('twitter', {
        scope : 'email'
    }))
    app.get('/auth/twitter/callback', passport.authenticate('twitter', {  // URL de callback
        successRedirect : '/',  // Redirecciona si el proceso es exitoso
        failureRedirect : '/accounts/signin',  // Redirecciona si el proceso falla
        failureFlash    : true  // Permite enviar mensajes Flash
    }))

// Linkedin ************************************************************************************************************
    app.get('/auth/linkedin', passport.authenticate('linkedin'))
    app.get('/auth/linkedin/callback', passport.authenticate('linkedin', {  // URL de callback
        successRedirect : '/',  // Redirecciona si el proceso es exitoso
        failureRedirect : '/accounts/signin',  // Redirecciona si el proceso falla
        failureFlash    : true  // Permite enviar mensajes Flash
    }))
// =====================================================================================================================
// AUTORIZACION(ENLAZAR REDES SOCIALES) ================================================================================
// =====================================================================================================================

// Local ***************************************************************************************************************
// todo Se puede reutilizar el formulario de registro
//     app.get('/connect/local', (req, res) => {
//         res.render('connect-local.ejs', { message: req.flash('loginMessage') })
//     })
//
//     app.post('/connect/local', passport.authenticate('local-signup', {
//         successRedirect : '/',  // Redirecciona si el proceso es exitoso
//         failureRedirect : '/connect/local',  // Redirecciona si el proceso falla
//         failureFlash : true
//     }))

// Facebook ************************************************************************************************************
    app.get('/connect/facebook', passport.authorize('facebook', {
        scope : 'email'
    }))

    app.get('/connect/facebook/callback',
        passport.authorize('facebook', {  // Solicita la autorizacion
            successRedirect : '/users/profile',  // Redirecciona si el proceso es exitoso
            failureRedirect : '/'  // Redirecciona si el proceso falla
        }))

// Twitter *************************************************************************************************************
    app.get('/connect/twitter', passport.authorize('twitter', {
        scope : 'email'
    }))

    app.get('/connect/twitter/callback',
        passport.authorize('twitter', {  // Solicita la autorizacion
            successRedirect : '/users/profile',  // Redirecciona si el proceso es exitoso
            failureRedirect : '/'  // Redirecciona si el proceso falla
        }))

// Linkedin ************************************************************************************************************
    app.get('/connect/linkedin', passport.authorize('linkedin', {
        scope : 'email'
    }))

    app.get('/connect/linkedin/callback',
        passport.authorize('linkedin', {  // Solicita la autorizacion
            successRedirect : '/users/profile',  // Redirecciona si el proceso es exitoso
            failureRedirect : '/'  // Redirecciona si el proceso falla
        }))

// #####################################################################################################################
// OPERACIONES CRUD USUARIOS ###########################################################################################
// #####################################################################################################################
    app.route('/user/:id')
        .get([auth.isLogged, user.getUser])  // Obtener un usuario
        .put([auth.isLogged, upload.single('photo'), validate.ifUserExists, user.updateUser])  // Actualizar un usuario
        .delete([auth.isLogged, user.deleteUser])  // Eliminar un usuario

    app.route('/users')
        .get([auth.isLogged, user.getUsers])  // Obtener todos los usuarios
        .post([upload.single('photo'), validate.ifUserExists, user.setUser])  // Agregar un nuevo usuario
}


text:
import { agent } from '../../../src/dependencies/agent';
import { decorateMember } from '../../../src/dependencies/agent';
import { TypeInvocation } from '../../../src/dependencies/agent';
import { Arguments } from '../../../src/dependencies/agent';

describe('4.6. getter interceptor', () => {
  describe('# should able to', () => {
    it('intercept class getter', () => {
      @agent()
      class Class414 {
        a!: number;

        @decorateMember({
          interceptor: {
            intercept(target: TypeInvocation, params: Arguments, receiver: any): any {
              return Math.floor(target.invoke(params, receiver));
            },
          },
        })
        get getter() {
          return this.a;
        }
      }
      const instance = new Class414();
      expect(instance).toBeInstanceOf(Class414);
      instance.a = 4.5;
      expect(instance.a).toBe(4.5);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
      expect(instance.getter).toBe(4);
    });
  });
});


text:
<?php

declare(strict_types=1);

namespace Psalm\Node;

use PhpParser\Node\Const_;

final class VirtualConst extends Const_ implements VirtualNode
{

}


text:
namespace inet {

namespace physicallayer {

RadioFrame::RadioFrame(const ITransmission *transmission) :
    transmission(transmission)
{
}

RadioFrame::RadioFrame(const RadioFrame& other) :
    cPacket(other),
    transmission(other.transmission)
{
}

std::ostream& RadioFrame::printToStream(std::ostream& stream, int level) const
{
    return stream << (cPacket *)this;
}

const ITransmission *RadioFrame::getTransmission() const
{
    return transmission;
}

const IArrival *RadioFrame::getArrival() const
{
    if (arrival == nullptr) {
        auto receiver = check_and_cast<const IRadio *>(getArrivalModule());
        arrival = transmission->getTransmitter()->getMedium()->getArrival(receiver, transmission);
    }
    return arrival;
}

const IListening *RadioFrame::getListening() const
{
    if (listening == nullptr) {
        auto receiver = check_and_cast<const IRadio *>(getArrivalModule());
        listening = transmission->getTransmitter()->getMedium()->getListening(receiver, transmission);
    }
    return listening;
}

const IReception *RadioFrame::getReception() const
{
    if (reception == nullptr) {
        auto receiver = check_and_cast<const IRadio *>(getArrivalModule());
        reception = transmission->getTransmitter()->getMedium()->getReception(receiver, transmission);
    }
    return reception;
}

} // namespace physicallayer

} // namespace inet


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Threading;
using System.Threading.Tasks;
using System.IO;

namespace Microsoft.Azure.WebJobs.Extensions.Storage.Blobs.Bindings
{
    internal class NotifyingBlobStream : DelegatingStream
    {
        private readonly IBlobCommitedAction _committedAction;

        public NotifyingBlobStream(Stream inner, IBlobCommitedAction committedAction)
            : base(inner)
        {
            _committedAction = committedAction;
        }

        public override void Flush()
        {
            base.Flush();
            if (_committedAction != null)
            {
                _committedAction.Execute();
            }
        }

        public override async Task FlushAsync(CancellationToken cancellationToken)
        {
            await base.FlushAsync(cancellationToken).ConfigureAwait(false);
            if (_committedAction != null)
            {
                await _committedAction.ExecuteAsync(cancellationToken).ConfigureAwait(false);
            }
        }

        public override void Close()
        {
            base.Close();
            if (_committedAction != null)
            {
                _committedAction.Execute();
            }
        }
    }
}


text:
[Code to generate html and javascript files](https://github.com/beh-gis/data-portal)

* [Generate html and javascript files for site](https://github.com/beh-gis/data-portal/blob/master/tasks/201506_generate_html_js/01-gen-html-js.ipynb)
* [Generate Data Dictionaries](https://github.com/beh-gis/data-portal/blob/master/tasks/201506_generate_markdown_data_dictionaries/01-gen-md-data-dictionaries.ipynb)
* [Merge tables](https://github.com/beh-gis/data-portal/blob/master/tasks/201506_v1_data_creation/00-merge-input-data-for-beh-data-portal.ipynb)

SQL Query for CartoDB Census Tracts 2010

	SELECT * FROM ct10 where ntaname != 'Airport' AND ntaname NOT LIKE 'park-cemetery%'

To Do: Tot Pop


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Server create and edit view
 *
 * @package PhpMyAdmin-Setup
 */

use PMA\libraries\config\ConfigFile;
use PMA\libraries\config\FormDisplay;

if (!defined('PHPMYADMIN')) {
    exit;
}

/**
 * Core libraries.
 */
require_once './setup/lib/form_processing.lib.php';

require './libraries/config/setup.forms.php';

$mode = isset($_GET['mode']) ? $_GET['mode'] : null;
$id = PMA_isValid($_GET['id'], 'numeric') ? $_GET['id'] : null;

/** @var ConfigFile $cf */
$cf = $GLOBALS['ConfigFile'];
$server_exists = !empty($id) && $cf->get("Servers/$id") !== null;

if ($mode == 'edit' && $server_exists) {
    $page_title = __('Edit server')
        . ' ' . $id
        . ' (' . htmlspecialchars($cf->getServerDSN($id)) . ')';
} elseif ($mode == 'remove' && $server_exists) {
    $cf->removeServer($id);
    header('Location: index.php' . PMA_URL_getCommon());
    exit;
} elseif ($mode == 'revert' && $server_exists) {
    // handled by process_formset()
} else {
    $page_title = __('Add a new server');
    $id = 0;
}
if (isset($page_title)) {
    echo '
' , $page_title . '
';
}
$form_display = new FormDisplay($cf);
foreach ($forms['Servers'] as $form_name => $form) {
    $form_display->registerForm($form_name, $form, $id);
}
PMA_Process_formset($form_display);


text:
<?php
// auto-generated by sfGeneratorConfigHandler
// date: 2010/12/02 06:57:55
require_once(sfConfig::get('sf_module_cache_dir').'/autoAUserAdmin/actions/actions.class.php');


text:
%% Homework 5: Seafloor subsidence due to cooling
% Partners: Paige Roban and Curtis Crandall
%
%% Part 1: Conductive heat flow
%% Part 1 - Step 1: A model
% Imagine an infinitely long and wide solid plate. The plate has thickness
% d. The temperature at the top of the plate is T1 and the temperature at
% the bottom of the plate is T2. Draw a diagram of this plate and label
% these parameters.

%           T1                T1
%   ____________________________________   _ _
%  |                                    |   |
%  |                                    |   |
%  |                                    |   | d = thickness
%  |                                    |   |
%  |____________________________________|  _|_
%           T2                T2

%% Part 1 - Step 2: Heat flow
% Assuming that T2>T1, the rate of change of heat flow per unit area up
% through the plate is proportional to (T2-T1)/d.
%
% In fact the rate of heat flow per unit area (Q) down through the plate is
% Q = -k(T2-T1)/d,
% where is k is called the thermal conductivity. Q is the rate of heat flow
% per unit area and has units Wm^-2; k has units Wm^-1C^-1.
% Why does the heat flow down in this equation?

% Heatflow is negative because we are losing heat as we are moving away
% from the source.
% If heatflow were positive, heat would be gained as it mvoes away from
% the source.

%% Part 1 - Step 3: Thermal conductivities
% Give the values of thermal conductivity for the following items. Make
% sure to cite where you found this value and make sure the units are in
% the SI units given in step 2.

% Silver: 406.0 (W/mK)
% Magnesium:156 (W/mK)
% Glass:0.8 (W/mK)
% Rock:2-7 (W/mK)
% Wood:0.12-0.04 (W/mK)
% Sources used to determine thermal conductivity:
% http://hyperphysics.phy-astr.gsu.edu/hbase/tables/thrcn.html and
% http://www.engineeringtoolbox.com/thermal-conductivity-d_429.html

%% Part 1 - Step 4: The heat transport equation

% Let's assume that the temperature of the upper surface(i.e. at z) is T
% and at the temperature at the lower surface (i.e. z+dz) is T+dT. Substitute these values
% into equation 1 (Think about how to replace d, T1, and T2).
% In the limit that dz goes to zero, some part of the right-hand side of
% your new equation becomes a derivative.
% Write this derivative.
% Q=-k([T+dT]-T/[Z-dZ]-Z)
% Write the heat flow (equation 1) using this derivative
% Q=-k(dt/dz)
% Write this same equation using the gradient operator
% Q=-kdT

%% Part 1 - Step 5: The conservation equation

% Use the heat transport equation and compute the derivative dQ/dz and
% insert this into the conservation equation.
% (cpP)(dT/dt)=A-k(dT^2/dZ^2)
% Assume that internal heat generation is zero, write the updated the
% conservation equation from the previous step.
% What is the value of k in this case?
% The value of k is in m^2/s, k=(k/cpP)

%% Part 2: Oceanic lithosphere cooling
%% Part 2 - Step 1: Setup the model domain and compute
%% Part 2 - Step 1: Nested for loop with erf function
tic
z = 1:100;
t = 1:100;
k = 31.556;
To = 640;
T1 = [];

for ii = 1:length(z);
    for jj = 1:length(t);
        T1(ii,jj) = To.*erf((ii)./(2*sqrt(k.*(jj))));
    end
end

figure(1);clf
imagesc(T1);
xlabel('Time [Ma]');
ylabel('Depth [km]');
c = colorbar;
c.Label.String = 'Temperature [C]'
colormap(jet)
toc
%% Part 2 - Step 1: Nested for loop with erf function and Meshgrid
tic
[X,Y] = meshgrid(z,t);
T1 = [];

for ii = 1:length(X);
    for jj = 1:length(Y);
        T1(ii,jj) = To.*erf((ii)./(2*sqrt(k.*(jj))));
    end
end
figure(2); clf
imagesc(T1);
xlabel('Time [Ma]');
ylabel('Depth [km]');
c = colorbar;
c.Label.String = 'Temperature [C]'
colormap(jet)
toc
% 1. Use two for loops to compute the function T(z,t).
% 2. Use the meshgrid() command to setup matrices for z and t and then
% compute the function T(z,t).
% Extra credit: Time how long it takes to compute T(z,t) using the two
% methods. If you don't notice a difference, try decreasing the sample
% interval in z and t. Discuss the differences in computation time.
% The first figure took 1.34 seconds to run on TREX. The second figure
% takes 0.45 seconds to run.

%% Part 2 - Step 2: Analyze the model output

% Answer the following questions in as much detail as possible.

% Does your model make sense given the boundary conditions used to derive
% the solution?
% Yes
% What controls the rate at which the temperature decays?
% Depth and Time, but mostly time.
% How could we convert this model from age to distance from ridge axis?
% It could follow a similar gradient, only temperature would decrease with
% distance from axis.
% What would be a more appropriate boundary condition at T(z=0) given
% what we know abot the oceans?
% Is 640C an appropriate value for the temperature at a mid-ocean ridge?
% Why or why not?
% Yes, because the ridge is where the crust is cracked, and magma is
% pushing upwards. It is active tectonism. Without a high temperature to
% facilitate the excretion of mass, there would be no spreading.

%% Part 3: Plate velocty and the depth of oceans
%% Part 3 - Step 1: Load and plot sea-floor depth data
% Load the file spreadingData.mat in MATLAB. This will load the structure
% Bath.
load('spreadingData.mat');
% These data are for the Pacific and Atlantic Oceans. The fields that end
% in z are the ocean depths [m] measured along a profile normal to a
% mid-ocean ridge. The fields that end in x are the distance [km] from the
% ridge where the data were collected. Plot depth vs. distance from the
% ridge; plot each ocean in its own subplot. make sure to label axes.

figure(3);clf
subplot(2,1,1);
load('spreadingData.mat');
plot(extractfield(Bath,'atlanticx'),(extractfield(Bath,'atlanticz')));
xlabel('Distance [km]')
ylabel('Depth [m]')
title('Atlantic Mid-Ocean Ridge')

subplot(2,1,2);
plot(extractfield(Bath,'pacificx'),(extractfield(Bath,'pacificz')));
xlabel('Distance [km]')
ylabel('Depth [m]')
title('Pacific Mid-Ocean Ridge')

% What does 2.65 represent in the equation (3)?
% It is an offset of the ridge axis depth.

% What are the plate veolocities [km/Ma] that match your data the closest?
% List both oceans.
% I will finish this after work. crc

% Convert these plate veolocities to [cm/yr] and compare with an estimate
% from the literature from these ocean basins. Do your estimates agree with
% published Pacific and Atlantic Ocean spreading rates?
% Gotta add these in

%% Part 3 - Step 2: A half-space model
%
atlanticT = ((extractfield(Bath,'atlanticz')-2.65)/0.345).^2;
pacificT = ((extractfield(Bath,'pacificz')-2.65)/0.345).^2;

atlanticV = (extractfield(Bath,'atlanticx')./atlanticT);
pacificV = (extractfield(Bath,'pacificx')./pacificT);

figure(4);clf
subplot(2,2,1);
load('spreadingData.mat');
plot(extractfield(Bath,'atlanticx'),(extractfield(Bath,'atlanticz')));
xlabel('Distance [km]')
ylabel('Depth [m]')
title('Atlantic Mid-Ocean Ridge')

subplot(2,2,2);
plot(extractfield(Bath,'pacificx'),(extractfield(Bath,'pacificz')));
xlabel('Distance [km]')
ylabel('Depth [m]')
title('Pacific Mid-Ocean Ridge')

subplot(2,2,3);
load('spreadingData.mat');
plot(atlanticT,(extractfield(Bath,'atlanticz')));
xlabel('Time [Ma]')
ylabel('Depth [m]')
title('Atlantic Mid-Ocean Ridge')

subplot(2,2,4);
plot(pacificT,(extractfield(Bath,'pacificz')));
xlabel('Time [Ma]')
ylabel('Depth [m]')
title('Pacific Mid-Ocean Ridge')
%% Part 4: Global oceanic plate ages
%% Part 4 - Step 1: Load topo data and plot sea-floor depths

load('topo'); % Load global topography
load('coastlines'); % load coastlines
[platelat,platelon] = importPlates('All_boundaries.txt');

h = figure(5);
h.InvertHardcopy = 'off'; % ensures color of saved fig. matches display
h.Color = 'k'; % (1 pt.) % changes fig. color to black
h.Position = [100 100 1000 500]; % specifies location/size of fig's drawable area
h.PaperPositionMode = 'auto'; % preserves fig's aspect ratio when printing
% setup the map axes
ax = axesm('Mollweid','Frame', 'on', 'Grid', 'on'); % sets map projection, inserts globe outline, inserts grid
setm(ax,'MLabelLocation',60); % sets lon. labels to every 60 degrees
setm(ax,'PLabelLocation',30); % sets lat. labels to every 30 degrees
mlabel('MLabelParallel',0); % sets lon. label location to the equator
plabel('PLabelMeridian',-25); % sets lat. label location to prime meridian
axis('off'); % prevents axes display
setm(ax,'FontColor',[0.9 0.9 0.9]); % brightens text
setm(ax,'GColor',[0.9 0.9 0.9]); % brightens grid
LAT = topolatlim(1):topolatlim(2);
LON =  topolonlim(1):topolonlim(2);
[lon, lat] = meshgrid(LON,LAT); % compute the lat/lon of every grid point in topo
pcolorm(lat,lon,topo); % plot the matrix of elevations on the map
hold on;
demcmap(topo); % give it a better colormap
c = colorbar; %
c = colorbar('color', [0.9 0.9 0.9]); % changes text color on color bar
c.Label.String = 'Elevation [M]';
plotm(coastlat, coastlon, 'w', 'LineWidth', 0.5); %plots coast lines
plotm(platelat,platelon,'k', 'LineWidth', 1.5); % plots plate boundaries

%% Part 4 - Step 2: Kill the topography and get the units right
[iy, ix] = find(topo > 0);

ocean = topo; % creates another matrix to hold values from the forloop

% for loop finds values of elevations that are negative
for ii = 1 : size( ix, 1 )
    ocean( iy(ii), ix(ii) ) = 0;
end

ocean = ocean.*-1e-3; % creates ocean depths, converts units, makes them positive

h = figure(6);
h.InvertHardcopy = 'off'; % ensures color of saved fig. matches display
h.Color = 'k'; % (1 pt.) % changes fig. color to black
h.Position = [100 100 1000 500]; % specifies location/size of fig's drawable area
h.PaperPositionMode = 'auto'; % preserves fig's aspect ratio when printing
% setup the map axes
ax = axesm('Mollweid','Frame', 'on', 'Grid', 'on'); % sets map projection, inserts globe outline, inserts grid
setm(ax,'MLabelLocation',60); % sets lon. labels to every 60 degrees
setm(ax,'PLabelLocation',30); % sets lat. labels to every 30 degrees
mlabel('MLabelParallel',0); % sets lon. label location to the equator
plabel('PLabelMeridian',-25); % sets lat. label location to prime meridian
axis('off'); % prevents axes display
setm(ax,'FontColor',[0.9 0.9 0.9]); % brightens text
setm(ax,'GColor',[0.9 0.9 0.9]); % brightens grid
LAT = topolatlim(1):topolatlim(2);
LON =  topolonlim(1):topolonlim(2);
[lon, lat] = meshgrid(LON,LAT); % compute the lat/lon of every grid point in topo
pcolorm(lat,lon,ocean); % plot the matrix of elevations on the map
hold on;
demcmap(ocean); % give it a better colormap
c = colorbar; %
c = colorbar('color', [0.9 0.9 0.9]); % changes text color on color bar
c.Label.String = 'Elevation [km]';
plotm(coastlat, coastlon, 'w', 'LineWidth', 0.5); %plots coast lines
plotm(platelat,platelon,'k', 'LineWidth', 1.5); % plots plate boundaries
colormap(flipud(jet(20))); %Flipud inverts the array of colors on the colormap and adds 20 increments of color scale

%% Part 4 - Step 3 Compute sea-floor age
d = ocean; % resaves matrix to hold values of depth for later
% for loop finds values of elevations that are negative
t = zeros(size(d));
for ii = 1:size(d)
    for jj = 1:length(d)
        t(ii,jj) = (((d(ii,jj) - 2.65)/0.345))^2;
    end
    t(t==59.000210039907586)=-10;
end

h = figure(7);
h.InvertHardcopy = 'off'; % ensures color of saved fig. matches display
h.Color = 'k'; % (1 pt.) % changes fig. color to black
h.Position = [100 100 1000 500]; % specifies location/size of fig's drawable area
h.PaperPositionMode = 'auto'; % preserves fig's aspect ratio when printing
% setup the map axes
ax = axesm('Mollweid','Frame', 'on', 'Grid', 'on'); % sets map projection, inserts globe outline, inserts grid
setm(ax,'MLabelLocation',60); % sets lon. labels to every 60 degrees
setm(ax,'PLabelLocation',30); % sets lat. labels to every 30 degrees
mlabel('MLabelParallel',0); % sets lon. label location to the equator
plabel('PLabelMeridian',-25); % sets lat. label location to prime meridian
axis('off'); % prevents axes display
setm(ax,'FontColor',[0.9 0.9 0.9]); % brightens text
setm(ax,'GColor',[0.9 0.9 0.9]); % brightens grid
LAT = topolatlim(1):topolatlim(2);
LON =  topolonlim(1):topolonlim(2);
[lon, lat] = meshgrid(LON,LAT); % compute the lat/lon of every grid point in topo
pcolorm(lat,lon,t); % plot the matrix of elevations on the map
hold on;
c = colorbar; %
c = colorbar('color', [0.9 0.9 0.9]); % changes text color on color bar
c.Label.String = 'Age[Ma]';
plotm(coastlat, coastlon, 'w', 'LineWidth', 0.5); %plots coast lines
plotm(platelat,platelon,'k', 'LineWidth', 1.5); % plots plate boundaries
cmap=(flipud(jet(20))); % Initializes color map as a variable (cmap) so later strings can be input to change plotting conditions.
% Flipud inverts the array of colors on the colormap and adds 20 increments of color scale
cmap = [0.5 0.5 0.5 ; cmap]; % Allows us to create a grey color for plotting negative ages.
cmap(end,:) = []; % Recreates an array to include grey within the jet color scheme.
colormap(cmap); % Compiles array of cmap RGB values and plots the new color sheme.

%% Part 4 - Step 5: Discuss your results

% Does your map of ocean ages make sense given the plate boundaries?
% Yes, only near spreadng centers and ocean basins.

% What is the oldest age in your map?
% ~180 Ma

% Where does this oldest age occur and does this make sense geologically?
% Off the north-east coast of Japan, the accepted age is near 160 Ma for
% that area.  It makes sense geologically because it is near a subduction
% zone where the oldest crust should be.

% Where do the youngest ages occur? Does this conform to your knowledge of
% oceanic listhosphere generation?
% Conforming to the model, the youngest ages occur along Mid-ocean ridges.

% Are there any assumptions that have gone into this model that might not
% be accurate?
% Spreading rate is not equal on both sides of the ridge axis. Certain
% geographic areas were younging when getting close to continental shelves;
% however, they should have been aging. Our model predicts the Mediteranean
% sea as being ~20Ma, while accepted values are puting the
% Mediteranean sea as some of the oldest oceanic crust.