text:
class CreateCoursewareableAssignments < ActiveRecord::Migration
  def change
    create_table :coursewareable_assignments do |t|
      t.string :slug, :null => false
      t.string :title
      t.text :content
      t.text :quiz
      t.references :lecture
      t.references :user
      t.references :classroom

      t.timestamps
    end
    add_index :coursewareable_assignments, :lecture_id
    add_index :coursewareable_assignments, :user_id
    add_index :coursewareable_assignments, :classroom_id
    add_index :coursewareable_assignments, :slug, :unique => true
  end
end


text:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('./config')
const os = require('os')
const HappyPack = require('happypack')
const happyThreadPool = HappyPack.ThreadPool({size: os.cpus().length})
const { VueLoaderPlugin } = require('vue-loader')
const vueLoaderConfig = require('./vue-loader.conf')

const createLintingRule = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [utils.resolve('src')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

const base = {
  context: path.resolve(__dirname, '../'),
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath:
      process.env.NODE_ENV === 'production'
        ? config.build.assetsPublicPath
        : config.dev.assetsPublicPath,
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      // 目录别名
      '@': utils.resolve('src'),
      '@static': utils.resolve('static'),
      '@assets': utils.resolve('src/assets'),
      '@less': utils.resolve('src/assets/less'),
      '@js': utils.resolve('src/assets/js'),
      '@components': utils.resolve('src/components'),
      '@mixins': utils.resolve('src/mixins'),
      '@filters': utils.resolve('src/filters'),
      '@store': utils.resolve('src/store'),
      '@views': utils.resolve('src/views'),

      // 文件别名
      'services': utils.resolve('src/services'),
      'variable': utils.resolve('src/assets/less/variable.less'),
      'utils': utils.resolve('node_modules/@liwb/cloud-utils/dist/cloud-utils.esm'),
      'mixins': utils.resolve('node_modules/magicless/magicless.less')
    }
  },
  module: {
    noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/,
    rules: [
      ...(config.dev.useEslint? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.(js|jsx)$/,
        use: ['happypack/loader?id=happybabel'],
        // see the website https://github.com/vuejs-templates/webpack/issues/1140
        include: [utils.resolve('src'), utils.resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        include: [utils.resolve('src')],
        options: {
          limit: 10000,
          name: utils.assetsPath('images/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        include: [utils.resolve('src')],
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        include: [utils.resolve('src')],
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  plugins: [
    // 开启 happypack 的线程池
    // 原有的 webpack 对 loader 的执行过程从单一进程的形式扩展多进程模式,原本的流程保持不变
    new HappyPack({
      id: 'happybabel',
      loaders: [
        {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true
          }
        }
      ],
      threadPool: happyThreadPool,
      verbose: true
    }),
    new VueLoaderPlugin()
  ],
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

if (process.env.NODE_ENV !== 'dll') {
  base.entry = {
    app: config.directory.src + '/main.js'
  }
}

module.exports = base;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Paypal\Controller;

/**
 * Payflow Checkout Controller
 */
abstract class Payflow extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $_orderFactory;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @var \Magento\Paypal\Model\PayflowlinkFactory
     */
    protected $_payflowModelFactory;

    /**
     * @var \Magento\Paypal\Helper\Checkout
     */
    protected $_checkoutHelper;

    /**
     * Redirect block name
     * @var string
     */
    protected $_redirectBlockName = 'payflow.link.iframe';

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Paypal\Model\PayflowlinkFactory $payflowModelFactory
     * @param \Magento\Paypal\Helper\Checkout $checkoutHelper
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Paypal\Model\PayflowlinkFactory $payflowModelFactory,
        \Magento\Paypal\Helper\Checkout $checkoutHelper,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_checkoutSession = $checkoutSession;
        $this->_orderFactory = $orderFactory;
        $this->_logger = $logger;
        $this->_payflowModelFactory = $payflowModelFactory;
        $this->_checkoutHelper = $checkoutHelper;
        parent::__construct($context);
    }

    /**
     * Cancel order, return quote to customer
     *
     * @param string $errorMsg
     * @return false|string
     */
    protected function _cancelPayment($errorMsg = '')
    {
        $gotoSection = false;
        $this->_checkoutHelper->cancelCurrentOrder($errorMsg);
        if ($this->_checkoutSession->restoreQuote()) {
            //Redirect to payment step
            $gotoSection = 'paymentMethod';
        }

        return $gotoSection;
    }
}


text:
function appFactory () {

  function createApp (config) {

    var app = {}

    return app

  }

  return createApp

}


text:
<tool id='gate.ner_2.0.0' name='GATE Named Entity Recognizer' version='2.0.0'>
    <description>Adds entity annotations (Date, Person, Location, Organization). Require Token+POS</description>
    <requirements>
        <requirement type='package' version='2.2.1'>lsdsl</requirement>
    </requirements>
    <command interpreter='lsd'>invoke.lsd gate.ner_2.0.0 $input $output $username $password</command>
    <inputs>
        <param name='input' type='data' label='input' format='gate' />
        <param name='username' type='text' label='Username' value='tester' />
        <param name='password' type='text' label='Password' value='tester' />
    </inputs>
    <outputs>
        <data name='output' format='gate' />
    </outputs>
    <tests>
        <test>
            <param name='input' value='gazetteer-expected.gate' />
            <param name='username' value='tester' />
            <param name='password' value='tester' />
            <output name='output' file='ner-expected.gate' ftype='gate' />
        </test>
    </tests>
    <help>Adds entity annotations (Date, Person, Location, Organization). Require Token+POS</help>
    <citations>
        <citation type='bibtex'>@Book{Cunningham2011a,
  author = {Hamish Cunningham and Diana Maynard and Kalina Bontcheva and Valentin Tablan and Niraj Aswani and Ian Roberts and
    Genevieve Gorrell and Adam Funk and Angus Roberts and Danica Damljanovic and Thomas Heitz and Mark A. Greenwood and
    Horacio Saggion and Johann Petrak and Yaoyong Li and Wim Peters},
  title = {{Text Processing with GATE (Version 6)}},
  isbn = {978-0956599315},
  year = 2011,
  url = {http://tinyurl.com/gatebook}
}
</citation>
    </citations>
</tool>


text:
OpenGLExample::OpenGLExample(gloperate::ResourceManager & resourceManager)
:   Painter(resourceManager)
,   m_targetFramebufferCapability(addCapability(new gloperate::TargetFramebufferCapability()))
,   m_viewportCapability(addCapability(new gloperate::ViewportCapability()))
,   m_projectionCapability(addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability)))
,   m_cameraCapability(addCapability(new gloperate::CameraCapability()))
{
}

OpenGLExample::~OpenGLExample() = default;

void OpenGLExample::setupProjection()
{
    //static const auto zNear = 0.3f, zFar = 15.f, fovy = 50.f;
}

void OpenGLExample::onInitialize()
{
    // create program

    globjects::init();

#ifdef __APPLE__
    globjects::Shader::clearGlobalReplacements();
    globjects::Shader::globalReplace("#version 140", "#version 150");

    globjects::debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif

    m_texture = new globjects::Texture;
    // void image2D(gl::GLint level, gl::GLenum internalFormat, gl::GLsizei width, gl::GLsizei height, gl::GLint border, gl::GLenum format, gl::GLenum type, const gl::GLvoid * data);
    m_texture->image2D(0, gl::GL_RGBA, m_viewportCapability->width(), m_viewportCapability->height(), 0, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, nullptr);

    m_fbo = new globjects::Framebuffer;
    m_fbo->attachTexture(gl::GL_COLOR_ATTACHMENT0, m_texture, 0);

    m_vertices = new globjects::Buffer;
    m_vertices->setData(std::vector<float>{
        -0.8f, -0.8f,
        0.8f, -0.8f,
        0.8f, 0.8f
    }, gl::GL_STATIC_DRAW);

    m_vao = new globjects::VertexArray;

    auto binding = m_vao->binding(0);
    binding->setAttribute(0);
    binding->setBuffer(m_vertices, 0, 2 * sizeof(float));
    binding->setFormat(2, gl::GL_FLOAT);

    m_vao->enable(0);

    m_program = new globjects::Program;
    m_program->attach(
        globjects::Shader::fromFile(gl::GL_VERTEX_SHADER, "data/openglexample/shader.vert"),
        globjects::Shader::fromFile(gl::GL_FRAGMENT_SHADER, "data/openglexample/shader.frag")
    );

    gl::glClearColor(1.0, 1.0, 1.0, 1.0);

    m_fbo->unbind();
}

void OpenGLExample::onPaint()
{
    if (m_viewportCapability->hasChanged())
    {
        m_texture->image2D(0, gl::GL_RGBA, m_viewportCapability->width(), m_viewportCapability->height(), 0, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, nullptr);

        m_viewportCapability->setChanged(false);
    }

    gl::glViewport(0, 0, m_viewportCapability->width() / 4, m_viewportCapability->height() / 4);

    m_vao->bind();
    m_program->use();

    m_fbo->bind();

    gl::glClear(gl::GL_COLOR_BUFFER_BIT);

    gl::glDrawArrays(gl::GL_TRIANGLES, 0, 3);

    std::array<int, 4> sourceRect = {{ 0, 0, m_viewportCapability->width() / 4, m_viewportCapability->height() / 4 }};
    std::array<int, 4> destRect = {{ 0, 0, m_viewportCapability->width(), m_viewportCapability->height() }};

    globjects::Framebuffer * targetFBO = m_targetFramebufferCapability->framebuffer() ? m_targetFramebufferCapability->framebuffer() : globjects::Framebuffer::defaultFBO();

    m_fbo->blit(gl::GL_COLOR_ATTACHMENT0, sourceRect, targetFBO, gl::GL_BACK_LEFT, destRect, gl::GL_COLOR_BUFFER_BIT, gl::GL_NEAREST);

    m_fbo->unbind();
}


text:
<?php
/**
 * @package    Adminimize
 * @subpackage Admininmiz Options for the settings page
 * @author     Frank Bültge
 * @since      2016-02-26
 */
if ( ! function_exists( 'add_action' ) ) {
	die( "Hi there!  I'm just a part of plugin, not much I can do when called directly." );
}
?>

		<div class="handlediv" title="<?php esc_attr_e( 'Click to toggle' ); ?>">

<?php esc_attr_e( 'Plugin Settings', 'adminimize' ) ?>

							<?php esc_attr_e( 'Active Debug Helper', 'adminimize' ); ?>

						<input type="checkbox" value="1" id="mw_adminimize_debug"
							name="mw_adminimize_debug" <?php checked(
							_mw_adminimize_get_option_value( 'mw_adminimize_debug' ),
							1, TRUE ); ?>>
						<?php esc_attr_e( 'After activation is it possible to see several information inside the console of the browser for the current active user.', 'adminimize' ); ?>

							<?php esc_attr_e( 'Support Multiple Roles', 'adminimize' ); ?>

						<input type="checkbox" value="1" id="mw_adminimize_multiple_roles"
							name="mw_adminimize_multiple_roles" <?php checked(
							_mw_adminimize_get_option_value( 'mw_adminimize_multiple_roles' ),
							1, TRUE ); ?>>
						<?php esc_attr_e( 'A user with multiple roles must have an option selected for all roles in order to hide the selected option. If the option is unselected for any of the user's roles, then the item will appear.', 'adminimize' ); ?>

							<?php esc_attr_e( 'Support bbPress Roles', 'adminimize' ); ?>

						<input type="checkbox" value="1" id="mw_adminimize_support_bbpress"
							name="mw_adminimize_support_bbpress" <?php checked(
							_mw_adminimize_get_option_value( 'mw_adminimize_support_bbpress' ),
							1,
							TRUE ); ?>>
						<?php esc_attr_e( 'See the bbPress roles also in each area to hide for this context.', 'adminimize' ); ?>

				<input type="hidden" name="_mw_adminimize_action" value="_mw_adminimize_insert" />
				<input class="button button-primary" type="submit" name="_mw_adminimize_save" value="<?php esc_attr_e(
					'Update Options', 'adminimize'
				); ?> »" /><input type="hidden" name="page_options" value="'dofollow_timeout'" />

				<?php esc_attr_e(
						'scroll to top', 'adminimize'
					); ?>


text:
require 'test_helper'

class ViolationsHelperTest < ActionView::TestCase
end


text:
package org.apache.deltaspike.jsf.spi.scope.window;

import javax.faces.context.FacesContext;
import java.io.Serializable;

/**
 * Configuration for ClientWindow handler which is used
 * to determine the correct windowId for ?WindowScoped beans.
 */
public interface ClientWindowConfig extends Serializable
{
    public enum ClientWindowRenderMode
    {
        /**
         * Any window or browser tab detection is disabled for this request
         */
        NONE,

        /**
         *
The GET request results in an intermediate small html page which
         * checks if the browser tab fits the selected windowId

         *
The ClientWindow html extracts the windowId from the window.name and
         * enforces a 2nd GET which will contain the windowId and will get routed
         * through to the target JSF page.

         */
        CLIENTWINDOW,

        /**
         * Render each GET request with the windowId you get during the request
         * and perform a lazy check on the client side via JavaScript or similar.
         */
        LAZY,

        /**
         * Delegates to the default window-handling of JSF 2.2+ (if configured)
         */
        DELEGATED,

        /**
         * If you set this mode, you also need to provide an own {@link ClientWindow} implementation.
         */
        CUSTOM

    }

    /**
     * @return whether JavaScript is enabled
     */
    boolean isJavaScriptEnabled();

    /**
     * @param javaScriptEnabled whether JavaScript is enabled
     */
    void setJavaScriptEnabled(boolean javaScriptEnabled);

    /**
     * Determine whether this request should take care of clientWindow detection.
     * This can e.g. get disabled for download pages or if a useragent doesn't
     * support html5 or any other required technique.
     * This only gets checked for GET requests!
     *
     * @param facesContext
     * @return the selected ClientWindowRenderMode
     */
    ClientWindowRenderMode getClientWindowRenderMode(FacesContext facesContext);

    /**
     * @return the prepared html which gets sent out to the client as intermediate client window.
     */
    String getClientWindowHtml();

    /**
     * @return Whether the DOM tree should stored in the localStorage for the windowhandler.html
     *         when clicking on a link.
     *         Currently it's only used by {@link ClientWindowRenderMode#CLIENTWINDOW}.
     * @see windowhandler.html
     */
    boolean isClientWindowStoreWindowTreeEnabledOnLinkClick();

    /**
     * @return Whether the DOM tree should stored in the localStorage for the windowhandler.html
     *         when clicking on a button.
     *         Currently it's only used by {@link ClientWindowRenderMode#CLIENTWINDOW}.
     * @see windowhandler.html
     */
    boolean isClientWindowStoreWindowTreeEnabledOnButtonClick();

    boolean isClientWindowTokenizedRedirectEnabled();

    /**
     * Restricts the number of active windows.
     *
     * @return limit for active windows
     */
    int getMaxWindowContextCount();
}


text:
run_spec(__dirname, ["flow"]);
run_spec(__dirname, ["flow"], { trailingComma: "all" });


text:
package mx.skyguardian.unigis.integration.quartz;

import mx.skyguardian.unigis.integration.business.GurtamUNIGISIntegrator;
import mx.skyguardian.unigis.integration.exception.GurtamRemoteAPIException;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class GurtamUnigisQuartzJob extends QuartzJobBean {
	private GurtamUNIGISIntegrator unigisIntegrator = null;
	private static Logger log = Logger.getLogger(GurtamUnigisQuartzJob.class);

	@Override
	 protected void executeInternal(JobExecutionContext arg0)  throws JobExecutionException {

		try {
			unigisIntegrator.sendEvent2UNIGIS();
		} catch (JSONException e) {

			e.printStackTrace();
		} catch (GurtamRemoteAPIException e) {
			e.printStackTrace();
		} catch (Exception e) {

			e.printStackTrace();
		}

	 }

	public GurtamUNIGISIntegrator getUnigisIntegrator() {
		return unigisIntegrator;
	}

	public void setUnigisIntegrator(GurtamUNIGISIntegrator unigisIntegrator) {
		this.unigisIntegrator = unigisIntegrator;
	}
}


text:
$: << File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))

require 'yaml'
require 'ingenia_api'

def demo(name)
  puts "\n\n"
  puts "#\n# #{name}\n#"

  output = yield

  puts "output:#{output.to_yaml}"
end

def main
  Ingenia::Api.api_key = "API_KEY"

  # Classify some text
  demo "classify" do
    Ingenia::Api.classify "What kind of cheese is the best cheese?"
  end

  # Train text onto the default tagset
  demo "train simple" do
    Ingenia::Api.train "I like cheeses", [ 'food', 'preference', 'cheese' ]
  end

  # Train into two specific tagsets
  demo "train complex" do
    Ingenia::Api.train "Is it safe to eat cheese from goats?", { :Cookery => [ 'cheese', 'safety' ], :post_type => [ 'question' ] }
  end

  demo "find items similar to your first item" do
    first_item = Ingenia::Item.all.first

    puts Ingenia::Api.similar_to(:id => first_item['id'])
  end

end

main if $0 == __FILE__


text:
@ParametersAreNonnullByDefault
package org.sonar.plugins.resharper;

import javax.annotation.ParametersAreNonnullByDefault;


text:
<?php

namespace yiithings\deploy\migration;

use yiithings\develop\helpers\MigrateHelper;

/**
 * Migration class file.
 */
class Migration extends \yii\db\Migration
{
    /**
     * @var string the table options
     */
    protected $tableOptions = '';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        if ($this->db->driverName === 'mysql') {
            $this->tableOptions = 'ENGINE=InnoDB CHARACTER SET=utf8 COLLATE=utf8_unicode_ci;SET GLOBAL FOREIGN_KEY_CHECKS = 0;';
        }
    }

    protected function preEncodeSql($sql)
    {
        return MigrateHelper::replaceTablePrefix($sql);
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.EventGrid.Models
{
    public partial class SystemTopicPatch : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            if (Optional.IsDefined(Identity))
            {
                writer.WritePropertyName("identity");
                JsonSerializer.Serialize(writer, Identity);
            }
            writer.WriteEndObject();
        }
    }
}


text:
/* CUBE demo toolkit by MasterM/Asenses */

#pragma once

#define CUBE_LOG(fmt, ...) Core::System::Instance()->Log(fmt, ##__VA_ARGS__)

namespace CUBE {

class FileNotify;
enum class PlacementMode;

typedef std::function<bool (float, float)> RenderFunction;
typedef std::function<void ()> KeyHandler;

namespace Core {

class UI;
class Config;

class System
{
private:
	 char        name[100];
	 bool        paused;
	 GLFWwindow* window;
	 HSTREAM     stream;
	 std::string contentDirectory;

	 std::map<int, KeyHandler> keyHandlers;

	 struct {
		 GLuint vao;
		 GLuint vbo;
	 } ScreenQuad;

	 mutable struct {
		 GLuint frameTimeQuery;
		 std::string SceneName;
	 } DebugInfo;

	 System();
private:
	 void UpdateDebugInfo(const GLuint64 frameTime);
	 void SetDefaults();

	 void CreateScreenQuadVAO();
	 void DeleteScreenQuadVAO();

	 static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
public:
	 static System* Instance();
	 class  FileNotify* NotifyService;
	 class  UI* UI;
public:
	 void Init();
	 void Terminate();

	 void Error(const char* error);
	 void Log(const char* fmt, ...);

	 void UseOpenGL(const int major, const int minor);

	 void OpenStream(const char* path);
	 void OpenDisplay(const int width, const int height, bool fullscreen);

	 void  SetName(const char* name);
	 void  GetDisplaySize(int& w, int& h);
	 float GetDisplayAspect();

	 float GetTime();
	 void  Seek(const float delta);

	 void  TogglePlayback();
	 void  ToggleUI();
	 void  ArrangeUI(PlacementMode placement);

	 void  RegisterKey(int key, KeyHandler handler);
	 void  UnregisterKey(int key);

	 void  DrawScreenQuad() const;

	 void  Run(RenderFunction renderFunction);

	 bool SetContentDirectory(const std::string& path);
	 const std::string& GetContentDirectory() const;

	 void Debug_SetSceneName(const char* name) const;

	 static void ClearErrorGL();
	 static void CheckErrorGL(const char* call, const char* file, const int line);
	 static void HandleException(const std::exception& e);
};

} // Global

extern class Core::System*  System;
extern class Core::Config*  Config;
extern class Core::UI*      UI;

} // CUBE


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:musical="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:background="@color/light"
            android:layout_height="match_parent">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:orientation="vertical"
            android:padding="20dp">

        <LinearLayout
                android:id="@+id/external_services"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/card_bg_play"
                android:orientation="vertical"
                android:padding="10dp">

            <com.musical.views.TypefaceTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/title_apis"
                    android:textSize="20sp"
                    musical:customTypeface="fonts/Roboto-Thin.ttf"/>

            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:weightSum="100">

                <ImageView
                        android:id="@+id/item_echonest"
                        android:layout_width="0dp"
                        android:layout_weight="45"
                        android:layout_gravity="center"
                        android:scaleType="fitCenter"
                        android:layout_height="wrap_content"
                        android:clickable="true"
                        android:src="@drawable/echonest"/>

                <Space android:layout_width="0dp" android:layout_weight="10" android:layout_height="match_parent"/>

                <ImageView
                        android:id="@+id/item_google"
                        android:layout_width="0dp"
                        android:layout_weight="45"

                        android:layout_gravity="center"
                        android:scaleType="fitCenter"
                        android:layout_height="wrap_content"
                        android:clickable="true"
                        android:src="@drawable/google_logo"/>
            </LinearLayout>
        </LinearLayout>

        <Space android:layout_width="match_parent" android:layout_height="20dp"/>

        <LinearLayout
                android:id="@+id/item_me"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/card_bg_play"
                android:orientation="vertical"
                android:padding="10dp">

            <com.musical.views.TypefaceTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/title_me"
                    android:textSize="20sp"
                    musical:customTypeface="fonts/Roboto-Thin.ttf"/>

            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="3">

                <ImageView
                        android:id="@+id/twitter_button"
                        android:layout_width="0dp"
                        android:layout_height="50dp"
                        android:layout_weight="1"
                        android:scaleType="centerInside"
                        android:src="@drawable/twitter"/>

                <ImageView
                        android:id="@+id/google_button"
                        android:layout_width="0dp"
                        android:layout_height="50dp"
                        android:layout_weight="1"
                        android:scaleType="centerInside"
                        android:src="@drawable/googleplus"/>

                <ImageView
                        android:id="@+id/linkedin_button"
                        android:layout_width="0dp"
                        android:layout_height="50dp"
                        android:layout_weight="1"
                        android:scaleType="centerInside"
                        android:src="@drawable/linkedin"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</ScrollView>


text:
import Emitter from 'tiny-emitter';
import Session from '../app/scripts/models/session.js';
import io from 'socket.io-client';

describe('session', function () {

  let session;
  let connect;
  let socket;

  before(function () {
    connect = sinon.stub(io, 'connect');
    socket = new Emitter();
    connect.returns(socket);
  });

  beforeEach(function () {
    session = new Session({
      url: 'http://localhost:8080',
      roomCode: 'ABCD'
    });
  });

  afterEach(function () {
    socket.off('my-event');
  });

  after(function () {
    connect.restore();
  });

  it('should initialize', function () {
    expect(session).to.have.property('url', 'http://localhost:8080');
    expect(session).to.have.property('roomCode', 'ABCD');
    expect(session).to.have.property('localPlayerId', null);
  });

  it('should not be connected by default', function () {
    expect(session).to.have.property('connected', false);
  });

  it('should not be disconnected by default', function () {
    expect(session).to.have.property('disconnected', false);
  });

  it('should connect', function () {
    session.connect();
    expect(connect).to.have.been.calledWith(session.url);
    expect(session).to.have.property('status', 'connecting');
    expect(session).to.have.property('socket', socket);
  });

  it('should disconnect', function () {
    socket.disconnect = sinon.stub();
    session.connect();
    session.disconnect();
    expect(socket.disconnect).to.have.been.calledWith();
    delete socket.disconnect;
  });

  it('should queue emit until connected', function () {
    session.localPlayerId = '356cd624-2c40-465c-9f4a-91f52c2705f3';
    const callback = sinon.stub();
    socket.on('my-event', ({ foo, playerId }) => {
      expect(foo).to.equal('bar');
      expect(playerId).to.equal(session.localPlayerId);
      callback();
    });
    session.emit('my-event', { foo: 'bar' });
    expect(callback).not.to.have.been.called;
    session.connect();
    expect(callback).to.have.been.called;
  });

  it('should emit immediately if already connected', function () {
    session.localPlayerId = '356cd624-2c40-465c-9f4a-91f52c2705f3';
    const callback = sinon.stub();
    socket.on('my-event', ({ foo, playerId }) => {
      expect(foo).to.equal('bar');
      expect(playerId).to.equal(session.localPlayerId);
      callback();
    });
    session.connect();
    session.emit('my-event', { foo: 'bar' });
    expect(callback).to.have.been.called;
  });

  it('should queue listener until connected', function () {
    const callback = sinon.stub();
    session.on('my-event', ({ foo }) => {
      expect(foo).to.equal('bar');
      callback();
    });
    socket.emit('my-event', { foo: 'bar' });
    expect(callback).not.to.have.been.called;
    session.connect();
    socket.emit('my-event', { foo: 'bar' });
    expect(callback).to.have.been.called;
  });

  it('should add listener immediately if already connected', function () {
    const callback = sinon.stub();
    session.connect();
    session.on('my-event', ({ foo }) => {
      expect(foo).to.equal('bar');
      callback();
    });
    socket.emit('my-event', { foo: 'bar' });
    expect(callback).to.have.been.called;
  });

});


text:
<!DOCTYPE html>

    <title>Pipeline</title>
    <meta charset="utf-8" />
    <link href="assets/css/controls/pipeline.min.css" rel="stylesheet" />

Pipeline


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>jQuery scrollbar plugin</title>
  <link rel="stylesheet" href="css/style.css">

12345

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

【神秘电台40年不间断发送信号 内容至今无人破解】据外媒4日报道,俄罗斯有一个神秘的短波无线电台,这一呼号为"UVB-76"的神秘电台自70年代起开始发送信号,后来呼号改为"MDZhB",吸引了来自世界各地的听众。但无人知晓电台的作用,也没有人知道广播的内容。

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

fheufffffffffffffffffffffffffffff

  <button class="j-repaint">改变html并重绘</button>
  <button class="j-hide">隐藏滚动条</button>
  <button class="j-show">显示滚动条</button>


text:
package org.apache.camel.component.xslt.springboot;

import javax.xml.transform.URIResolver;
import org.apache.camel.component.xslt.XsltUriResolverFactory;
import org.apache.camel.converter.jaxp.XmlConverter;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Transforms the message using a XSLT template.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@ConfigurationProperties(prefix = "camel.component.xslt")
public class XsltComponentConfiguration {

    /**
     * To use a custom implementation of
     * org.apache.camel.converter.jaxp.XmlConverter
     */
    private XmlConverter xmlConverter;
    /**
     * To use a custom javax.xml.transform.URIResolver which depends on a
     * dynamic endpoint resource URI or which is a subclass of XsltUriResolver.
     * Do not use in combination with uriResolver. See also link
     * setUriResolver(URIResolver).
     */
    private XsltUriResolverFactory uriResolverFactory;
    /**
     * To use a custom javax.xml.transform.URIResolver. Do not use in
     * combination with uriResolverFactory. See also link
     * setUriResolverFactory(XsltUriResolverFactory).
     */
    private URIResolver uriResolver;
    /**
     * Cache for the resource content (the stylesheet file) when it is loaded.
     * If set to false Camel will reload the stylesheet file on each message
     * processing. This is good for development. A cached stylesheet can be
     * forced to reload at runtime via JMX using the clearCachedStylesheet
     * operation.
     */
    private Boolean contentCache = true;
    /**
     * Whether to use Saxon as the transformerFactoryClass. If enabled then the
     * class net.sf.saxon.TransformerFactoryImpl. You would need to add Saxon to
     * the classpath.
     */
    private Boolean saxon;

    public XmlConverter getXmlConverter() {
        return xmlConverter;
    }

    public void setXmlConverter(XmlConverter xmlConverter) {
        this.xmlConverter = xmlConverter;
    }

    public XsltUriResolverFactory getUriResolverFactory() {
        return uriResolverFactory;
    }

    public void setUriResolverFactory(XsltUriResolverFactory uriResolverFactory) {
        this.uriResolverFactory = uriResolverFactory;
    }

    public URIResolver getUriResolver() {
        return uriResolver;
    }

    public void setUriResolver(URIResolver uriResolver) {
        this.uriResolver = uriResolver;
    }

    public Boolean getContentCache() {
        return contentCache;
    }

    public void setContentCache(Boolean contentCache) {
        this.contentCache = contentCache;
    }

    public Boolean getSaxon() {
        return saxon;
    }

    public void setSaxon(Boolean saxon) {
        this.saxon = saxon;
    }
}


text:
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World");
});

var host = (process.env.VCAP_APP_HOST || 'localhost');
var port = (process.env.VCAP_APP_PORT || 3000);
server.listen(port, host);

console.log('App started on port ' + port);


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet GZView *gzview;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

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

@end


text: Web portal to list Curitiba csv open data apis


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>ossfuzz</groupId>
	<artifactId>beanutils-fuzzer</artifactId>
	<version>${beanutilsVersion}</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>15</maven.compiler.source>
		<maven.compiler.target>15</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<exec.mainClass>ossfuzz.BeanutilsFuzzer</exec.mainClass>
	</properties>

	<dependencies>
		<!--
		on the CI, install the jazzer file with

			mvn install:install-file -Dfile=${JAZZER_API_PATH} \
				-DgroupId="com.code-intelligence" \
				-DartifactId="jazzer-api" \
				-Dversion="0.12.0" \
				-Dpackaging=jar

		to avoid mismatching driver/api versions
		-->
		<dependency>
			<groupId>com.code-intelligence</groupId>
			<artifactId>jazzer-api</artifactId>
			<version>0.12.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-beanutils2</artifactId>
			<version>${beanutilsVersion}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>3.3.0</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
brew install node

if [ ! -d $HOME/.node_modules_global ]; then
	mkdir $HOME/.node_modules_global
fi

# set npm to install globally to user owned folder to avoid using sudo
npm config set prefix=$HOME/.node_modules_global


text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>

#include "Parser.h"
#include "Tokenizer.h"
#include "../scene/scene.h"
#include "../scene/material.h"
#include "../ui/TraceUI.h"
extern TraceUI* traceUI;

using namespace std;

template< typename T >
auto_ptr<T> wrap_auto_ptr( T* pointer )
{
	return auto_ptr<T>( pointer );
}

Scene* Parser::parseScene()
{
  _tokenizer.Read(SBT_RAYTRACER);

  auto_ptr<Token> versionNumber( _tokenizer.Read(SCALAR) );

  if( versionNumber->value() > 1.1 )
  {
    ostringstream ost;
    ost << "SBT-raytracer version number " << versionNumber->value() <<
      " too high; only able to parse v1.1 and below.";
    throw ParserException( ost.str() );
  }

  Scene* scene = new Scene;
  auto_ptr<Material> mat( new Material );

  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case SPHERE:
      case BOX:
      case SQUARE:
      case CYLINDER:
      case CONE:
      case TRIMESH:
      case TRANSLATE:
      case ROTATE:
      case SCALE:
      case TRANSFORM:
      case LBRACE:
         parseTransformableElement(scene, &scene->transformRoot, *mat);
      break;
      case POINT_LIGHT:
         scene->add( parsePointLight( scene ) );
         break;
      case DIRECTIONAL_LIGHT:
         scene->add( parseDirectionalLight( scene ) );
         break;
      case AMBIENT_LIGHT:
         parseAmbientLight( scene );
         break;
      case CAMERA:
         parseCamera( scene );
         break;
      case MATERIAL:
		 {
           auto_ptr<Material> temp( parseMaterialExpression( scene, *mat ));
		   mat = temp;
		 }
         break;
      case SEMICOLON:
         _tokenizer.Read( SEMICOLON );
         break;
      case EOFSYM:
         return scene;
      default:
         throw SyntaxErrorException( "Expected: geometry, camera, or light information", _tokenizer );
    }
  }
}

void Parser::parseCamera( Scene* scene )
{
  bool hasViewDir( false ), hasUpDir( false );
  Vec3d viewDir, upDir;

  _tokenizer.Read( CAMERA );
  _tokenizer.Read( LBRACE );

  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    Vec4d quaternian;
    switch( t->kind() )
    {
      case POSITION:
        scene->getCamera().setEye( parseVec3dExpression() );
        break;

      case FOV:
        scene->getCamera().setFOV( parseScalarExpression() );
        break;

      case QUATERNIAN:
        quaternian = parseVec4dExpression();
        scene->getCamera().setLook(
          quaternian[0], quaternian[1], quaternian[2], quaternian[3] );
        break;

      case ASPECTRATIO:
        scene->getCamera().setAspectRatio( parseScalarExpression() );
        break;

      case VIEWDIR:
        viewDir = parseVec3dExpression();
        hasViewDir = true;
        break;

      case UPDIR:
        upDir = parseVec3dExpression();
        hasUpDir = true;
        break;

      case RBRACE:
        // semantic checks
        if( hasViewDir )
        {
          if( !hasUpDir )
            throw SyntaxErrorException( "Expected: 'updir'", _tokenizer );
          scene->getCamera().setLook( viewDir, upDir );
        }
        else
        {
           if( hasUpDir )
              throw SyntaxErrorException( "Expected: 'viewdir'", _tokenizer );
        }
        _tokenizer.Read( RBRACE );
        return;

      default:
        throw SyntaxErrorException( "Expected: camera attribute", _tokenizer );
    }
  }
}

void Parser::parseTransformableElement( Scene* scene, TransformNode* transform, const Material& mat )
{
    const Token* t = _tokenizer.Peek();
    switch( t->kind() )
    {
      case SPHERE:
      case BOX:
      case SQUARE:
      case CYLINDER:
      case CONE:
      case TRIMESH:
      case TRANSLATE:
      case ROTATE:
      case SCALE:
      case TRANSFORM:
         parseGeometry(scene, transform, mat);
      break;
      case LBRACE:
         parseGroup(scene, transform, mat);
         break;
      default:
         throw SyntaxErrorException( "Expected: transformable element", _tokenizer );
    }
}

// parse a group of geometry, i.e., enclosed in {} blocks.
void Parser::parseGroup(Scene* scene, TransformNode* transform, const Material& mat )
{
  auto_ptr<Material> newMat;
  _tokenizer.Read( LBRACE );
  for( ;; )
  {
    const Token* t = _tokenizer.Peek();
    switch( t->kind() )
    {
      case SPHERE:
      case BOX:
      case SQUARE:
      case CYLINDER:
      case CONE:
      case TRIMESH:
      case TRANSLATE:
      case ROTATE:
      case SCALE:
      case TRANSFORM:
      case LBRACE:
        parseTransformableElement( scene, transform, newMat.get() ? *newMat : mat );
        break;
      case RBRACE:
        _tokenizer.Read( RBRACE );
        return;
      case MATERIAL:
		{
          auto_ptr<Material> temp(parseMaterialExpression(scene, mat));
          newMat = temp;
		}
      default:
        throw SyntaxErrorException( "Expected: '}' or geometry", _tokenizer );
    }
  }
}

void Parser::parseGeometry(Scene* scene, TransformNode* transform, const Material& mat)
{
  const Token* t = _tokenizer.Peek();
  switch( t->kind() )
  {
    case SPHERE:
      parseSphere(scene, transform, mat);
      return;
    case BOX:
      parseBox(scene, transform, mat);
      return;
    case SQUARE:
      parseSquare(scene, transform, mat);
      return;
    case CYLINDER:
      parseCylinder(scene, transform, mat);
      return;
    case CONE:
      parseCone(scene, transform, mat);
      return;
    case TRIMESH:
      parseTrimesh(scene, transform, mat);
      return;
    case TRANSLATE:
      parseTranslate(scene, transform, mat);
      return;
    case ROTATE:
      parseRotate(scene, transform, mat);
      return;
    case SCALE:
      parseScale(scene, transform, mat);
      return;
    case TRANSFORM:
      parseTransform(scene, transform, mat);
      return;
    default:
      throw ParserFatalException( "Unrecognized geometry type." );
  }
}

void Parser::parseTranslate(Scene* scene, TransformNode* transform, const Material& mat)
{
  _tokenizer.Read( TRANSLATE );
  _tokenizer.Read( LPAREN );
  double x = parseScalar();
  _tokenizer.Read( COMMA );
  double y = parseScalar();
  _tokenizer.Read( COMMA );
  double z = parseScalar();
  _tokenizer.Read( COMMA );

  // Parse child geometry
  parseTransformableElement( scene,
    transform->createChild( Mat4d::createTranslation( x, y, z ) ), mat );

  _tokenizer.Read( RPAREN );
  _tokenizer.CondRead(SEMICOLON);

  return;
}

void Parser::parseRotate(Scene* scene, TransformNode* transform, const Material& mat)
{
  _tokenizer.Read( ROTATE );
  _tokenizer.Read( LPAREN );
  double x = parseScalar();
  _tokenizer.Read( COMMA );
  double y = parseScalar();
  _tokenizer.Read( COMMA );
  double z = parseScalar();
  _tokenizer.Read( COMMA );
  double w = parseScalar();
  _tokenizer.Read( COMMA );

  // Parse child geometry
  parseTransformableElement( scene,
    transform->createChild( Mat4d::createRotation( w, x, y, z ) ), mat );

  _tokenizer.Read( RPAREN );
  _tokenizer.CondRead(SEMICOLON);

  return;
}

void Parser::parseScale(Scene* scene, TransformNode* transform, const Material& mat)
{
  _tokenizer.Read( SCALE );
  _tokenizer.Read( LPAREN );
  double x, y, z;

  x = parseScalar();
  _tokenizer.Read( COMMA );

  const Token* next = _tokenizer.Peek();
  if( SCALAR == next->kind() )
  {
     y = parseScalar();
     _tokenizer.Read( COMMA );
     z = parseScalar();
     _tokenizer.Read( COMMA );
  }
  else
  {
     y = x;
     z = x;
  }

  // Parse child geometry
  parseTransformableElement( scene,
    transform->createChild( Mat4d::createScale( x, y, z ) ), mat );

  _tokenizer.Read( RPAREN );
  _tokenizer.CondRead(SEMICOLON);

  return;
}

void Parser::parseTransform(Scene* scene, TransformNode* transform, const Material& mat)
{
  _tokenizer.Read( TRANSFORM );
  _tokenizer.Read( LPAREN );

  Vec4d row1 = parseVec4d();
  _tokenizer.Read( COMMA );
  Vec4d row2 = parseVec4d();
  _tokenizer.Read( COMMA );
  Vec4d row3 = parseVec4d();
  _tokenizer.Read( COMMA );
  Vec4d row4 = parseVec4d();
  _tokenizer.Read( COMMA );

  parseTransformableElement( scene,
    transform->createChild( Mat4d(row1, row2, row3, row4) ), mat );

  _tokenizer.Read( RPAREN );
  _tokenizer.CondRead(SEMICOLON);

  return;
}

void Parser::parseSphere(Scene* scene, TransformNode* transform, const Material& mat)
{
  Sphere* sphere = 0;
  Material* newMat = 0;

  _tokenizer.Read( SPHERE );
  _tokenizer.Read( LBRACE );

  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case MATERIAL:
        delete newMat;
        newMat = parseMaterialExpression( scene, mat );
        break;
      case NAME:
        parseIdentExpression();
        break;
      case RBRACE:
        _tokenizer.Read( RBRACE );
        sphere = new Sphere(scene, newMat ? newMat : new Material(mat));
        sphere->setTransform( transform );
        scene->add( sphere );
        scene->addBB( sphere );

        return;
      default:
        throw SyntaxErrorException( "Expected: sphere attributes", _tokenizer );

    }
  }
}

void Parser::parseBox(Scene* scene, TransformNode* transform, const Material& mat)
{
  Box* box = 0;

  _tokenizer.Read( BOX );
  _tokenizer.Read( LBRACE );

  Material* newMat = 0;
  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case MATERIAL:
        delete newMat;
        newMat = parseMaterialExpression( scene, mat );
        break;
      case NAME:
        parseIdentExpression();
        break;
      case RBRACE:
         _tokenizer.Read( RBRACE );
        box = new Box(scene, newMat ? newMat : new Material(mat) );
        box->setTransform( transform );
        scene->add( box );
        scene->addBB( box );
        return;
      default:
        throw SyntaxErrorException( "Expected: box attributes", _tokenizer );

    }
  }
}

void Parser::parseSquare(Scene* scene, TransformNode* transform, const Material& mat)
{
  Square* square = 0;
  Material* newMat = 0;

  _tokenizer.Read( SQUARE );
  _tokenizer.Read( LBRACE );

  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case MATERIAL:
        delete newMat;
        newMat = parseMaterialExpression( scene, mat );
        break;
      case NAME:
        parseIdentExpression();
        break;
      case RBRACE:
         _tokenizer.Read( RBRACE );
        square = new Square(scene, newMat ? newMat : new Material(mat));
        square->setTransform( transform );
        scene->add( square );
        scene->addBB( square );
        return;
      default:
        throw SyntaxErrorException( "Expected: square attributes", _tokenizer );

    }
  }
}

void Parser::parseCylinder(Scene* scene, TransformNode* transform, const Material& mat)
{
  Cylinder* cylinder = 0;
  Material* newMat = 0;

  _tokenizer.Read( CYLINDER );
  _tokenizer.Read( LBRACE );

  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case MATERIAL:
        delete newMat;
        newMat = parseMaterialExpression( scene, mat );
        break;
      case NAME:
        parseIdentExpression();
        break;
      case RBRACE:
         _tokenizer.Read( RBRACE );
        cylinder = new Cylinder(scene, newMat ? newMat : new Material(mat));
        cylinder->setTransform( transform );
        scene->add( cylinder );
        scene->addBB( cylinder );
        return;
      default:
        throw SyntaxErrorException( "Expected: cylinder attributes", _tokenizer );
    }
  }

}

void Parser::parseCone(Scene* scene, TransformNode* transform, const Material& mat)
{
  _tokenizer.Read( CONE );
  _tokenizer.Read( LBRACE );

  Cone* cone;
  Material* newMat = 0;

  double bottomRadius = 1.0;
  double topRadius = 0.0;
  double height = 1.0;
  bool capped = true;				// Capped by default

  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case MATERIAL:
        delete newMat;
        newMat = parseMaterialExpression( scene, mat );
        break;
      case NAME:
         parseIdentExpression();
         break;
      case CAPPED:
        capped = parseBooleanExpression();
        break;
      case BOTTOM_RADIUS:
        bottomRadius = parseScalarExpression();
        break;
      case TOP_RADIUS:
        topRadius = parseScalarExpression();
        break;
      case HEIGHT:
        height = parseScalarExpression();
        break;
      case RBRACE:
        _tokenizer.Read( RBRACE );
        cone = new Cone( scene, newMat ? newMat : new Material(mat),
          height, bottomRadius, topRadius, capped );
        cone->setTransform( transform );
        scene->add( cone );
        scene->addBB( cone );
        return;
      default:
        throw SyntaxErrorException( "Expected: cone attributes", _tokenizer );
    }
  }
}

void Parser::parseTrimesh(Scene* scene, TransformNode* transform, const Material& mat)
{
  Trimesh* tmesh = new Trimesh( scene, new Material(mat), transform);
  string fName;
  _tokenizer.Read( TRIMESH );
  _tokenizer.Read( LBRACE );

  bool generateNormals( false );
  bool haveObj(false);
  // bool hasNormals = false;
  list<Vec3d> faces;

  char* error;
  for( ;; )
  {
    const Token* t = _tokenizer.Peek();

    switch( t->kind() )
    {
      case GENNORMALS:
        _tokenizer.Read( GENNORMALS );
        _tokenizer.Read( SEMICOLON );
        generateNormals = true;
        break;

      case MATERIAL:
        tmesh->setMaterial( parseMaterialExpression( scene, mat ) );
        break;

      case NAME:
         parseIdentExpression();
         break;

      case MATERIALS:
        _tokenizer.Read( MATERIALS );
        _tokenizer.Read( EQUALS );
        _tokenizer.Read( LPAREN );
        if( RPAREN != _tokenizer.Peek()->kind() )
        {
          tmesh->addMaterial( parseMaterial( scene, tmesh->getMaterial() ) );
          for( ;; )
          {
             const Token* nextToken = _tokenizer.Peek();
             if( RPAREN == nextToken->kind() )
               break;
             _tokenizer.Read( COMMA );
             tmesh->addMaterial( parseMaterial( scene, tmesh->getMaterial() ) );
          }
        }
        _tokenizer.Read( RPAREN );
        _tokenizer.Read( SEMICOLON );
        break;

      case NORMALS:
        _tokenizer.Read( NORMALS );
        _tokenizer.Read( EQUALS );
        _tokenizer.Read( LPAREN );
        if( RPAREN != _tokenizer.Peek()->kind() )
        {
          // hasNormals = true;
          tmesh->addNormal( parseVec3d() );
          for( ;; )
          {
             const Token* nextToken = _tokenizer.Peek();
             if( RPAREN == nextToken->kind() )
               break;
             _tokenizer.Read( COMMA );
             tmesh->addNormal( parseVec3d() );
          }
        }
        _tokenizer.Read( RPAREN );
        _tokenizer.Read( SEMICOLON );
        break;

      case FACES:
        _tokenizer.Read( FACES );
        _tokenizer.Read( EQUALS );
        _tokenizer.Read( LPAREN );
        if( RPAREN != _tokenizer.Peek()->kind() )
        {
          parseFaces( faces );
          for( ;; )
          {
             const Token* nextToken = _tokenizer.Peek();
             if( RPAREN == nextToken->kind() )
               break;
             _tokenizer.Read( COMMA );
             parseFaces( faces );
          }
        }
        _tokenizer.Read( RPAREN );
        _tokenizer.Read( SEMICOLON );
        break;

      case POLYPOINTS:
        _tokenizer.Read( POLYPOINTS );
        _tokenizer.Read( EQUALS );
        _tokenizer.Read( LPAREN );
        if( RPAREN != _tokenizer.Peek()->kind() )
        {
          tmesh->addVertex( parseVec3d() );
          for( ;; )
          {
             const Token* nextToken = _tokenizer.Peek();
             if( RPAREN == nextToken->kind() )
               break;
             _tokenizer.Read( COMMA );
             tmesh->addVertex( parseVec3d() );
          }
        }
        _tokenizer.Read( RPAREN );
        _tokenizer.Read( SEMICOLON );
        break;
      case OBJFILE:
        // _tokenizer.Read( OBJFILE );
        fName = parseIdentExpression();
        parseObj(fName, scene, mat, transform);
        // delete tmesh;
        // _tokenizer.Read( SEMICOLON );

        // return;
        haveObj = true;

        break;
      case RBRACE:
      {
        _tokenizer.Read( RBRACE );

        // Now add all the faces into the trimesh, since hopefully
        // the vertices have been parsed out
        if(!haveObj){
          for( list<Vec3d>::const_iterator vitr = faces.begin(); vitr != faces.end(); vitr++ )
          {
            if( !tmesh->addFace( (*vitr)[0], (*vitr)[1], (*vitr)[2] ) )
            {
              ostringstream oss;
              oss << "Bad face in trimesh: (" << (*vitr)[0] << ", " << (*vitr)[1] <<
                ", " << (*vitr)[2] << ")";
              throw ParserException( oss.str() );
            }
          }

          // if( generateNormals  || !hasNormals)
          if(generateNormals){
            // std::cout<<"Generating Normals";
            tmesh->generateNormals();
          }

          if( error = tmesh->doubleCheck() ){
            throw ParserException( error );
          }

        } else{
          // delete tmesh;
        }

        // tmesh->buildKdTree();
        scene->addBB( tmesh );
        return;
      }

      default:
        throw SyntaxErrorException( "Expected: trimesh attributes", _tokenizer );
    }
  }
}

void Parser::parseFaces( list< Vec3d >& faces )
{
  list< double > points = parseScalarList();

  // triangulate here and now.  assume the poly is
  // concave (convex?) and we can triangulate using an arbitrary fan
  if( points.size() < 3 )
     throw SyntaxErrorException( "Faces must have at least 3 vertices.", _tokenizer );

  list<double>::const_iterator i = points.begin();
  double a = (*i++);
  double b = (*i++);
  while( i != points.end() )
  {
    double c = (*i++);
    faces.push_back( Vec3d( a, b, c ) );
    b = c;
  }
}

// Ambient lights are a bit special in that we don't actually
// create a separate Light for each ambient light; instead
// we simply sum all the ambient intensities and put them in
// the scene as the I_a coefficient.
void Parser::parseAmbientLight( Scene* scene )
{
  _tokenizer.Read( AMBIENT_LIGHT );
  _tokenizer.Read( LBRACE );
  if( _tokenizer.Peek()->kind() != COLOR )
    throw SyntaxErrorException( "Expected color attribute", _tokenizer );

  scene->addAmbient( parseVec3dExpression() );
  _tokenizer.Read( RBRACE );
  return;
}

PointLight* Parser::parsePointLight( Scene* scene )
{
  Vec3d position;
  Vec3d color;

  // Default to the 'default' system
  float constantAttenuationCoefficient = 0.0f;
  float linearAttenuationCoefficient = 0.0f;
  float quadraticAttenuationCoefficient = 1.0f;

  bool hasPosition( false ), hasColor( false );

  _tokenizer.Read( POINT_LIGHT );
  _tokenizer.Read( LBRACE );

  for( ;; )
  {
     const Token* t = _tokenizer.Peek();
     switch( t->kind() )
     {
       case POSITION:
         if( hasPosition )
           throw SyntaxErrorException( "Repeated 'position' attribute", _tokenizer );
         position = parseVec3dExpression();
         hasPosition = true;
         break;

       case COLOR:
         if( hasColor )
            throw SyntaxErrorException( "Repeated 'color' attribute", _tokenizer );
         color = parseVec3dExpression();
         hasColor = true;
         break;

       case CONSTANT_ATTENUATION_COEFF:
         constantAttenuationCoefficient = parseScalarExpression();
		 break;

       case LINEAR_ATTENUATION_COEFF:
         linearAttenuationCoefficient = parseScalarExpression();
		 break;

       case QUADRATIC_ATTENUATION_COEFF:
         quadraticAttenuationCoefficient = parseScalarExpression();
		 break;

       case RBRACE:
         if( !hasColor )
           throw SyntaxErrorException( "Expected: 'color'", _tokenizer );
         if( !hasPosition )
           throw SyntaxErrorException( "Expected: 'position'", _tokenizer );
         _tokenizer.Read( RBRACE );
         return new PointLight( scene, position, color, constantAttenuationCoefficient,
           linearAttenuationCoefficient, quadraticAttenuationCoefficient );

        default:
          throw SyntaxErrorException(
			  "expecting 'position' or 'color' attribute, or 'constant_attenuation_coeff', 'linear_attenuation_coeff', or 'quadratic_attenuation_coeff'",
            _tokenizer );
     }
  }
}

DirectionalLight* Parser::parseDirectionalLight( Scene* scene )
{
  Vec3d direction;
  Vec3d color;

  bool hasDirection( false ), hasColor( false );

  _tokenizer.Read( DIRECTIONAL_LIGHT );
  _tokenizer.Read( LBRACE );

  for( ;; )
  {
     const Token* t = _tokenizer.Peek();
     switch( t->kind() )
     {
       case DIRECTION:
         if( hasDirection )
           throw SyntaxErrorException( "Repeated 'direction' attribute", _tokenizer );
         direction = parseVec3dExpression();
         hasDirection = true;
         break;

       case COLOR:
         if( hasColor )
            throw SyntaxErrorException( "Repeated 'color' attribute", _tokenizer );
         color = parseVec3dExpression();
         hasColor = true;
         break;

        case RBRACE:
          if( !hasColor )
            throw SyntaxErrorException( "Expected: 'color'", _tokenizer );
          if( !hasDirection )
            throw SyntaxErrorException( "Expected: 'position'", _tokenizer );
          _tokenizer.Read( RBRACE );
          return new DirectionalLight( scene, direction, color );

        default:
          throw SyntaxErrorException( "expecting 'position' or 'color' attribute",
            _tokenizer );
     }
  }
}

// These ought to be done with template member functions, but compiler support for
// these is rather iffy...
double Parser::parseScalarExpression()
{
  // Throw out first token, which precedes the = sign
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  double value( parseScalar() );
  _tokenizer.CondRead(SEMICOLON);
  return value;
}

bool Parser::parseBooleanExpression()
{
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  bool value( parseBoolean() );
  _tokenizer.CondRead(SEMICOLON);
  return value;
}

Vec3d Parser::parseVec3dExpression()
{
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  Vec3d value( parseVec3d() );
  _tokenizer.CondRead(SEMICOLON);
  return value;
}

Vec4d Parser::parseVec4dExpression()
{
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  Vec4d value( parseVec4d() );
  _tokenizer.CondRead(SEMICOLON);
  return value;
}

void Parser::parseObj(string inputfile, Scene* scene, const Material& parent, TransformNode* transform){
  // Trimesh* tmesh = new Trimesh( scene, new Material(mat), transform);
  std::cout << inputfile << std::endl;
  std::vector<tinyobj::shape_t> shapes;
  std::vector<tinyobj::material_t> materials;

  std::string err;
  bool ret = tinyobj::LoadObj(shapes, materials, err, inputfile.c_str());

  if (!err.empty()) { // `err` may contain warning message.
    std::cerr << err << std::endl;
  }

  if (!ret) {
    exit(1);
  }

  //Else successful now add the objects to the scene
  for(int i = 0; i < shapes.size(); i++){
    //Will only support one material per object
    // Get Materials
    Trimesh* tmesh;
    if(!shapes[i].mesh.material_ids.empty()){
      auto mtr = materials[shapes[i].mesh.material_ids[0]];
  // float ambient[3];
  // float diffuse[3];
  // float specular[3];
  // float transmittance[3];
  // float emission[3];
  // float shininess;
  // float ior;

      Vec3d ke(mtr.emission[0], mtr.emission[1], mtr.emission[2]     );
      Vec3d ka(mtr.ambient[0], mtr.ambient[1], mtr.ambient[2]      );
      Vec3d ks(mtr.specular[0], mtr.specular[1], mtr.specular[2]     );
      Vec3d kd(mtr.diffuse[0], mtr.diffuse[1], mtr.diffuse[2]      );
      // Vec3d kt(mtr.transmittance[0], mtr.transmittance[1], mtr.transmittance[2]);
      Vec3d kt(1.0 - mtr.dissolve, 1.0 - mtr.dissolve,1.0 -  mtr.dissolve);
      std::cout  << "Tr " << mtr.transmittance[0]<< " " << mtr.transmittance[1] << " " <<  mtr.transmittance[2] << " :d->: "<< mtr.dissolve << std::endl;
      Vec3d kr = Vec3d(0.0,0.0,0.0);
      // if(mtr.dissolve < 1.0) kr = ks;
      if(mtr.dissolve < 1.0) kr = Vec3d(0.2,0.2,0.2);

     tmesh = new Trimesh( scene, new Material(ke, ka, ks, kd, kr,kt, mtr.shininess, mtr.ior), transform);
    }else{
     std::cerr << "Note: OBJ file missing material" << std::endl;
     tmesh = new Trimesh( scene, new Material(parent), transform);
    }
    for (size_t v = 0; v < shapes[i].mesh.positions.size() / 3; v++) {
    //First Add Vertices
      Vec3d vert(shapes[i].mesh.positions[3*v+0], shapes[i].mesh.positions[3*v+1], shapes[i].mesh.positions[3*v+2]);
      tmesh->addVertex(vert);
    }
    for (size_t f = 0; f < shapes[i].mesh.indices.size() / 3; f++) {
    //Then Add Faces
      tmesh->addFace(shapes[i].mesh.indices[3*f+0], shapes[i].mesh.indices[3*f+1], shapes[i].mesh.indices[3*f+2]);
    }
    tmesh->generateNormals();
    // tmesh->buildKdTree();
    scene->addBB( tmesh );

  }
}

Material* Parser::parseMaterialExpression( Scene* scene, const Material& parent )
{
  _tokenizer.Read(MATERIAL);
  _tokenizer.Read(EQUALS);
  Material* mat = parseMaterial( scene, parent );
  _tokenizer.CondRead( SEMICOLON );
  return mat;
}

string Parser::parseIdentExpression()
{
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  string value( parseIdent() );
  _tokenizer.CondRead(SEMICOLON);
  return value;
}

double Parser::parseScalar()
{
  auto_ptr<Token> scalar( _tokenizer.Read( SCALAR ) );

  return scalar->value();
}

string Parser::parseIdent()
{
  auto_ptr<Token> scalar( _tokenizer.Read( IDENT ) );

  return scalar->ident();
}

// string Parser::parseQuoted(){
//   tokenizer.Read( EQUALS );
//   auto_ptr<Token> scalar( _tokenizer.Read( SCALAR ) );

// }

list<double> Parser::parseScalarList()
{
  list<double> ret;

  _tokenizer.Read( LPAREN );
  if( RPAREN != _tokenizer.Peek()->kind() )
  {
    ret.push_back( parseScalar() );
    for( ;; )
    {
      const Token* nextToken = _tokenizer.Peek();
      if( RPAREN == nextToken->kind() )
        break;
      _tokenizer.Read( COMMA );
      ret.push_back( parseScalar() );
    }
  }
  _tokenizer.Read( RPAREN );

  return ret;

}
// std::string Parser::parseIdent
bool Parser::parseBoolean()
{
  const Token* next = _tokenizer.Peek();
  if( SYMTRUE == next->kind() )
  {
     _tokenizer.Read(SYMTRUE);
     return true;
  }
  if( SYMFALSE == next->kind() )
  {
     _tokenizer.Read(SYMFALSE);
     return false;
  }
  throw SyntaxErrorException( "Expected boolean", _tokenizer );
}

Vec3d Parser::parseVec3d()
{
  _tokenizer.Read( LPAREN );
  auto_ptr<Token> value1( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( COMMA );
  auto_ptr<Token> value2( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( COMMA );
  auto_ptr<Token> value3( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( RPAREN );

  return Vec3d( value1->value(),
    value2->value(),
    value3->value() );
}

Vec4d Parser::parseVec4d()
{
  _tokenizer.Read( LPAREN );
  auto_ptr<Token> value1( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( COMMA );
  auto_ptr<Token> value2( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( COMMA );
  auto_ptr<Token> value3( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( COMMA );
  auto_ptr<Token> value4( _tokenizer.Read( SCALAR ) );
  _tokenizer.Read( RPAREN );

  return Vec4d( value1->value(),
    value2->value(),
    value3->value(),
    value4->value() );
}

Material* Parser::parseMaterial( Scene* scene, const Material& parent )
{
  const Token* tok = _tokenizer.Peek();
  if( IDENT == tok->kind() )
  {
     return new Material(materials[ tok->ident() ]);
  }

  _tokenizer.Read( LBRACE );

  bool setReflective( false );
  string name;

  Material* mat = new Material(parent);

  for( ;; )
  {
    const Token* token = _tokenizer.Peek();
    switch( token->kind() )
    {
      case EMISSIVE:
        mat->setEmissive( parseVec3dMaterialParameter(scene) );
        break;

      case AMBIENT:
        mat->setAmbient( parseVec3dMaterialParameter(scene) );
        break;

      case SPECULAR:
      {
        MaterialParameter specular = parseVec3dMaterialParameter(scene);
        mat->setSpecular( specular );
//        if( ! setReflective )
//          mat->setReflective( specular );  // Default kr = ks if none specified
        break;
      }

      case DIFFUSE:
        mat->setDiffuse( parseVec3dMaterialParameter(scene) );
        break;

      case REFLECTIVE:
        mat->setReflective( parseVec3dMaterialParameter(scene) );
        setReflective = true;
        break;

      case TRANSMISSIVE:
        mat->setTransmissive( parseVec3dMaterialParameter(scene) );
        break;

      case INDEX:
        mat->setIndex( parseScalarMaterialParameter(scene) );
        break;

      case SHININESS:
        mat->setShininess( parseScalarMaterialParameter(scene) );
        break;

      case NAME:
         _tokenizer.Read(NAME);
         name = (_tokenizer.Read(IDENT))->ident();
         _tokenizer.Read( SEMICOLON );
         break;

      case RBRACE:
        _tokenizer.Read( RBRACE );
        if( ! name.empty() )
        {
           if( materials.find( name ) == materials.end() )
              materials[ name ] = *mat;
           else
           {
              ostringstream oss;
              oss << "Redefinition of material '" << name << "'.";
              throw SyntaxErrorException( oss.str(), _tokenizer );
           }
        }
        return mat;

      default:
         throw SyntaxErrorException( "Expected: material attribute", _tokenizer );

    }
  }
}

MaterialParameter Parser::parseVec3dMaterialParameter( Scene* scene )
{
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  if( _tokenizer.CondRead( MAP ) )
  {
    _tokenizer.Read( LPAREN );
    string filename = _basePath;
    filename.append( "/" );
    filename.append(parseIdent());
    _tokenizer.Read( RPAREN );
    _tokenizer.CondRead(SEMICOLON);
    return MaterialParameter( scene->getTexture( filename ) );
  }
  else
  {
    Vec3d value( parseVec3d() );
    _tokenizer.CondRead(SEMICOLON);
    return MaterialParameter( value );
  }
}

MaterialParameter Parser::parseScalarMaterialParameter( Scene* scene )
{
  _tokenizer.Get();
  _tokenizer.Read(EQUALS);
  if( _tokenizer.CondRead(MAP) )
  {
    _tokenizer.Read( LPAREN );
    string filename = parseIdent();
    _tokenizer.Read( RPAREN );
    _tokenizer.CondRead(SEMICOLON);
    return MaterialParameter( scene->getTexture( filename ) );
  }
  else
  {
    double value = parseScalar();
    _tokenizer.CondRead(SEMICOLON);
    return MaterialParameter( value );
  }
}


text:
<?php
/*
	// dimaninc

	// 2015/05/01
		* ::insert_or_update() added

	// 2015/01/21
		* multi-insert error catching added

	// 2014/02/20
		* ::insert() improved: multi-insert added

	// 2014/02/11
		* ::rs_go() added

	// 2013/10/31
		* some precache improvements

	// 2013/06/22
		* reorganized
		* dimysqli class added
		* precache added

	// 2012/11/07
		* ::reset() added

	// 2012/04/06
		* ::insert() updated: *fields (w/o '') added

	// 2010/05/31
		* ::delete() updated: direct int ID and array IDs support added

	// 2010/05/18
		* ::update() and ::ar() updated: direct int ID and array IDs support added

	// 2009/11/02
		* init method params order changed
		* silent mode added

	// 2009/05/05
		* some improvements

	// 2008/12/05
		* random methods added
		* debug added

	// 2008/10/07
		* ::ar() methods added

	// 2008/06/05
		* ::drop(), ::delete() methods added

	// 2008/04/01
		* birthday
*/

use diCore\Data\Config;
use diCore\Helper\FileSystemHelper;
use diCore\Helper\StringHelper;

abstract class diDB
{
	const QUOTE_TABLE = '`';
	const QUOTE_FIELD = '`';
	const QUOTE_VALUE = "'";

	const CHARSET_INIT_NEEDED = true;

	const DEFAULT_PORT = null;

	// basic db info
	protected $host;
	protected $port;
	protected $dbname;
	protected $username;
	protected $password;

	protected $link;
	protected $logFolder = 'log/db/';
	protected $log;
	protected $execution_time = 0;
	protected $execution_time_log = [];

	protected $tables_ar;
	protected $debug = false;
	protected $logStackTrace = false;
	private $debugFileName;
	protected $silent = false;

	protected $transactionNestingLevel = 0;

	public $affected_rows = 0;
	public $cached_db_data = [];

	protected $lastInsertId;

	public function __construct($settingsOrHost, $username = null, $password = null, $dbname = null)
	{
		if (
		    is_array($settingsOrHost) &&
            $username === null &&
            $password === null &&
            $dbname === null
        ) {
			$settings = extend([
				'host' => null,
				'username' => null,
				'password' => null,
				'dbname' => null,
				'port' => static::DEFAULT_PORT,
			], $settingsOrHost);
		} else {
			$settings = [
				'host' => $settingsOrHost,
				'username' => $username,
				'password' => $password,
				'dbname' => $dbname,
				'port' => static::DEFAULT_PORT,
			];
		}

		$this->populateBasicSettings($settings);

		$this->log = [];

		if ($this->debug) {
			$this->enableDebug();
		}

		if (!empty($GLOBALS['engine']['tables_ar'])) {
			$this->set_tables_ar($GLOBALS['engine']['tables_ar']);
		}

		if (!$this->connect()) {
			$this->_fatal('unable to connect to database');
		}

		$this->initCharset();
	}

	protected function populateBasicSettings($settings)
    {
        $this->host = $settings['host'];
        $this->dbname = $settings['dbname'];
        $this->username = $settings['username'];
        $this->password = $settings['password'];
        $this->port = $settings['port'];

        return $this;
    }

	public function getLink()
	{
		return $this->link;
	}

	public function enableDebug()
	{
		$this->debug = true;

		$this->debugMessage([
			'URL',
			\diRequest::requestUri(),
		]);

		return $this;
	}

	public function withStackTrace()
    {
        $this->logStackTrace = true;

        return $this;
    }

	private function checkDebugFilename()
	{
		if (!$this->debugFileName) {
			do {
				$this->debugFileName = \diDateTime::format('Y-m-d-H-i-s-') . get_unique_id() . '.csv';
			} while (is_file($this->getDebugLogFileName()));
		}

		return $this;
	}

	protected function getFullDebugLogFolder()
	{
		return Config::getLogFolder() . $this->logFolder;
	}

	protected function getDebugLogFileName()
	{
		$this->checkDebugFilename();

		return StringHelper::slash($this->getFullDebugLogFolder()) . $this->debugFileName;
	}

	public function debugMessage($message)
	{
		if (is_array($message)) {
            $message = join("", array_map(function ($s) {
                return '"' . str_replace('"', '\"', $s) . '";';
            }, $message));
        }

		FileSystemHelper::createTree(Config::getLogFolder(), $this->logFolder, 0777);

		file_put_contents($this->getDebugLogFileName(), $message . "\n", FILE_APPEND | LOCK_EX);

		if ($this->logStackTrace) {
		    file_put_contents($this->getDebugLogFileName(), var_export((new \Exception)->getTraceAsString(), true) . "\n", FILE_APPEND | LOCK_EX);
        }

		return $this;
	}

	protected function getCreateDatabaseQuery()
	{
	    $quote = static::QUOTE_TABLE;

		return "CREATE DATABASE IF NOT EXISTS {$quote}{$this->dbname}{$quote} /*!40100 COLLATE '" . Config::getDbCollation() . "' */";
	}

	protected function initCharset()
	{
		if (!static::CHARSET_INIT_NEEDED) {
			return $this;
		}

		$enc = Config::getDbEncoding() ?: 'UTF8';

		$this->q('SET NAMES ' . $enc . ' COLLATE ' . Config::getDbCollation());
		$this->set_charset($enc);

		return $this;
	}

	/**
	 * @deprecated
	 * Use \diDB->escape_string() instead
	 */
	public static function _in($s)
	{
		return StringHelper::in($s);
	}

	public static function _out($s, $replaceAmp = false)
	{
		return StringHelper::out($s, $replaceAmp);
	}

	public static function is_rs($rs)
	{
		return is_resource($rs) || (is_object($rs) && method_exists($rs, 'fetch_object'));
	}

	public function getHost()
	{
		return $this->host;
	}

	public function getDatabase()
	{
		return $this->dbname;
	}

	public function getUsername()
	{
		return $this->username;
	}

	public function getPassword()
	{
		return $this->password;
	}

	public function getPort()
	{
		return $this->port;
	}

	public function getExecutionTime()
	{
		return $this->execution_time;
	}

	public function getExecutionLog()
	{
		return $this->execution_time_log;
	}

	public function getLog()
	{
		return $this->log;
	}

	public function getLogStr($lineBreak = "\n")
	{
		return join($lineBreak, $this->log);
	}

	public function resetLog()
	{
		$this->log = [];

		return $this;
	}

	public function dierror($message = '')
	{
		if ($this->silent) {
			exit(0);
		}

		if (count($this->log)) {
			$this->_fatal($message);
		}

		return $this;
	}

	protected function _log($message, $add_native_error_message = true)
	{
		$this->log[] = $message;
		if ($add_native_error_message) {
			$this->log[] = $this->error();
		}

		return false;
	}

	protected function _fatal($message)
	{
		dierror(join("\n", $this->log), DIE_WARNING);
		dierror($message, $this->silent ? DIE_WARNING : DIE_FATAL);

		return false;
	}

	protected function time_log($method, $duration, $query = '', $message = '')
	{
		if (!$this->debug) {
			return $this;
		}

		$duration = sprintf('%.10f', $duration);

		//$this->log[] = "$message: $duration sec";

        $data = [
            $method,
            $query,
            $duration,
            $message,
        ];

        $explainData = $query
			? $this->__fetch_array($this->__q("EXPLAIN $query"))
			: null;

		if ($explainData) {
			foreach ($explainData as $k => $v) {
				$data[] = "$k = $v";
			}
		}

		$this->debugMessage($data);

		return $this;
	}

	public function set_tables_ar($ar)
	{
		$this->tables_ar = $ar;

		return $this;
	}

	public function get_table_name($table, $escape = false)
	{
		$name = $this->tables_ar && isset($this->tables_ar[$table]) ? $this->tables_ar[$table] : $table;

		if ($escape) {
			$name = $this->escape_string($name);
		}

		return $name;
	}

	public function doesColumnExist($table, $column)
    {
        $rs = $this->q("SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = '{$table}'
             AND table_schema = '{$this->getDatabase()}'
             AND column_name = '{$column}'");

        return $this->count($rs) > 0;
    }

	/** @deprecated  */
	public function precache_rs($table, $query_or_ids_ar = '', $fields = '*')
	{
		if (is_array($table)) {
			$realTable = $table['table'];
			$table = $table['queryTable'];
		} else {
			$realTable = $table;
		}

		if (empty($this->cached_db_data[$realTable])) {
			$this->cached_db_data[$realTable] = array();
		}

		$rs = $this->rs($table, $query_or_ids_ar, $fields);
		while ($r = $this->fetch($rs)) {
			$this->cached_db_data[$realTable][$r->id] = $r;
		}

		$this->reset($rs);

		return $rs;
	}

    /** @deprecated  */
	public function precache_r($table, $id, $fields = '*', $force = true)
	{
		return $this->get_precached_r($table, $id, $fields, $force);
	}

    /** @deprecated  */
	public function get_precached_r($table, $id, $fields = '*', $force = true)
	{
		if (empty($this->cached_db_data[$table])) {
            $this->cached_db_data[$table] = [];
        }

		if (empty($this->cached_db_data[$table][$id]) && $id) {
			$r = $force ? $this->r($table, $id) : null;

			if ($r && !empty($r->id)) $id = $r->id;
			$this->cached_db_data[$table][$id] = $r;
		}

		return $id ? $this->cached_db_data[$table][$id] : null;
	}

    /** @deprecated  */
	public function clear_precached($table = false)
	{
		$this->flush_precached($table);

		return $this;
	}

    /** @deprecated  */
	public function flush_precached($table = false)
	{
		if ($table)
			$this->cached_db_data[$table] = array();
		else
			$this->cached_db_data = array();

		return $this;
	}

	public function escape_string($s, $binary = false)
	{
		return $s;
	}

	public static function in($ar = [], $digits_only = false, $positive = true)
	{
		if (is_array($ar)) {
			if (count($ar) == 1) {
				$c = $positive ? '=' : '!=';

				return $c . ' ' . static::QUOTE_VALUE . current($ar) . static::QUOTE_VALUE;
			} else {
				$c = $positive ? ' in' : ' not in';

				return $digits_only
                    ? $c . ' (' . join(',', $ar) . ')'
                    : $c . ' (' . static::QUOTE_VALUE . join(static::QUOTE_VALUE . ',' . static::QUOTE_VALUE, $ar) . static::QUOTE_VALUE . ')';
			}
		} else {
			$c = $positive ? '=' : '!=';

			return $c . ' ' . static::QUOTE_VALUE . $ar . static::QUOTE_VALUE;
		}
	}

	public static function not_in($ar = [], $digits_only = false)
	{
		return static::in($ar, $digits_only, false);
	}

	/* main methods */

	public function connect()
	{
		$time1 = utime();

		$result = $this->__connect();

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		return $result;
	}

	public function close()
	{
		if ($this->debug) {
			$this->time_log('total', $this->execution_time);
		}

		return $this->__close();
	}

	public function error()
	{
		return $this->__error();
	}

	public function q($q)
	{
		$time1 = utime();

		$result = $this->__q($q);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		$err = $this->error();

		if (!$result && $err) {
			$this->_log("unable to exec query \"$q\"", false);
			$this->_log($err, false);
		}

		$this->time_log('q', $time2 - $time1, $q);

		return $result;
	}

	public function rq($q)
	{
		$time1 = utime();

		$result = $this->__rq($q);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		if (!$result)
			$this->_log("unable to exec query \"$q\"");

		$this->time_log('rq', $time2 - $time1, $q);

		return $result;
	}

	public function mq($q)
	{
		$time1 = utime();

		$result = $this->__mq($q);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		if ($result === false)
			$this->_log("unable to exec query \"$q\"");

		$this->time_log('mq', $time2 - $time1, $q);

		return $result;
	}

	public function getQueryForRs($table, $q_ending = "", $q_fields = "*")
	{
		if (is_numeric($q_ending)) {
			$q_ending = "WHERE id='$q_ending'" . $this->limitOffset(1);
		} elseif (is_array($q_ending)) {
			$q_ending = "WHERE id" . $this->in($q_ending);
		}

		if (is_array($q_fields)) {
			$q_fields = join(",", $q_fields);
		}

		$t = $this->get_table_name($table);

		return "SELECT $q_fields FROM $t $q_ending";
	}

	public function getQueryForR($table, $q_ending = "", $q_fields = "*")
	{
		if (is_numeric($q_ending)) {
			$q_ending = "WHERE id = '$q_ending'";
		} elseif (is_array($q_ending)) {
			$q_ending = "WHERE id " . $this->in($q_ending);
		}

		if (is_array($q_fields)) {
			$q_fields = join(",", $q_fields);
		}

		$t = $this->get_table_name($table);

		return "SELECT $q_fields FROM $t $q_ending" . $this->limitOffset(1);
	}

	public function rs($table, $q_ending = "", $q_fields = "*")
	{
		$time1 = utime();

		$q = $this->getQueryForRs($table, $q_ending, $q_fields);

		$rs = $this->__q($q);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		$this->time_log("rs", $time2 - $time1, $q);

		if (!$rs) {
            return $this->_log("unable to exec query \"$q\"");
        }

		return $rs;
	}

	/**
	 * @param string $table
	 * @param mixed $q_ending
	 * @param string $q_fields
	 * @return object
	 */
	public function r($table, $q_ending = "", $q_fields = "*")
	{
		// alias to ::fetch()
		if ((self::is_rs($table) || $table === false) && $q_ending === "") {
			return $this->fetch($table);
		}
		//

		$q = $this->getQueryForR($table, $q_ending, $q_fields);

		$time1 = utime();

		$rs = $this->__q($q);
		$r = $rs ? $this->__fetch($rs) : false;

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		$this->time_log("r", $time2 - $time1, $q);

		if (!$r) {
			$err = $this->error();

			if ($err) {
				$this->_log("unable to exec query \"$q\"", false);
				$this->_log($err, false);
			}

			return false;
		}

		return $r;
	}

	public function random_rs($table, $limit, $q_ending = "", $q_fields = "*")
	{
		$time1 = utime();

		$t = $this->get_table_name($table);

		/*
		$r = $this->r($t, $q_ending, "COUNT(*) AS cc");
		$count = $r ? $r->cc : 0;

		if ($count <= $limit)
			return $this->rs($table, $q_ending, $q_fields);

		srand((double)microtime() * 1000000);
		$start = rand(0, $count - $limit);

		$q = "SELECT $q_fields FROM $t $q_ending " . $this->limitOffset($limit, $start);
		*/

		if (is_array($q_fields)) {
			$q_fields = join(",", $q_fields);
		}

		$q = "SELECT $q_fields FROM $t $q_ending ORDER BY RAND()" . $this->limitOffset($limit);

		$rs = $this->__q($q);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		$this->time_log("random_rs", $time2 - $time1, $q);

		if (!$rs) {
            return $this->_log("unable to exec query $q");
        }

		return $rs;
	}

	public function random_r($table, $q_ending = "", $q_fields = "*")
	{
		$rs = $this->random_rs($table, 1, $q_ending, $q_fields);
		return $rs ? $this->__fetch($rs) : false;
	}

	public function ar($table, $q_ending = "", $q_fields = "*")
	{
		// alias to ::fetch_array()
		if ((self::is_rs($table) || $table === false) && $q_ending === "") {
			return $this->fetch_array($table);
		}
		//

		$time1 = utime();

		$q = $this->getQueryForR($table, $q_ending, $q_fields);

		$rs = $this->__q($q);
		$r = $rs ? $this->fetch_array($rs) : false;

		$time2 = utime();
		$this->execution_time += $time2 - $time1;

		$this->time_log("ar", $time2 - $time1, $q);

		if (!$r) {
			$err = $this->error();

			if ($err) {
				$this->_log("unable to exec query \"$q\"", false);
				$this->_log($err, false);
			}

			return false;
		}

		return $r;
	}

	public static function fields_to_string_for_insert($ar)
	{
		return join(',', array_map(function($k) {
			return static::QUOTE_FIELD . ($k && $k[0] == '*' ? substr($k, 1) : $k) . static::QUOTE_FIELD;
		}, array_keys($ar)));
	}

	public static function values_to_string_for_insert($ar)
	{
        $outAr = [];

        foreach ($ar as $f => $v) {
			if ($f[0] == '*') {
				$outAr[] = $v;
			} elseif ($v === null) {
			    $outAr[] = 'NULL';
            } else {
				$outAr[] = static::QUOTE_VALUE . $v . static::QUOTE_VALUE;
			}
		}

		return join(',', $outAr);
	}

	public static function fields_and_values_to_string_for_update($ar)
	{
        $q_ar = [];

        foreach ($ar as $f => $v) {
			if ($v === null) {
				$q_ar[] = static::QUOTE_FIELD . $f . static::QUOTE_FIELD . ' = NULL';

				continue;
			}

			$q_ar[] = $f[0] === '*'
				? static::QUOTE_FIELD . substr($f, 1) . static::QUOTE_FIELD . ' = ' . $v
				: static::QUOTE_FIELD . $f . static::QUOTE_FIELD . ' = ' . static::QUOTE_VALUE . $v. static::QUOTE_VALUE;
		}

		return join(',', $q_ar);
	}

    /*
     * enter $keyField if it differs from 'id'
     */
    protected static function insertUpdateQuery($fields_values, $keyField = null)
    {
        $q1 = static::insertUpdateQueryBeginning($keyField);
        $q3 = static::fields_and_values_to_string_for_update($fields_values) . static::insertUpdateQueryEnding();

        return " {$q1} {$q3}";
    }

    public static function insertUpdateQueryBeginning($keyField = null)
    {
        return 'ON DUPLICATE KEY UPDATE';
    }

    public static function insertUpdateQueryEnding()
    {
        return '';
    }

	public function lockTable($table)
    {
        $this->__q("LOCK TABLES $table WRITE");

        return $this;
    }

    public function unlockTable($table = null)
    {
        $this->__q("UNLOCK TABLES");

        return $this;
    }

	public function insert($table, $fieldValues = [])
    {
        $t = $this->get_table_name($table);

        // preparing for multi-insert
        if (!is_array(current($fieldValues))) {
            $fieldValues = [$fieldValues];
        }

        $q1 = "(" . self::fields_to_string_for_insert(current($fieldValues)) . ")";
        $q2_ar = [];

        foreach ($fieldValues as $ar) {
            $q2_ar[] = "(" . self::values_to_string_for_insert($ar) . ")";
        }

        $time1 = utime();

        $this->lockTable($t);
        if (!$this->__rq("INSERT INTO {$t}{$q1} VALUES" . join(",", $q2_ar) . ";")) {
            $this->_log("Unable to insert into table $t", true);

            $this->unlockTable($t);

            return false;
        }
        $this->lastInsertId = $this->__insert_id();
        $this->unlockTable($t);

        $time2 = utime();
        $this->execution_time += $time2 - $time1;
        $this->time_log("insert", $time2 - $time1);

        return $this->lastInsertId;
	}

	public function getLastInsertId()
    {
        return $this->lastInsertId;
    }

    public function getUpdateSingleLimit()
    {
        return $this->limitOffset(1);
    }

	public function update($table, $fieldValues = array(), $q_ending = "")
	{
		$time1 = utime();

		$t = $this->get_table_name($table);

		// fast construction to get record by id
		if (is_numeric($q_ending)) {
            $q_ending = "WHERE {$this->escapeField('id')} = " . $this->escapeValue($q_ending) . $this->getUpdateSingleLimit();
        } elseif (is_array($q_ending)) {
            $q_ending = "WHERE " . $this->escapeField('id') . $this->in($q_ending);
        } elseif (!$q_ending && $q_ending !== "") {
			$this->_log("Warning, empty Q_ENDING in update ($table)", false);

			return false;
			//$q_ending = "WHERE 1=0";
		}
		//

        $q = "UPDATE $t SET " . self::fields_and_values_to_string_for_update($fieldValues) . " $q_ending";

		$this->lockTable($t);
		if (!$this->__rq($q)) {
			$this->_log("Unable to update: $q", true);

            $this->unlockTable($t);

			return false;
		}

		$this->affected_rows = $this->__affected_rows();
        $this->unlockTable($t);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;
		$this->time_log("update", $time2 - $time1, $q);

		return true;
	}

    public function getDeleteSingleLimit()
    {
        return  $this->limitOffset(1);
    }

	public function delete($table, $q_ending = "")
	{
		$time1 = utime();

		$t = $this->get_table_name($table);

		// fast construction to get record by id
        if (is_numeric($q_ending)) {
            $q_ending = "WHERE id = '$q_ending'" . $this->getDeleteSingleLimit();
        } elseif (is_array($q_ending)) {
            $q_ending = "WHERE id" . $this->in($q_ending);
        } elseif (!$q_ending && $q_ending !== "") {
            $this->_log("Warning, empty Q_ENDING in delete ($table)", false);

            return false;
        }

		$q = "DELETE FROM $t $q_ending";

        $this->lockTable($t);
		if (!$this->__rq($q)) {
			$this->_log("Unable to delete: $q", false);

            $this->unlockTable($t);

			return false;
		}
        $this->unlockTable($t);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;
		$this->time_log("delete", $time2 - $time1, $q);

		return true;
	}

	/*
	 * enter $keyField if it differs from 'id'
	 */
	public function insert_or_update($table, $fields_values = [], $keyField = null)
	{
		$t = $this->get_table_name($table);

        $q1 = "(" . static::fields_to_string_for_insert($fields_values) . ")";
        $q2 = "(" . static::values_to_string_for_insert($fields_values) . ")";
        $q3 = static::insertUpdateQuery($fields_values, $keyField);

		$time1 = utime();

        $this->lockTable($t);
        $query = "INSERT INTO {$t}{$q1} VALUES{$q2}{$q3};";
		if (!$this->__rq($query)) {
			$this->_log("unable to insert/update into table $t", false);

            $this->unlockTable($t);

			return false;
		}
		$id = $this->__insert_id();
        $this->unlockTable($t);

		$time2 = utime();
		$this->execution_time += $time2 - $time1;
		$this->time_log("insert", $time2 - $time1);

		return $id;
	}

	public function drop($table)
	{
		$t = $this->get_table_name($table);

		if (!$this->__rq("DROP TABLE $t")) {
            return $this->_log("unable to drop table $t", false);
        }

		return true;
	}

	public function reset(&$rs)
	{
		return $this->__reset($rs);
	}

	public function fetch($rs)
	{
		return $rs ? $this->__fetch($rs) : null;
	}

	public function fetch_array($rs)
	{
		return $rs ? $this->__fetch_array($rs) : null;
	}

	public function fetch_ar($rs)
	{
		return $rs ? $this->fetch_array($rs) : null;
	}

	public function rs_go($func, $table, $q_ending = "", $q_fields = "*")
	{
		$i = 0;

		$rs = $this->rs($table, $q_ending, $q_fields);
		while ($r = $this->fetch($rs)) {
			$func($r, $i++);
		}

		return $this;
	}

	public function count($rs)
	{
		return $this->__count($rs);
	}

	public function set_charset($name)
	{
		return $this->__set_charset($name);
	}

	public function get_charset()
	{
		return $this->__get_charset();
	}

	protected function getStartTransactionQuery()
    {
        return 'START TRANSACTION';
    }

    protected function getCommitTransactionQuery()
    {
        return 'COMMIT';
    }

    protected function getRollbackTransactionQuery()
    {
        return 'ROLLBACK';
    }

	public function startTransaction()
	{
		$this->transactionNestingLevel++;

		if ($this->getStartTransactionQuery()) {
            $this->q($this->getStartTransactionQuery());
        }

		return $this;
	}

	public function commitTransaction()
	{
		if ($this->transactionNestingLevel) {
			$this->transactionNestingLevel--;

			if ($this->getCommitTransactionQuery()) {
                $this->q($this->getCommitTransactionQuery());
            }
		}

		return $this;
	}

	public function rollbackTransaction()
	{
		if ($this->transactionNestingLevel) {
			$this->transactionNestingLevel--;

			if ($this->getRollbackTransactionQuery()) {
                $this->q($this->getRollbackTransactionQuery());
            }
		}

		return $this;
	}

	public function getBetweenOperator($val1 = null, $val2 = null)
    {
        if ($val1) {
            $val1 = $this->escapeValue($val1);
        }

        if ($val2) {
            $val2 = $this->escapeValue($val2);
        }

        if ($val1 && $val2) {
            $op = "BETWEEN $val1 AND $val2";
        } elseif ($val1) {
            $op = ">= $val1";
        } elseif ($val2) {
            $op = "<= $val2";
        } else {
            $op = null;
        }

        return $op;
    }

	/**
	 * Prepares and quotes string for query as param
	 *
	 * @param $string
	 *
	 * @return string
	 */
	public function escapeTable($string)
	{
		return static::QUOTE_TABLE . $this->escape_string($string) . static::QUOTE_TABLE;
	}

	/**
	 * Prepares and quotes string for query as param
	 *
	 * @param $string
	 *
	 * @return string
	 */
	public function escapeField($string)
	{
		$x = strpos($string, '.');

		if ($x !== false) {
			$alias = static::QUOTE_FIELD . substr($string, 0, $x) . static::QUOTE_FIELD . '.';
			$field = substr($string, $x + 1);
		} else {
			$alias = '';
			$field = $string;
		}

		return $field !== '*'
			? $alias . static::QUOTE_FIELD . $this->escape_string($field) . static::QUOTE_FIELD
			: $alias . $field;
	}

	/**
	 * Prepares and quotes string for query as param
	 *
	 * @param $string
	 *
	 * @return string
	 */
	public function escapeValue($string)
	{
		return static::QUOTE_VALUE . $this->escape_string($string) . static::QUOTE_VALUE;
	}

	public function limitOffset($limit = null, $offset = null)
    {
        $ar = [];

        if ($limit) {
            $ar[] = "LIMIT $limit";
        }

        if ($offset) {
            $ar[] = "OFFSET $offset";
        }

        return ' ' . join(' ', $ar);
    }

    /**
     * @param string $field
     * @param string $method get/set/has
     */
    public function getFieldMethodForModel($field, $method)
    {
        return camelize(underscore($method) . '_' . $field);
    }

	/* these methods should be overwritten */

	abstract protected function __connect();
	abstract protected function __close();
	abstract protected function __error();
	abstract protected function __q($q);
	abstract protected function __rq($q);
	abstract protected function __mq($q);
	abstract protected function __mq_flush();
	abstract protected function __reset(&$rs);
	abstract protected function __fetch($rs);
	abstract protected function __fetch_array($rs);
	abstract protected function __count($rs);
	abstract protected function __insert_id();
	abstract protected function __affected_rows();
	abstract protected function __set_charset($name);
	abstract protected function __get_charset();
    abstract public function getTablesInfo();
	abstract public function getTableNames();
    abstract public function getFields($table);
}


text:
package redeyes.doc

import scalaz.Monoid

sealed trait Doc {
  import Doc._

  def toBlock: Block

  def :+ (that: Doc): Doc = (this, that) match {
    case (Empty, _) => that
    case (_, Empty) => this

    case (BlockRun(content1), BlockRun(content2)) => BlockRun(content1 ++ content2)

    case (BlockRun(content1), that : Block) => BlockRun(content1 :+ that)
    case (BlockRun(content1), that : Inline) => BlockRun(content1 :+ BlockText(Vector(that)))

    case (this0 : Block, BlockRun(content2)) => BlockRun(this0 +: content2)
    case (this0 : Inline, BlockRun(content2)) => BlockRun(BlockText(Vector(this0)) +: content2)

    case (InlineRun(content1), InlineRun(content2)) => InlineRun(content1 ++ content2)

    case (InlineRun(content1), that : Inline) => InlineRun(content1 :+ that)

    case (this0 : Inline, InlineRun(content2)) => InlineRun(this0 +: content2)

    case (this0 : Block, that : Block) => BlockRun(Vector(this0, that))

    case (this0 : Block, that : Inline) => BlockRun(Vector(this0, that.toBlock))

    case (this0 : Inline, that : Block) => BlockRun(Vector(this0.toBlock, that))

    case (this0 : Inline, that : Inline) => InlineRun(Vector(this0, that))
  }
}

trait DocInstances {
  implicit def DocumentDocumented[A <: Doc]: Documented[A] = new Documented[A] {
    def document(value: A) = value
  }

  implicit val DocMonoid = new Monoid[Doc] {
    def zero = Doc.Empty

    def append(v1: Doc, v2: => Doc) = v1 :+ v2
  }
}

object Doc extends DocInstances {
  sealed trait Inline extends Doc
  sealed trait Block extends Doc {
    def toBlock = this
  }

  case object Empty extends Inline with Block

  final case class Section(title: String, content: Doc) extends Block
  final case class BlockRun(content: Vector[Block]) extends Block

  final case class Th(content: String, align: Align)
  final case class Table(header: Vector[Th], content: Vector[Vector[Doc]]) extends Block

  final case class BlockText(content: Vector[Inline]) extends Block
  final case class BlockCode(language: String, content: String) extends Block

  final case class OrderedList(content: Vector[Doc]) extends Block
  final case class UnorderedList(content: Vector[Doc]) extends Block

  final case class InlineText(content: String) extends Inline {
    def toBlock = BlockText(Vector[Inline](this))
  }
  final case class InlineCode(language: String, content: String) extends Inline {
    def toBlock = BlockCode(language, content)
  }
  final case class InlineEmphasis(content: String) extends Inline {
    def toBlock = BlockText(Vector[Inline](this))
  }
  final case class InlineLink(name: String, url: String) extends Inline {
    def toBlock = BlockText(Vector[Inline](this))
  }
  final case class InlineRun(content: Vector[Inline]) extends Inline {
    def toBlock = BlockText(Vector[Inline](this))
  }

  sealed trait Align
  object Align {
    case object Left extends Align
    case object Right extends Align
    case object Center extends Align
  }
}

trait Documented[A] {
  def document(value: A): Doc
}

object Documented {
  @inline
  final def apply[A](implicit d: Documented[A]) = d
}


text:
//Declare an integer variable and assign it with the value 254 in hexadecimal format (0x##).
//Use Windows Calculator to find its hexadecimal representation.
//Print the variable and ensure that the result is 254.
using System;

namespace Variable_in_Hexadecimal_Format
{
    class Program
    {
        static void Main()
        {
            int myInt = 254;
            string myHex = myInt.ToString("X");
            int myNewInt = Convert.ToInt32(myHex, 16);
            Console.WriteLine(myNewInt);
        }
    }
}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Conf extends Model
{
    protected $table = 'config';
    //protected $fillable = ['parent_id', 'level', 'name', 'name_en', 'org', 'for_org', 'independent', 'allow_admin', 'allow_root', 'allow_master', 'is_shop', 'is_supplier', 'is_customer', 'locked', 'hide', 'order', 'extra', 'content', 'content_en', 'created_by'];
    public $timestamps = false;
}