text:
package com.darly.im.ui.chatting.model;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.darly.dlclent.R;
import com.darly.im.common.utils.DemoUtils;
import com.darly.im.common.utils.FileAccessor;
import com.darly.im.common.utils.ResourceHelper;
import com.darly.im.storage.IMessageSqlManager;
import com.darly.im.storage.ImgInfoSqlManager;
import com.darly.im.ui.chatting.ChattingActivity;
import com.darly.im.ui.chatting.holder.BaseHolder;
import com.darly.im.ui.chatting.holder.ImageRowViewHolder;
import com.darly.im.ui.chatting.view.ChattingItemContainer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.yuntongxun.ecsdk.ECMessage;

/**
 *

 * Title: ImageRxRow.java
 *

 *

 * Description:
 *

 *

 * Copyright: Copyright (c) 2014
 *

 *

 * Company: Beijing Speedtong Information Technology Co.,Ltd
 *

 *
 * @author Jorstin Chan
 * @date 2014-4-17
 * @version 1.0
 */
public class ImageRxRow extends BaseChattingRow {

	public ImageRxRow(int type) {
		super(type);
	}

	@Override
	public View buildChatView(LayoutInflater inflater, View convertView) {

		// we have a don't have a converView so we'll have to create a new one
		if (convertView == null) {
			convertView = new ChattingItemContainer(inflater,
					R.layout.chatting_item_from_picture);

			// use the view holder pattern to save of already looked up subviews
			ImageRowViewHolder holder = new ImageRowViewHolder(mRowType);
			convertView.setTag(holder.initBaseHolder(convertView, true));

		}
		// actually setup the view
		return convertView;
	}

	@Override
	public void buildChattingData(Context context, BaseHolder baseHolder,
			ECMessage detail, int position) {

		String isRead = IMessageSqlManager.getMsgReadStatus(detail.getMsgId());

		boolean isFireMsg = IMessageSqlManager.isFireMsg(detail.getMsgId());

		final ImageRowViewHolder holder = (ImageRowViewHolder) baseHolder;
		String userData = detail.getUserData();
		ViewHolderTag holderTag = ViewHolderTag.createTag(detail,
				ViewHolderTag.TagType.TAG_VIEW_PICTURE, position);
		View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment
				.getChattingAdapter().getOnClickListener();
		holder.chattingContentIv.setTag(holderTag);
		holder.chattingContentIv.setOnClickListener(onClickListener);
		if (isFireMsg && "1".equals(isRead)) {
			holder.chattingContentIv.setOnClickListener(null);
		}

		holder.chattingContentIv.setImageResource(0);
		holder.chattingContentIv.invalidate();

		if (TextUtils.isEmpty(userData)) {
			return;
		}
		int start = userData.indexOf("THUMBNAIL://");
		int gif = userData.indexOf(",PICGIF://");
		boolean isGif = userData.contains("PICGIF://true");
		if (start != -1) {
			String thumbnail;
			if (gif == -1) {
				thumbnail = userData.substring(start);
			} else {
				thumbnail = userData.substring(start, gif);
			}
			Bitmap thumbBitmap = ImgInfoSqlManager.getInstance()
					.getThumbBitmap(thumbnail, 2);
			final ImgInfo imgInfo = ImgInfoSqlManager.getInstance().getImgInfo(
					detail.getMsgId());
			DisplayImageOptions.Builder optionsBuilder = DemoUtils
					.getChatDisplayImageOptionsBuilder();
			optionsBuilder.showImageOnLoading(new BitmapDrawable(thumbBitmap));
			if (imgInfo != null && !TextUtils.isEmpty(imgInfo.getBigImgPath())) {
				if (imgInfo.getBigImgPath().startsWith("http:")) {
					if (isFireMsg) {
						if ("1".equals(isRead)) {
							ImageLoader.getInstance().displayImage("assets://msg_fire_readed.png", holder.chattingContentIv);

						} else {
							ImageLoader.getInstance().displayImage("assets://msg_fire_unread.png", holder.chattingContentIv);
						}
					} else {
						ImageLoader.getInstance().displayImage(
								imgInfo.getBigImgPath(),
								holder.chattingContentIv,
								optionsBuilder.build(),
								new SimpleImageLoadingListener() {
									@Override
									public void onLoadingComplete(
											String imageUri, View view,
											Bitmap loadedImage) {
										super.onLoadingComplete(imageUri, view,
												loadedImage);
										if (imageUri.startsWith("http:")) {
											File imgCacheFile = DiskCacheUtils
													.findInCache(
															imageUri,
															ImageLoader
																	.getInstance()
																	.getDiskCache());
											if (imgCacheFile != null) {
												imgInfo.setBigImgPath(imgCacheFile
														.getAbsolutePath()
														.substring(
																imgCacheFile
																		.getAbsolutePath()
																		.lastIndexOf(
																				"/")));
												ImgInfoSqlManager.getInstance()
														.updateImageInfo(
																imgInfo);
											}
										}
									}
								});
					}

				} else {
					if (isFireMsg) {
						if ("1".equals(isRead)) {
							ImageLoader.getInstance().displayImage("assets://msg_fire_readed.png", holder.chattingContentIv);
						} else {
							ImageLoader.getInstance().displayImage("assets://msg_fire_unreaded.png", holder.chattingContentIv);
						}
					} else {
						ImageLoader.getInstance().displayImage(
								"file://" + FileAccessor.getImagePathName()
										+ "/" + imgInfo.getBigImgPath(),
								holder.chattingContentIv,
								optionsBuilder.build());
					}
				}
			}
		}

		if (isGif) {
			boolean showGif = detail.getMsgStatus() == ECMessage.MessageStatus.SUCCESS
					|| detail.getMsgStatus() == ECMessage.MessageStatus.RECEIVE;
			if (holder.mGifIcon != null) {
				holder.mGifIcon.setVisibility(!showGif ? View.GONE
						: View.VISIBLE);
			}
		} else {
			holder.mGifIcon.setVisibility(View.GONE);
		}
		int startWidth = userData.indexOf("outWidth://");
		int startHeight = userData.indexOf(",outHeight://");
		FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.chattingContentIv
				.getLayoutParams();
		if (startWidth != -1 && startHeight != -1 && start != -1) {
			int imageMinWidth = ResourceHelper.fromDPToPix(context, isGif ? 200
					: 100);
			int width = DemoUtils.getInt(userData.substring(startWidth
					+ "outWidth://".length(), startHeight), imageMinWidth);
			int height = DemoUtils.getInt(userData.substring(startHeight
					+ ",outHeight://".length(), start - 1), imageMinWidth);
			holder.chattingContentIv.setMinimumWidth(imageMinWidth);
			params.width = imageMinWidth;
			int _height = height * imageMinWidth / width;
			if (_height > ResourceHelper.fromDPToPix(context, 230)) {
				_height = ResourceHelper.fromDPToPix(context, 230);
				holder.chattingContentIv
						.setScaleType(ImageView.ScaleType.CENTER_CROP);
			}
			if (width != 0) {
				holder.chattingContentIv.setMinimumHeight(_height);
				params.height = _height;
			} else {
				holder.chattingContentIv.setMinimumHeight(imageMinWidth);
				params.height = imageMinWidth;
			}

			holder.chattingContentIv.setLayoutParams(params);

		}

	}

	@Override
	public int getChatViewType() {

		return ChattingRowType.IMAGE_ROW_RECEIVED.ordinal();
	}

	@Override
	public boolean onCreateRowContextMenu(ContextMenu contextMenu,
			View targetView, ECMessage detail) {
		// TODO Auto-generated method stub
		return false;
	}

}


text:
export declare var Math: Math;
export declare var NaN: any;

redpajama_set_name: RedPajamaGithub


text:
package org.kaaproject.kaa.server.common.core.schema;

public class KaaSchemaFactoryImpl implements KaaSchemaFactory {

  @Override
  public BaseSchema createBaseSchema(String schema) {
    return new BaseSchema(schema);
  }

  @Override
  public OverrideSchema createOverrideSchema(String schema) {
    return new OverrideSchema(schema);
  }

  @Override
  public ProtocolSchema createProtocolSchema(String schema) {
    return new ProtocolSchema(schema);
  }

  @Override
  public DataSchema createDataSchema(String schema) {
    return new DataSchema(schema);
  }

}


text:
checkAuthenticated(req, res, next)

Checks that a user is autenticated for a request, returns user to the login page if they are not.

initialize(app)

Initalizes the passport and sets up oAuth routes.

## checkAuthenticated(req, res, next)
Checks that a user is autenticated for a request, returns user to the login page if they are not.

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| req | Request | express request object. |
| res | Response | express response object |
| next | callback | express next callback, next function to call after success. |

## initialize(app)
Initalizes the passport and sets up oAuth routes.

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| app | App | express js application ojbect. |


text:
from perfrunner.helpers import local
from perfrunner.helpers.cbmonitor import timeit, with_stats
from perfrunner.helpers.profiler import with_profiles
from perfrunner.helpers.worker import java_dcp_client_task
from perfrunner.tests import PerfTest

class DCPThroughputTest(PerfTest):

    def _report_kpi(self, time_elapsed: float, clients: int, stream: str):
        self.reporter.post(
            *self.metrics.dcp_throughput(time_elapsed, clients, stream)
        )

    @with_stats
    @timeit
    @with_profiles
    def access(self, *args):
        username, password = self.cluster_spec.rest_credentials

        for target in self.target_iterator:
            local.run_dcptest(
                host=target.node,
                username=username,
                password=password,
                bucket=target.bucket,
                num_items=self.test_config.load_settings.items,
                num_connections=self.test_config.dcp_settings.num_connections
            )

    def warmup(self):
        self.remote.stop_server()
        self.remote.drop_caches()

        return self._warmup()

    def _warmup(self):
        self.remote.start_server()
        for master in self.cluster_spec.masters:
            for bucket in self.test_config.buckets:
                self.monitor.monitor_warmup(self.memcached, master, bucket)

    def run(self):
        self.load()
        self.wait_for_persistence()
        self.check_num_items()
        self.compact_bucket()

        if self.test_config.dcp_settings.invoke_warm_up:
            self.warmup()

        time_elapsed = self.access()

        self.report_kpi(time_elapsed,
                        int(self.test_config.java_dcp_settings.clients),
                        self.test_config.java_dcp_settings.stream)

class JavaDCPThroughputTest(DCPThroughputTest):

    def init_java_dcp_client(self):
        local.clone_git_repo(repo=self.test_config.java_dcp_settings.repo,
                             branch=self.test_config.java_dcp_settings.branch)
        local.build_java_dcp_client()

    @with_stats
    @timeit
    @with_profiles
    def access(self, *args):
        for target in self.target_iterator:
            local.run_java_dcp_client(
                connection_string=target.connection_string,
                messages=self.test_config.load_settings.items,
                config_file=self.test_config.java_dcp_settings.config,
            )

    def run(self):
        self.init_java_dcp_client()

        super().run()

class JavaDCPCollectionThroughputTest(DCPThroughputTest):

    def init_java_dcp_clients(self):
        if self.worker_manager.is_remote:
            self.remote.init_java_dcp_client(repo=self.test_config.java_dcp_settings.repo,
                                             branch=self.test_config.java_dcp_settings.branch,
                                             worker_home=self.worker_manager.WORKER_HOME,
                                             commit=self.test_config.java_dcp_settings.commit)

        else:
            local.clone_git_repo(repo=self.test_config.java_dcp_settings.repo,
                                 branch=self.test_config.java_dcp_settings.branch,
                                 commit=self.test_config.java_dcp_settings.commit)
            local.build_java_dcp_client()

    @with_stats
    @timeit
    @with_profiles
    def access(self, *args, **kwargs):
        access_settings = self.test_config.access_settings
        access_settings.workload_instances = int(self.test_config.java_dcp_settings.clients)
        PerfTest.access(self, task=java_dcp_client_task, settings=access_settings)

    def run(self):
        self.init_java_dcp_clients()
        self.load()
        self.wait_for_persistence()
        self.check_num_items()
        self.compact_bucket()

        if self.test_config.access_settings.workers > 0:
            self.access_bg()

        time_elapsed = self.access()

        self.report_kpi(time_elapsed,
                        int(self.test_config.java_dcp_settings.clients),
                        self.test_config.java_dcp_settings.stream)


text:
package java.nio.channels;

public class AlreadyConnectedException
  extends java.lang.IllegalStateException{
  // Constructors

  public AlreadyConnectedException(){
    super();
  }
}


text:
#region Apache License, Version 2.0
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
#endregion

using GalaSoft.MvvmLight.Messaging;
using Microsoft.Practices.ServiceLocation;
using SaveAndPlay.DAL.Entities;
using SaveAndPlay.Service;
using SaveAndPlay.ViewModels;
using SaveAndPlay.ViewModels.Messages;
using SaveAndPlay.ViewService;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace SaveAndPlay.UI.Pages
{
    public partial class MusicListPage : BasePage
    {
        public MusicListPage()
        {
            InitializeComponent();
            base.baseProgressOverlay = this.progressOverlay;
            base.baseProgressBarLabel = this.baseProgressBarLabel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            this.progressOverlay.Visibility = System.Windows.Visibility.Visible;
            App.DataCacheServiceInstance.Register((MusicListViewModel)this.DataContext);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            App.DataCacheServiceInstance.Unregister((MusicListViewModel)this.DataContext);
            ((MusicListViewModel)this.DataContext).Unload();
            this.progressOverlay.Visibility = System.Windows.Visibility.Visible;
        }

        private void ApplicationBarMenuItem_Settings_Click(object sender, EventArgs e)
        {
            if (this.ApplicationSettingsService.IsDefinedPassword())
            {
                this.NavigationViewService.NavigateTo("/UI/Pages/ProtectedModePage.xaml");
            }
            else
            {
                this.NavigationViewService.NavigateTo("/UI/Pages/ProtectedModeNewPasswordPage.xaml");
            }
        }

        private void ApplicationBarMenuItem_About_Click(object sender, EventArgs e)
        {
            this.NavigationViewService.NavigateTo("/UI/Pages/AboutPage.xaml");
        }

        private void SongButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender != null)
            {
                var media = ((Button)sender).DataContext as AudioMedia;
                if (media != null)
                {
                    this.PlaybackAgentService.Play(media);
                }
            }
        }

        private void AlbumButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender != null)
            {
                var media = ((Button)sender).DataContext as Album;
                if (media != null)
                {
                    this.PlaybackAgentService.Play(media);
                }
            }
        }

        private void ArtistButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender != null)
            {
                var media = ((Button)sender).DataContext as Artist;
                if (media != null)
                {
                    this.PlaybackAgentService.Play(media);
                }
            }
        }

        private void PlaylistButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender != null)
            {
                var media = ((Button)sender).DataContext as Playlist;
                if (media != null)
                {
                    this.PlaybackAgentService.Play(media);
                }
            }
        }

        private void SongsJumpList_SelectedItemChanged(object sender, EventArgs e)
        {
            if (this.SongsJumpList.SelectedItem != null)
            {
                ((MusicListViewModel)this.DataContext).SelectedSong = (AudioMedia)this.SongsJumpList.SelectedItem;
                this.SongsJumpList.SelectedItem = null;
            }
        }

        private void AlbumsJumpList_SelectedItemChanged(object sender, EventArgs e)
        {
            if (this.AlbumsJumpList.SelectedItem != null)
            {
                ((MusicListViewModel)this.DataContext).SelectedAlbum = (Album)this.AlbumsJumpList.SelectedItem;
                this.AlbumsJumpList.SelectedItem = null;
            }
        }

        private void ArtistsJumpList_SelectedItemChanged(object sender, EventArgs e)
        {
            if (this.ArtistsJumpList.SelectedItem != null)
            {
                ((MusicListViewModel)this.DataContext).SelectedArtist = (Artist)this.ArtistsJumpList.SelectedItem;
                this.ArtistsJumpList.SelectedItem = null;
            }
        }

        private void PlaylistsJumpList_SelectedItemChanged(object sender, EventArgs e)
        {
            if (this.PlaylistsJumpList.SelectedItem != null)
            {
                ((MusicListViewModel)this.DataContext).SelectedPlaylist = (Playlist)this.PlaylistsJumpList.SelectedItem;
                this.PlaylistsJumpList.SelectedItem = null;
            }
        }

        private void AddPlaylistButton_Click(object sender, RoutedEventArgs e)
        {
            ((MusicListViewModel)this.DataContext).NewPlaylist();
        }

        private void PlayAllRandom_Click(object sender, RoutedEventArgs e)
        {
            this.PlaybackAgentService.PlayRandom(App.DataCacheServiceInstance.SongsVisible.ToList());
        }
    }
}


text:
package org.springframework.cloud.servicebroker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;

public final class JsonUtils {

	private JsonUtils() {
	}

	public static String toJson(Object object) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.writeValueAsString(object);
		}
		catch (JsonProcessingException e) {
			fail("Error creating JSON string from object: " + e);
			throw new IllegalStateException(e);
		}
	}

	public static DocumentContext toJsonPath(Object object) {
		Configuration configuration = Configuration.builder()
				.jsonProvider(new JacksonJsonProvider())
				.mappingProvider(new JacksonMappingProvider())
				.build();

		return JsonPath.parse(toJson(object), configuration);
	}

	public static <T> T fromJson(String json, Class<T> contentType) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.readerFor(contentType).readValue(json);
		}
		catch (IOException e) {
			fail("Error creating object from JSON: " + e);
			throw new IllegalStateException(e);
		}
	}

	public static <T> T readTestDataFile(String filename, Class<T> contentType) {
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			return objectMapper.readValue(getTestDataFileReader(filename), contentType);
		}
		catch (IOException e) {
			fail("Error reading test JSON file: " + e);
			throw new IllegalStateException(e);
		}
	}

	private static Reader getTestDataFileReader(String fileName) {
		return new BufferedReader(new InputStreamReader(JsonUtils.class.getResourceAsStream("/" + fileName)));
	}

	/**
	 * Detect duplicate properties in json object through searching ":" in json string (reading into a map would remove
	 * such duplicate, preventing effective duplicate detection)
	 */
	public static void assertThatJsonHasExactNumberOfProperties(Object object, int expectedNbProperties) {
		//
		String jsonString = toJson(object);
		assertThat(jsonString.split(":")).as("extra duplicate properties in json object: " + jsonString)
				.hasSize(1 + expectedNbProperties);
	}

}


text:
layout: post
title: My favorite chrome extension
published: false
---

* [Chrome buddy](https://chrome.google.com/webstore/detail/session-buddy/edacconmaakjimmfgnblocblbcdcpbko/related?hl=en)


text:
class CreateMeetupGroups < ActiveRecord::Migration
  def change
    create_table "meetup_groups", id: false, primary_key: 'meetup_group_id' do |t|
      t.string  "meetup_group_id",  null: false
      t.string  "name",             null: false
      t.string  "urlname",          null: false
      t.boolean "enable_sync",      null: false, default: true
      t.string  "tags",             null: false, default: [], array: true

      t.timestamps
    end
  end
end


text:
package com.xinyou.frame.service;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import com.xinyou.frame.domain.biz.FrameConfig;
import com.xinyou.frame.domain.biz.USR_BIZ;
import com.xinyou.frame.domain.entities.USR_MAIN;
import com.xinyou.frame.domain.models.EntityListDM;
import com.xinyou.frame.domain.models.FUN_NODE;
import com.xinyou.frame.domain.models.USR_MAIN_VIEW;
import com.xinyou.frame.request.UsrRequest;
import com.xinyou.frame.response.UsrResponse;
import com.xinyou.util.ConnectionManager;
import com.xinyou.util.Log;
import com.xinyou.util.ServiceBase;

@Path("/Usr")
@Produces({MediaType.APPLICATION_JSON})
public class Usr extends ServiceBase {

	  USR_MAIN ui = null;
	  private void getUserInfo(String  token,Connection conn) throws Exception {
		   ui = new USR_MAIN();
		   if(token == null || token.length() == 0) {
			   ui.setStatus(1);
			   return;
		   }

		   USR_BIZ biz = new USR_BIZ();
		   ui = biz.getUserInfo(token, conn);
	  }
	  /**
	   *  用户登录(网页)
	   * */
	  @POST
	  @Consumes( {MediaType.APPLICATION_JSON })
	  @Path(value="/signIn")
	  public UsrResponse signIn(UsrRequest usr_request,
			                 @Context HttpServletResponse httpResponse) {
		   UsrResponse response = new UsrResponse();
		   Connection conn = null;

		   try {

			   conn = ConnectionManager.getConnection(FrameConfig.DSNAME);
			   if(usr_request.getUsr_name() == null || usr_request.getUsr_name().isEmpty()) {
				    throw new IllegalArgumentException("");
			   }

			   if(usr_request.getUsr_pswd()==null||usr_request.getUsr_pswd().isEmpty()){
					throw new IllegalArgumentException("密码不能为空");
				}
				if(usr_request.getUsr_pswd().length()<1){
					throw new IllegalArgumentException("密码长度不小于1位");
				}

				USR_BIZ biz = new USR_BIZ();
				USR_MAIN_VIEW usr_main_view = biz.signIn(usr_request.getUsr_name(), usr_request.getUsr_pswd(), conn);
				Cookie tokenCookie = new Cookie("frame_token",usr_main_view.getToken());
				tokenCookie.setPath("/");
				tokenCookie.setMaxAge(7200);
				httpResponse.addCookie(tokenCookie);
				response.setInfo("");
				response.setStatus("0");

		   }catch(Exception ex) {

			   response.setInfo(ex.getMessage()== null ? "null":ex.getMessage());
			   response.setStatus("1");

			   StackTraceElement StackTrace = new Exception().getStackTrace()[0];
			   Log.logSys(FrameConfig.CONFIGNAME, StackTrace.getClassName(), StackTrace.getMethodName(), response.getInfo(), "Exception");

		   }finally {

				try {if(conn!=null&&!conn.isClosed())conn.close();}
				catch (SQLException e) {};
		   }

		   return response;

	  }

	  /**
	   * PDA 用户登录
	   * */
	  @POST
	  @Consumes({MediaType.APPLICATION_JSON})
	  @Path(value="/signIn_pda")
	  public UsrResponse signIn_pda(USR_MAIN usr) {
		  UsrResponse response = new UsrResponse();
		  Connection conn=null;
		  try {
			  conn = ConnectionManager.getConnection(FrameConfig.DSNAME);
			  if(usr.getUsr_name()==null||usr.getUsr_name().isEmpty()){
					throw new IllegalArgumentException("用户名不能为空");
				}
				if(usr.getUsr_pswd()==null||usr.getUsr_pswd().isEmpty()){
					throw new IllegalArgumentException("密码不能为空");
				}
				if(usr.getUsr_pswd().length()<6){
					throw new IllegalArgumentException("密码长度不小于6位");
				}
				USR_BIZ biz = new USR_BIZ();
			  EntityListDM<USR_MAIN,FUN_NODE>	 dm =   biz.signIn_pda(usr, conn);
			  response.setDataDM( dm );
			  response.setInfo("");
			  response.setStatus("0");

		  }catch(Exception ex) {

			  response.setInfo(ex.getMessage()==null?"java.lang.NullPointerException: null":ex.getMessage());
			  response.setStatus("1");

		  }finally {
				try {if(conn!=null&&!conn.isClosed())conn.close();} catch (SQLException e) {};

		  }

		  return response;
	  }
}


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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <parent>
	<groupId>org.wso2.carbon</groupId>
	<artifactId>apimgt</artifactId>
	<version>4.3.0-SNAPSHOT</version>
	<relativePath>../pom.xml</relativePath>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.wso2.carbon</groupId>
  <artifactId>org.wso2.carbon.apimgt.core</artifactId>
  <version>4.3.0-SNAPSHOT</version>
  <packaging>bundle</packaging>
  <name>WSO2 Carbon - API Management Core </name>

   <dependencies>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.core</artifactId>
            <version>${carbon.kernel.version}</version>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.throttle.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.apimgt.impl</artifactId>
            <version>${apim.version}</version>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.apimgt.keymgt.stub</artifactId>
            <version>${apim.version}</version>
        </dependency>
	<dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.apimgt.usage.publisher</artifactId>
            <version>${apim.version}</version>
        </dependency>
   </dependencies>

   <build>
	<plugins>
   	   <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>1.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Private-Package>
                        </Private-Package>
                        <Export-Package>
                            org.wso2.carbon.apimgt.core.*,
                        </Export-Package>
                        <Import-Package>
                            org.wso2.carbon.core,
                            org.wso2.carbon.registry.core.service,
                            javax.xml.soap;version="1.0.0",
                            org.wso2.carbon.apimgt.impl.*,
                            *;resolution:=optional
                        </Import-Package>
                        <DynamicImport-Package>*</DynamicImport-Package>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
                <version>1.0.10</version>
                <executions>
                    <execution>
                        <id>generate-scr-scrdescriptor</id>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
      </plugins>
    </build>

</project>


text:
<?php
class foo {}
var_dump (is_scalar (TRUE));
var_dump (is_scalar (1));
var_dump (is_scalar (1.0));
var_dump (is_scalar ("Hi!"));
var_dump (is_scalar (NULL));
var_dump (is_scalar (array ()));
var_dump (is_scalar (new foo()));
var_dump (is_scalar (opendir('.')));
?>


text:
import { Component, OnInit } from '@angular/core';
import { Logger } from './logger.model';

@Component({
  selector: 'paragraph',
  templateUrl: './paragraph.component.html',
  styleUrls: ['./paragraph.component.css']
})
export class ParagraphComponent implements OnInit {

  private showParagraph: boolean = false;
  private buttonText: string = "Show Details"
  private logs: Array<Logger> = [];

  constructor() {

  }

  ngOnInit() {
  }

  public showDetails(event: HTMLInputElement) {
    this.addLogger(this.buttonText);

    if (this.showParagraph) {
      this.showParagraph = false;
      this.buttonText = "Show Details";
    }
    else {
      this.showParagraph = true;
      this.buttonText = "Hide Details";
    }
  }

  private addLogger(buttonClicked: string) {
    let timestamp: Date = new Date();

    let log: Logger = new Logger();
    log.buttonClicked = buttonClicked;
    log.rawTimestamp = timestamp.getTime().toString();
    log.dateTime = timestamp.toISOString();

    this.logs.push(log);
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1" name="viewport">

    <meta content="" name="description">
    <meta content="Scott Cole" name="author">
    <link href="../../favicon.ico" rel="icon">
    <title>Test Project</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/hub.css" rel="stylesheet">

    <link href="css/justified-nav.css" rel="stylesheet">

            <form class="navbar-form navbar-left" role="search">

                    <input class="form-control" placeholder="Search" type=
                    "text">

<button class="btn btn-primary" type=
                "submit">Submit</button>
            </form>

                    Tasks

                    Vegas

                    Casino

                    Bingo

                    Poker

                    Releases

                    Rota

                    Handover

                    Links

                    FAQ's

                    <form class="navbar-form navbar-left"></form>

Sky Casino

Guides and Procedures

Offer/Page Builds How to build every type of Sky
                Casino offer

Info Page Build

How to build a basic info page in IMS - Includes
                        step by step how to build the back end, sync through to
                        Pitboss and how to build the front end in Pitboss.

Guide

Deposit Offer Build

How to build a deposit offer in IMS - Includes step
                        by step how to build the back end, sync through to
                        Pitboss and how to build the front end in Pitboss.

Guide

Staking Offer Build

How to build a staking offer in IMS - Includes step
                        by step how to build the back end, sync through to
                        Pitboss and how to build the front end in Pitboss.

Guide

Spend Over Time Offer Build

How to build a spend over time offer in IMS -
                        Includes step by step how to build the back end, sync
                        through to Pitboss and how to build the front end in
                        Pitboss.

Guide

Giveaway Offers (free bonus)

How to build a free giveaway offer in IMS - Includes
                        step by step how to build the back end, sync through to
                        Pitboss and how to build the front end in Pitboss.

Guide

Cross Sell Offers

How to build a cross sell offer in IMS - Includes
                        step by step how to build the back end, sync through to
                        Pitboss and how to build the front end in Pitboss.

Guide

Payments/Crediting How to credit and upload the
                    lists for all Sky Casino offers

Uploading Customer Groups

How to upload a customer group to a covert offer

Guide

Live Casino Mondays

How to credit Live Casino Mondays - Includes checks and
                    autorsation steps

Guide

Racing Rebate

How to credit Racing Rebate - Includes checks and
                    authorisation steps

Guide

Cash Out Boost Credit

How to credit the Cash Out Boost - Includes checks and
                    authorisation steps

Guide

Oktoberfest Playback

How to credit Oktoberfest Playback promotion

Guide

Mystery Chips Credit

How to credit Sky Casino Mystery chips

Guide

Other Weekly/Daily tasks

Sign Up Report

How to pull the life time sign ups for Sky Casino
                    customers

Guide

Casino CIP's

How upload customers into IMS

Guide


text:
@class MyFavoritesDB;

@interface FavoritesSearchDB : NSObject
{
    MyFavoritesDB *_mmDB;
}

- (void).cxx_destruct;
- (_Bool)getSearchItemList:(id)arg1 byType:(int)arg2 SearchContent:(id)arg3 tags:(id)arg4;
- (_Bool)getSearchItemList:(id)arg1 byType:(int)arg2 SearchContent:(id)arg3;
- (_Bool)deleteSearchItemByLocalFavId:(unsigned int)arg1;
- (_Bool)insertOrUpdateSearchItem:(id)arg1;
- (void)initDB:(id)arg1;
- (id)init;

@end


text:
"""Generates match setups, given race and map constraints and an opponent."""

import collections
import random
from typing import Sequence

from absl import logging
from alphastar.commons import competitors
from pysc2.env import sc2_env

Match = collections.namedtuple('Match', ['home_race', 'away_race', 'map_name'])

class MatchGenerator:
  """Generates match setups, given race and map constraints and an opponent."""

  def __init__(self, home_races: Sequence[sc2_env.Race],
               away_races: Sequence[sc2_env.Race], map_names: Sequence[str]):
    """Initializer.

    Args:
      home_races: Races which the home (first) player may select.
      away_races: Races which the away (second) player may select.
      map_names: Maps which may be selected from.
    """
    if not home_races:
      raise ValueError('home_races must be non-empty')
    if not away_races:
      raise ValueError('away_races must be non-empty')
    if not map_names:
      raise ValueError('map_names must be non-empty')

    self._home_races = home_races
    self._away_races = away_races
    self._map_names = map_names

  def generate(self, opponent_name: str) -> Match:
    """Returns a random Match, taking into account opponent constraints.

    Args:
      opponent_name: Built-in bot difficulty name, else a competitor name.
    """
    if competitors.is_built_in_bot(opponent_name):
      home_races_available = self._home_races
      away_races_available = self._away_races
      map_names_available = self._map_names
    else:
      raise ValueError('Only games against built-in bots are supported at '
                       'the moment.')

    home_race = sc2_env.Race(random.choice(home_races_available))
    away_race = sc2_env.Race(random.choice(away_races_available))
    map_name = random.choice(map_names_available)
    logging.info('Match setup: Agent as %s, %s as %s - on %s.', home_race.name,
                 opponent_name, away_race.name, map_name)
    return Match(home_race, away_race, map_name)


text:
{{ page.title }}

          {% if page.tagline %}
{{ page.tagline }}
{% endif %}

    {% if page.title2 %}

{{ page.title2 }}

{% endif %}

    {% if page.title3 %}

{{ page.title3 }}
{% endif %}

{% include themes/bootstrap/nav-bar.html %}

          {% include ads-block.html %}

           {{ content }}

          {% include ads-block.html %}

                   {% include social-share.html %}

                {% unless page.categories == empty %}

                            Categories | {{page.categories | array_to_sentence_string}}

                {% endunless %}

We Love  New Opinions
Leave us a comment or a question

            {% include JB/comments %}

          {% include side-bar.html %}

Previous post

                    {% if page.previous %}

← {{ page.previous.title }}

                    {% else %}

← No more old posts

                     {% endif %}

Next Post

                            {% if page.next %}

{{ page.next.title }} →

                            {% else %}

No more new posts →

                            {% endif %}

        <button type="button" class="overlay-close">Close</button>

          <form action="//altervista.us8.list-manage.com/subscribe/post?u=a36bd3e356847dab838227fce&id=3c63d825b2" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

              Name

              <input class="span11" type="text" name="FNAME" id="first_name" placeholder="Jonathan">

              Email

              <input class="span11" type="text" id="email" name="EMAIL" placeholder="jon@doe.com">

              <input class="cbp-mc-submit" type="submit" value="Invia" name="subscribe" />

        </form>


text:
const assert = require('assert')

Object.prototype.checkMatch = function(o) {
	const self = this
	return Object.keys(this).every(function(key) {
		const val = self[key]
		// console.log(key, val, o[key] === val || val.checkMatch(o[key]))
		return o[key] === val || val.checkMatch(o[key])
	})
}

Function.prototype.checkMatch = function(o) {
	return this === o || this(o)
}

String.prototype.checkMatch = function(o) {
	return o === this
}

module.exports = function(o) {
	var handlers = []

	o.trigger = function(e) {
		handlers.filter(function(handler) {
			return handler[0].checkMatch(e)
		}).forEach(function(handler) {
			handler[1](e)
		})
	}

	o.addHandler = function(handler) {
		assert.equal(typeof(handler), 'object'); assert.notStrictEqual(handler, null)
		assert.equal(handler.length, 2)
		assert.equal(typeof(handler[1]), 'function')

		handlers.push(handler)
	}

	return o
}


text:
/* global async, Handlebars */

// https://support.google.com/chrome_webstore/answer/186213?hl=en
// http://developer.chrome.com/extensions/declare_permissions.html
var RISK_CATEGORY_TO_PERMISSIONS_MAP = {
  'high': [
    'plugin',
    'privacy'
  ],
  'medium': [
    'cookies',
    'geolocation',
    'unlimitedStorage'
  ],
  'low': [
    'management',
    'bookmarks',
    'history',
    'tabs',
    'notifications',
    'clipboardRead',
    'clipboardWrite',
    'storage'
  ]
};

// http://developer.chrome.com/extensions/match_patterns.html
var RISK_CATEGORY_TO_HOST_PERMISSIONS_MAP = {
  'high': [
    'http://*/*',
    'https://*/*',
    '*://*/*',
    '<all_urls>'
  ]
};

var RISK_SEVERITY_MAP = {
  'high': 3,
  'medium': 2,
  'low': 1
};

var DISABLED_REASON_MAP = {
  'unknown': 'Unknown',
  'permissions_increase': 'Disabled due to increased permission requirements'
};

var DEFAULT_DESIRED_ICON_SIZE = 24;
var EXTENSION_OVERVIEW_TMPL = Handlebars.templates['extension_overview'];
var EXTENSION_DETAILS_TMPL = Handlebars.templates['extension_details'];

function getRiskCategory(permissions, hostPermissions) {
  var i, categoryPermissions, permission, category;

  category = 'low';

  categoryPermissions = RISK_CATEGORY_TO_PERMISSIONS_MAP.high;

  for (i = 0; i < categoryPermissions.length; i++) {
    permission = categoryPermissions[i];

    if (permissions.indexOf(permission) !== -1) {
      category = 'high';
    }
  }

  categoryPermissions = RISK_CATEGORY_TO_HOST_PERMISSIONS_MAP.high;

  for (i = 0; i < categoryPermissions.length; i++) {
    permission = categoryPermissions[i];

    if (hostPermissions.indexOf(permission) !== -1) {
      category = 'high';
    }
  }

  if (category === 'high') {
    // No need to check further
    return category;
  }

  categoryPermissions = RISK_CATEGORY_TO_PERMISSIONS_MAP.medium;

  for (i = 0; i < categoryPermissions.length; i++) {
    permission = categoryPermissions[i];

    if (permissions.indexOf(permission) !== -1) {
      category = 'medium';
    }
  }

  return category;
}

function getContextForExtension(extension, desiredIconSize) {
  var icons, i, item, icon, context, permissions, hostPermissions, permissionWarnings;

  icon = null;
  context = {};

  desiredIconSize = desiredIconSize || DEFAULT_DESIRED_ICON_SIZE;

  icons = extension.icons || [];
  icons.sort(function compare(a, b) {
    if (a.size  b.size) {
      return 1;
    }
    else {
      return 0;
    }
  });

  // If deseried size is not available, find the largest one close to
  // the desired size
  for (i = 0; i < icons.length; i++) {
    item = icons[0];

    if (item.size === desiredIconSize) {
      icon = item.url;
      break;
    }
    else if (item.size > desiredIconSize) {
      icon = item.url;
      break;
    }
  }

  // If the closest largest icon is not available, use the first one
  if (!icon) {
    if (icons.length >= 1) {
      icon = icons[0].url;
    }
    else {
      icon = 'assets/img/questionmark.png';
    }
  }

  hostPermissions = extension.hostPermissions || [];
  permissionWarnings = extension.permissionWarnings || [];

  context.id = extension.id;
  context.name = extension.name;
  context.description = extension.description;
  context.website = extension.homepageUrl;
  context.disabled = !extension.enabled;
  context.disabledReason = null;
  context.icon = icon;

  context.hostPermissions = hostPermissions;
  context.permissions = extension.permissions;
  context.permissionWarnings = extension.permissionWarnings;
  context.riskCategory = getRiskCategory(extension.permissions,
                                         extension.hostPermissions);

  if (context.disabled && extension.disabledReason) {
    context.disabledReason = DISABLED_REASON_MAP[extension.disabledReason];
  }

  if (permissionWarnings.length >= 1) {
    context.summary = permissionWarnings[0];
  }
  else {
    context.summary = '';
  }

  return context;
}

function compareEnabledFirst(a, b) {
  if ((a.enabled && b.enabled) || (!a.enabled && !b.enabled)) {
    return 0;
  }

  if (a.enabled && !b.enabled) {
    return -1;
  }

  if (!a.enabled && b.enabled) {
    return 1;
  }
}

async.waterfall([
  function displayLoadingImage(callback) {
    var categories = Object.keys(RISK_SEVERITY_MAP), category;

    categories.forEach(function(category) {
      $('#' + category + '-risk-notice').html('');
    });

    callback();
  },

  function getAllPlugins(callback) {
    chrome.management.getAll(function(result) {
      callback(null, result);
    });
  },

  function filterExtension(result, callback) {
    var extensions = result.filter(function(item) {
      return (item.type === 'extension');
    });

    callback(null, extensions);
  },

  function assignPermissionWarnings(extensions, callback) {
    async.forEach(extensions, function(extension, callback) {
      chrome.management.getPermissionWarningsById(extension.id, function(warnings) {
        extension.permissionWarnings = warnings;
        callback();
      });
    }, function(err) {
      callback(err, extensions);
    });
  },

  function sortAndAssignContext(extensions, callback) {
    var result, categories, category;

    result = {
      'high': [],
      'medium': [],
      'low': []
    };

    categories = Object.keys(result);

    for (category in result) {
      $('#' + category + '-risk-notice').html('');
    }

    extensions.forEach(function(extension) {
      var htmlOverview, htmlDetails, context;

      context = getContextForExtension(extension);
      extension.context = context;
      result[context.riskCategory].push(extension);
    });

    for (category in result) {
      result[category].sort(compareEnabledFirst);
      extensions = result[category];

      $('#' + category + '-risk-count').html(extensions.length);

      if (extensions.length >= 1) {
        $('#' + category + '-risk-notice').remove();
      }
      else {
        $('#' + category + '-risk-notice').html('No extensions found');
      }

      extensions.forEach(function(extension) {
        var htmlOverview, htmlDetails;

        htmlOverview = EXTENSION_OVERVIEW_TMPL(extension.context);
        htmlDetails = EXTENSION_DETAILS_TMPL(extension.context);

        $('#' + category + '-risk-table').append(htmlOverview);
        $('tr#overview-' + extension.id).parent().append(htmlDetails);
      });
    }

    callback();
  }
]);


text:
package io.reactivex.netty.events;

import io.reactivex.netty.test.util.MockEventListener;
import org.hamcrest.Matchers;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import rx.Subscription;

import java.util.Collection;

import static org.hamcrest.MatcherAssert.*;

public class ListenersHolderRule extends ExternalResource {

    private ListenersHolder<MockEventListener> holder;

    @Override
    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                holder = new ListenersHolder<>();
                base.evaluate();
            }
        };
    }

    public ListenerWithSub addAListener() {
        final MockEventListener listener = new MockEventListener();
        Subscription subscription = holder.subscribe(listener);
        assertListenerAdded(listener);

        return new ListenerWithSub(listener, subscription);
    }

    public void assertListenerAdded(MockEventListener... listeners) {
        Collection<MockEventListener> allListeners = holder.getAllListeners();
        assertThat("Unexpected listeners count in the holder.", allListeners, Matchers.hasSize(listeners.length));
        assertThat("Listener not added to the holder.", allListeners, Matchers.contains(listeners));
    }

    public ListenersHolder<MockEventListener> getHolder() {
        return holder;
    }

    public static class ListenerWithSub {

        final MockEventListener listener;
        final Subscription subscription;

        public ListenerWithSub(MockEventListener listener, Subscription subscription) {
            this.subscription = subscription;
            this.listener = listener;
        }

        public MockEventListener getListener() {
            return listener;
        }

        public Subscription getSubscription() {
            return subscription;
        }
    }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#if ENABLE_HTTP_FOR_NFS

#include "NetworkFileSystemPrivatePCH.h"
#include "NetworkFileServerHttp.h"

class FNetworkFileServerClientConnectionHTTP : public FNetworkFileServerClientConnection
{

public:
	FNetworkFileServerClientConnectionHTTP(const FFileRequestDelegate& InFileRequestDelegate,
		const FRecompileShadersDelegate& InRecompileShadersDelegate, const TArray<ITargetPlatform*>& InActiveTargetPlatforms )
		:  FNetworkFileServerClientConnection( InFileRequestDelegate,InRecompileShadersDelegate,InActiveTargetPlatforms)
	{
	}

	bool SendPayload( TArray<uint8> &Out )
	{
		// Make Boundaries between payloads, add a visual marker for easier debugging.

		uint32 Marker = 0xDeadBeef;
		uint32 Size = Out.Num();

		OutBuffer.Append((uint8*)&Marker,sizeof(uint32));
		OutBuffer.Append((uint8*)&Size,sizeof(uint32));
		OutBuffer.Append(Out);

		return true;
	}

private:

	TArray<uint8>& GetOutBuffer() { return OutBuffer; }
	void ResetBuffer() { OutBuffer.Reset(); }

	TArray<uint8> OutBuffer;

    friend class FNetworkFileServerHttp;
};

//////////////////////////////////////////////////////////////////////////
// LibWebsockets specific structs.

// a object of this type is associated by libwebsocket to every http session.
struct PerSessionData
{
	// data being received.
	TArray<uint8> In;
	// data being sent out.
	TArray<uint8> Out;
};

// protocol array.
static struct libwebsocket_protocols Protocols[] = {
	/* first protocol must always be HTTP handler */
	{
			"http-only",   // name
			FNetworkFileServerHttp::CallBack_HTTP, // callback
			sizeof(PerSessionData),             // per_session_data_size
			15 * 1024,
			15 * 1024
	},
	{
		NULL, NULL, 0   /* End of list */
	}
};
//////////////////////////////////////////////////////////////////////////

FNetworkFileServerHttp::FNetworkFileServerHttp(
	int32 InPort,
	const FFileRequestDelegate* InFileRequestDelegate,
	const FRecompileShadersDelegate* InRecompileShadersDelegate,
	const TArray<ITargetPlatform*>& InActiveTargetPlatforms
	)
	:ActiveTargetPlatforms(InActiveTargetPlatforms)
	,Port(InPort)
{
	if (Port < 0 )
	{
		Port = DEFAULT_HTTP_FILE_SERVING_PORT;
	}

	UE_LOG(LogFileServer, Warning, TEXT("Unreal Network Http File Server starting up..."));

	if (InFileRequestDelegate && InFileRequestDelegate->IsBound())
	{
		FileRequestDelegate = *InFileRequestDelegate;
	}

	if (InRecompileShadersDelegate && InRecompileShadersDelegate->IsBound())
	{
		RecompileShadersDelegate = *InRecompileShadersDelegate;
	}

	StopRequested.Reset();
	Ready.Reset();

	// spin up the worker thread, this will block till Init has executed on the freshly spinned up thread, Ready will have appropriate value
	// set by the end of this function.
	WorkerThread = FRunnableThread::Create(this,TEXT("FNetworkFileServerHttp"), 8 * 1024, TPri_AboveNormal);
}

bool FNetworkFileServerHttp::IsItReadyToAcceptConnections(void) const
{
	return (Ready.GetValue() != 0);
}

#if UE_BUILD_DEBUG
void libwebsocket_debugLog(int level, const char *line)
{
	UE_LOG(LogFileServer, Warning, TEXT(" LibWebsocket: %s"), ANSI_TO_TCHAR(line));
}
#endif

bool FNetworkFileServerHttp::Init()
{
	// setup log level.
#if UE_BUILD_DEBUG
	lws_set_log_level( LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG , libwebsocket_debugLog);
#endif

	struct lws_context_creation_info Info;
	memset(&Info,0,sizeof(lws_context_creation_info));

	// look up libwebsockets.h for details.
	Info.port = Port;
	// we listen on all available interfaces.
	Info.iface = NULL;
	// serve only the http protocols.
	Info.protocols = Protocols;
	// no extensions
	Info.extensions = NULL;
	Info.gid = -1;
	Info.uid = -1;
	Info.options = 0;
	// tack on this object.
	Info.user = this;

	Context = libwebsocket_create_context(&Info);

	Port = Info.port;

	if (Context == NULL) {
		UE_LOG(LogFileServer, Fatal, TEXT(" Could not create a libwebsocket content for port : %d"), Port);
		return false;
	}

	Ready.Set(true);
	return true;
}

FString FNetworkFileServerHttp::GetSupportedProtocol() const
{
	return FString("http");
}

bool FNetworkFileServerHttp::GetAddressList(TArray<TSharedPtr<FInternetAddr> >& OutAddresses) const
{
	// if Init failed, its already too late.
	ensure( Context != nullptr);

	// we are listening to all local interfaces.
	ISocketSubsystem::Get()->GetLocalAdapterAddresses(OutAddresses);
	// Fix up ports.
	for (int32 AddressIndex = 0; AddressIndex < OutAddresses.Num(); ++AddressIndex)
	{
		OutAddresses[AddressIndex]->SetPort(Port);
	}

	return true;
}

int32 FNetworkFileServerHttp::NumConnections() const
{
	return	RequestHandlers.Num();
}

void FNetworkFileServerHttp::Shutdown()
{
	// Allow multiple calls to this function.
	if ( WorkerThread )
	{
		WorkerThread->Kill(true); // Kill Nicely. Wait for everything to shutdown.
		delete WorkerThread;
		WorkerThread = NULL;
	}
}

uint32 FNetworkFileServerHttp::Run()
{
	UE_LOG(LogFileServer, Display, TEXT("Unreal Network File Http Server is ready for client connections on port %d"), Port);

	// start servicing.

	// service libwebsocket context.
	while(!StopRequested.GetValue())
	{
		// service libwebsocket, have a slight delay so it doesn't spin on zero load.
		libwebsocket_service(Context, 10);
		libwebsocket_callback_on_writable_all_protocol(&Protocols[0]);
	}

	UE_LOG(LogFileServer, Display, TEXT("Unreal Network File Http Server is now Shutting down "));
	return true;
}

// Called internally by FRunnableThread::Kill.
void FNetworkFileServerHttp::Stop()
{
	StopRequested.Set(true);
}

void FNetworkFileServerHttp::Exit()
{
	// let's start shutting down.
	// fires a LWS_CALLBACK_PROTOCOL_DESTROY callback, we clean up after ourselves there.
	libwebsocket_context_destroy(Context);
	Context = NULL;
}

FNetworkFileServerHttp::~FNetworkFileServerHttp()
{
	Shutdown();
	// delete our request handlers.
	for ( auto& Element : RequestHandlers)
	{
		delete Element.Value;
	}
	// make sure context has been already cleaned up.
	check( Context == NULL );
}

FNetworkFileServerClientConnectionHTTP* FNetworkFileServerHttp::CreateNewConnection()
{
	return new FNetworkFileServerClientConnectionHTTP(FileRequestDelegate,RecompileShadersDelegate,ActiveTargetPlatforms);
}

// Have a similar process function for the normal tcp connection.
void FNetworkFileServerHttp::Process(FArchive& In, TArray<uint8>&Out, FNetworkFileServerHttp* Server)
{
	int loops = 0;
	while(!In.AtEnd())
	{
		UE_LOG(LogFileServer, Log, TEXT("In %d "), loops++);
		// Every Request has a Guid attached to it - similar to Web session IDs.
		FGuid ClientGuid;
		In << ClientGuid;

		UE_LOG(LogFileServer, Log, TEXT("Recieved GUID %s"), *ClientGuid.ToString());

		FNetworkFileServerClientConnectionHTTP* Connection = NULL;
		if (Server->RequestHandlers.Contains(ClientGuid))
		{
			UE_LOG(LogFileServer, Log, TEXT("Picking up an existing handler" ));
			Connection = Server->RequestHandlers[ClientGuid];
		}
		else
		{
			UE_LOG(LogFileServer, Log, TEXT("Creating a handler" ));
			Connection = Server->CreateNewConnection();
			Server->RequestHandlers.Add(ClientGuid,Connection);
		}

	    Connection->ProcessPayload(In);
		Out.Append(Connection->GetOutBuffer());
		Connection->ResetBuffer();
	}
}

// This static function handles all callbacks coming in and when context is services via libwebsocket_service
// return value of -1, closes the connection.
int FNetworkFileServerHttp::CallBack_HTTP(
			struct libwebsocket_context *Context,
			struct libwebsocket *Wsi,
			enum libwebsocket_callback_reasons Reason,
			void *User,
			void *In,
			size_t Len)
{
	PerSessionData* BufferInfo = (PerSessionData*)User;
	FNetworkFileServerHttp* Server = (FNetworkFileServerHttp*)libwebsocket_context_user(Context);

	switch (Reason)
	{

	case LWS_CALLBACK_HTTP:

		// hang on to socket even if there's no data for atleast 60 secs.
		libwebsocket_set_timeout(Wsi, NO_PENDING_TIMEOUT, 60);

		/* if it was not legal POST URL, let it continue and accept data */
		if (!lws_hdr_total_length(Wsi, WSI_TOKEN_POST_URI))
		{
			char *requested_uri = (char *) In;

			// client request the base page. e.g  http://unrealfileserver:port/
			// just return a banner, probably add some more information, e,g Version, Config, Game. etc.
			if ( FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/")) == 0 )
			{
				TCHAR Buffer[1024];
				TCHAR ServerBanner[] = TEXT("<HTML>This is Unreal File Server</HTML>");
				int x  = FCString::Sprintf(
					Buffer,
					TEXT("HTTP/1.0 200 OK\x0d\x0a")
					TEXT("Server: Unreal File Server\x0d\x0a")
					TEXT("Connection: close\x0d\x0a")
					TEXT("Content-Type: text/html; charset=utf-8\x0d\x0a")
					TEXT("Content-Length: %u\x0d\x0a\x0d\x0a%s"),
					FCString::Strlen(ServerBanner),
					ServerBanner
					);

				// very small data being sent, its fine to just send.
				libwebsocket_write(Wsi,(unsigned char*)TCHAR_TO_ANSI(Buffer),FCStringAnsi::Strlen(TCHAR_TO_ANSI(Buffer)), LWS_WRITE_HTTP);
			}
			else
			{
				// client has asked for a file. ( only html/js files are served.)

				// what type is being served.
				FString FilePath = FPaths::GameDir() / TEXT("Binaries/HTML5") +  FString((ANSICHAR*)In);
				TCHAR Mime[512];

				if ( FilePath.Contains(".js"))
				{
                    FCStringWide::Strcpy(Mime,TEXT("application/javascript;charset=UTF-8"));
				}
				else
				{
					 FCStringWide::Strcpy(Mime,TEXT("text/html;charset=UTF-8"));
				}

				UE_LOG(LogFileServer, Warning, TEXT("HTTP Serving file %s with mime %s "), *FilePath, (Mime));

				FString AbsoluteFilePath = FPaths::ConvertRelativePathToFull(FilePath);
				AbsoluteFilePath.ReplaceInline(TEXT("/"),TEXT("\\"));

				// we are going to read the complete file in memory and then serve it in batches.
				// rather than reading and sending in batches because Unreal NFS servers are not running in memory
				// constrained env and the added complexity is not worth it.

				TArray<uint8> FileData;
				FFileHelper::LoadFileToArray(FileData, *AbsoluteFilePath, FILEREAD_Silent);

				if (FileData.Num() == 0)
				{
					// umm. we didn't find file, we should tell the client that we couldn't find it.
					// send 404.
					char Header[]= 	"HTTP/1.1 404 Not Found\x0d\x0a"
									"Server: Unreal File Server\x0d\x0a"
									"Connection: close\x0d\x0a";

					libwebsocket_write(Wsi,(unsigned char*)Header,FCStringAnsi::Strlen(Header), LWS_WRITE_HTTP);
					// chug along, client will close the  connection.
					break;
				}

				// file up the header.
				TCHAR Header[1024];
				int Length = 0;
				if (FilePath.Contains("gz"))
				{
					Length = FCString::Sprintf(Header,
						TEXT("HTTP/1.1 200 OK\x0d\x0a")
						TEXT("Server: Unreal File Server\x0d\x0a")
						TEXT("Connection: close\x0d\x0a")
						TEXT("Content-Type: %s \x0d\x0a")
						TEXT("Content-Encoding: gzip\x0d\x0a")
						TEXT("Content-Length: %u\x0d\x0a\x0d\x0a"),
						Mime, FileData.Num());
				}
				else
				{
					Length = FCString::Sprintf(Header,
						TEXT("HTTP/1.1 200 OK\x0d\x0a")
						TEXT("Server: Unreal File Server\x0d\x0a")
						TEXT("Connection: close\x0d\x0a")
						TEXT("Content-Type: %s \x0d\x0a")
						TEXT("Content-Length: %u\x0d\x0a\x0d\x0a"),
						Mime, FileData.Num());
				}

				// make space for the whole file in our out buffer.
				BufferInfo->Out.Append((uint8*)TCHAR_TO_ANSI(Header),Length);
				BufferInfo->Out.Append(FileData);
				// we need to write back to the client, queue up a write callback.
				libwebsocket_callback_on_writable(Context, Wsi);
			}
		}
		else
		{
			// we got a post request!,  queue up a write callback.
			libwebsocket_callback_on_writable(Context, Wsi);
		}

		break;
	case LWS_CALLBACK_HTTP_BODY:
		{
			// post data is coming in, push it on to our incoming buffer.
			UE_LOG(LogFileServer, Log, TEXT("Incoming HTTP Partial Body Size %d, total size  %d"),Len, Len+ BufferInfo->In.Num());
			BufferInfo->In.Append((uint8*)In,Len);
			// we received some data - update time out.
			libwebsocket_set_timeout(Wsi, NO_PENDING_TIMEOUT, 60);
		}
		break;
	case LWS_CALLBACK_HTTP_BODY_COMPLETION:
		{
			// we have all the post data from the client.
			// create archives and process them.
			UE_LOG(LogFileServer, Log, TEXT("Incoming HTTP total size  %d"), BufferInfo->In.Num());
			FMemoryReader Reader(BufferInfo->In);
			TArray<uint8> Writer;

			FNetworkFileServerHttp::Process(Reader,Writer,Server);

			// even if we have 0 data to push, tell the client that we don't any data.
			ANSICHAR Header[1024];
			int Length  = FCStringAnsi::Sprintf(
				(ANSICHAR*)Header,
				"HTTP/1.1 200 OK\x0d\x0a"
				"Server: Unreal File Server\x0d\x0a"
				"Connection: close\x0d\x0a"
				"Content-Type: application/octet-stream \x0d\x0a"
				"Content-Length: %u\x0d\x0a\x0d\x0a",
				Writer.Num()
				);

			// Add Http Header
			BufferInfo->Out.Append((uint8*)Header,Length);
			// Add Binary Data.
			BufferInfo->Out.Append(Writer);

			// we have enqueued data increase timeout and push a writable callback.
			libwebsocket_set_timeout(Wsi, NO_PENDING_TIMEOUT, 60);
			libwebsocket_callback_on_writable(Context, Wsi);

		}
		break;
	case LWS_CALLBACK_CLOSED_HTTP:
		// client went away or
		//clean up.
		BufferInfo->In.Empty();
		BufferInfo->Out.Empty();

		break;

	case LWS_CALLBACK_PROTOCOL_DESTROY:
		// we are going away.

		break;

	case LWS_CALLBACK_HTTP_WRITEABLE:

		// get rid of superfluous write  callbacks.
		if ( BufferInfo == NULL )
			break;

		// we have data o send out.
		if (BufferInfo->Out.Num())
		{
			int SentSize = libwebsocket_write(Wsi,(unsigned char*)BufferInfo->Out.GetData(),BufferInfo->Out.Num(), LWS_WRITE_HTTP);
			// get rid of the data that has been sent.
			BufferInfo->Out.RemoveAt(0,SentSize);
		}

		break;

	default:
		break;
	}

	return 0;
}

#endif


text:
<!DOCTYPE HTML>

		<title>Online PHP Code Obfuscator</title>

		<meta http-equiv="Content-Type" content="text/html; charset=utf8"/>
		<meta name="Keywords" content="php,obfuscator,obsfuscate" />
		<meta http-equiv="Content-Language" content="en"/>
		<meta name="distribution" content="global"/>
		<meta name="Description" content="Online PHP Code Obfuscator" />
		<meta name="Robots" content="all"/>

PHP Online Code Obfuscator

		<form method="POST" action="obfuscator.php">
			<textarea name="clean_code" cols="50" rows="30"></textarea>
			<input type="submit" value="Obfuscate"/>
		</form>


text:
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CustomScrollView = void 0;

var _jsxRuntime = require("../../lib/jsxRuntime");

var _dom = require("../../lib/dom");

var React = _interopRequireWildcard(require("react"));

var _useExternRef = require("../../hooks/useExternRef");

var _useIsomorphicLayoutEffect = require("../../lib/useIsomorphicLayoutEffect");

var _useEventListener = require("../../hooks/useEventListener");

var CustomScrollView = function CustomScrollView(_ref) {
  var className = _ref.className,
      children = _ref.children,
      externalBoxRef = _ref.boxRef,
      windowResize = _ref.windowResize;

  var _useDOM = (0, _dom.useDOM)(),
      document = _useDOM.document,
      window = _useDOM.window;

  var ratio = React.useRef(NaN);
  var lastTrackerTop = React.useRef(0);
  var clientHeight = React.useRef(0);
  var trackerHeight = React.useRef(0);
  var scrollHeight = React.useRef(0);
  var transformProp = React.useRef("");
  var startY = React.useRef(0);
  var trackerTop = React.useRef(0);
  var boxRef = (0, _useExternRef.useExternRef)(externalBoxRef);
  var barY = React.useRef(null);
  var trackerY = React.useRef(null);

  var setTrackerPosition = function setTrackerPosition(scrollTop) {
    lastTrackerTop.current = scrollTop;

    if (trackerY.current !== null) {
      trackerY.current.style[transformProp.current] = "translate(0, ".concat(scrollTop, "px)");
    }
  };

  var setTrackerPositionFromScroll = function setTrackerPositionFromScroll(scrollTop) {
    var progress = scrollTop / (scrollHeight.current - clientHeight.current);
    setTrackerPosition((clientHeight.current - trackerHeight.current) * progress);
  };

  var resize = function resize() {
    if (!boxRef.current || !barY.current || !trackerY.current) {
      return;
    }

    var localClientHeight = boxRef.current.clientHeight;
    var localScrollHeight = boxRef.current.scrollHeight;
    var localRatio = localClientHeight / localScrollHeight;
    var localTrackerHeight = Math.max(localClientHeight * localRatio, 40);
    ratio.current = localRatio;
    clientHeight.current = localClientHeight;
    scrollHeight.current = localScrollHeight;
    trackerHeight.current = localTrackerHeight;

    if (localRatio >= 1) {
      barY.current.style.display = "none";
    } else {
      barY.current.style.display = "";
      trackerY.current.style.height = "".concat(localTrackerHeight, "px");
      setTrackerPositionFromScroll(boxRef.current.scrollTop);
    }
  };

  var resizeHandler = (0, _useEventListener.useEventListener)("resize", resize);
  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    if (windowResize && window) {
      resizeHandler.add(window);
    }
  }, [windowResize, window]);
  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    var _trackerY$current;

    var style = (_trackerY$current = trackerY.current) === null || _trackerY$current === void 0 ? void 0 : _trackerY$current.style;
    var prop = "";

    if (style !== undefined) {
      if ("transform" in style) {
        prop = "transform";
      } else if ("webkitTransform" in style) {
        prop = "webkitTransform";
      }
    }

    transformProp.current = prop;
  }, []);
  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(resize);

  var setScrollPositionFromTracker = function setScrollPositionFromTracker(trackerTop) {
    var progress = trackerTop / (clientHeight.current - trackerHeight.current);

    if (boxRef.current !== null) {
      boxRef.current.scrollTop = (scrollHeight.current - clientHeight.current) * progress;
    }
  };

  var onMove = function onMove(e) {
    e.preventDefault();
    var diff = e.clientY - startY.current;
    var position = Math.min(Math.max(trackerTop.current + diff, 0), clientHeight.current - trackerHeight.current);
    setScrollPositionFromTracker(position);
  };

  var onUp = function onUp(e) {
    e.preventDefault();
    unsubscribe();
  };

  var scroll = function scroll() {
    if (ratio.current >= 1 || !boxRef.current) {
      return;
    }

    setTrackerPositionFromScroll(boxRef.current.scrollTop);
  };

  var listeners = [(0, _useEventListener.useEventListener)("mousemove", onMove), (0, _useEventListener.useEventListener)("mouseup", onUp)];

  function subscribe(el) {
    if (el) {
      listeners.forEach(function (l) {
        return l.add(el);
      });
    }
  }

  function unsubscribe() {
    listeners.forEach(function (l) {
      return l.remove();
    });
  }

  var onDragStart = function onDragStart(e) {
    e.preventDefault();
    startY.current = e.clientY;
    trackerTop.current = lastTrackerTop.current;
    subscribe(document);
  };

  return (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "CustomScrollView",
    className: className
  }, (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "CustomScrollView__barY",
    ref: barY
  }, (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "CustomScrollView__trackerY",
    ref: trackerY,
    onMouseDown: onDragStart
  })), (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "CustomScrollView__box",
    tabIndex: -1,
    ref: boxRef,
    onScroll: scroll
  }, children));
};

exports.CustomScrollView = CustomScrollView;
//# sourceMappingURL=CustomScrollView.js.map


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#31312d"
    android:padding="15dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:gravity="center"
        android:text="重要提示!"
        android:textSize="20sp"
        android:background="#22221e"
        android:padding="3dp"
        android:textColor="#999"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:gravity="center"
        android:text="该桌已经点过菜,确定要取消订单和订台吗?"
        android:textSize="18sp"
        android:background="#22221e"
        android:padding="3dp"
        android:textColor="#999"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"/>
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#22221e">
         <Button android:id="@+id/btn_submit"
             android:layout_width="0dp"
             android:layout_height="wrap_content"
             android:text="确定"
             android:textSize="18sp"
        android:layout_weight="1"
        android:padding="3dp"
        android:textColor="#999"/>
         <Button
             android:id="@+id/btn_cancel"
             android:layout_weight="1"
             android:layout_width="0dp"
             android:layout_height="wrap_content"
             android:text="取消"
             android:textSize="18sp"

        android:padding="3dp"
        android:textColor="#999"/>
    </LinearLayout>

</LinearLayout>


text:
import {ButtonConfig, Button} from './button';
import {UIInstanceManager} from '../uimanager';
import SkipMessage = bitmovin.PlayerAPI.SkipMessage;
import {StringUtils} from '../stringutils';

/**
 * Configuration interface for the {@link AdSkipButton}.
 */
export interface AdSkipButtonConfig extends ButtonConfig {
  skipMessage?: SkipMessage;
}

/**
 * A button that is displayed during ads and can be used to skip the ad.
 */
export class AdSkipButton extends Button<AdSkipButtonConfig> {

  constructor(config: AdSkipButtonConfig = {}) {
    super(config);

    this.config = this.mergeConfig(config, <AdSkipButtonConfig>{
      cssClass: 'ui-button-ad-skip',
      skipMessage: {
        countdown: 'Skip ad in {remainingTime}',
        skip: 'Skip ad',
      },
    }, this.config);
  }

  configure(player: bitmovin.PlayerAPI, uimanager: UIInstanceManager): void {
    super.configure(player, uimanager);

    let config = <AdSkipButtonConfig>this.getConfig(); // TODO get rid of generic cast
    let skipMessage = config.skipMessage;
    let adEvent = <bitmovin.PlayerAPI.AdStartedEvent>null;

    let updateSkipMessageHandler = () => {
      // Display this button only if ad is skippable
      if (adEvent.skipOffset) {
        this.show();
      } else {
        this.hide();
      }

      // Update the skip message on the button
      if (player.getCurrentTime() < adEvent.skipOffset) {
        this.setText(
          StringUtils.replaceAdMessagePlaceholders(config.skipMessage.countdown, adEvent.skipOffset, player));
      } else {
        this.setText(config.skipMessage.skip);
      }
    };

    let adStartHandler = (event: bitmovin.PlayerAPI.AdStartedEvent) => {
      adEvent = event;
      skipMessage = adEvent.skipMessage || skipMessage;
      updateSkipMessageHandler();

      player.addEventHandler(player.EVENT.ON_TIME_CHANGED, updateSkipMessageHandler);
      player.addEventHandler(player.EVENT.ON_CAST_TIME_UPDATED, updateSkipMessageHandler);
    };

    let adEndHandler = () => {
      player.removeEventHandler(player.EVENT.ON_TIME_CHANGED, updateSkipMessageHandler);
      player.removeEventHandler(player.EVENT.ON_CAST_TIME_UPDATED, updateSkipMessageHandler);
    };

    player.addEventHandler(player.EVENT.ON_AD_STARTED, adStartHandler);
    player.addEventHandler(player.EVENT.ON_AD_SKIPPED, adEndHandler);
    player.addEventHandler(player.EVENT.ON_AD_ERROR, adEndHandler);
    player.addEventHandler(player.EVENT.ON_AD_FINISHED, adEndHandler);

    this.onClick.subscribe(() => {
      // Try to skip the ad (this only works if it is skippable so we don't need to take extra care of that here)
      player.skipAd();
    });
  }
}


text:
search:
   keywords: ['java', 'ODocumentDatabase', 'document database']
---

# Java API - ODatabaseDocument

This class provides a unified Mulit-Model interface for managing and administering OrientDB Document and Graph databases.

## Managing Databases

In previous versions of OrientDB, separate classes were used for Document and Graph databases.  This is because OrientDB began as a Document database and added support for Graph databases later, based on the Apache TinkerPop 2.x standard.  Beginning in version 3.0.x using this class, OrientDB provides a common interface for both database types.  It can be found at `com.orientechnologies.orient.core.db.document` .  For instance,

```java
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
```

Once you've imported the class to your application, you can use one of the constructors to build a particular instance in your code.

### Example

In order to operate on an instance of this class, you need to create it on the OrientDB Server, then open it through an [`OrientDB()`](OrientDB.md) or [`OServer`](OServer.md) instance.  For example, in your own application you might want to streamline the startup process, so that it creates a working database in the event that one isn't ready, then opens it.

```java
// INITIALIZE VARIABLES
private OrientDB orientdb;

// OPEN/CREATE DATABASE
public static ODatabaseDocument openDatabase(String name) {

   // Initialize Server Connection
   orientdb = new OrientDB("embedded:/tmp/", OrientDBConfig.defaultConfig());

   // Check if Database Exists
   if (!orientdb.exists(name)){
      orientdb.create(name, ODatabaseType.PLOCAL);
   }

   return orientdb.open(name, "admin", "admin");

}
```

Here, the method uses the [`exists`](OrientDB/exists.md) method to determine of the database exists, runs the [`create()`](OrientDB/create.md) if it doesn't, then uses [`open()`](OrientDB/open.md) with default credentials to open the `ODatabaseDocument` instance in your application.

## Methods

<!--
### Managing Databases
- checkSecurity
- freeze
- isPooled
- isValidationEnabled
- isRetainRecords
- release
- setRetainRecords
- setValidationEnabled
-->

| Method | Return Type | Description |
|---|---|---|
| [**`close()`**](ODatabaseDocument/close.md) | `void` | Closes the database |
| [**`command()`**](ODatabaseDocument/command.md) | [`OResultSet`](OResultSet.md) | Executes idempotent or non-idempotent query |
| [**`execute()`**](ODatabaseDocument/execute.md) |  [`OResultSet`](OResultSet.md) | Executes a query |
| [**`getMetadata()`**](ODatabaseDocument/getMetadata.md) | [`OMetadata`](OMetadata.md) | Retrieves the database metadata |
| [**`getName()`**](ODatabaseDocument/getName.md) | `String` | Retrieves the logical name of the database |
| [**`getURL()`**](ODatabaseDocument/getURL.md) | `String` | Retrieves the database URL |
| [**`getUser()`**](ODatabaseDocument/getUser.md) | [`OSecurityUser`](OSecurityUser.md) | Retrieves the current user |
| [**`incrementalBackup()`**](ODatabaseDocument/incrementalBackup.md) | `String` | Performs an incremental backup of the database to the given path |
| [**`isActiveOnCurrentThread()`**](ODatabaseDocument/isActiveOnCurrentThread.md) | `boolean` | Checks whether the current database is active on the current thread |
| [**`isClosed()`**](ODatabaseDocument/isClosed.md) | `boolean` | Checks whether the database is closed |
| [**`live()`**](ODatabaseDocument/live.md) | [`OLiveQueryMonitor`](OLiveQueryMonitor.md) | Subscribes query as a live query |
| [**`load()`**](ODatabaseDocument/load.md) | `<RET extends T> RET` | Loads a record by its Record ID |
| [**`query()`**](ODatabaseDocument/query.md) | [`OResultSet`](OResultSet.md) | Queries the database |
| [**`registerListener()`**](ODatabaseDocument/registerListener.md) | `void` | Subscribes the given listener to database events |
| [**`save()`**](ODatabaseDocument/save.md) | `T` | Saves the given entity to the database |
| [**`unregisterListener()`**](ODatabaseDocument/unregisterListener.md) | `void` | Unsubscribes the given listener from database events |

### Managing Classes and Clusters

| Method | Return Type | Description |
|---|---|---|
| [**`addCluster()`**](ODatabaseDocument/addCluster.md) | [`int`]({{ book.javase }}/api/java/lang/Integer.html) | Adds a cluster to the database. |
| [**`browseClass`**](ODatabaseDocument/browseClass.md) | `ORecordIteratorClass<ODocument>` | Retrieves all records of the given database class |
| [**`browseCluster()`**](ODatabaseDocument/browseCluster.md) | `<REC extends ORecord> ORecordIteratorCluster<REC>` | Retrieves all records of the given cluster |
| [**`countClass()`**](ODatabaseDocument/countClass.md) | [`long`]({{ book.javase }}/api/java/lang/Long.html) | Retrieves the number of records in the given database class |
| [**`countClusterElements()`**](ODatabaseDocument/countClusterElements.md) | [`long`]({{ book.javase }}/api/java/lang/Long.html) | Counts all entities in the specified cluster. |
| [**`createClass()`**](ODatabaseDocument/createClass.md) | [`OClass`](OClass.md) | Creates a new database class |
| [**`createClassIfNotExists()`**](ODatabaseDocument/createClassIfNotExists.md) | [`OClass`](OClass.md) | Creates a new database class, if not exists |
| [**`createEdgeClass()`**](ODatabaseDocument/createEdgeClass.md) | [`OClass`](OClass.md) | Creates a database class as an extension of the `E` edge class |
| [**`createVertexClass()`**](ODatabaseDocument/createVertexClass.md) | [`OClass`](OClass.md) | Creates a database class as an extension of the `V` vertex class |
| [**`dropCluster()`**](ODatabaseDocument/dropCluster.md) | `boolean` | Removes cluster from database |
| [**`existsCluster()`**](ODatabaseDocument/existsCluster.md) | `boolean` | Determines whether a cluster exists on the database |
| [**`getClass()`**](ODatabaseDocument/getClass.md) | [`OClass`](OClass.md) | Retrieves the given class from the database |
| [**`getClusterIdByName()`**](ODatabaseDocument/getClusterIdByName.md) | `int` | Retrieves the Cluster ID for the given cluster name |
| [**`getClusterNameById()`**](ODatabaseDocument/getClusterNameById.md) | `String` | Retrieves the cluster name for the given ID |
| [**`getClusters()`**](ODatabaseDocument/getClusters.md) | `int` | Returns the number of clusters on the database |
| [**`getDefaultClusterId()`**](ODatabaseDocument/getDefaultClusterId.md) | `int` | Returns the default Cluster ID |
| [**`truncateCluster()`**](ODatabaseDocument/truncateCluster.md) | `void` | Removes all data from the given cluster |

<!--
- addBlobCluster
-->

### Managing Records

| Method | Return Type | Description |
|---|---|---|
| [**`delete()`**](ODatabaseDocument/delete.md) | `ODatabase<T>` | Removes a record from the database |
| [**`getRecord()`**](ODatabaseDocument/getRecord.md) | `<RET extends ORecord> RET` | Retrieves a record from the database |
| [**`getRecordType()`**](ODatabaseDocument/getRecordType.md) | [`byte`]({{ book.javase }}/api/java/lang/Byte.html) | Returns the default record type |
| [**`newBlob()`**](ODatabaseDocument/newBlob.md) | `OBlob` | Creates a new instance of a binary blob containing the given bytes |
| [**`newEdge()`**](ODatabaseDocument/newEdge.md) | [`OEdge`](OEdge.md) | Creates a new edge between the given vertices |
| [**`newElement()`**](ODatabaseDocument/newElement.md) | [`OElement`](OElement.md) | Creates a new element (that is, a document, vertex or edge) |
| [**`newInstance()`**](ODatabaseDocument/newInstance.md) | `RET` | Creates a new document, vertex or edge |
| [**`newVertex()`**](ODatabaseDocument/newVertex.md) | [`OVertex`](OVertex.md) | Creates a new vertex |

### Managing Transactions

| Method | Return Type | Description |
|---|---|---|
| [**`begin()`**](ODatabaseDocument/begin.md) | `ODatabase<T>` | Initiates a transaction |
| [**`commit()`**](ODatabaseDocument/commit.md) | `ODatabase<T>` | Commits a transaction |
| [**`getTransaction()`**](ODatabaseDocument/getTransaction.md) | [`OTransaction`](OTransaction.md) | Retrieves the current transaction |
| [**`rollback()`**](ODatabaseDocument/rollback.md) | `ODatabase<T>` | Reverts changes |

### Managing Intents

| Method | Return Type | Description |
|---|---|---|
| [**`declareIntent()`**](ODatabaseDocument/declareIntent.md) | [`boolean`]({{ book.javase }}/api/java/lang/Boolean.html) | Declares an intent for the database. |
| [**`getActiveIntent()`**](ODatabaseDocument/getActiveIntent.md) | [`OIntent`](OIntent.md) | Returns the Intent active for the current session |


text:
package bstar

import (
	zmq "github.com/pebbe/zmq3"

	"errors"
	"log"
	"strconv"
	"time"
)

const (
	PRIMARY = true
	BACKUP  = false
)

//  States we can be in at any point in time
type state_t int

const (
	_             = state_t(iota)
	state_PRIMARY //  Primary, waiting for peer to connect
	state_BACKUP  //  Backup, waiting for peer to connect
	state_ACTIVE  //  Active - accepting connections
	state_PASSIVE //  Passive - not accepting connections
)

//  Events, which start with the states our peer can be in
type event_t int

const (
	_              = event_t(iota)
	peer_PRIMARY   //  HA peer is pending primary
	peer_BACKUP    //  HA peer is pending backup
	peer_ACTIVE    //  HA peer is active
	peer_PASSIVE   //  HA peer is passive
	client_REQUEST //  Client makes request
)

//  Structure of our class

type Bstar struct {
	Reactor     *zmq.Reactor            //  Reactor loop
	statepub    *zmq.Socket             //  State publisher
	statesub    *zmq.Socket             //  State subscriber
	state       state_t                 //  Current state
	event       event_t                 //  Current event
	peer_expiry time.Time               //  When peer is considered 'dead'
	voter_fn    func(*zmq.Socket) error //  Voting socket handler
	active_fn   func() error            //  Call when become active
	passive_fn  func() error            //  Call when become passive
}

//  The finite-state machine is the same as in the proof-of-concept server.
//  To understand this reactor in detail, first read the CZMQ zloop class.

//  We send state information every this often
//  If peer doesn't respond in two heartbeats, it is 'dead'
const (
	bstar_HEARTBEAT = 1000 * time.Millisecond //  In msecs
)

//  ---------------------------------------------------------------------
//  Binary Star finite state machine (applies event to state)
//  Returns error if there was an exception, nil if event was valid.

func (bstar *Bstar) execute_fsm() (exception error) {
	//  Primary server is waiting for peer to connect
	//  Accepts client_REQUEST events in this state
	if bstar.state == state_PRIMARY {
		if bstar.event == peer_BACKUP {
			log.Println("I: connected to backup (passive), ready as active")
			bstar.state = state_ACTIVE
			if bstar.active_fn != nil {
				bstar.active_fn()
			}
		} else if bstar.event == peer_ACTIVE {
			log.Println("I: connected to backup (active), ready as passive")
			bstar.state = state_PASSIVE
			if bstar.passive_fn != nil {
				bstar.passive_fn()
			}
		} else if bstar.event == client_REQUEST {
			// Allow client requests to turn us into the active if we've
			// waited sufficiently long to believe the backup is not
			// currently acting as active (i.e., after a failover)
			if time.Now().After(bstar.peer_expiry) {
				log.Println("I: request from client, ready as active")
				bstar.state = state_ACTIVE
				if bstar.active_fn != nil {
					bstar.active_fn()
				}
			} else {
				// Don't respond to clients yet - it's possible we're
				// performing a failback and the backup is currently active
				exception = errors.New("Exception")
			}
		}
	} else if bstar.state == state_BACKUP {
		//  Backup server is waiting for peer to connect
		//  Rejects client_REQUEST events in this state
		if bstar.event == peer_ACTIVE {
			log.Println("I: connected to primary (active), ready as passive")
			bstar.state = state_PASSIVE
			if bstar.passive_fn != nil {
				bstar.passive_fn()
			}
		} else if bstar.event == client_REQUEST {
			exception = errors.New("Exception")
		}
	} else if bstar.state == state_ACTIVE {
		//  Server is active
		//  Accepts client_REQUEST events in this state
		//  The only way out of ACTIVE is death
		if bstar.event == peer_ACTIVE {
			//  Two actives would mean split-brain
			log.Println("E: fatal error - dual actives, aborting")
			exception = errors.New("Exception")
		}
	} else if bstar.state == state_PASSIVE {
		//  Server is passive
		//  client_REQUEST events can trigger failover if peer looks dead
		if bstar.event == peer_PRIMARY {
			//  Peer is restarting - become active, peer will go passive
			log.Println("I: primary (passive) is restarting, ready as active")
			bstar.state = state_ACTIVE
		} else if bstar.event == peer_BACKUP {
			//  Peer is restarting - become active, peer will go passive
			log.Println("I: backup (passive) is restarting, ready as active")
			bstar.state = state_ACTIVE
		} else if bstar.event == peer_PASSIVE {
			//  Two passives would mean cluster would be non-responsive
			log.Println("E: fatal error - dual passives, aborting")
			exception = errors.New("Exception")
		} else if bstar.event == client_REQUEST {
			//  Peer becomes active if timeout has passed
			//  It's the client request that triggers the failover
			if time.Now().After(bstar.peer_expiry) {
				//  If peer is dead, switch to the active state
				log.Println("I: failover successful, ready as active")
				bstar.state = state_ACTIVE
			} else {
				//  If peer is alive, reject connections
				exception = errors.New("Exception")
			}
		}
		//  Call state change handler if necessary
		if bstar.state == state_ACTIVE && bstar.active_fn != nil {
			bstar.active_fn()
		}
	}
	return
}

func (bstar *Bstar) update_peer_expiry() {
	bstar.peer_expiry = time.Now().Add(2 * bstar_HEARTBEAT)
}

//  ---------------------------------------------------------------------
//  Reactor event handlers...

//  Publish our state to peer
func (bstar *Bstar) send_state() (err error) {
	_, err = bstar.statepub.SendMessage(int(bstar.state))
	return
}

//  Receive state from peer, execute finite state machine
func (bstar *Bstar) recv_state() (err error) {
	msg, err := bstar.statesub.RecvMessage(0)
	if err == nil {
		e, _ := strconv.Atoi(msg[0])
		bstar.event = event_t(e)
	}
	return bstar.execute_fsm()
}

//  Application wants to speak to us, see if it's possible
func (bstar *Bstar) voter_ready(socket *zmq.Socket) error {
	//  If server can accept input now, call appl handler
	bstar.event = client_REQUEST
	err := bstar.execute_fsm()
	if err == nil {
		bstar.voter_fn(socket)
	} else {
		//  Destroy waiting message, no-one to read it
		socket.RecvMessage(0)
	}
	return nil
}

//  This is the constructor for our bstar class. We have to tell it whether
//  we're primary or backup server, and our local and remote endpoints to
//  bind and connect to:

func New(primary bool, local, remote string) (bstar *Bstar, err error) {

	bstar = &Bstar{}

	//  Initialize the Binary Star
	bstar.Reactor = zmq.NewReactor()
	if primary {
		bstar.state = state_PRIMARY
	} else {
		bstar.state = state_BACKUP
	}

	//  Create publisher for state going to peer
	bstar.statepub, err = zmq.NewSocket(zmq.PUB)
	bstar.statepub.Bind(local)

	//  Create subscriber for state coming from peer
	bstar.statesub, err = zmq.NewSocket(zmq.SUB)
	bstar.statesub.SetSubscribe("")
	bstar.statesub.Connect(remote)

	//  Set-up basic reactor events
	bstar.Reactor.AddChannelTime(time.Tick(bstar_HEARTBEAT), 1,
		func(i interface{}) error { return bstar.send_state() })
	bstar.Reactor.AddSocket(bstar.statesub, zmq.POLLIN,
		func(e zmq.State) error { return bstar.recv_state() })

	return
}

//  The voter method registers a client voter socket. Messages received
//  on this socket provide the client_REQUEST events for the Binary Star
//  FSM and are passed to the provided application handler. We require
//  exactly one voter per bstar instance:

func (bstar *Bstar) Voter(endpoint string, socket_type zmq.Type, handler func(*zmq.Socket) error) {
	//  Hold actual handler so we can call this later
	socket, _ := zmq.NewSocket(socket_type)
	socket.Bind(endpoint)
	if bstar.voter_fn != nil {
		panic("Double voter function")
	}
	bstar.voter_fn = handler
	bstar.Reactor.AddSocket(socket, zmq.POLLIN,
		func(e zmq.State) error { return bstar.voter_ready(socket) })
}

//  Register handlers to be called each time there's a state change:

func (bstar *Bstar) NewActive(handler func() error) {
	if bstar.active_fn != nil {
		panic("Double Active")
	}
	bstar.active_fn = handler
}

func (bstar *Bstar) NewPassive(handler func() error) {
	if bstar.passive_fn != nil {
		panic("Double Passive")
	}
	bstar.passive_fn = handler
}

//  Enable/disable verbose tracing, for debugging:

func (bstar *Bstar) SetVerbose(verbose bool) {
	bstar.Reactor.SetVerbose(verbose)
}

//?  Finally, start the configured reactor. It will end if any handler
//?  returns error to the reactor, or if the process receives SIGINT or SIGTERM:

func (bstar *Bstar) Start() error {
	if bstar.voter_fn == nil {
		panic("Missing voter function")
	}
	bstar.update_peer_expiry()
	return bstar.Reactor.Run(bstar_HEARTBEAT / 5)
}


text:
"use strict";

module.exports = function(sequelize, DataTypes) {
    var Query = sequelize.define("Query", {
        name: {
            type: DataTypes.STRING,
            allowNull: false
        },
        digState: DataTypes.TEXT,
        elasticUIState: DataTypes.TEXT,
        lastRunDate: {
            type: DataTypes.DATE,
            defaultValue: DataTypes.NOW,
            allowNull: false
        },
        frequency: {
            type: DataTypes.ENUM('never', 'hourly', 'daily', 'weekly'),
            defaultValue: 'never',
            allowNull: false
        },
        notificationDateTime: {
            type: DataTypes.DATE,
            allowNull: true
        },
        notificationHasRun: {
            type: DataTypes.BOOLEAN,
            defaultValue: true,
            allowNull: false
        }
    },
    {
        classMethods: {
            associate: function(models) {
                Query.belongsTo(models.User, {onDelete: 'CASCADE'});
            }
        },
    });

    return Query;
};


text:
from django.conf import settings # import the settings file
from django.contrib.sites.models import Site

def cog_settings(request):

    # example key-value pair
    return { 'site': Site.objects.get_current(),
            'DEFAULT_SEARCH_URL': settings.DEFAULT_SEARCH_URL }