text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>类 com.netease.cloud.http.Protocol的使用 (com.netease.cloud:streamproxy-sdk-java 0.1 API)</title>
<meta name="date" content="2016-12-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类的使用
com.netease.cloud.http.Protocol

使用Protocol的程序包

程序包
说明

com.netease.cloud.config

com.netease.cloud.http

com.netease.cloud.config中Protocol的使用

返回Protocol的com.netease.cloud.config中的方法

限定符和类型
方法和说明

Protocol
ClientConfiguration.getProtocol()

Returns the protocol (HTTP or HTTPS) to use when connecting to the Web Services.

参数类型为Protocol的com.netease.cloud.config中的方法

限定符和类型
方法和说明

void
ClientConfiguration.setProtocol(Protocol protocol)

Sets the protocol (i.e.

ClientConfiguration
ClientConfiguration.withProtocol(Protocol protocol)

Sets the protocol (i.e.

com.netease.cloud.http中Protocol的使用

返回Protocol的com.netease.cloud.http中的方法

限定符和类型
方法和说明

static Protocol
Protocol.valueOf(String name)

返回带有指定名称的该类型的枚举常量。

static Protocol[]
Protocol.values()

按照声明该枚举类型的常量的顺序, 返回
包含这些常量的数组。

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

Copyright © 2016. All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
@interface YDClient : NSObject

+ (instancetype)sharedClient;

@property (nonatomic, strong) NSString *name;

@end


text:
package com.subitolabs.cordova.galleryapi;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class GalleryAPI extends CordovaPlugin {
    public static final String ACTION_CHECK_PERMISSION = "checkPermission";
    public static final String ACTION_GET_MEDIA = "getMedia";
    public static final String ACTION_GET_MEDIA_THUMBNAIL = "getMediaThumbnail";
    public static final String ACTION_GET_HQ_IMAGE_DATA = "getHQImageData";
    public static final String ACTION_GET_ALBUMS = "getAlbums";
    public static final String DIR_NAME = ".mendr";
    public static final String SUB_DIR_NAME = ".mendr_hq";

    private static final int BASE_SIZE = 300;

    private static BitmapFactory.Options ops = null;

    private static final int STORAGE_PERMISSIONS_REQUEST = 1;

    private CallbackContext cbc = null;

    @Override
    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        try {
            if (ACTION_GET_MEDIA.equals(action)) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        try {
                            JSONObject object = (JSONObject) args.get(0);
                            ArrayOfObjects albums = getMedia(object.getString("title"));
                            callbackContext.success(new JSONArray(albums));
                        } catch (Exception e) {
                            e.printStackTrace();
                            callbackContext.error(e.getMessage());
                        }
                    }
                });

                return true;
            } else if (ACTION_CHECK_PERMISSION.equals(action)) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cbc = callbackContext;
                        checkPermission();
                    }
                });
                return true;
            } else if (ACTION_GET_MEDIA_THUMBNAIL.equals(action)) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        try {
                            JSONObject media = getMediaThumbnail((JSONObject) args.get(0));
                            callbackContext.success(media);
                        } catch (Exception e) {
                            e.printStackTrace();
                            callbackContext.error(e.getMessage());
                        }
                    }
                });
                return true;
            } else if (ACTION_GET_HQ_IMAGE_DATA.equals(action)) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        try {
                            File imagePath = getHQImageData((JSONObject) args.get(0));
                            callbackContext.success(imagePath.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                            callbackContext.error(e.getMessage());
                        }
                    }
                });
                return true;
            } else if (ACTION_GET_ALBUMS.equals(action)) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        try {
                            ArrayOfObjects albums = getBuckets();
                            callbackContext.success(new JSONArray(albums));
                        } catch (Exception e) {
                            e.printStackTrace();
                            callbackContext.error(e.getMessage());
                        }
                    }
                });

                return true;
            }
            callbackContext.error("Invalid action");
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            callbackContext.error(e.getMessage());
            return false;
        }
    }

    public ArrayOfObjects getBuckets() throws JSONException {
        Object columns = new Object() {{
            put("id", MediaStore.Images.ImageColumns.BUCKET_ID);
            put("title", MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME);
        }};

        final ArrayOfObjects results = queryContentProvider(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, "1) GROUP BY 1,(2");

        Object collection = null;
        for (int i = 0; i < results.size(); i++) {
            collection = results.get(i);
            if (collection.getString("title").equals("Camera")) {
                results.remove(i);
                break;
            }
        }

        if (collection != null)
            results.add(0, collection);

        return results;
    }

    private ArrayOfObjects getMedia(String bucket) throws JSONException {
        Object columns = new Object() {{
            put("int.id", MediaStore.Images.Media._ID);
            put("data", MediaStore.MediaColumns.DATA);
            put("int.date_added", MediaStore.Images.ImageColumns.DATE_ADDED);
            put("title", MediaStore.Images.ImageColumns.DISPLAY_NAME);
            put("int.height", MediaStore.Images.ImageColumns.HEIGHT);
            put("int.width", MediaStore.Images.ImageColumns.WIDTH);
            put("int.orientation", MediaStore.Images.ImageColumns.ORIENTATION);
            put("mime_type", MediaStore.Images.ImageColumns.MIME_TYPE);
            put("float.lat", MediaStore.Images.ImageColumns.LATITUDE);
            put("float.lon", MediaStore.Images.ImageColumns.LONGITUDE);
            put("int.size", MediaStore.Images.ImageColumns.SIZE);
            put("int.thumbnail_id", MediaStore.Images.ImageColumns.MINI_THUMB_MAGIC);
        }};

        final ArrayOfObjects results = queryContentProvider(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, "bucket_display_name = \"" + bucket + "\"");

        ArrayOfObjects temp = new ArrayOfObjects();

        for (Object media : results) {
            media.put("thumbnail", "");
            media.put("error", "false");

            if (media.getInt("height") <= 0 || media.getInt("width") <= 0) {
                System.err.println(media);
            } else {
                temp.add(media);
            }
        }

        Collections.reverse(temp);
        return temp;
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<String>();

            boolean isReadDenied = false;
            boolean isWriteDenied = false;

            if (ContextCompat.checkSelfPermission(this.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this.cordova.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE))
                    isReadDenied = true;
                else
                    permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            if (ContextCompat.checkSelfPermission(this.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this.cordova.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE))
                    isWriteDenied = true;
                else
                    permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }

            if (isReadDenied || isWriteDenied) {
                String message;

                if (isReadDenied && isWriteDenied)
                    message = "Read and Write permissions are denied";
                else if (isReadDenied)
                    message = "Read permission is denied";
                else
                    message = "Write permission is denied";

                sendCheckPermissionResult(false, message);
            } else if (permissions.size() > 0) {
                String[] pArray = new String[permissions.size()];
                pArray = permissions.toArray(pArray);
                ActivityCompat.requestPermissions(this.cordova.getActivity(), pArray, STORAGE_PERMISSIONS_REQUEST);
            } else
                sendCheckPermissionResult(true, "Authorized");
        } else
            sendCheckPermissionResult(true, "Authorized");
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case STORAGE_PERMISSIONS_REQUEST: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    sendCheckPermissionResult(true, "Authorized");
                else
                    sendCheckPermissionResult(false, "Denied");
                return;
            }
        }
    }

    private void sendCheckPermissionResult(Boolean success, String message) {
        try {
            JSONObject result = new JSONObject();
            result.put("success", success);
            result.put("message", message);
            cbc.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            cbc.error(e.getMessage());
        }
    }

    private JSONObject getMediaThumbnail(JSONObject media) throws JSONException {

        File thumbnailPath = thumbnailPathFromMediaId(media.getString("id"));
        if (thumbnailPath.exists()) {
            System.out.println("Thumbnail Already Exists!!!. Not Creating New One");
            media.put("thumbnail", thumbnailPath);
        } else {
            if (ops == null) {
                ops = new BitmapFactory.Options();
                ops.inJustDecodeBounds = false;
                ops.inSampleSize = 1;
            }
            media.put("error", "true");

            File image = new File(media.getString("data"));

            int sourceWidth = media.getInt("width");
            int sourceHeight = media.getInt("height");

            if (sourceHeight > 0 && sourceWidth > 0) {
                int destinationWidth, destinationHeight;

                if (sourceWidth > sourceHeight) {
                    destinationHeight = BASE_SIZE;
                    destinationWidth = (int) Math.ceil(destinationHeight * ((double) sourceWidth / sourceHeight));
                } else {
                    destinationWidth = BASE_SIZE;
                    destinationHeight = (int) Math.ceil(destinationWidth * ((double) sourceHeight / sourceWidth));
                }

                if (sourceWidth * sourceHeight > 600000 && sourceWidth * sourceHeight < 1000000) {
                    ops.inSampleSize = 4;
                } else if (sourceWidth * sourceHeight > 1000000) {
                    ops.inSampleSize = 8;
                }

                Bitmap originalImageBitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), ops); //creating bitmap of original image

                if (originalImageBitmap == null) {
                    ops.inSampleSize = 1;
                    originalImageBitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), ops);
                }

                if (originalImageBitmap != null) {

                    if (destinationHeight <= 0 || destinationWidth <= 0) {
                        System.out.println("destinationHeight: " + destinationHeight + "  destinationWidth: " + destinationWidth);
                    }

                    Bitmap thumbnailBitmap = Bitmap.createScaledBitmap(originalImageBitmap, destinationWidth, destinationHeight, true);
                    originalImageBitmap.recycle();

                    if (thumbnailBitmap != null) {
                        int orientation = media.getInt("orientation");
                        if (orientation > 0)
                            thumbnailBitmap = rotate(thumbnailBitmap, orientation);

                        byte[] thumbnailData = getBytesFromBitmap(thumbnailBitmap);
                        thumbnailBitmap.recycle();
                        if (thumbnailData != null) {
                            FileOutputStream outStream;
                            try {
                                outStream = new FileOutputStream(thumbnailPath);
                                outStream.write(thumbnailData);
                                outStream.close();
                            } catch (IOException e) {
                                Log.e("Mendr", "Couldn't write the thumbnail image data");
                                e.printStackTrace();
                            }

                            if (thumbnailPath.exists()) {
                                System.out.println("Thumbnail didn't Exists!!!. Created New One");
                                media.put("thumbnail", thumbnailPath);
                                media.put("error", "false");
                            }
                        } else
                            Log.e("Mendr", "Couldn't convert thumbnail bitmap to byte array");
                    } else
                        Log.e("Mendr", "Couldn't create the thumbnail bitmap");
                } else
                    Log.e("Mendr", "Couldn't decode the original image");
            } else
                Log.e("Mendr", "Invalid Media!!! Image width or height is 0");
        }

        return media;
    }

    private File getHQImageData(JSONObject media) throws JSONException {
        File imagePath = imagePathFromMediaId(media.getString("id"));

        BitmapFactory.Options ops = new BitmapFactory.Options();
        ops.inJustDecodeBounds = false;
        ops.inSampleSize = 1;

        File image = new File(media.getString("data"));

        int sourceWidth = media.getInt("width");
        int sourceHeight = media.getInt("height");

        if (sourceHeight > 0 && sourceWidth > 0) {
            Bitmap originalImageBitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), ops); //creating bitmap of original image

            if (originalImageBitmap != null) {
                int orientation = media.getInt("orientation");
                if (orientation > 0)
                    originalImageBitmap = rotate(originalImageBitmap, orientation);

                byte[] imageData = getBytesFromBitmap(originalImageBitmap);
                originalImageBitmap.recycle();
                if (imageData != null) {
                    FileOutputStream outStream;
                    try {
                        outStream = new FileOutputStream(imagePath);
                        outStream.write(imageData);
                        outStream.close();
                    } catch (IOException e) {
                        Log.e("Mendr", "Couldn't write the image data");
                        e.printStackTrace();
                    }
                }
            } else
                Log.e("Mendr", "Couldn't decode the original image");
        } else
            Log.e("Mendr", "Invalid Media!!! Image width or height is 0");

        return imagePath;
    }

    private byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
    }

    private static Bitmap rotate(Bitmap source, int orientation) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) orientation);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
    }

    private File thumbnailPathFromMediaId(String mediaId) {
        File thumbnailPath = null;

        String thumbnailName = mediaId + "_mthumb.png";
        File dir = new File(this.getContext().getApplicationInfo().dataDir, DIR_NAME);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                Log.e("Mendr", "Failed to create storage directory.");
                return thumbnailPath;
            }
        }

        thumbnailPath = new File(dir.getPath() + File.separator + thumbnailName);

        return thumbnailPath;
    }

    private File imagePathFromMediaId(String mediaId) {
        File imagePath = null;

        File rootDir = new File(this.getContext().getApplicationInfo().dataDir, DIR_NAME);
        File dir = new File(rootDir, SUB_DIR_NAME);

        //check if root directory exist
        if (rootDir.exists()) {
            //root directory exists
            if (dir.exists()) {
                //dir exists so deleting it
                deleteRecursive(dir);
            }

            if (!dir.mkdirs()) {
                Log.e("Mendr", "Failed to create hq storage directory.");
                return imagePath;
            } else {
                //dir created successfully
            }
        } else {
            //root directory doesn't exist
            //trying to create root directory
            if (!rootDir.mkdirs()) {
                Log.e("Mendr", "Failed to create root storage directory.");
                return imagePath;
            } else {
                //root dir created successfully
                if (!dir.mkdirs()) {
                    Log.e("Mendr", "Failed to create hq storage directory.");
                    return imagePath;
                } else {
                    //dir created successfully
                }
            }
        }

        String imageName = mediaId + ".png";
        imagePath = new File(dir.getPath() + File.separator + imageName);

        return imagePath;
    }

    void deleteRecursive(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                deleteRecursive(child);

        fileOrDirectory.delete();
    }

    private Context getContext() {
        return this.cordova.getActivity().getApplicationContext();
    }

    private ArrayOfObjects queryContentProvider(Uri collection, Object columns, String whereClause) throws JSONException {
        final ArrayList<String> columnNames = new ArrayList<String>();
        final ArrayList<String> columnValues = new ArrayList<String>();

        Iterator<String> iteratorFields = columns.keys();

        while (iteratorFields.hasNext()) {
            String column = iteratorFields.next();

            columnNames.add(column);
            columnValues.add("" + columns.getString(column));
        }

        final Cursor cursor = getContext().getContentResolver().query(collection, columnValues.toArray(new String[columns.length()]), whereClause, null, null);
        final ArrayOfObjects buffer = new ArrayOfObjects();

        if (cursor.moveToFirst()) {
            do {
                Object item = new Object();

                for (String column : columnNames) {
                    int columnIndex = cursor.getColumnIndex(columns.get(column).toString());

                    if (column.startsWith("int.")) {
                        item.put(column.substring(4), cursor.getInt(columnIndex));
                        if (column.substring(4).equals("width") && item.getInt("width") == 0) {
                            System.err.println("cursor: " + cursor.getInt(columnIndex));

                        }
                    } else if (column.startsWith("float.")) {
                        item.put(column.substring(6), cursor.getFloat(columnIndex));
                    } else {
                        item.put(column, cursor.getString(columnIndex));
                    }
                }

                buffer.add(item);
            }
            while (cursor.moveToNext());
        }

        cursor.close();

        return buffer;
    }

    private class Object extends JSONObject {

    }

    private class ArrayOfObjects extends ArrayList<Object> {

    }
}


text:
package org.mdoc.sbt.mdoc

import org.mdoc.sbt.mdoc.MdocPlugin.autoImport.addCommandsAlias
import sbt._

object ExtCommands {
  lazy val settings = Seq(
    Keys.commands += mkCommandAlias("mdocValidate", MdocKeys.mdocValidateCommands),
    MdocKeys.mdocValidateCommands := Seq(
      "clean",
      "coverage",
      "compile",
      "test",
      "coverageReport",
      "coverageOff",
      "scalastyle",
      "test:scalastyle",
      "doc",
      "package",
      "packageSrc"
    )
  ) ++
    addCommandsAlias("mdocPublishJar", Seq("clean", MdocKeys.mdocBintrayCredentials.key.label, "reload", "publish")) ++
    addCommandsAlias("mdocPublishDeb", Seq("clean", MdocKeys.mdocBintrayDeployJson.key.label, "debian:packageBin"))

  def mkCommandAlias(name: String, commandsKey: SettingKey[Seq[String]]): Command =
    Command.command(name) { (state: State) =>
      val extracted = Project.extract(state)
      val commands = extracted.get(commandsKey)
      state.copy(remainingCommands = commands ++ state.remainingCommands)
    }
}


text:
#ifndef RENDERER_TARGET_H
#define RENDERER_TARGET_H

namespace SampleRenderer
{

	class RendererTarget
	{
		friend class Renderer;
	public:
		RendererTarget(void);
		virtual ~RendererTarget(void);

		void release(void) { delete this; }

	private:
		virtual void bind(void)=0;
		virtual void unbind(void)=0;
	};

} // namespace SampleRenderer

#endif


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Array
struct Il2CppArray;
// System.Object
struct Il2CppObject;

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Array_InternalEnumerator_1_gen2795948550.h"
#include "mscorlib_System_Array1146569071.h"
#include "mscorlib_System_Resources_ResourceReader_ResourceI4013605874.h"

// System.Void System.Array/InternalEnumerator`1<System.Resources.ResourceReader/ResourceInfo>::.ctor(System.Array)
extern "C"  void InternalEnumerator_1__ctor_m2865872515_gshared (InternalEnumerator_1_t2795948550 * __this, Il2CppArray * ___array0, const MethodInfo* method);
#define InternalEnumerator_1__ctor_m2865872515(__this, ___array0, method) ((  void (*) (InternalEnumerator_1_t2795948550 *, Il2CppArray *, const MethodInfo*))InternalEnumerator_1__ctor_m2865872515_gshared)(__this, ___array0, method)
// System.Void System.Array/InternalEnumerator`1<System.Resources.ResourceReader/ResourceInfo>::System.Collections.IEnumerator.Reset()
extern "C"  void InternalEnumerator_1_System_Collections_IEnumerator_Reset_m3939002941_gshared (InternalEnumerator_1_t2795948550 * __this, const MethodInfo* method);
#define InternalEnumerator_1_System_Collections_IEnumerator_Reset_m3939002941(__this, method) ((  void (*) (InternalEnumerator_1_t2795948550 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_Reset_m3939002941_gshared)(__this, method)
// System.Object System.Array/InternalEnumerator`1<System.Resources.ResourceReader/ResourceInfo>::System.Collections.IEnumerator.get_Current()
extern "C"  Il2CppObject * InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m763692585_gshared (InternalEnumerator_1_t2795948550 * __this, const MethodInfo* method);
#define InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m763692585(__this, method) ((  Il2CppObject * (*) (InternalEnumerator_1_t2795948550 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m763692585_gshared)(__this, method)
// System.Void System.Array/InternalEnumerator`1<System.Resources.ResourceReader/ResourceInfo>::Dispose()
extern "C"  void InternalEnumerator_1_Dispose_m3639607322_gshared (InternalEnumerator_1_t2795948550 * __this, const MethodInfo* method);
#define InternalEnumerator_1_Dispose_m3639607322(__this, method) ((  void (*) (InternalEnumerator_1_t2795948550 *, const MethodInfo*))InternalEnumerator_1_Dispose_m3639607322_gshared)(__this, method)
// System.Boolean System.Array/InternalEnumerator`1<System.Resources.ResourceReader/ResourceInfo>::MoveNext()
extern "C"  bool InternalEnumerator_1_MoveNext_m3402661033_gshared (InternalEnumerator_1_t2795948550 * __this, const MethodInfo* method);
#define InternalEnumerator_1_MoveNext_m3402661033(__this, method) ((  bool (*) (InternalEnumerator_1_t2795948550 *, const MethodInfo*))InternalEnumerator_1_MoveNext_m3402661033_gshared)(__this, method)
// T System.Array/InternalEnumerator`1<System.Resources.ResourceReader/ResourceInfo>::get_Current()
extern "C"  ResourceInfo_t4013605874  InternalEnumerator_1_get_Current_m3891250378_gshared (InternalEnumerator_1_t2795948550 * __this, const MethodInfo* method);
#define InternalEnumerator_1_get_Current_m3891250378(__this, method) ((  ResourceInfo_t4013605874  (*) (InternalEnumerator_1_t2795948550 *, const MethodInfo*))InternalEnumerator_1_get_Current_m3891250378_gshared)(__this, method)


text:
require 'rails_helper'

RSpec.describe BedfordDavisServicesProcessor do
  let!(:pals) { TestPals.create! }

  def social_emotional_fixture_file_text
    IO.read("#{Rails.root}/spec/importers/transitions/bedford_davis_social_emotional_fixture.csv")
  end

  def transition_notes_fixture_file_text
    IO.read("#{Rails.root}/spec/importers/transitions/bedford_davis_transition_notes_fixture.csv")
  end

  def create_processor(options = {})
    log = LogHelper::FakeLog.new
    processor = BedfordDavisServicesProcessor.new(pals.rich_districtwide, {
      log: log,
      time_now: pals.time_now
    })
    [processor, log]
  end

  describe 'private #find_service_type_names' do
    it 'works with an example using the mapping' do
      processor, _ = create_processor()
      row = {
        "Teacher"=>"X",
        "LASID"=>"111222222",
        "Student Name"=>"Mari Kenobi",
        "Soc.Emo. Check in w/ counselor"=>"FALSE",
        "Soc. Emo. Small group"=>"TRUE",
        "Soc. Emo. individual counseling"=>"FALSE",
        "Formal Behavior Plan"=>"FALSE",
        "Notes from the counselor"=>nil,
        "Counselor "=>nil
      }
      expect(processor.send(:find_service_type_names, row)).to eq([
        'Social Group'
      ])
    end
  end

  it 'works for social emotional format' do
    processor, log = create_processor()
    rows = processor.dry_run(social_emotional_fixture_file_text)

    records = rows.map {|row| Service.create!(row)} # to exercise validations
    expect(log.output).to include('processed_rows_count=>4')
    expect(records.size).to eq(2)
    expect(records.as_json({
      except: [:id, :created_at, :updated_at]
    })).to eq([{
      "student_id"=>pals.shs_senior_kylo.id,
      "service_type_id"=>703,
      'recorded_by_educator_id' => pals.rich_districtwide.id,
      "recorded_at"=>'2018-03-13T11:03:00.000Z',
      "date_started"=>'2017-08-15T00:00:00.000Z',
      "estimated_end_date"=>'2018-06-30T00:00:00.000Z',
      "discontinued_at"=>'2018-06-30T00:00:00.000Z',
      "discontinued_by_educator_id"=>pals.rich_districtwide.id,
      "provided_by_educator_name"=>nil,
      "service_upload_id"=>nil
    },{
      "student_id"=>pals.shs_freshman_amir.id,
      "service_type_id"=>705,
      'recorded_by_educator_id' => pals.rich_districtwide.id,
      "recorded_at"=>'2018-03-13T11:03:00.000Z',
      "date_started"=>'2017-08-15T00:00:00.000Z',
      "estimated_end_date"=>'2018-06-30T00:00:00.000Z',
      "discontinued_at"=>'2018-06-30T00:00:00.000Z',
      "discontinued_by_educator_id"=>pals.rich_districtwide.id,
      "provided_by_educator_name"=>nil,
      "service_upload_id"=>nil
    }])
  end

  it 'works for transition notes format' do
    processor, log = create_processor()
    rows = processor.dry_run(transition_notes_fixture_file_text)

    records = rows.map {|row| Service.create!(row)} # to exercise validations
    expect(log.output).to include('processed_rows_count=>1')
    expect(records.size).to eq(2)
    expect(records.as_json({
      except: [:id, :created_at, :updated_at]
    })).to eq([{
      'student_id' => pals.healey_kindergarten_student.id,
      'service_type_id'=>707,
      'recorded_by_educator_id' => pals.rich_districtwide.id,
      "recorded_at"=>'2018-03-13T11:03:00.000Z',
      "date_started"=>'2017-08-15T00:00:00.000Z',
      "estimated_end_date"=>'2018-06-30T00:00:00.000Z',
      "discontinued_at"=>'2018-06-30T00:00:00.000Z',
      "discontinued_by_educator_id"=>pals.rich_districtwide.id,
      "provided_by_educator_name"=>nil,
      "service_upload_id"=>nil
    },{
      'student_id' => pals.healey_kindergarten_student.id,
      'service_type_id'=>708,
      'recorded_by_educator_id' => pals.rich_districtwide.id,
      "recorded_at"=>'2018-03-13T11:03:00.000Z',
      "date_started"=>'2017-08-15T00:00:00.000Z',
      "estimated_end_date"=>'2018-06-30T00:00:00.000Z',
      "discontinued_at"=>'2018-06-30T00:00:00.000Z',
      "discontinued_by_educator_id"=>pals.rich_districtwide.id,
      "provided_by_educator_name"=>nil,
      "service_upload_id"=>nil
    }])
  end
end


text:
using System;
using Azure.Core;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Storage.Models;

namespace Azure.ResourceManager.Storage
{
    /// <summary> A class representing the EncryptionScope data model. </summary>
    public partial class EncryptionScopeData : ResourceData
    {
        /// <summary> Initializes a new instance of EncryptionScopeData. </summary>
        public EncryptionScopeData()
        {
        }

        /// <summary> Initializes a new instance of EncryptionScopeData. </summary>
        /// <param name="id"> The id. </param>
        /// <param name="name"> The name. </param>
        /// <param name="resourceType"> The resourceType. </param>
        /// <param name="systemData"> The systemData. </param>
        /// <param name="source"> The provider for the encryption scope. Possible values (case-insensitive):  Microsoft.Storage, Microsoft.KeyVault. </param>
        /// <param name="state"> The state of the encryption scope. Possible values (case-insensitive):  Enabled, Disabled. </param>
        /// <param name="createdOn"> Gets the creation date and time of the encryption scope in UTC. </param>
        /// <param name="lastModifiedOn"> Gets the last modification date and time of the encryption scope in UTC. </param>
        /// <param name="keyVaultProperties"> The key vault properties for the encryption scope. This is a required field if encryption scope 'source' attribute is set to 'Microsoft.KeyVault'. </param>
        /// <param name="requireInfrastructureEncryption"> A boolean indicating whether or not the service applies a secondary layer of encryption with platform managed keys for data at rest. </param>
        internal EncryptionScopeData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, EncryptionScopeSource? source, EncryptionScopeState? state, DateTimeOffset? createdOn, DateTimeOffset? lastModifiedOn, EncryptionScopeKeyVaultProperties keyVaultProperties, bool? requireInfrastructureEncryption) : base(id, name, resourceType, systemData)
        {
            Source = source;
            State = state;
            CreatedOn = createdOn;
            LastModifiedOn = lastModifiedOn;
            KeyVaultProperties = keyVaultProperties;
            RequireInfrastructureEncryption = requireInfrastructureEncryption;
        }

        /// <summary> The provider for the encryption scope. Possible values (case-insensitive):  Microsoft.Storage, Microsoft.KeyVault. </summary>
        public EncryptionScopeSource? Source { get; set; }
        /// <summary> The state of the encryption scope. Possible values (case-insensitive):  Enabled, Disabled. </summary>
        public EncryptionScopeState? State { get; set; }
        /// <summary> Gets the creation date and time of the encryption scope in UTC. </summary>
        public DateTimeOffset? CreatedOn { get; }
        /// <summary> Gets the last modification date and time of the encryption scope in UTC. </summary>
        public DateTimeOffset? LastModifiedOn { get; }
        /// <summary> The key vault properties for the encryption scope. This is a required field if encryption scope 'source' attribute is set to 'Microsoft.KeyVault'. </summary>
        public EncryptionScopeKeyVaultProperties KeyVaultProperties { get; set; }
        /// <summary> A boolean indicating whether or not the service applies a secondary layer of encryption with platform managed keys for data at rest. </summary>
        public bool? RequireInfrastructureEncryption { get; set; }
    }
}


text: google-site-verification: google276e6a4a635c7927.html


text:
package current

import (
	"testing"

	booking_handler "github.com/bborbe/booking/handler"

	. "github.com/bborbe/assert"
)

func TestNewHandlerImplementsHttpHandler(t *testing.T) {
	r := New(nil, nil)
	var i (*booking_handler.Handler) = nil
	err := AssertThat(r, Implements(i).Message("check implements http.Handler"))
	if err != nil {
		t.Fatal(err)
	}
}


text:
package org.pentaho.python;

import org.apache.commons.io.IOUtils;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.i18n.BaseMessages;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Class implementing a session for interacting with Python
 *
 * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
 */
public class PythonSession {

  /**
   * Kettle variable key to specify the full path to the python command. Takes precedence over both the java
   * property and the system evnironment variable
   */
  public static final String KETTLE_CPYTHON_COMMAND_PROPERTY_KEY = "pdi.cpython.command";

  /**
   * Java property to specify full path to python command. If not set (and env var not set), we assume 'python' is in
   * the PATH. Takes precedence over the env var.
   */
  public static final String CPYTHON_COMMAND_PROPERTY_KEY = "pentaho.cpython.command";

  /**
   * System environment variable to specify full path to python command. If not set (and java prop is not set), we
   * assume 'python' is in the PATH.
   */
  public static final String CPYTHON_COMMAND_ENV_VAR_KEY = "PENTAHO_CPYTHON_COMMAND";

  public static enum PythonVariableType {
    DataFrame, Image, String, Unknown;
  }

  /**
   * Simple container for row meta data and rows
   *
   * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
   */
  public static class RowMetaAndRows {
    public Object[][] m_rows;
    public RowMetaInterface m_rowMeta;
  }

  /**
   * The command used to start python
   */
  private String m_pythonCommand;

  /**
   * The session singleton
   */
  private static PythonSession s_sessionSingleton;

  /**
   * the current session holder
   */
  private static Object s_sessionHolder;

  /**
   * The results of the python check script
   */
  private static String s_pythonEnvCheckResults = "";

  /**
   * For locking
   */
  protected SessionMutex m_mutex = new SessionMutex();

  /**
   * Server socket
   */
  protected ServerSocket m_serverSocket;

  /**
   * Local socket for comms with the python server
   */
  protected Socket m_localSocket;

  /**
   * The process executing the server
   */
  protected Process m_serverProcess;

  /**
   * True when the server has been shutdown
   */
  protected boolean m_shutdown;

  /**
   * A shutdown hook for stopping the server
   */
  protected Thread m_shutdownHook;

  /**
   * PID of the running python server
   */
  protected int m_pythonPID = -1;

  /**
   * The log to use
   */
  protected LogChannelInterface m_log;

  // TODO fix this
  protected String m_kettlePluginDir = "./";

  protected String m_osTmpDir = "";

  /**
   * Acquire the session for the requester
   *
   * @param requester the object requesting the session
   * @return the session singleton
   * @throws SessionException if python is not available
   */
  public static PythonSession acquireSession( Object requester ) throws SessionException {
    return s_sessionSingleton.getSession( requester );
  }

  /**
   * Release the session so that other clients can obtain it. This method does
   * nothing if the requester is not the current session holder
   *
   * @param requester the session holder
   */
  public static void releaseSession( Object requester ) {
    s_sessionSingleton.dropSession( requester );
  }

  /**
   * Returns true if the python environment/server is available
   *
   * @return true if the python environment/server is available
   */
  public static boolean pythonAvailable() {
    return s_sessionSingleton != null;
  }

  protected static File installPyScriptsToTmp() throws IOException {
    ClassLoader loader = PythonSession.class.getClassLoader();
    InputStream in = loader.getResourceAsStream( "py/pyCheck.py" );
    if ( in == null ) {
      throw new IOException( "Unable to read the pyCheck.py script as a resource" );
    }

    String tmpDir = System.getProperty( "java.io.tmpdir" );
    // System.err.println( "******* System tmp dir: " + tmpDir );
    File tempDir = new File( tmpDir );
    String pyCheckDest = tmpDir + File.separator + "pyCheck.py";
    String pyServerDest = tmpDir + File.separator + "pyServer.py";

    PrintWriter outW = null;
    BufferedReader inR = null;
    try {
      outW = new PrintWriter( new BufferedWriter( new FileWriter( pyCheckDest ) ) );
      inR = new BufferedReader( new InputStreamReader( in ) );
      String line;
      while ( ( line = inR.readLine() ) != null ) {
        outW.println( line );
      }
      outW.flush();
      outW.close();
      inR.close();

      in = loader.getResourceAsStream( "py/pyServer.py" );
      outW = new PrintWriter( new BufferedWriter( new FileWriter( pyServerDest ) ) );
      inR = new BufferedReader( new InputStreamReader( in ) );
      while ( ( line = inR.readLine() ) != null ) {
        outW.println( line );
      }
    } catch ( IOException ex ) {
      ex.printStackTrace();
      throw ex;
    } finally {
      if ( outW != null ) {
        outW.flush();
        outW.close();
      }
      if ( inR != null ) {
        inR.close();
      }
    }

    return tempDir;
  }

  /**
   * Private constructor
   *
   * @param pythonCommand the command used to start python
   * @throws IOException if a problem occurs
   */
  private PythonSession( String pythonCommand ) throws IOException {
    m_pythonCommand = pythonCommand;
    s_sessionSingleton = null;
    s_pythonEnvCheckResults = "";

    // Read scripts from classpath and write them to tmp.
    /* String
        tester =
        m_kettlePluginDir + File.separator + File.separator + "resources" + File.separator + "py" + File.separator
            + "pyCheck.py"; */
    File tmpDir = installPyScriptsToTmp();
    m_osTmpDir = tmpDir.toString();
    String tester = m_osTmpDir + File.separator + "pyCheck.py";
    ProcessBuilder builder = new ProcessBuilder( pythonCommand, tester );
    Process pyProcess = builder.start();
    StringWriter writer = new StringWriter();
    IOUtils.copy( pyProcess.getInputStream(), writer );
    s_pythonEnvCheckResults = writer.toString();
    m_shutdown = false;

    // launch the server socket and python server
    if ( s_pythonEnvCheckResults.length() < 5 ) {
      launchServer( true );
      s_sessionSingleton = this;
    }
  }

  /**
   * Gets the access to python for a requester. Handles locking.
   *
   * @param requester the requesting object
   * @return the session
   * @throws SessionException if python is not available
   */
  private synchronized PythonSession getSession( Object requester ) throws SessionException {
    if ( s_sessionSingleton == null ) {
      throw new SessionException( "Python not available!" );
    }

    if ( s_sessionHolder == requester ) {
      return this;
    }

    m_mutex.safeLock();
    s_sessionHolder = requester;
    return this;
  }

  /**
   * Release the session for a requester
   *
   * @param requester the requesting object
   */
  private void dropSession( Object requester ) {
    if ( requester == s_sessionHolder ) {
      s_sessionHolder = null;
      m_mutex.unlock();
    }
  }

  /**
   * Launches the python server. Performs some basic requirements checks for the
   * python environment - e.g. python needs to have numpy, pandas and sklearn
   * installed.
   *
   * @param startPython true if the server is to actually be started. False is
   *                    really just for debugging/development where the server can be
   *                    manually started in a separate terminal
   * @throws IOException if a problem occurs
   */
  private void launchServer( boolean startPython ) throws IOException {
    if ( m_log != null ) {
      m_log.logDebug( "Launching server socket..." );
    }
    m_serverSocket = new ServerSocket( 0 );
    m_serverSocket.setSoTimeout( 10000 );
    int localPort = m_serverSocket.getLocalPort();
    if ( m_log != null ) {
      m_log.logDebug( "Local port: " + localPort );
    } else {
      System.err.println( "Local port: " + localPort );
    }
    Thread acceptThread = new Thread() {
      @Override public void run() {
        try {
          m_localSocket = m_serverSocket.accept();
        } catch ( IOException e ) {
          m_localSocket = null;
        }
      }
    };
    acceptThread.start();

    if ( startPython ) {
      /*String
          serverScript =
          m_kettlePluginDir + File.separator + "resources" + File.separator + "py" + File.separator + "pyServer.py"; */
      String serverScript = m_osTmpDir + File.separator + "pyServer.py";
      boolean debug = m_log != null && m_log.isDebug();
      ProcessBuilder
          processBuilder =
          new ProcessBuilder( m_pythonCommand, serverScript, "" + localPort, debug ? "debug" : "" );
      m_serverProcess = processBuilder.start();
    }
    try {
      acceptThread.join();
    } catch ( InterruptedException e ) {
    }

    if ( m_localSocket == null ) {
      shutdown();
      throw new IOException( "Was unable to start python server" );
    } else {
      m_pythonPID = ServerUtils.receiveServerPIDAck( m_localSocket.getInputStream() );

      m_shutdownHook = new Thread() {
        @Override public void run() {
          shutdown();
        }
      };
      Runtime.getRuntime().addShutdownHook( m_shutdownHook );
    }
  }

  public void setLog( LogChannelInterface log ) {
    m_log = log;
  }

  /**
   * Initialize the session. This needs to be called exactly once in order to
   * run checks and launch the server. Creates a session singleton. Assumes python
   * is in the PATH; alternatively, can specify full path to python exe via the java
   * property or system environment variable pentaho.cpython.command.
   *
   * @param pythonCommand the python command
   * @param vars          Kettle variables
   * @param log           logging
   * @return true if the server launched successfully
   * @throws KettleException if there was a problem - missing packages in python,
   *                         or python could not be started for some reason
   */
  public static synchronized boolean initSession( String pythonCommand, VariableSpace vars, LogChannelInterface log )
      throws KettleException {

    if ( s_sessionSingleton != null ) {
      return true;
      // throw new KettleException( BaseMessages.getString( ServerUtils.PKG, "PythonSession.Error.EnvAlreadyAvailable" ) );
    }

    if ( vars != null && !Const.isEmpty( vars.getVariable( KETTLE_CPYTHON_COMMAND_PROPERTY_KEY ) ) ) {
      pythonCommand = vars.getVariable( KETTLE_CPYTHON_COMMAND_PROPERTY_KEY );
      File pyExe = new File( pythonCommand );
      if ( !pyExe.exists() || !pyExe.isFile() ) {
        throw new KettleException( "Python exe: " + pythonCommand + " does not seem to exist on the " + "filesystem!" );
      }
    } else if ( System.getProperty( CPYTHON_COMMAND_PROPERTY_KEY ) != null ) {
      pythonCommand = System.getProperty( CPYTHON_COMMAND_PROPERTY_KEY );
      File pyExe = new File( pythonCommand );
      if ( !pyExe.exists() || !pyExe.isFile() ) {
        throw new KettleException( "Python exe: " + pythonCommand + " does not seem to exist on the " + "filesystem!" );
      }
    } else if ( System.getenv( CPYTHON_COMMAND_ENV_VAR_KEY ) != null ) {
      pythonCommand = System.getenv( CPYTHON_COMMAND_ENV_VAR_KEY );
      File pyExe = new File( pythonCommand );
      if ( !pyExe.exists() || !pyExe.isFile() ) {
        throw new KettleException( "Python exe: " + pythonCommand + " does not seem to exist on the " + "filesystem!" );
      }
    }

    log.logDebug( "Python command: " + pythonCommand );
    String path = System.getenv( "PATH" );
    if ( path != null && path.length() > 0 ) {
      log.logDebug( "PATH: " + path );
    }
    try {
      new PythonSession( pythonCommand );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }

    return s_pythonEnvCheckResults.length() < 5;
  }

  /**
   * Gets the result of running the checks in python
   *
   * @return a string containing the possible errors
   */
  public static String getPythonEnvCheckResults() {
    return s_pythonEnvCheckResults;
  }

  /**
   * Transfer Kettle rows into python as a named pandas data frame
   *
   * @param rowMeta         the metadata of the rows
   * @param rows            the rows to transfer
   * @param pythonFrameName the name of the data frame to use in python
   * @throws KettleException if a problem occurs
   */
  public void rowsToPythonDataFrame( RowMetaInterface rowMeta, List<Object[]> rows, String pythonFrameName )
      throws KettleException {
    try {
      ServerUtils.sendRowsToPandasDataFrame( m_log, rowMeta, rows, pythonFrameName, m_localSocket.getOutputStream(),
          m_localSocket.getInputStream() );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Transfer a pandas data frame from python and convert into Kettle rows and metadata
   *
   * @param frameName       the name of the pandas data frame to get
   * @param includeRowIndex true to include the pandas data frame row index as a field
   * @return rows and row metadata encapsulated in a RowMetaAndRows object
   * @throws KettleException if a problem occurs
   */
  public RowMetaAndRows rowsFromPythonDataFrame( String frameName, boolean includeRowIndex ) throws KettleException {
    try {
      return ServerUtils
          .receiveRowsFromPandasDataFrame( m_log, frameName, includeRowIndex, m_localSocket.getOutputStream(),
              m_localSocket.getInputStream() );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Check if a named variable is set in pythong
   *
   * @param pyVarName the name of the python variable to check for
   * @return true if the named variable exists in the python environment
   * @throws KettleException if a problem occurs
   */
  public boolean checkIfPythonVariableIsSet( String pyVarName ) throws KettleException {
    try {
      return ServerUtils.checkIfPythonVariableIsSet( m_log, pyVarName, m_localSocket.getInputStream(),
          m_localSocket.getOutputStream() );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Grab the contents of the debug buffer from the python server. The server
   * redirects both sys out and sys err to StringIO objects. If debug has been
   * specified, then server debugging output will have been collected in these
   * buffers. Note that the buffers will potentially also contain output from
   * the execution of arbitrary scripts too. Calling this method also resets the
   * buffers.
   *
   * @return the contents of the sys out and sys err streams. Element 0 in the
   * list contains sys out and element 1 contains sys err
   * @throws KettleException if a problem occurs
   */
  public List<String> getPythonDebugBuffer() throws KettleException {
    try {
      return ServerUtils.receiveDebugBuffer( m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Get the type of a variable (according to pre-defined types that we can do something with) in python
   *
   * @param varName the name of the variable to get the type of
   * @return whether the variable is a DataFrame, Image, String or Unknown. DataFrames will be converted to rows; Images
   * (png form) and Strings are output as a single row with fields for each variable value. Unknown types will be
   * returned in their string form.
   * @throws KettleException if a problem occurs
   */
  public PythonVariableType getPythonVariableType( String varName ) throws KettleException {
    try {
      return ServerUtils
          .getPythonVariableType( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Execute a python script.
   *
   * @param pyScript the script to execute
   * @return a List of strings - index 0 contains std out from the script and
   * index 1 contains std err
   * @throws KettleException if a problem occurs
   */
  public List<String> executeScript( String pyScript ) throws KettleException {
    try {
      return ServerUtils
          .executeUserScript( pyScript, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Get an image from python. Assumes that the image is a matplotlib.figure.Figure object. Retrieves this as png
   * data and returns a BufferedImage
   *
   * @param varName the name of the variable containing the image in python
   * @return the image as a BufferedImage
   * @throws KettleException if a problem occurs
   */
  public BufferedImage getImageFromPython( String varName ) throws KettleException {
    try {
      return ServerUtils
          .getPNGImageFromPython( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Get the value of a variable from python in plain text form
   *
   * @param varName the name of the variable to get
   * @return the value of the variable
   * @throws KettleException if a problem occurs
   */
  public String getVariableValueFromPythonAsPlainString( String varName ) throws KettleException {
    try {
      return ServerUtils
          .receivePickledVariableValue( varName, m_localSocket.getOutputStream(), m_localSocket.getInputStream(), true,
              m_log );
    } catch ( IOException ex ) {
      throw new KettleException( ex );
    }
  }

  /**
   * Shutdown the python server
   */
  private void shutdown() {
    if ( !m_shutdown ) {
      try {
        m_shutdown = true;
        if ( m_localSocket != null ) {
          if ( m_log == null ) {
            System.err.println( "Sending shutdown command..." );
          } else if ( m_log.isDebug() ) {
            m_log.logDebug( "Sending shutdown command..." );
          }
          if ( m_log == null || m_log.isDebug() ) {
            List<String>
                outAndErr =
                ServerUtils
                    .receiveDebugBuffer( m_localSocket.getOutputStream(), m_localSocket.getInputStream(), m_log );
            if ( outAndErr.get( 0 ).length() > 0 ) {
              if ( m_log == null ) {
                System.err.println( "Python debug std out:\n" + outAndErr.get( 0 ) + "\n" );
              } else {
                m_log.logDebug( "Python debug std out:\n" + outAndErr.get( 0 ) + "\n" );
              }
            }
            if ( outAndErr.get( 1 ).length() > 0 ) {
              if ( m_log == null ) {
                System.err.println( "Python debug std err:\n" + outAndErr.get( 1 ) + "\n" );
              } else {
                m_log.logDebug( "Python debug std err:\n" + outAndErr.get( 1 ) + "\n" );
              }
            }
          }
          ServerUtils.sendServerShutdown( m_localSocket.getOutputStream() );
          m_localSocket.close();
          if ( m_serverProcess != null ) {
            m_serverProcess.destroy();
            m_serverProcess = null;
          }
        }

        if ( m_serverSocket != null ) {
          m_serverSocket.close();
        }
        s_sessionSingleton = null;
      } catch ( Exception ex ) {
        ex.printStackTrace();
        if ( m_pythonPID > 0 ) {
          // try to kill process, just in case
          ProcessBuilder killer;
          if ( System.getProperty( "os.name" ).toLowerCase().contains( "win" ) ) {
            killer = new ProcessBuilder( "taskkill", "/F", "/PID", "" + m_pythonPID );
          } else {
            killer = new ProcessBuilder( "kill", "-9", "" + m_pythonPID );
          }
          try {
            killer.start();
          } catch ( IOException e ) {
            e.printStackTrace();
          }
        }
      } finally {
        if ( m_serverProcess != null ) {
          m_serverProcess.destroy();
        }
      }
    }
  }

  public static void main( String[] args ) {
    try {

/*      File tmp = PythonSession.installPyScriptsToTmp();
      System.err.println( tmp ); */

      if ( !PythonSession.initSession( "python", null, null ) ) {
        System.err.print( "Initialization failed!" );
        System.exit( 1 );
      }

      String temp = "";
      PythonSession session = PythonSession.acquireSession( temp );

      Object[] rowData = { 22, 300.22, "Hello bob", false, new Date(), new Timestamp( new Date().getTime() ), null };
      RowMetaInterface rowMeta = new RowMeta();
      //rowMeta.addValueMeta( new ValueMeta( "Field1", ValueMetaInterface.TYPE_INTEGER ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field1", ValueMetaInterface.TYPE_INTEGER ) );
      //rowMeta.addValueMeta( new ValueMeta( "Field2", ValueMetaInterface.TYPE_NUMBER ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field2", ValueMetaInterface.TYPE_NUMBER ) );
      // rowMeta.addValueMeta( new ValueMeta( "Field3", ValueMetaInterface.TYPE_STRING ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field3", ValueMetaInterface.TYPE_STRING ) );
      // rowMeta.addValueMeta( new ValueMeta( "Field4", ValueMetaInterface.TYPE_BOOLEAN ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field4", ValueMetaInterface.TYPE_BOOLEAN ) );
      // rowMeta.addValueMeta( new ValueMeta( "Field5", ValueMetaInterface.TYPE_DATE ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field5", ValueMetaInterface.TYPE_DATE ) );
      // rowMeta.addValueMeta( new ValueMeta( "Field6", ValueMetaInterface.TYPE_TIMESTAMP ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "Field6", ValueMetaInterface.TYPE_TIMESTAMP ) );
      // rowMeta.addValueMeta( new ValueMeta( "NullField", ValueMetaInterface.TYPE_STRING ) );
      rowMeta.addValueMeta( ValueMetaFactory.createValueMeta( "NullField", ValueMetaInterface.TYPE_STRING ) );

      List<Object[]> data = new ArrayList<Object[]>();
      data.add( rowData );
      session.rowsToPythonDataFrame( rowMeta, data, "test" );

      if ( session.checkIfPythonVariableIsSet( "test" ) ) {
        RowMetaAndRows fromPy = session.rowsFromPythonDataFrame( "test", false );
        System.err.println( "Nubmer of field metas returned: " + fromPy.m_rowMeta.size() );
        System.err.println( "Number of rows returned: " + fromPy.m_rows.length );
        for ( ValueMetaInterface v : fromPy.m_rowMeta.getValueMetaList() ) {
          System.err.println( "Col: " + v.getName() + " Type: " + v.getType() );
        }
      } else {
        System.err.println( "Variable 'test' does not seem to be set in python!!!!" );
      }

      session.executeScript( "x = 100\n" );
      if ( session.checkIfPythonVariableIsSet( "x" ) ) {
        System.err.println( "Var x is set!" );
      }
      PythonVariableType t = session.getPythonVariableType( "x" );
      System.err.println( "X is of type " + t.toString() );
    } catch ( Exception ex ) {
      ex.printStackTrace();
    }
  }
}


text:
namespace scv {

ComponentSpring::ComponentSpring(Component *component, int min, int pref, int max) : Spring() {
   _component = component;

   _min = min;
   _pref = pref;
   _max = max;
}

int ComponentSpring::calculateMinimumSize(Axis axis) {
   if (!isVisible()) {
      return 0;
   }
   if (_min >= 0) {
      return _min;
   }
   if (_min == PREFERRED_SIZE) {
      return calculatePreferredSize(axis);
   }
   assert (_min == DEFAULT_SIZE);
   return getSizeAlongAxis(axis, _component->getMinimumSize());
}

int ComponentSpring::calculatePreferredSize(Axis axis) {
   if (!isVisible()) {
      return 0;
   }
   if (_pref >= 0) {
      return _pref;
   }
   assert (_pref == DEFAULT_SIZE || _pref == PREFERRED_SIZE);
   return getSizeAlongAxis(axis, _component->getPreferredSize());
}

int ComponentSpring::calculateMaximumSize(Axis axis) {
   if (!isVisible()) {
      return 0;
   }
   if (_max >= 0) {
      return _max;
   }
   if (_max == PREFERRED_SIZE) {
      return calculatePreferredSize(axis);
   }
   assert (_max == DEFAULT_SIZE);
   return getSizeAlongAxis(axis, _component->getMaximumSize());
}

void ComponentSpring::setSize(Axis axis, int origin, int size) {
   Spring::setSize(axis, origin, size);
   switch (axis) {
   case Spring::HORIZONTAL:
      _component->setRelativePosition(Point(origin, _component->getRelativePosition().y));
      _component->setWidth(size);
      break;
   case Spring::VERTICAL:
      _component->setRelativePosition(Point(_component->getRelativePosition().x, origin));
      _component->setHeight(size);
      break;
   }
}

int ComponentSpring::getSizeAlongAxis(Axis axis, scv::Point size) {
   return (axis == HORIZONTAL)? size.x : size.y;
}

} //namespace scv


text:
namespace carto {

    GeocodingResult::GeocodingResult(const std::shared_ptr<Projection>& projection, const GeocodingAddress& address, float rank, const std::shared_ptr<FeatureCollection>& featureCollection) :
        _address(address),
        _rank(rank),
        _featureCollection(featureCollection),
        _projection(projection)
    {
        if (!featureCollection) {
            throw NullArgumentException("Null geometry");
        }
        if (!projection) {
            throw NullArgumentException("Null projection");
        }
    }

    GeocodingResult::~GeocodingResult() {
    }

    const GeocodingAddress& GeocodingResult::getAddress() const {
        return _address;
    }

    float GeocodingResult::getRank() const {
        return _rank;
    }

    const std::shared_ptr<FeatureCollection>& GeocodingResult::getFeatureCollection() const {
        return _featureCollection;
    }

    const std::shared_ptr<Projection>& GeocodingResult::getProjection() const {
        return _projection;
    }

    std::string GeocodingResult::toString() const {
        std::stringstream ss;
        ss << std::setiosflags(std::ios::fixed);
        ss << "GeocodingResult [";
        ss << "rank=" << _rank << ", ";
        ss << "address=" << _address.toString();
        ss << "]";
        return ss.str();
    }

}

#endif


text:
layout: post
title: "Pigeons and Madame Knip"
date: 2017-04-07 20:20:00 +0000
tags:
image: https://s3.amazonaws.com/hackedu/2017-04-07-pigeon.jpg
imagecredits: https://www.flickr.com/photos/43158397@N02/5483422385
---

From an article published by the Smithsonian Libraries, "Publishing, Pretense, and Pigeons: The Case of Madame Knip":

It is unfortunate that Madame Knip is now better remembered for her "sundry alterations" to Les Pigeons than for her beautiful art. But perhaps her story of pigeon-based subterfuge will make you consider your grey feathered friends in a different light!


text:
require 'spec_helper'

describe DeliverySugar::DSL do
  let(:example_knife_rb) { File.join(SUPPORT_DIR, 'example_knife.rb') }
  let(:example_config) do
    Chef::Config.from_file(example_knife_rb)
    config = Chef::Config.save
    Chef::Config.reset
    config
  end
  let(:custom_workspace) { '/var/my/awesome/workspace' }
  let(:default_workspace) { '/workspace' }

  subject do
    Object.new.extend(described_class)
  end

  before do
    allow_any_instance_of(DeliverySugar::DSL).to receive(:node)
      .and_return(cli_node)
  end

  describe '#automate_knife_rb' do
    context 'when node attribute is set from the delivery-cli' do
      before { cli_node['delivery']['workspace_path'] = custom_workspace }
      it 'returns the custom delivery knife.rb' do
        expect(subject.automate_knife_rb).to eq("#{custom_workspace}/.chef/knife.rb")
      end
    end

    context 'when node attribute is not set' do
      it 'returns the default delivery knife.rb' do
        expect(subject.automate_knife_rb).to eq("#{default_workspace}/.chef/knife.rb")
      end
    end
  end

  describe '#workflow_workspace' do
    context 'when node attribute is set from the delivery-cli' do
      before { cli_node['delivery']['workspace_path'] = custom_workspace }
      it 'returns the custom workspace' do
        expect(subject.workflow_workspace).to eq(custom_workspace)
      end
    end

    context 'when old version of delivery-cli sets partial attribute' do
      it 'returns the default workspace' do
        expect(subject.workflow_workspace).to eq(default_workspace)
      end
    end

    context 'when node attribute is not set' do
      it 'returns the default workspace' do
        expect(subject.workflow_workspace).to eq(default_workspace)
      end
    end
  end

  describe '#with_server_config' do
    before do
      allow_any_instance_of(DeliverySugar::DSL).to receive(:delivery_knife_rb)
        .and_return(example_knife_rb)
    end

    it 'runs code block with the chef server\'s Chef::Config' do
      block = lambda do
        subject.with_server_config do
          Chef::Config[:chef_server_url]
        end
      end
      expect(Chef::Config[:chef_server_url])
        .not_to eql(example_config[:chef_server_url])
      expect(block.call).to match(example_config[:chef_server_url])
    end
  end

  describe '#run_recipe_against_automate_chef_server' do
    before do
      allow_any_instance_of(DeliverySugar::DSL).to receive(:delivery_knife_rb)
        .and_return(example_knife_rb)
    end

    it 'calls chef_server.load_server_config' do
      subject.run_recipe_against_automate_chef_server
      expect(Chef::Config[:chef_server_url]).to eql(example_config[:chef_server_url])
    end
  end

  describe '#get_all_project_cookbooks' do
    it 'calls get_all_project_cookbooks on the change object' do
      expect(subject).to receive_message_chain(:change,
                                               :get_all_project_cookbooks)
      subject.get_all_project_cookbooks
    end
  end

  describe '#define_project_application' do
    it 'calls define_project_application on the change object' do
      expect(subject).to receive_message_chain(:change,
                                               :define_project_application)
      subject.define_project_application('test', '1.2.3', {})
    end
  end

  describe '#get_project_application' do
    it 'calls get_project_application on the change object' do
      expect(subject).to receive_message_chain(:change,
                                               :get_project_application)
      subject.get_project_application('test')
    end
  end

  describe '.changed_cookbooks' do
    it 'gets a list of changed cookbook from the change object' do
      expect(subject).to receive_message_chain(:change,
                                               :changed_cookbooks)
      subject.changed_cookbooks
    end
  end

  describe '.changed_files' do
    it 'gets a list of changed files from the change object' do
      expect(subject).to receive_message_chain(:change, :changed_files)
      subject.changed_files
    end
  end

  describe '.changed_dirs' do
    let(:depth) { 1 }
    it 'gets a list of changed directories based on the changed files' do
      expect(subject).to receive_message_chain(:change, :changed_dirs).with(depth)
      subject.changed_dirs(depth)
    end
  end

  describe '.change_log' do
    it 'gets a list of commit log entries' do
      expect(subject).to receive_message_chain(:change, :change_log)
      subject.change_log
    end
  end

  describe '.automate_chef_server_details' do
    let(:chef_server_configuration) { double 'a configuration hash' }

    it 'returns a cheffish configuration for interacting with the chef server' do
      expect(subject).to receive_message_chain(:automate_chef_server, :cheffish_details)
        .and_return(chef_server_configuration)

      expect(subject.automate_chef_server_details).to eql(chef_server_configuration)
    end
  end

  describe '.workflow_chef_environment_for_stage' do
    it 'get the current environment from the Change object' do
      expect(subject).to receive_message_chain(:change,
                                               :environment_for_current_stage)
      subject.workflow_chef_environment_for_stage
    end
  end

  describe '.workflow_project_acceptance_environment' do
    it 'gets the acceptance environment for the pipeline from the change object' do
      expect(subject).to receive_message_chain(:change,
                                               :acceptance_environment)
      subject.workflow_project_acceptance_environment
    end
  end

  describe '.workflow_project_slug' do
    it 'gets slug from Change object' do
      expect(subject).to receive_message_chain(:change, :project_slug)
      subject.workflow_project_slug
    end
  end

  describe '.get_project_secrets' do
    let(:project_slug) { 'ent-org-proj' }
    let(:data_bag_contents) do
      {
        'id' => 'ent-org-proj',
        'secret' => 'password',
      }
    end

    it 'gets the secrets from the project level' do
      expect(subject).to receive_message_chain(:change, :project_slug)
        .and_return(project_slug)
      expect(subject)
        .to receive_message_chain(:automate_chef_server, :data_bag_item)
        .with('delivery-secrets', project_slug, nil).and_return(data_bag_contents)

      expect(subject.get_project_secrets).to eql(data_bag_contents)
    end
  end

  describe '.get_organization_secrets' do
    let(:organization_slug) { 'ent-org' }
    let(:data_bag_contents) do
      {
        'id' => 'ent-org',
        'secret' => 'password',
      }
    end

    it 'gets the secrets from the organization level' do
      expect(subject).to receive_message_chain(:change, :organization_slug)
        .and_return(organization_slug)
      expect(subject)
        .to receive_message_chain(:automate_chef_server, :data_bag_item)
        .with('delivery-secrets', organization_slug, nil).and_return(data_bag_contents)

      expect(subject.get_organization_secrets).to eql(data_bag_contents)
    end
  end

  describe '.get_chef_vault' do
    it 'returns a Chef Vault item' do
      allow(subject)
        .to receive_message_chain(:automate_chef_server, :chef_vault_item)
        .with('workflow-vaults', 'ent')
        .and_return(id: 'ent', data: 'data')

      expect(subject.get_chef_vault('workflow-vaults', 'ent'))
        .to eql(id: 'ent', data: 'data')
    end
  end

  describe '.get_chef_vault_data_list' do
    let(:node) do
      {
        'delivery_builder' => {
          'build_user' => 'dbuild',
        },
        'delivery' => {
          'workspace' => {
            'repo' => 'workspace_repo',
            'cache' => 'workspace_cache',
            'chef' => 'workspace_chef',
          },
          'change' => {
            'stage' => 'stage_name',
            'enterprise' => 'ent',
            'organization' => 'org',
            'project' => 'proj',
            'pipeline' => 'pipe',
            'patchset_branch' => 'patchset_branch',
            'sha' => '',
          },
        },
      }
    end

    let(:enterprise_vault) do
      { id: 'ent', ent_data: 'data' }
    end

    let(:organization_vault) do
      { id: 'ent-org', org_data: 'data' }
    end

    let(:project_vault) do
      { id: 'ent-org-proj', project_data: 'data' }
    end

    before do
      allow(subject).to receive(:change).and_return(DeliverySugar::Change.new(node))
      allow_any_instance_of(DeliverySugar::DSL).to receive(:delivery_knife_rb)
        .and_return(example_knife_rb)
    end

    context 'when all vaults are present' do
      let(:chef_vault_data_list) do
        [enterprise_vault, organization_vault, project_vault]
      end

      before do
        allow(ChefVault::Item).to receive(:load)
          .with('workflow-vaults', 'ent')
          .and_return(enterprise_vault)
        allow(ChefVault::Item).to receive(:load)
          .with('workflow-vaults', 'ent-org')
          .and_return(organization_vault)
        allow(ChefVault::Item).to receive(:load)
          .with('workflow-vaults', 'ent-org-proj')
          .and_return(project_vault)
      end

      it 'returns a complete list of Chef Vaults' do
        expect(subject.get_chef_vault_data_list).to eql(chef_vault_data_list)
      end
    end

    context 'when a vault is missing' do
      let(:incomplete_chef_vault_data_list) do
        [enterprise_vault, organization_vault, {}]
      end

      before do
        allow(ChefVault::Item).to receive(:load)
          .with('workflow-vaults', 'ent')
          .and_return(enterprise_vault)
        allow(ChefVault::Item).to receive(:load)
          .with('workflow-vaults', 'ent-org')
          .and_return(organization_vault)
        allow(ChefVault::Item).to receive(:load)
          .with('workflow-vaults', 'ent-org-proj')
          .and_raise(ChefVault::Exceptions::KeysNotFound)
      end

      it 'returns a list of Chef Vaults containing an empty hash' do
        expect(subject.get_chef_vault_data_list).to eql(incomplete_chef_vault_data_list)
      end
    end
  end

  describe '.get_chef_vault_data' do
    let(:vault_data_list) do
      [
        { ent_data: 'from_ent_vault', overwritten: 'no' },
        { org_data: 'from_org_vault', overwritten: 'no' },
        { project_data: 'from_project_vault', overwritten: 'yes' },
      ]
    end

    let(:merged_vault_data) do
      {
        ent_data: 'from_ent_vault',
        org_data: 'from_org_vault',
        project_data: 'from_project_vault',
        overwritten: 'yes',
      }
    end

    it 'returns a merged hash of Chef Vault data' do
      allow(subject).to receive(:get_chef_vault_data_list).and_return(vault_data_list)
      expect(subject.get_chef_vault_data).to eql(merged_vault_data)
    end
  end

  describe '.enterprise_slug' do
    it 'gets slug from Change object' do
      expect(subject).to receive_message_chain(:change, :enterprise_slug)
      subject.enterprise_slug
    end
  end
end


text:
import {
  defaultCanvasHeight,
  defaultCanvasWidth,
  doublePi,
  isIE8,
  isRuntimeSupported,
  orientationSupport,
  piBy180,
  regExp,
} from '@/src/common/constants'

test('piBy180', () => {
  expect(piBy180).toBe(Math.PI / 180)
})

test('doublePi', () => {
  expect(doublePi).toBe(Math.PI * 2)
})

test('default Canvas dimension', () => {
  expect(defaultCanvasWidth).toBe(485)
  expect(defaultCanvasHeight).toBe(300)
})

test('isIE8', () => {
  expect(isIE8).toBe(false)
})

test('isRuntimeSupported', () => {
  expect(isRuntimeSupported).toBe(true)
})

test('orientationSupport', () => {
  expect(orientationSupport).toBe(false)
})

test('regExp.trimAll', () => {
  function trimAll(str: string) {
    return str.replace(regExp.trimAll, '')
  }
  expect(trimAll(' a \f \n  \r\t\v b ')).toBe('ab')
})

test('regExp.http', () => {
  expect(regExp.http.test('http://')).toBeTruthy()
  expect(regExp.http.test('http://example.com')).toBeTruthy()
  expect(regExp.http.test('https://')).toBeTruthy()
  expect(regExp.http.test('https://example.com')).toBeTruthy()
  expect(regExp.http.test('//example.com')).toBeTruthy()

  expect(regExp.http.test('http:/')).toBeFalsy()
  expect(regExp.http.test('https:/')).toBeFalsy()
  expect(regExp.http.test('xhttp://')).toBeFalsy()
  expect(regExp.http.test('xhttps://')).toBeFalsy()
  expect(regExp.http.test('/example.com')).toBeFalsy()
})

test('regExp.shapeStar', () => {
  expect(regExp.shapeStar.test('star')).toBeTruthy()
  expect(regExp.shapeStar.test('star:5:0.5')).toBeTruthy()
  expect(regExp.shapeStar.test('star:50:50')).toBeTruthy()

  expect(regExp.shapeStar.test('xstar')).toBeFalsy()
  expect(regExp.shapeStar.test('start')).toBeFalsy()
  expect(regExp.shapeStar.test('star:')).toBeFalsy()
  expect(regExp.shapeStar.test('star:5')).toBeFalsy()
  expect(regExp.shapeStar.test('star:5:')).toBeFalsy()
  expect(regExp.shapeStar.test('star:5:0..05')).toBeFalsy()
  expect(regExp.shapeStar.test('star:5:0.5:')).toBeFalsy()
})

test('regExp.imageBase64', () => {
  expect(regExp.imageBase64.test('data:image/png;base64,')).toBeTruthy()
  expect(regExp.imageBase64.test('data:image/png;base64,')).toBeTruthy()
  expect(regExp.imageBase64.test('data:image/jpg;base64,i')).toBeTruthy()
  expect(regExp.imageBase64.test('data:image/jpeg;base64,i')).toBeTruthy()
  expect(regExp.imageBase64.test('data:image/gif;base64,i')).toBeTruthy()
  expect(regExp.imageBase64.test('data:image/svg+xml;base64,i')).toBeTruthy()

  expect(regExp.imageBase64.test('data:image/png;base64')).toBeFalsy()
  expect(regExp.imageBase64.test('xdata:image/png;base64,')).toBeFalsy()
})


text:
    overflow: visible;
}

#typesetting-hmenu .topNav {
    padding-left: 0;
}

.btnBar {
    margin-left: 100px;
}
ul.projectNav > li {
    background: #777 none repeat scroll 0% 0%;
    display: inline-block;
    margin-top: 2px;
    margin-right: 7px;
}

.projectNav {
    margin-top: 50px;
}
ul.projectNav a {
    color: #FFF;
    display: block;
    padding: 6px 12px;
    text-decoration: none;
}
ul.projectNav li:hover {
    background: #08C none repeat scroll 0% 0%;
}
hr {
    height: 1px;
    background-color: #DCDCDC;
    border: 0px;
}
.row {
    margin-left: 0px !important;
}
.inline-block  div {
    display: inline-block;
}


text:
package steno

import (
	"runtime"
	"strings"
	"time"
)

// FIXME: Missing fields
type Record struct {
	Timestamp float64
	Message   string
	Level     LogLevel
	Data      map[string]string
	File      string
	Method    string
	Line      int
}

func NewRecord(level LogLevel, message string, data map[string]string) *Record {
	record := new(Record)

	record.Timestamp = float64(time.Now().UnixNano()) / 1000000000
	record.Message = message
	record.Level = level
	record.Data = data

	if config.EnableLOC {
		var function *runtime.Func
		var file string
		var line int

		pc := make([]uintptr, 50)
		nptrs := runtime.Callers(2, pc)
		for i := 0; i < nptrs; i++ {
			function = runtime.FuncForPC(pc[i])
			file, line = function.FileLine(pc[i])
			if !strings.HasSuffix(file, "logger.go") {
				break
			}
		}
		record.File = file
		record.Method = function.Name()
		record.Line = line
	}

	return record
}


text:
var marked = require('marked');
var htmlparser = require("htmlparser2");
var toHTML = require("./lib/toHTML.js");
function MC(mcStr) {
  var result = "";
  var mdStr = marked(mcStr.replace(/{{/g, "<css>").replace(/}}/g, "</css>"));
  var handler = new htmlparser.DomHandler(function (error, dom) {
    if (error) {
      return result;
    } else {
      result = toHTML(dom);
    }
  });
  var parser = new htmlparser.Parser(handler);
  parser.write(mdStr);
  parser.done();
  return result;
}

module.exports = MC;


text:
module Elmas
  # We can use the AgingReceivablesList to change the status of SalesInvoices from
  # Open to 'Verwerkt' while at the same time sending a PDF of the invoice to the
  # end user by e-mail.
  #
  # This endpoint only supports the POST method.
  #
  class AgingReceivablesList
    include Elmas::Resource

    def valid_actions
      [:get]
    end

    def base_path
      "read/financial/AgingReceivablesList"
    end

    def mandatory_attributes
      []
    end

    # https://start.exactonline.nl/docs/HlpRestAPIResourcesDetails.aspx?name=SalesInvoiceAgingReceivablesLists
    def other_attributes
      [
        :account_id, :account_code, :account_name, :age_group1, :age_group1_amount, :age_group1_description,
        :age_group2, :age_group2_amount, :age_group2_description, :age_group3, :age_group3_amount, :age_group3_description,
        :age_group4, :age_group4_amount, :age_group4_description, :currency_code, :total_amount
      ]
    end
  end
end


text:
<?php

namespace Shop\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * UserRoleLinker
 *
 * @ORM\Table(name="user_role_linker", indexes={@ORM\Index(name="role_id", columns={"role_id"})})
 * @ORM\Entity
 */
class UserRoleLinker
{
    /**
     * @var \Shop\Entity\UserRole
     *
     * @ORM\ManyToOne(targetEntity="Shop\Entity\UserRole")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=true)
     * })
     */
    private $role;

    /**
     * @var \Shop\Entity\User
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Shop\Entity\User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
     * })
     */
    private $user;

    /**
     * Set role
     *
     * @param \Shop\Entity\UserRole $role
     *
     * @return UserRoleLinker
     */
    public function setRole(\Shop\Entity\UserRole $role = null)
    {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return \Shop\Entity\UserRole
     */
    public function getRole()
    {
        return $this->role;
    }

    /**
     * Set user
     *
     * @param \Shop\Entity\User $user
     *
     * @return UserRoleLinker
     */
    public function setUser(\Shop\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Shop\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
//
//   Copyright 2016  Cityzen Data
//
//   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 io.warp10.script.functions;

import io.warp10.WarpConfig;
import io.warp10.continuum.Configuration;
import io.warp10.continuum.store.Constants;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptLib;
import io.warp10.script.WarpScriptStack;
import io.warp10.script.WarpScriptStackFunction;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.google.common.base.Charsets;

/**
 * Execute WarpScript on a remote endpoint
 */
public class REXEC extends NamedWarpScriptFunction implements WarpScriptStackFunction {

  private final boolean enabled;

  private final boolean compress;

  public REXEC(String name) {
    this(name, false);
  }

  public REXEC(String name, boolean compress) {
    super(name);

    this.compress = compress;

    Properties props = WarpConfig.getProperties();

    this.enabled = null != props && "true".equals(props.getProperty(Configuration.WARPSCRIPT_REXEC_ENABLE));
  }

  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {

    if (!this.enabled) {
      throw new WarpScriptException(getName() + " is not enabled, set '" + Configuration.WARPSCRIPT_REXEC_ENABLE + "' to true to enable it.");
    }

    String endpoint = stack.pop().toString();

    String warpscript = stack.pop().toString();

    HttpURLConnection conn = null;

    try {
      URL url = new URL(endpoint);

      if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) {
        throw new WarpScriptException(getName() + " invalid endpoint protocol.");
      }

      conn = (HttpURLConnection) url.openConnection();
      conn.setChunkedStreamingMode(8192);
      conn.setRequestProperty("Accept-Encoding", "gzip");

      if (this.compress) {
        conn.setRequestProperty("Content-Type", "application/gzip");
      }

      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");

      OutputStream connout = conn.getOutputStream();
      OutputStream out = connout;

      if (this.compress) {
        out = new GZIPOutputStream(out);
      }

      out.write(warpscript.getBytes(Charsets.UTF_8));
      out.write('\n');
      out.write(WarpScriptLib.SNAPSHOT.getBytes(Charsets.UTF_8));
      out.write('\n');
      out.write(WarpScriptLib.TOOPB64.getBytes(Charsets.UTF_8));
      out.write('\n');

      if (this.compress) {
        out.close();
      }

      connout.flush();

      InputStream in = conn.getInputStream();

      if ("gzip".equals(conn.getContentEncoding())) {
        in = new GZIPInputStream(in);
      }

      if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) {
        throw new WarpScriptException(getName() + " remote execution encountered an error: " + conn.getHeaderField(Constants.getHeader(Constants.HTTP_HEADER_ERROR_MESSAGE_DEFAULT)));
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      byte[] buf = new byte[1024];

      while(true) {
        int len = in.read(buf);
        if (len < 0) {
          break;
        }
        baos.write(buf, 0, len);
      }

      byte[] bytes = baos.toByteArray();

      // Strip '[ ' ' ]'
      String result = new String(bytes, 2, bytes.length - 4, Charsets.US_ASCII);

      stack.push(result);

      stack.exec(WarpScriptLib.OPB64TO);
      stack.push("UTF-8");
      stack.exec(WarpScriptLib.BYTESTO);
      stack.exec(WarpScriptLib.EVAL);

    } catch (WarpScriptException e) {
      throw e;
    } catch (Exception e) {
      throw new WarpScriptException(e);
    } finally {
      if (null != conn) {
        conn.disconnect();
      }
    }

    return stack;
  }
}


text:
module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '..',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'chai'],

    // list of files / patterns to load in the browser
    files: [
      'integration-test/*.test.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {

    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeApp'],

    customLaunchers: {
      ChromeCanaryApp: {
        base: 'ChromeCanary',
        // flags: ['--load-and-launch-app=chrome-app']
      },
      ChromeApp: {
        base: 'Chrome',
        flags: [
          // '--load-and-launch-app=chrome-app',
          '--no-first-run',
          '--no-sandbox'
        ]
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};


text:
package org.thingml.compilers.uml;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;

import org.thingml.compilers.Context;
import org.thingml.compilers.configuration.CfgMainGenerator;
import org.thingml.xtext.constraints.ThingMLHelpers;
import org.thingml.xtext.helpers.ActionHelper;
import org.thingml.xtext.helpers.AnnotatedElementHelper;
import org.thingml.xtext.helpers.ConfigurationHelper;
import org.thingml.xtext.helpers.ThingHelper;
import org.thingml.xtext.thingML.Configuration;
import org.thingml.xtext.thingML.Connector;
import org.thingml.xtext.thingML.Enumeration;
import org.thingml.xtext.thingML.EnumerationLiteral;
import org.thingml.xtext.thingML.ExternExpression;
import org.thingml.xtext.thingML.ExternStatement;
import org.thingml.xtext.thingML.ExternalConnector;
import org.thingml.xtext.thingML.Function;
import org.thingml.xtext.thingML.Instance;
import org.thingml.xtext.thingML.InternalPort;
import org.thingml.xtext.thingML.Message;
import org.thingml.xtext.thingML.ObjectType;
import org.thingml.xtext.thingML.Parameter;
import org.thingml.xtext.thingML.PlatformAnnotation;
import org.thingml.xtext.thingML.Port;
import org.thingml.xtext.thingML.PrimitiveType;
import org.thingml.xtext.thingML.Property;
import org.thingml.xtext.thingML.Protocol;
import org.thingml.xtext.thingML.ProvidedPort;
import org.thingml.xtext.thingML.Thing;
import org.thingml.xtext.thingML.ThingMLModel;
import org.thingml.xtext.thingML.Type;

/**
 * Created by bmori on 10.12.2014.
 */
public class PlantUMLCfgMainGenerator extends CfgMainGenerator {

	private Set<String> classes = new HashSet<>();
	private Set<String> includes = new HashSet<>();

	private void generateIncludes(Thing thing, StringBuilder classes) {
		for (Thing include : thing.getIncludes()) {
			if(!includes.contains(include.getName() + "<" + thing.getName())) {
				classes.append(include.getName());
				classes.append(" <|-- ");
				classes.append(thing.getName());
				classes.append("\n");
				includes.add(include.getName() + "<" + thing.getName());
			}
			generateIncludes(include, classes);
		}
	}

	private boolean isPSM(Thing thing) {
		boolean result = ThingMLHelpers.getAllExpressions(thing, ExternExpression.class).size() > 0 || ActionHelper.getAllActions(thing, ExternStatement.class).size() > 0;
		if (result)
			return result;
		for (Thing t : ThingHelper.allIncludedThings(thing)) {
			if (isPSM(t))
				return true;
		}
		return false;
	}

	private boolean isGUI(Thing thing) {
		return AnnotatedElementHelper.isDefined(thing,"mock", "true");
	}

	private void generateClass(Thing thing, StringBuilder classes, Context ctx, boolean compact) throws UnsupportedEncodingException {
		if (!this.classes.contains(thing.getName())) {
			this.classes.add(thing.getName());
			if (thing.isFragment()) {
				classes.append("class " + thing.getName() + " <<(F,#BC74ED)Fragment>> {\n");
			} else if (isGUI(thing)) {
				classes.append("class " + thing.getName() + " <<(G,#5394FC)GUI>> {\n");
			}
			else if(isPSM(thing)) {//PSM
				classes.append("class " + thing.getName() + " <<(T,#F94918)PSM>> {\n");
			} else {//PIM
				classes.append("class " + thing.getName() + " <<(T,#5BBF09)PIM>> {\n");
			}

			if (!compact) { // Do not include properties in the compact version
				if (thing.getProperties().size() > 0)
					classes.append("..Properties..\n");
				for (Property p : thing.getProperties()) {
					classes.append("-" + p.getName() + " : " + p.getTypeRef().getType().getName());
					if (p.getInit() != null) {
						classes.append(" = ");
						ctx.getCompiler().getThingActionCompiler().generate(p.getInit(), classes, ctx);
					}
					classes.append("\n");
				}
			}

			if (thing.getMessages().size() > 0)
				classes.append("..Messages..\n");
			for (Message m : thing.getMessages()) {
				classes.append("-" + m.getName() + "(");
				if (compact) {
					if (m.getParameters().size() > 0)
						classes.append("...");
				} else {
					for (Parameter p : m.getParameters()) {
						if (m.getParameters().indexOf(p) > 0)
							classes.append(", ");
						classes.append(p.getName() + " : " + p.getTypeRef().getType().getName());
					}
				}
				classes.append(")");
				classes.append("\n");
			}

			for (Port p : thing.getPorts()) {
				if (p instanceof InternalPort) {
					classes.append("..▶  Port " + p.getName() + " ◀ ..\n");
				} else {
					final String type = (p instanceof ProvidedPort) ? "▲" : "▼";
					classes.append(".." + type + " Port " + p.getName() + " " + type +"..\n");
				}
				for (Message m : p.getReceives()) {
					classes.append("▶ " + m.getName() + "\n");
				}
				for (Message m : p.getSends()) {
					classes.append("◀ " + m.getName() + "\n");
				}
			}

			if (!compact) { // Do not include functions in the compact version
				if (thing.getFunctions().size() > 0)
					classes.append("..Functions..\n");
				for (Function f : thing.getFunctions()) {
					classes.append("-" + f.getName() + "(");
					if (compact) {
						if (f.getParameters().size() > 0)
							classes.append("...");
					} else {
						for (Parameter p : f.getParameters()) {
							if (f.getParameters().indexOf(p) > 0)
								classes.append(", ");
							classes.append(p.getName() + " : " + p.getTypeRef().getType().getName());
						}
					}
					classes.append(") : ");
					if (f.getTypeRef() != null && f.getTypeRef().getType() != null) {
						classes.append(f.getTypeRef().getType().getName());
					} else {
						classes.append("void");
					}
					classes.append("\n");
				}
			}

			classes.append("}\n");

			/* Remove annotation from the diagrams. We should have a way to configure the generator
			 *  either using more annotations, e.g. @uml_show "annoatations" or some global settings for the generator
			 */

			/*
            if (thing.getAnnotations().size() > 0)
                classes.append("note left of " + thing.getName() + " : ");
            for(PlatformAnnotation a : thing.getAnnotations()) {
                classes.append("@" + a.getName() + "");
                if (a.getValue().length() > 16 || a.getValue().contains("\n"))
                	classes.append(" <color:royalBlue>\"...\"</color>\\n");
                else
                	classes.append(" <color:royalBlue>\"" + a.getValue().replace("\n", "\\n") + "\"</color>\\n");
            }
            if (thing.getAnnotations().size() > 0)
                classes.append("\n");
			 */

			for (Thing include : thing.getIncludes()) {
				generateClass(include, classes, ctx, compact);
			}
		}
	}

	String getLabel(Instance i) {
		return "[" + i.getName() + " : " + i.getType().getName() + "]";
	}

	@Override
	public void generateMainAndInit(Configuration cfg, ThingMLModel model, Context ctx) {
		//Instance component diagram
		final StringBuilder builder = ctx.getBuilder(cfg.getName() + ".plantuml");
		builder.append("@startuml\n");
		builder.append("caption Instances and Connectors in configuration " + cfg.getName() + "\n");
		for (Instance i : ConfigurationHelper.allInstances(cfg)) {
			builder.append("component " + getLabel(i) + (isGUI(i.getType())?"<<GUI>>":isPSM(i.getType())?"<<PSM>>":"<<PIM>>") + "\n");
		}
		for(Protocol p : ConfigurationHelper.getUsedProtocols(cfg)) {
			builder.append("boundary " + p.getName() + "\n");
		}
		for (Connector c : ConfigurationHelper.allConnectors(cfg)) {
			builder.append(getLabel(c.getCli()) + " -(0- " + getLabel(c.getSrv()) + " : " +
					c.getRequired().getName() + " => " + c.getProvided().getName() + "\n");
		}
		for (ExternalConnector c : ConfigurationHelper.getExternalConnectors(cfg)) {
			builder.append(getLabel(c.getInst()) + " .. " + c.getProtocol().getName() + " : " + c.getPort().getName() + "\n");
		}
		builder.append("@enduml");

		//Type/Thing class diagram
		final StringBuilder classes = ctx.getBuilder("detailed/" + cfg.getName() + "_class.plantuml");
		final StringBuilder classes2 = ctx.getBuilder(cfg.getName() + "_class.plantuml");
		classes.append("@startuml\n");
		classes.append("caption Things used in configuration " + cfg.getName() + "\n");
		classes2.append("@startuml\n");
		classes2.append("caption Things used in configuration " + cfg.getName() + "\n");
		try {
			this.classes.clear();
			for(Thing thing : ConfigurationHelper.allThings(cfg)) {
				generateClass(thing, classes, ctx, false);
			}
			this.classes.clear();
			for(Thing thing : ConfigurationHelper.allThings(cfg)) {
				generateClass(thing, classes2, ctx, true);
			}
		} catch (Exception e) {
			System.err.println("Error while generating class diagrams");
			e.printStackTrace();
		}
		this.includes.clear();
		for(Thing thing : ConfigurationHelper.allThings(cfg)) {
			generateIncludes(thing, classes);
		}
		this.includes.clear();
		for(Thing thing : ConfigurationHelper.allThings(cfg)) {
			generateIncludes(thing, classes2);
		}
		classes.append("@enduml");
		classes2.append("@enduml");

		final StringBuilder datatypes = ctx.getBuilder(cfg.getName() + "_datatypes.plantuml");
		datatypes.append("@startuml\n");
		datatypes.append("caption Datatypes used in configuration " + cfg.getName() + "\n");
		for(Type t : ThingMLHelpers.allUsedSimpleTypes(ThingMLHelpers.findContainingModel(cfg))) {
			if (t instanceof PrimitiveType) {
				datatypes.append("class " + t.getName() + " <<(D,#D2E524)" + ((PrimitiveType) t).getByteSize() + ">> {\n");
			} else if (t instanceof  ObjectType){
				datatypes.append("class " + t.getName() + " <<(O,#E5D224)>> {\n");
			} else if (t instanceof  Enumeration) {
				datatypes.append("class " + t.getName() + " <<(E,#24E5B2)>> {\n");
				final Enumeration e = (Enumeration)t;
				for(EnumerationLiteral l : e.getLiterals()) {
					datatypes.append("-" + l.getName() + "\n");
				}
			}
			datatypes.append("}\n");
			if (t.getAnnotations().size() > 0)
				datatypes.append("note bottom of " + t.getName() + " : ");
			for(PlatformAnnotation a : t.getAnnotations()) {
				datatypes.append("@" + a.getName() + "");
				if (AnnotatedElementHelper.toString(a.getValue()) != null) {
					if (AnnotatedElementHelper.toString(a.getValue()).length() > 16 || AnnotatedElementHelper.toString(a.getValue()).contains("\n"))
						datatypes.append(" <color:royalBlue>\"...\"</color>\\n");
					else
						datatypes.append(" <color:royalBlue>\"" + AnnotatedElementHelper.toString(a.getValue()).replace("\n", "\\n") + "\"</color>\\n");
				}
			}
			if (t.getAnnotations().size() > 0)
				datatypes.append("\n");
		}
		datatypes.append("@enduml");

		//TODO: Protocols

	}
}