code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package net.gree.aurora.application.config.defaultconfig;
/**
* Redis用{@link AuroraDefaultConfig}。
*/
public interface AuroraDefaultRedisConfig extends AuroraDefaultConfig {
/**
* データベース番号を取得する。
*
* @return データベース番号
*/
Integer getDatabaseNumber();
/**
* パスワードを取得する。
*
* @return パスワード
*/
String getPassword();
}
| gree/aurora | aurora-core/src/main/java/net/gree/aurora/application/config/defaultconfig/AuroraDefaultRedisConfig.java | Java | mit | 453 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M2 6.67V22h20V6H8.3l8.26-3.34L15.88 1 2 6.67zM7 20c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm13-8h-2v-2h-2v2H4V8h16v4z"
}), 'RadioSharp'); | AlloyTeam/Nuclear | components/icon/esm/radio-sharp.js | JavaScript | mit | 272 |
<?php
/*
* This file is part of OAuth 2.0 Laravel.
*
* (c) Luca Degasperi <packages@lucadegasperi.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LucaDegasperi\OAuth2Server\Storage;
use Carbon\Carbon;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Storage\AuthCodeInterface;
/**
* This is the fluent auth code class.
*
* @author Luca Degasperi <packages@lucadegasperi.com>
*/
class FluentAuthCode extends AbstractFluentAdapter implements AuthCodeInterface
{
/**
* Get the auth code.
*
* @param string $code
*
* @return \League\OAuth2\Server\Entity\AuthCodeEntity
*/
public function get($code)
{
$result = $this->getConnection()->table('oauth_auth_codes')
->where('oauth_auth_codes.id', $code)
->where('oauth_auth_codes.expire_time', '>=', time())
->first();
if (is_null($result)) {
return;
}
if (is_array($result)) {
$result = (object) $result;
}
return (new AuthCodeEntity($this->getServer()))
->setId($result->id)
->setRedirectUri($result->redirect_uri)
->setExpireTime((int) $result->expire_time);
}
/**
* Get the scopes for an access token.
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code
*
* @return array Array of \League\OAuth2\Server\Entity\ScopeEntity
*/
public function getScopes(AuthCodeEntity $token)
{
$result = $this->getConnection()->table('oauth_auth_code_scopes')
->select('oauth_scopes.*')
->join('oauth_scopes', 'oauth_auth_code_scopes.scope_id', '=', 'oauth_scopes.id')
->where('oauth_auth_code_scopes.auth_code_id', $token->getId())
->get();
$scopes = [];
foreach ($result as $scope) {
if (is_array($scope)) {
$scope = (object) $scope;
}
$scopes[] = (new ScopeEntity($this->getServer()))->hydrate([
'id' => $scope->id,
'description' => $scope->description,
]);
}
return $scopes;
}
/**
* Associate a scope with an access token.
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @return void
*/
public function associateScope(AuthCodeEntity $token, ScopeEntity $scope)
{
$this->getConnection()->table('oauth_auth_code_scopes')->insert([
'auth_code_id' => $token->getId(),
'scope_id' => $scope->getId(),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
/**
* Delete an access token.
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The access token to delete
*
* @return void
*/
public function delete(AuthCodeEntity $token)
{
$this->getConnection()->table('oauth_auth_codes')
->where('oauth_auth_codes.id', $token->getId())
->delete();
}
/**
* Create an auth code.
*
* @param string $token The token ID
* @param int $expireTime Token expire time
* @param int $sessionId Session identifier
* @param string $redirectUri Client redirect uri
*
* @return void
*/
public function create($token, $expireTime, $sessionId, $redirectUri)
{
$this->getConnection()->table('oauth_auth_codes')->insert([
'id' => $token,
'session_id' => $sessionId,
'redirect_uri' => $redirectUri,
'expire_time' => $expireTime,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
| BunceeLLC/oauth2-server-laravel | src/Storage/FluentAuthCode.php | PHP | mit | 3,992 |
using System;
using System.Collections.Generic;
using System.Linq;
namespace School
{
public class Teacher : Person
{
//field
private string comments;
//property
public List<Discipline> SetOfDisciplines{ get; private set; }
public string Comments
{
get
{
return this.comments;
}
set
{
this.comments = value;
}
}
//constructor
public Teacher(string name)
: base(name)
{
this.SetOfDisciplines = new List<Discipline>();
}
public Teacher(string name, string comments)
: this(name)
{
this.Comments = comments;
}
//methods
//add discipline
public void AddDiscipline(Discipline discipline)
{
SetOfDisciplines.Add(discipline);
}
public void AddDisciplines(List<Discipline> disciplines)
{
SetOfDisciplines.AddRange(disciplines);
}
}
}
| niki-funky/Telerik_Academy | Programming/OOP/05. OOP Principles I/01. School/Teacher.cs | C# | mit | 1,097 |
/**
* @author: @NikhilS
*/
require('ts-node/register');
var helpers = require('./helpers');
exports.config = {
baseUrl: 'http://localhost:3000/',
// use `npm run e2e`
specs: [
helpers.root('src/**/**.e2e.ts'),
helpers.root('src/**/*.e2e.ts')
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
directConnect: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['show-fps-counter=true']
}
},
onPrepare: function() {
browser.ignoreSynchronization = true;
},
/**
* Angular 2 configuration
*
* useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
* `rootEl`
*/
useAllAngular2AppRoots: true
};
| nikhilsarvaiye/PeopleManager | config/protractor.conf.js | JavaScript | mit | 931 |
<?php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
class DefaultController extends Controller
{
public function indexAction(){
return $this->render('BlogBundle:Entry:index.html.twig');
}
public function langAction(Request $request){
return $this->redirectToRoute("blog_homepage");
}
}
| alexciobanu4/symfony3 | src/BlogBundle/Controller/DefaultController.php | PHP | mit | 451 |
#include<cstdio>
void main()
{
int queenNum,i;
while(scanf("%d",&queenNum))
{
if(queenNum==0)break;
if(queenNum%6!=2 && queenNum%6!=3)
{
for(i=2;i<=queenNum;i+=2)printf("%d ",i);
for(i=1;i<=queenNum;i+=2)printf("%d ",i);
}
else
{
if((queenNum/2)%2==0)
{
for(i=queenNum/2;i<=queenNum;i+=2)printf("%d ",i);
for(i=2;i<=queenNum/2-2;i+=2)printf("%d ",i);
for(i=queenNum/2+3;i<=queenNum-1;i+=2)printf("%d ",i);
for(i=1;i<=queenNum/2+1;i+=2)printf("%d ",i);
}
else
{
for(i=queenNum/2;i<=queenNum-1;i+=2)printf("%d ",i);
for(i=1;i<=queenNum/2-2;i+=2)printf("%d ",i);
for(i=queenNum/2+3;i<=queenNum;i+=2)printf("%d ",i);
for(i=2;i<=queenNum/2+1;i+=2)printf("%d ",i);
}
if(queenNum%2!=0)printf("%d ",queenNum);
}
printf("\n");
}
} | junzh0u/poj-solutions | 3239/3002024_AC_0MS_72K.cpp | C++ | mit | 834 |
from carapace import config
from carapace.sdk import registry
config.updateConfig()
registry.registerConfig(config)
| oubiwann/carapace | carapace/app/__init__.py | Python | mit | 118 |
# frozen_string_literal: true
require "set"
# Niceness of a node means that it cannot be nil.
#
# Note that the module depends on the includer
# to provide #scope (for #nice_variable)
module Niceness
# Literals are nice, except the nil literal.
NICE_LITERAL_NODE_TYPES = [
:self,
:false, :true,
:int, :float,
:str, :sym, :regexp,
:array, :hash, :pair, :irange, # may contain nils but they are not nil
:dstr, # "String #{interpolation}" mixes :str, :begin
:dsym # :"#{foo}"
].to_set
def nice(node)
nice_literal(node) || nice_variable(node) || nice_send(node) ||
nice_begin(node)
end
def nice_literal(node)
NICE_LITERAL_NODE_TYPES.include? node.type
end
def nice_variable(node)
node.type == :lvar && scope[node.children.first].nice
end
# Methods that preserve niceness if all their arguments are nice
# These are global, called with a nil receiver
NICE_GLOBAL_METHODS = {
# message, number of arguments
_: 1
}.freeze
NICE_OPERATORS = {
# message, number of arguments (other than receiver)
:+ => 1
}.freeze
def nice_send(node)
return false unless node.type == :send
receiver, message, *args = *node
if receiver.nil?
arity = NICE_GLOBAL_METHODS.fetch(message, -1)
else
return false unless nice(receiver)
arity = NICE_OPERATORS.fetch(message, -1)
end
args.size == arity && args.all? { |a| nice(a) }
end
def nice_begin(node)
node.type == :begin && nice(node.children.last)
end
end
| yast/zombie-killer | lib/zombie_killer/niceness.rb | Ruby | mit | 1,574 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UNIFreelancerDataBaseEntry.CCandidateService;
namespace UNIFreelancerDataBaseEntry
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var client = new CCandidateService.CandidateServiceClient();
var test = client.GetCandidates(new CandidateDetailSearchRequest());
}
}
}
| mayurdo/UNISoftware | UNIFreelancerDataBaseEntry/Form1.cs | C# | mit | 759 |
require File.dirname(__FILE__) + '/test_helper.rb'
class TestScbiFastq < Test::Unit::TestCase
def setup
@test_file='/tmp/sanger.fastq';
@test_file_gz='/tmp/sanger.fastq.gz';
@seq_fasta='ACTG'
@seq_qual=[31]
@seq_name='SEQ'
end
def test_gz_sanger
fqr=FastqFile.new(File.join(File.dirname(__FILE__),'sanger2.fastq.gz'))
i=1
fqr.each do |n,s,q|
assert_equal(@seq_name+i.to_s,n)
assert_equal(@seq_fasta*i,s)
assert_equal((@seq_qual*i*@seq_fasta.length),q)
i+=1
end
fqr.close
end
def fill_file(n,offset=33)
f=FastqFile.new(@test_file,'w')
n.times do |c|
i = c+1
name = "#{@seq_name+i.to_s}"
f.write_seq(name,@seq_fasta*i,(@seq_qual*i*@seq_fasta.length),'comments')
# f.puts('@'+name)
# f.puts(@seq_fasta*i)
# f.puts('+'+name)
# f.puts((@seq_qual*i*@seq_fasta.length).map{|e| (e+offset).chr}.join)
end
f.close
end
def fill_file_no_qual(n,offset=33)
f=FastqFile.new(@test_file,'w')
n.times do |c|
i = c+1
name = "#{@seq_name+i.to_s}"
f.write_seq(name,@seq_fasta*i,'','comments')
# f.puts('@'+name)
# f.puts(@seq_fasta*i)
# f.puts('+'+name)
# f.puts((@seq_qual*i*@seq_fasta.length).map{|e| (e+offset).chr}.join)
end
f.close
end
def test_each
# make new file and fill with data
fill_file(100)
fqr=FastqFile.new(@test_file)
i=1
fqr.each do |n,s,q|
assert_equal(@seq_name+i.to_s,n)
assert_equal(@seq_fasta*i,s)
assert_equal((@seq_qual*i*@seq_fasta.length),q)
i+=1
end
fqr.close
end
def test_each_comments
# make new file and fill with data
fill_file(100)
fqr=FastqFile.new(@test_file)
i=1
fqr.each do |n,s,q,c|
assert_equal(@seq_name+i.to_s,n)
assert_equal(@seq_fasta*i,s)
assert_equal((@seq_qual*i*@seq_fasta.length),q)
assert_equal('comments',c)
i+=1
end
fqr.close
end
def test_next_seq_comments
# make new file and fill with data
fill_file(100)
fqr=FastqFile.new(@test_file)
i=1
begin
n,s,q,c = fqr.next_seq
if !n.nil?
assert_equal(@seq_name+i.to_s,n)
assert_equal(@seq_fasta*i,s)
assert_equal((@seq_qual*i*@seq_fasta.length),q)
assert_equal('comments',c)
i+=1
end
end until n.nil?
fqr.close
end
def test_to_fastq
puts FastqFile.to_fastq(@seq_name,@seq_fasta*10,'','')
end
def test_each_no_qual
# make new file and fill with data
fill_file_no_qual(100)
fqr=FastqFile.new(@test_file,'r',:sanger, false,false)
i=1
fqr.each do |n,s,q|
# puts n,s,q
assert_equal(@seq_name+i.to_s,n)
assert_equal(@seq_fasta*i,s)
# assert_equal((@seq_qual*i*@seq_fasta.length),q)
i+=1
end
fqr.close
end
def fill_file_gz(n,offset=33)
f=FastqFile.new(@test_file_gz,'w.gz')
puts "FILE GZ"
n.times do |c|
i = c+1
name = "#{@seq_name+i.to_s}"
f.write_seq(name,@seq_fasta*i,(@seq_qual*i*@seq_fasta.length),'comments')
# f.puts('@'+name)
# f.puts(@seq_fasta*i)
# f.puts('+'+name)
# f.puts((@seq_qual*i*@seq_fasta.length).map{|e| (e+offset).chr}.join)
end
f.close
end
def test_each_gz
# make new file and fill with data
fill_file_gz(100)
fqr=FastqFile.new(@test_file_gz)
i=1
fqr.each do |n,s,q|
assert_equal(@seq_name+i.to_s,n)
assert_equal(@seq_fasta*i,s)
assert_equal((@seq_qual*i*@seq_fasta.length),q)
i+=1
end
assert_equal(i,101)
fqr.close
end
# def test_open_file
# fill_file(100)
# fq=FastqFile.new('test/sanger.fastq')
#
# fq.each do |n,f,q|
# puts n,f,q
# puts fq.num_seqs
# end
#
# fq.close
#
# end
def test_each_large
# make new file and fill with data
#fill_file(100)
#fqr=FastqFile.new('/tmp/pair2.fastq.gz')
fqr=FastqFile.new('/tmp/659634_4-4_2.fastq.gz')
i=1
fqr.each do |n,s,q|
#puts n
#assert_equal(@seq_name+i.to_s,n)
#assert_equal(@seq_fasta*i,s)
#assert_equal((@seq_qual*i*@seq_fasta.length),q)
i+=1
end
assert_equal(40,i)
fqr.close
end
end
| dariogf/scbi_fastq | test/scbi_fastq_test.rb | Ruby | mit | 4,582 |
// Include assertion library "Should"
var should = require('should'); // jshint ignore:line
var PowerupElection = require('polyball/shared/powerups/PowerupElection.js');
var Vote = require('polyball/shared/model/Vote.js');
// An example test that runs using Mocha and uses "Should" for assertion testing
describe('Powerup Election', function() {
"use strict";
describe('#addVote()', function() {
it('should increase the size of the votes array by 1', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
pe.addVote(new Vote({spectatorID: 1, powerup:1}));
pe.votes.length.should.equal(1);
});
it('should increase the size of the votes array by 1 for each added vote', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
var n = 10;
for (var i = 0; i < n; i++){
pe.addVote(new Vote({spectatorID: i, powerup:1}));
}
pe.votes.length.should.equal(n);
});
it('should replace the current vote with new vote', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
pe.addVote(new Vote({spectatorID: 1, powerup:1}));
pe.addVote(new Vote({spectatorID: 1, powerup:2}));
pe.votes.length.should.equal(1);
(pe.votes[0]).powerup.should.equal(2);
});
it('should replace the current vote with new vote for each additional ' +
'vote from same spectator', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
var n = 10;
var firstVote = 1;
var secondVote = 2;
for (var i = 0; i < n; i++){
pe.addVote(new Vote({spectatorID: i, powerup: firstVote}));
pe.addVote(new Vote({spectatorID: i, powerup: secondVote}));
}
pe.votes.length.should.equal(n);
pe.votes.forEach(function(elm){
elm.powerup.should.equal(secondVote);
});
});
});
describe('#removeVote()', function() {
it('should decrease the size of the votes array by 1', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
pe.addVote(new Vote({spectatorID: 1, powerup:1}));
pe.removeVote(1);
pe.votes.length.should.equal(0);
});
it('should decrease the size of the votes array by 1 for each additional call', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
var n = 10;
for (var i = 0; i < n; i++){
pe.addVote(new Vote({spectatorID: i, powerup:1}));
}
for (i = 0; i < n; i++){
pe.removeVote(i);
}
pe.votes.length.should.equal(0);
});
});
describe('#getWinner()', function() {
it('should return the powerup with the most votes ', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
pe.addVote(new Vote({spectatorID: 1, powerup:1}));
pe.addVote(new Vote({spectatorID: 2, powerup:2}));
pe.addVote(new Vote({spectatorID: 3, powerup:2}));
pe.getWinner().should.equal(2);
});
it('should decrease the size of the votes array by 1 for each additional call', function() {
var pe = new PowerupElection({powerups: [1,2,3]});
var winner = pe.getWinner();
(winner != null).should.be.ok; //jshint ignore:line
[1,2,3].should.containEql(winner);
});
});
}); | polyball/polyball | polyball/tests/shared/model/PowerupElectionTests.js | JavaScript | mit | 3,626 |
version https://git-lfs.github.com/spec/v1
oid sha256:92a4f24d3a4ad4de3bbed1013b330d5ca23f4d0cbeed4a7536dcd6b3cd3e492d
size 4461
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.7.2/nls/nb/colors.js | JavaScript | mit | 129 |
version https://git-lfs.github.com/spec/v1
oid sha256:50ef15b4c4f47fb98410127b48f1db6e32dc7f759cab685bd27afbfcfd7fdd38
size 23119
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/jsonp/jsonp-coverage.js | JavaScript | mit | 130 |
<?php
/**
* Handle BB code.
*
* This plugin is the most powerful plugin, if you don't want to write every
* text in HTML. It also enables users that are not allowed to post HTML to
* format their text.
*
* A detailed documentation of how to use the tags can be found at
* http://github.com/marcoraddatz/candyCMS/wiki/BBCode
*
* @link http://github.com/marcoraddatz/candyCMS
* @author Marco Raddatz <http://marcoraddatz.com>
* @license MIT
* @since 1.0
* @see https://github.com/marcoraddatz/candyCMS/wiki/BBCode
*
*/
namespace candybox\Plugins;
use candyCMS\Core\Helpers\I18n;
use candyCMS\Core\Helpers\Helper;
use candyCMS\Core\Helpers\Image;
final class Bbcode {
/**
* Identifier for Template Replacements
*
* @var constant
*
*/
const IDENTIFIER = 'Bbcode';
/**
* @var array
* @access protected
*
*/
protected $_aRequest;
/**
* @var array
* @access protected
*
*/
protected $_aSession;
/**
* Initialize the plugin and register all needed events.
*
* @access public
* @param array $aRequest alias for the combination of $_GET and $_POST
* @param array $aSession alias for $_SESSION
* @param object $oPlugins the PluginManager
*
*/
public function __construct(&$aRequest, &$aSession, &$oPlugins) {
$this->_aRequest = & $aRequest;
$this->_aSession = & $aSession;
# now register some events with the pluginmanager
#$oPlugins->registerContentDisplayPlugin($this);
$oPlugins->registerEditorPlugin($this);
}
/**
* Search and replace BB code.
*
* @final
* @static
* @access private
* @param string $sStr HTML to replace
* @return string $sStr HTML with formated code
*
*/
private final static function _setFormatedText($sStr) {
# BBCode
$sStr = str_replace('[hr]', '<hr />', $sStr);
$sStr = preg_replace('/\[center\](.*)\[\/center]/isU', '<div style=\'text-align:center\'>\1</div>', $sStr);
$sStr = preg_replace('/\[left\](.*)\[\/left]/isU', '<left>\1</left>', $sStr);
$sStr = preg_replace('/\[right\](.*)\[\/right]/isU', '<right>\1</right>', $sStr);
$sStr = preg_replace('/\[p\](.*)\[\/p]/isU', '<p>\1</p>', $sStr);
$sStr = preg_replace('=\[b\](.*)\[\/b\]=Uis', '<strong>\1</strong>', $sStr);
$sStr = preg_replace('=\[i\](.*)\[\/i\]=Uis', '<em>\1</em>', $sStr);
$sStr = preg_replace('=\[u\](.*)\[\/u\]=Uis', '<span style="text-decoration:underline">\1</span>', $sStr);
$sStr = preg_replace('=\[del\](.*)\[\/del\]=Uis', '<span style="text-decoration:line-through">\1</span>', $sStr);
$sStr = preg_replace('#\[abbr=(.*)\](.*)\[\/abbr\]#Uis', '<abbr title="\1">\2</abbr>', $sStr);
$sStr = preg_replace('#\[acronym=(.*)\](.*)\[\/acronym\]#Uis', '<acronym title="\1">\2</acronym>', $sStr);
$sStr = preg_replace('#\[color=(.*)\](.*)\[\/color\]#Uis', '<span style="color:\1">\2</span>', $sStr);
$sStr = preg_replace('#\[size=(.*)\](.*)\[\/size\]#Uis', '<span style="font-size:\1%">\2</span>', $sStr);
$sStr = preg_replace('#\[anchor:(.*)\]#Uis', '<a name="\1"></a>', $sStr);
# Load specific icon
$sStr = preg_replace('#\[icon:(.*)\]#Uis', '<i class="icon-\1"></i>', $sStr);
# Replace images with image tag (every location allowed
while (preg_match('=\[img\](.*)\[\/img\]=isU', $sStr, $sUrl)) {
$sUrl[1] = Helper::removeSlash($sUrl[1]);
$sImageExtension = strtolower(substr(strrchr($sUrl[1], '.'), 1));
$sTempFileName = md5(MEDIA_DEFAULT_X . $sUrl[1]);
$sTempFilePath = Helper::removeSlash(PATH_UPLOAD . '/temp/bbcode/' . $sTempFileName . '.' . $sImageExtension);
$sHTML = '';
if (!file_exists($sTempFilePath)) {
require_once PATH_STANDARD . '/vendor/candycms/core/helpers/Image.helper.php';
# This might be very slow. So we try to use it rarely.
$aInfo = @getImageSize($sUrl[1]);
# If external, download image and save as preview
if (substr($sUrl[1], 0, 4) == 'http')
file_put_contents($sTempFilePath, file_get_contents($sUrl[1]));
if ($aInfo[0] > MEDIA_DEFAULT_X) {
$oImage = new Image($sTempFileName, 'temp', $sUrl[1], $sImageExtension);
$oImage->resizeDefault(MEDIA_DEFAULT_X, '', 'bbcode');
}
}
$sUrl[1] = substr($sUrl[1], 0, 4) !== 'http' ? WEBSITE_URL . '/' . $sUrl[1] : $sUrl[1];
# Remove capty and change image information.
if (file_exists($sTempFilePath)) {
$aNewInfo = getImageSize($sTempFilePath);
$sTempFilePath = WEBSITE_URL . Helper::addSlash($sTempFilePath);
$sClass = 'js-image';
$sAlt = I18n::get('global.image.click_to_enlarge');
}
else {
$aNewInfo[3] = '';
$sTempFilePath = $sUrl[1];
$sClass = '';
$sAlt = $sTempFilePath;
}
$sHTML .= '<figure class="image">';
$sHTML .= '<a class="js-fancybox fancybox-thumb" rel="fancybox-thumb" href="' . $sUrl[1] . '">';
$sHTML .= '<img class="' . $sClass . '" alt="' . $sAlt . '"';
$sHTML .= 'src="' . $sTempFilePath . '" ' . $aNewInfo[3] . ' />';
$sHTML .= '</a>';
$sHTML .= '</figure>';
$sStr = preg_replace('=\[img\](.*)\[\/img\]=isU', $sHTML, $sStr, 1);
}
# using [audio]file.ext[/audio]
while (preg_match('#\[audio\](.*)\[\/audio\]#Uis', $sStr, $aMatch)) {
$sUrl = 'http://url2vid.com/?url=' . $aMatch[1] . '&w=' . MEDIA_DEFAULT_X . '&h=30&callback=?';
$sStr = preg_replace('#\[audio\](.*)\[\/audio\]#Uis',
'<div class="js-media" title="' . $sUrl . '"><a href="' . $sUrl . '">' . $aMatch[1] . '</a></div>',
$sStr,
1);
}
# [video]file[/video]
while (preg_match('#\[video\](.*)\[\/video\]#Uis', $sStr, $aMatch)) {
$sUrl = 'http://url2vid.com/?url=' . $aMatch[1] . '&w=' . MEDIA_DEFAULT_X . '&h=' . MEDIA_DEFAULT_Y . '&callback=?';
$sStr = preg_replace('#\[video\](.*)\[\/video\]#Uis',
'<a href="' . $aMatch[1] . '" class="js-media" title="' . $sUrl . '">' . $aMatch[1] . '</a>',
$sStr,
1);
}
# [video thumbnail]file[/video]
while (preg_match('#\[video (.*)\](.*)\[\/video]#Uis', $sStr, $aMatch)) {
$sUrl = 'http://url2vid.com/?url=' . $aMatch[2] . '&w=' . MEDIA_DEFAULT_X . '&h=' . MEDIA_DEFAULT_Y . '&p=' . $aMatch[1] . '&callback=?';
$sStr = preg_replace('#\[video (.*)\](.*)\[\/video]#Uis',
'<div class="js-media" title="' . $sUrl . '"><a href="' . $aMatch[2] . '">' . $aMatch[2] . '</a></div>',
$sStr,
1);
}
# [video width height thumbnail]file[/video]
while (preg_match('#\[video ([0-9]+) ([0-9]+) (.*)\](.*)\[\/video\]#Uis', $sStr, $aMatch)) {
$sUrl = 'http://url2vid.com/?url=' . $aMatch[4] . '&w=' . $aMatch[1] . '&h=' . $aMatch[2] . '&p=' . $aMatch[3] . '&callback=?';
$sStr = preg_replace('#\[video ([0-9]+) ([0-9]+) (.*)\](.*)\[\/video\]#Uis',
'<div class="js-media" title="' . $sUrl . '"><a href="' . $aMatch[4] . '" class="js-media">' . $aMatch[4] . '</a></div>',
$sStr,
1);
}
# Quote
while (preg_match("/\[quote\]/isU", $sStr) && preg_match("/\[\/quote]/isU", $sStr) ||
preg_match("/\[quote\=/isU", $sStr) && preg_match("/\[\/quote]/isU", $sStr)) {
$sStr = preg_replace("/\[quote\](.*)\[\/quote]/isU", "<blockquote>\\1</blockquote>", $sStr);
$sStr = preg_replace("/\[quote\=(.+)\](.*)\[\/quote]/isU", "<blockquote><h4>" . I18n::get('global.quote.by') . " \\1</h4>\\2</blockquote>", $sStr);
}
# Code
while (preg_match('#\[code\](.*)\[\/code\]#Uis', $sStr, $aMatch)) {
$sStr = preg_replace('#\[code\](.*)\[\/code\]#Uis',
'<pre>' . htmlentities($aMatch[1]) . '</pre>',
$sStr,
1);
}
# Bugfix: Fix quote and allow these tags for comment quoting
$sStr = str_replace("<blockquote>", "<blockquote>", $sStr);
$sStr = str_replace("</blockquote>", "</blockquote>", $sStr);
$sStr = str_replace("<h4>", "<h4>", $sStr);
$sStr = str_replace("</h4>", "</h4>", $sStr);
return $sStr;
}
/**
* Return the formatted code.
*
* @final
* @static
* @access public
* @param string $sStr
* @return string HTML with formated code
*
*/
public final function prepareContent($sStr) {
return self::_setFormatedText($sStr);
}
/**
* Show nothing, since this plugin does not need to output additional javascript.
*
* @final
* @access public
* @return string HTML
*
*/
public final function show() {
return '';
}
/**
* Generate an Info Array ('url' => '', 'iconurl' => '', 'description' => '')
*
* @final
* @access public
* @return array|boolean infor array or false
* @todo return array with bbcode logo and link to github info page
*
*/
public final function getInfo() {
return false;
}
}
| cnlpete/candybox | plugins/Bbcode/Bbcode.controller.php | PHP | mit | 9,003 |
//
// Created by Per-Arne on 27.02.2017.
//
#ifndef WARC2SIM_COLORCONVERTER_H
#define WARC2SIM_COLORCONVERTER_H
#include <SFML/Graphics/Color.hpp>
class ColorConverter {
public:
static sf::Color hsv(double hue, double sat, double val)
{
hue = fmod(hue, 360);
while(hue<0) hue += 360;
if(sat<0.f) sat = 0.f;
if(sat>1.f) sat = 1.f;
if(val<0.f) val = 0.f;
if(val>1.f) val = 1.f;
int h = hue/60;
double f = (hue)/60-h;
double p = val*(1.f-sat);
double q = val*(1.f-sat*f);
double t = val*(1.f-sat*(1-f));
switch(h)
{
default:
case 0:
case 6: return sf::Color(val*255, t*255, p*255);
case 1: return sf::Color(q*255, val*255, p*255);
case 2: return sf::Color(p*255, val*255, t*255);
case 3: return sf::Color(p*255, q*255, val*255);
case 4: return sf::Color(t*255, p*255, val*255);
case 5: return sf::Color(val*255, p*255, q*255);
}
}
};
#endif //WARC2SIM_COLORCONVERTER_H
| UIA-CAIR/DeepRTS | src/util/ColorConverter.hpp | C++ | mit | 1,098 |
package morbrian.mormessages.controller;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import morbrian.mormessages.dataformat.CalendarDeserializer;
import morbrian.mormessages.dataformat.CalendarSerializer;
import morbrian.mormessages.dataformat.DurationAsLongMillisSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
@JsonIgnoreProperties(ignoreUnknown = true) public class Subscription {
private String subscriptionId;
private String userIdentity;
private String topicId;
private Calendar expirationTime;
private Duration duration;
public Subscription(String userIdentity, String topicId, String subscriptionId) {
this.subscriptionId = subscriptionId;
this.userIdentity = userIdentity;
this.topicId = topicId;
this.duration = Duration.ofSeconds(SubscriptionManager.DEFAULT_DURATION_SECONDS);
this.expirationTime = Calendar.getInstance();
this.expirationTime.setTime(Date.from(Instant.now().plusSeconds(duration.getSeconds())));
}
public Subscription(String userIdentity, String topicId) {
this(userIdentity, topicId, UUID.randomUUID().toString());
}
public Subscription(String userIdentity, String topicId, Calendar expirationTime) {
this(userIdentity, topicId);
if (expirationTime != null) {
this.expirationTime = expirationTime;
this.duration =
Duration.ofMillis(expirationTime.getTimeInMillis() - System.currentTimeMillis());
}
}
public Subscription(String userIdentity, String topicId, Duration duration) {
this(userIdentity, topicId);
if (duration != null) {
this.duration = duration;
this.expirationTime = Calendar.getInstance();
this.expirationTime.setTime(Date.from(Instant.now().plusSeconds(duration.getSeconds())));
}
}
public Subscription(String userIdentity, String topicId, Calendar expiration, Duration duration) {
this(userIdentity, topicId);
this.duration = duration;
this.expirationTime = expiration;
}
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public static Subscription jsonCreator(@JsonProperty(value = "id") String subscriptionId,
@JsonProperty(value = "userIdentity") String userIdentity,
@JsonProperty(value = "topicId") String topicId,
@JsonProperty(value = "durationMillis") long durationMillis,
@JsonProperty(value = "expiration") Calendar expiration) {
Subscription subscription =
new Subscription(userIdentity, topicId, expiration, Duration.ofMillis(durationMillis));
subscription.subscriptionId = subscriptionId;
return subscription;
}
public String getSubscriptionId() {
return subscriptionId;
}
public String getTopicId() {
return topicId;
}
public String getUserIdentity() {
return userIdentity;
}
public Subscription renew(Duration duration) {
Subscription extended = new Subscription(userIdentity, topicId, duration);
extended.subscriptionId = this.subscriptionId;
return extended;
}
@JsonSerialize(using = CalendarSerializer.class)
@JsonDeserialize(using = CalendarDeserializer.class) public Calendar getExpiration() {
return expirationTime;
}
public boolean isExpired() {
return expirationTime.getTimeInMillis() < System.currentTimeMillis();
}
@JsonSerialize(using = DurationAsLongMillisSerializer.class)
@JsonProperty(value = "durationMillis") public Duration getDuration() {
return duration;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Subscription that = (Subscription) o;
return Objects.equals(subscriptionId, that.subscriptionId) &&
Objects.equals(getUserIdentity(), that.getUserIdentity()) &&
Objects.equals(getTopicId(), that.getTopicId()) &&
Objects.equals(expirationTime, that.expirationTime) &&
Objects.equals(getDuration(), that.getDuration());
}
@Override public int hashCode() {
return Objects
.hash(subscriptionId, getUserIdentity(), getTopicId(), expirationTime, getDuration());
}
}
| morbrian/mormessages | src/main/java/morbrian/mormessages/controller/Subscription.java | Java | mit | 4,448 |
/* transparency component */
define([
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/_base/array',
'dojo/query',
'dojo/dom-style',
'dijit/PopupMenuItem',
'dijit/TooltipDialog',
'dijit/form/HorizontalSlider',
'dijit/form/HorizontalRuleLabels'
], function (
declare,
lang,
array,
query,
domStyle,
PopupMenuItem,
TooltipDialog,
HorizontalSlider,
HorizontalRuleLabels
) {
return declare(PopupMenuItem, {
layer: null,
constructor: function (options) {
options = options || {};
lang.mixin(this, options);
},
postCreate: function () {
this.inherited(arguments);
var transparencySlider = new HorizontalSlider({
value: this.layer.layer.getOpacity(),
minimum: 0,
maximum: 1,
discreteValues: 21,
intermediateChanges: true,
showButtons: false,
onChange: lang.hitch(this, function (value) {
this.layer.layer.setOpacity(value);
array.forEach(query('.' + this.layer.id + '-layerLegendImage'), function (img) {
domStyle.set(img, 'opacity', value);
});
})
});
var rule = new HorizontalRuleLabels({
labels: ['100%', '50%', '0%'],
style: 'height:1em;font-size:75%;'
}, transparencySlider.bottomDecoration);
rule.startup();
transparencySlider.startup();
this.popup = new TooltipDialog({
style: 'width:200px;',
content: transparencySlider
});
domStyle.set(this.popup.connectorNode, 'display', 'none');
this.popup.startup();
}
});
}); | pri0ri7y/OpenMap | js/widgets/templates/layercontrol/plugins/Transparency.js | JavaScript | mit | 1,864 |
class AswersController < ApplicationController
def index
@aswers = Aswer.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @aswers }
end
end
def show
@aswer = Aswer.find(params[:id])
respond_to do |format|
format.html #show.html.erb
format.xml { render :xml => @aswer }
end
end
end | serviceweb2012/Plugin-Enquete | generators/enquete/templates/app/controllers/aswers_controller.rb | Ruby | mit | 391 |
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
// 0. You just DO WHAT THE FUCK YOU WANT TO.
function Map3DGeometry (data, innerRadius) {
if ((arguments.length < 2) || isNaN(parseFloat(innerRadius)) || !isFinite(innerRadius) || (innerRadius < 0)) {
// if no valid inner radius is given, do not extrude
innerRadius = 42;
}
THREE.Geometry.call (this);
// data.vertices = [lat, lon, ...]
// data.polygons = [[poly indices, hole i-s, ...], ...]
// data.triangles = [tri i-s, ...]
var i, uvs = [];
for (i = 0; i < data.vertices.length; i += 2) {
var lon = data.vertices[i];
var lat = data.vertices[i + 1];
// colatitude
var phi = +(90 - lat) * 0.01745329252;
// azimuthal angle
var the = +(180 - lon) * 0.01745329252;
// translate into XYZ coordinates
var wx = Math.sin (the) * Math.sin (phi) * -1;
var wz = Math.cos (the) * Math.sin (phi);
var wy = Math.cos (phi);
// equirectangular projection
var wu = 0.25 + lon / 360.0;
var wv = 0.5 + lat / 180.0;
this.vertices.push (new THREE.Vector3 (wx, wy, wz));
uvs.push (new THREE.Vector2 (wu, wv));
}
var n = this.vertices.length;
if (innerRadius <= 1) {
for (i = 0; i < n; i++) {
var v = this.vertices[i];
this.vertices.push (v.clone ().multiplyScalar (innerRadius));
}
}
for (i = 0; i < data.triangles.length; i += 3) {
var a = data.triangles[i];
var b = data.triangles[i + 1];
var c = data.triangles[i + 2];
this.faces.push( new THREE.Face3( a, b, c, [ this.vertices[a], this.vertices[b], this.vertices[c] ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ a ], uvs[ b ], uvs[ c ] ]);
if ((0 < innerRadius) && (innerRadius <= 1)) {
this.faces.push( new THREE.Face3( n + b, n + a, n + c, [
this.vertices[b].clone ().multiplyScalar (-1),
this.vertices[a].clone ().multiplyScalar (-1),
this.vertices[c].clone ().multiplyScalar (-1)
] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ a ], uvs[ c ] ]); // shitty uvs to make 3js exporter happy
}
}
// extrude
if (innerRadius < 1) {
for (i = 0; i < data.polygons.length; i++) {
var polyWithHoles = data.polygons[i];
for (var j = 0; j < polyWithHoles.length; j++) {
var polygonOrHole = polyWithHoles[j];
for (var k = 0; k < polygonOrHole.length; k++) {
var a = polygonOrHole[k], b = polygonOrHole[(k + 1) % polygonOrHole.length];
var va1 = this.vertices[a], vb1 = this.vertices[b];
var va2 = this.vertices[n + a], vb2 = this.vertices[n + b];
var normal;
if (j < 1) {
// polygon
normal = vb1.clone ().sub (va1).cross ( va2.clone ().sub (va1) ).normalize ();
this.faces.push ( new THREE.Face3( a, b, n + a, [ normal, normal, normal ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ a ], uvs[ b ], uvs[ a ] ]); // shitty uvs to make 3js exporter happy
if (innerRadius > 0) {
this.faces.push ( new THREE.Face3( b, n + b, n + a, [ normal, normal, normal ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ b ], uvs[ a ] ]); // shitty uvs to make 3js exporter happy
}
} else {
// hole
normal = va2.clone ().sub (va1).cross ( vb1.clone ().sub (va1) ).normalize ();
this.faces.push ( new THREE.Face3( b, a, n + a, [ normal, normal, normal ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ a ], uvs[ a ] ]); // shitty uvs to make 3js exporter happy
if (innerRadius > 0) {
this.faces.push ( new THREE.Face3( b, n + a, n + b, [ normal, normal, normal ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ b ], uvs[ a ], uvs[ b ] ]); // shitty uvs to make 3js exporter happy
}
}
}
}
}
}
this.computeFaceNormals ();
this.boundingSphere = new THREE.Sphere (new THREE.Vector3 (), 1);
}
Map3DGeometry.prototype = Object.create (THREE.Geometry.prototype); | beeva-hodeilopez/beeva-data-visualization-hackathon | three-js/map3d.js | JavaScript | mit | 4,972 |
logparser = r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d{3})\s+' \
r'(DEBUG|ERROR|INFO)\s+\[(\w+):(\w+):?(\w+)?\]\s+(.+)$'
| the-zebulan/CodeWars | katas/kyu_6/parse_the_log.py | Python | mit | 134 |
using System;
using System.Net;
using System.Net.Http;
namespace AonWeb.FluentHttp.Exceptions
{
public interface IWriteableExceptionResponseMetadata : IExceptionResponseMetadata
{
new HttpStatusCode StatusCode { get; set; }
new string ReasonPhrase { get; set; }
new long? ResponseContentLength { get; set; }
new string ResponseContentType { get; set; }
new Uri RequestUri { get; set; }
new HttpMethod RequestMethod { get; set; }
new long? RequestContentLength { get; set; }
new string RequestContentType { get; set; }
}
} | aonweb/fluent-http | AonWeb.FluentHttp.Serialization/Exceptions/IWriteableExceptionResponseMetadata.cs | C# | mit | 601 |
using UnityEngine;
using System.Collections;
public class ItemBase : MonoBehaviour {
//public GameObject brokenItemsPrefab;
public int life;
public int speeddown;
public int super;
public int confuse;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider otherCollider)
{
if (otherCollider.GetComponent<BBPlayer>())
{
if(life == 1){
if(CollisionCount.count != 0)
CollisionCount.count--;
}
Destroy(gameObject);
}
}
}
| seonggwang/blueberry-pi | Assets/Scripts/ItemBase.cs | C# | mit | 551 |
module SwiftServer
module Controllers
class Keystone1 < ApplicationController
include Concerns::CredentialsHelper
attr_accessor :tenant, :username
def show
if authorize
safe_append_header('X-Storage-Url', app.url('/v1/AUTH_tester'))
safe_append_header('X-Auth-Token', 'tk_tester')
safe_append_header('X-Storage-Token', 'stk_tester')
app.status 200
else
app.status 401
end
end
private
def authorize
req_headers[:x_auth_user].split(':').tap do |v|
@tenant = v.first
@username = v.last
end
valid_tenant?(tenant) && valid_username?(username) && valid_password?(req_headers[:x_auth_key])
end
end
end
end
| mdouchement/swift-server | lib/swift_server/controllers/keystone_1.rb | Ruby | mit | 775 |
package edu.rutgers.rumad.rumadworkshopthree.completed;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import edu.rutgers.rumad.rumadworkshopthree.R;
public class MainActivity extends ActionBarActivity {
Button login, signin, cancel;
EditText usernameField, passwordField, nameField;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//store context in variable so we can access in inner methods
ctx = this;
//initialize buttons
login = (Button)findViewById(R.id.loginBtn);
signin = (Button)findViewById(R.id.signinBtn);
cancel = (Button)findViewById(R.id.cancelBtn);
//initialize text fields
usernameField = (EditText)findViewById(R.id.username);
passwordField = (EditText)findViewById(R.id.password);
nameField = (EditText)findViewById(R.id.name);
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (signin.getText().toString().equalsIgnoreCase("Sign Up")) {
login.setVisibility(View.INVISIBLE);
cancel.setVisibility(View.VISIBLE);
signin.setText("Done");
nameField.setVisibility(View.VISIBLE);
} else {
//initialize a new user
ParseUser user = new ParseUser();
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
String name = nameField.getText().toString();
//built in method that assigns username to user
user.setUsername(username);
//built in method that encrypts and assigns password to user
user.setPassword(password);
//or add in your own data like:
user.put("name", name);
//where the first parameter is the key and the second parameter is the value
/*
You can do other stuff too like:
//another built in method
user.setEmail(email);
//whatever you want
user.put("age", 18);
for now we will just do username and password
*/
//check if username or password is not there
if (username == null || password == null) {
Toast.makeText(ctx, "Oops, you must enter a username AND password to sign up", Toast.LENGTH_SHORT).show();
} else {
//parse automatically does it in the background thread so no need for AsyncTasks!!!
//it also checks automatically if the username was already used
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
//check if there is no error
if (e == null) {
//if there isn't we're successful! Go to the next screen and resume initial state of screen!
signin.setText("Sign Up");
cancel.setVisibility(View.INVISIBLE);
nameField.setVisibility(View.INVISIBLE);
login.setVisibility(View.INVISIBLE);
Intent intent = new Intent(ctx, SecondActivity.class);
startActivity(intent);
}
//otherwise, let's see what happened
else {
//go to LogCat and look for error tag if what you expected didn't happen
Log.e("error", "user sign up error: " + e.getMessage());
}
}
});
}
}
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//get inputs
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
ParseUser.logInInBackground(username, password, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
//make sure there is no error
if(e == null){
//go to next activity
Intent intent = new Intent(ctx, SecondActivity.class);
startActivity(intent);
}
//error, what's wrong?
else{
Log.e("error logging in",e.getMessage());
}
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| RutgersMobileApplicationDevelopment/RUMADWorkshopThree | app/src/main/java/edu/rutgers/rumad/rumadworkshopthree/completed/MainActivity.java | Java | mit | 6,604 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php include('head.php') ?>
<style>
a.link{
text-decoration: none;
}
</style>
</head>
<body>
<!--Menu Begin-->
<?php include('menu.php') ?>
<!--Menu Ends-->
<div class="container">
<table class="table table-responsive">
<form method="post" action="<?php echo base_url('price_change/change'); ?>">
<tr><td>Current Purchase Price</td><td><?php if(isset($p_price)) echo "<h2>".$p_price."</h2>"; ?></td></tr>
<tr><td>Current Sales Price</td><td><?php if(isset($s_price)) echo "<h2>".$s_price."</h2>"; ?></td></tr>
<tr><td>Purchase Price</td><td><input type="text" name="p_price" required="" pattern="[0-9]{1,2}" title="Number only, range 1-99"></td></tr>
<tr><td>Sales Price</td><td><input type="text" name="s_price" required="" pattern="[0-9]{1,2}" title="Number only, range 1-99"></td></tr>
<tr><td colspan="2"><button type="submit" class="btn btn-primary">Update</button></td></tr>
<tr><td colspan="2"><?php if(isset($message)) echo "<h2>".$message."</h2>"; ?></td></tr>
</form>
</table>
</div>
<!--Footer Begin-->
<?php include('footer.php') ?>
<!--Footer Ends-->
</body>
</html> | soorajnraju/oruma | application/views/price_change.php | PHP | mit | 1,165 |
module StatefulJobs
module Controller
extend ActiveSupport::Concern
included do
class << self
attr_accessor :stateful_jobs_class, :stateful_jobs_options
end
end
module ClassMethods
def stateful_jobs klass, options = {}
self.stateful_jobs_class = klass.to_s.camelcase.constantize
self.stateful_jobs_options = options
if options[:action]
define_method options[:action] do
end
else
if self.stateful_jobs_class.stateful_jobs.is_a? Hash
self.stateful_jobs_class.stateful_jobs.keys.each do |job|
define_method job do
end
end
end
end
end
end
def state
render json: stateful_jobs_class.where(id: params[:id]).limit(1).select('current_job, current_state').first.to_json
end
def stateful_jobs_class
self.class.stateful_jobs_class
end
end
end | metascape/stateful_jobs | lib/stateful_jobs/controller.rb | Ruby | mit | 955 |
class BaseWoodTile < MapTile
def initialize(position)
super
@type = :wood
@speed_modifier = Settings.wood_floor_movement_points
end
end
class ClientWoodTile < BaseWoodTile
def initialize(position)
super
@image = Images[:wood_floor]
end
end
| MichaelBaker/zombie-picnic | lib/game/lib/map_tiles/wood_tile.rb | Ruby | mit | 279 |
package problems;
/**
* Created by wanghongkai on 2017/1/16.
*
* 问题:将一个字符串转为正数,实现atoi的功能
*
* 思路:注意正负号,注意溢出判断
*
* 更优解法:优化溢出时的判断,参考p007
*/
public class P008_string_to_integer {
public static int myAtoi(String str) {
if (str == null) {
return 0;
}
str = str.trim();
int length = str.length();
if (length > 0) {
int index = 0;
boolean positive = true;
char first = str.charAt(0);
if (first == '-') {
positive = false;
index++;
} else if (first == '+') {
index++;
}
if (index >= length) {
return 0;
}
char firstNum = str.charAt(index);
if (firstNum >= '0' && firstNum <= '9') {
long result = (int) firstNum - 48;
while (++index < length) {
char next = str.charAt(index);
if (next < '0' || next > '9') {
break;
}
result = result * 10 + ((int) next - 48);
if (positive && result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (!positive && -result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
return (int) (positive ? result : -result);
}
}
return 0;
}
public static void main(String[] args) {
String[] test = new String[]{
"0",
"1",
"-1",
" 0 ",
" 1 ",
" -1 ",
" +1 ",
" a1 ",
" 1a",
" +19826385692345982734",
" -19826385692345982734",
" -",
};
for (String s : test) {
System.out.println(myAtoi(s));
}
}
}
| ironwang/leetcode | src/problems/P008_string_to_integer.java | Java | mit | 2,145 |
using BlueSheep.Interface;
using BlueSheep.Interface.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
namespace BlueSheep.Engine.Types
{
public class WatchDog
{
#region Fields
private AccountUC m_Account;
private DateTime PathAction;
private Thread m_PathDog;
#endregion
#region Constructors
public WatchDog(AccountUC account)
{
m_Account = account;
}
#endregion
#region Public Methods
public void StartPathDog()
{
m_PathDog = new Thread(new ThreadStart(PathDog));
m_PathDog.Start();
}
public void StopPathDog()
{
if (m_PathDog != null)
m_PathDog.Abort();
}
public void Update()
{
PathAction = DateTime.Now;
}
#endregion
#region Private Methods
private void PathDog()
{
DateTime now = PathAction;
double endwait = Environment.TickCount + 10000;
while (Environment.TickCount < endwait)
{
System.Threading.Thread.Sleep(1);
System.Windows.Forms.Application.DoEvents();
}
DateTime after = PathAction;
if (DateTime.Compare(now, after) == 0 && CheckState())
{
m_Account.Log(new DebugTextInformation("[WatchDog] Relaunch path"), 0);
m_Account.Path.ParsePath();
StartPathDog();
}
else
{
m_Account.Log(new DebugTextInformation("[WatchDog] Nothing to do."), 0);
StartPathDog();
}
}
private bool CheckState()
{
return (m_Account.state == Enums.Status.None ||
m_Account.state == Enums.Status.Moving ||
m_Account.state == Enums.Status.Busy);
}
#endregion
}
}
| Sadikk/BlueSheep | BlueSheep/Engine/Types/WatchDog.cs | C# | mit | 2,065 |
<!DOCTYPE html>
<html>
<head>
<title>Other page</title>
</head>
<body>
<h1>You know... some other page</h1>
</body>
</html>
| alexandresalome/php-webdriver | website/other.php | PHP | mit | 156 |
#include <bits/stdc++.h>
using namespace std;
int n, m;
struct Edge {
int u, v, r;
Edge() {}
Edge(int _u, int _v, int _r) : u(_u), v(_v), r(_r) {}
};
vector<Edge> e[10];
int bit_count(int x) {
int c = 0;
while (x) {
++c;
x -= x&(-x);
}
return c;
}
int f(int r, int sta) {
// cout << "r = " << r << " sta " << sta << endl;
if (r > n)
return 1;
vector<Edge> tmp;
int cnt = 0;
for (int i = 0; i < (int)e[r].size(); ++i) {
if (sta & (1<<e[r][i].r))
cnt++;
else
tmp.push_back(e[r][i]);
}
if (cnt > (int)tmp.size())
return 0;
int ans = 0;
for (int i = 0; i < (1 << tmp.size()); ++i) {
if ((cnt + bit_count(i)) * 2 != (int)e[r].size())
continue;
bool flag = false;
int new_sta = sta;
for (int j = 0; j < (int)tmp.size(); ++j) {
if (i & (1 << j)) {
new_sta |= (1 << tmp[j].r);
if (tmp[j].v < r)
flag = true;
}
}
if (flag)
continue;
ans += f(r + 1, new_sta);
}
return ans;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
for (int i = 0; i < 10; ++i)
e[i].clear();
scanf("%d %d", &n, &m);
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d %d", &u, &v);
e[u].push_back(Edge(u, v, i));
e[v].push_back(Edge(v, u, i));
}
printf("%d\n", m % 2 ? 0 : f(0, 0));
}
return 0;
}
| hangim/ACM | HDU/5305_Friends/5305.cc | C++ | mit | 1,603 |
using System;
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using SharePointPnP.PowerShell.Commands.Base.PipeBinds;
using SharePointPnP.PowerShell.Commands.Enums;
namespace SharePointPnP.PowerShell.Commands.Features
{
[Cmdlet(VerbsLifecycle.Disable, "PnPFeature", SupportsShouldProcess = false)]
[CmdletAlias("Disable-SPOFeature")]
[CmdletHelp("Disables a feature", Category = CmdletHelpCategory.Features)]
[CmdletExample(
Code = "PS:> Disable-PnPFeature -Identity 99a00f6e-fb81-4dc7-8eac-e09c6f9132fe",
Remarks = @"This will disable the feature with the id ""99a00f6e-fb81-4dc7-8eac-e09c6f9132fe""",
SortOrder = 1)]
[CmdletExample(
Code = "PS:> Disable-PnPFeature -Identity 99a00f6e-fb81-4dc7-8eac-e09c6f9132fe -Force",
Remarks = @"This will disable the feature with the id ""99a00f6e-fb81-4dc7-8eac-e09c6f9132fe"" with force.",
SortOrder = 2)]
[CmdletExample(
Code = "PS:> Disable-PnPFeature -Identity 99a00f6e-fb81-4dc7-8eac-e09c6f9132fe -Scope Web",
Remarks = @"This will disable the feature with the id ""99a00f6e-fb81-4dc7-8eac-e09c6f9132fe"" with the web scope.",
SortOrder = 3)]
public class DisableFeature : SPOWebCmdlet
{
[Parameter(Mandatory = true, Position = 0, ParameterSetName = ParameterAttribute.AllParameterSets, HelpMessage = "The id of the feature to disable.")]
public GuidPipeBind Identity;
[Parameter(Mandatory = false, ParameterSetName = ParameterAttribute.AllParameterSets, HelpMessage = "Forcibly disable the feature.")]
public SwitchParameter Force;
[Parameter(Mandatory = false, HelpMessage = "Specify the scope of the feature to deactivate, either Web or Site. Defaults to Web.")]
public FeatureScope Scope = FeatureScope.Web;
protected override void ExecuteCmdlet()
{
Guid featureId = Identity.Id;
if (Scope == FeatureScope.Web)
{
SelectedWeb.DeactivateFeature(featureId);
}
else
{
ClientContext.Site.DeactivateFeature(featureId);
}
}
}
}
| iiunknown/PnP-PowerShell | Commands/Features/DisableFeature.cs | C# | mit | 2,265 |
<?php
namespace Tutto\CommonBundle\Form\Subscriber;
use Exception;
/**
* Class SubscriberException
* @package Tutto\CommonBundle\Form\Subscriber
*/
class SubscriberException extends Exception { } | apihour/crm | src/Tutto/CommonBundle/Form/Subscriber/SubscriberException.php | PHP | mit | 201 |
package seedu.task.ui;
import java.net.URL;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import seedu.task.MainApp;
import seedu.task.commons.core.LogsCenter;
import seedu.task.commons.util.FxViewUtil;
/**
* Controller for a help page
*/
public class HelpWindow extends UiPart<Region> {
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String ICON = "/images/help_icon.png";
private static final String FXML = "HelpWindow.fxml";
private static final String TITLE = "Help";
private static final String USERGUIDE_URL = "/view/KITUserGuide.html";
@FXML
private WebView browser;
private final Stage dialogStage;
public HelpWindow() {
super(FXML);
Scene scene = new Scene(getRoot());
//Null passed as the parent stage to make it non-modal.
dialogStage = createDialogStage(TITLE, null, scene);
dialogStage.setMaximized(false); //TODO: set a more appropriate initial size
FxViewUtil.setStageIcon(dialogStage, ICON);
URL help = MainApp.class.getResource(USERGUIDE_URL);
browser.getEngine().load(help.toString());
FxViewUtil.applyAnchorBoundaryParameters(browser, 0.0, 0.0, 0.0, 0.0);
}
public void show() {
logger.fine("Showing help page about the application.");
dialogStage.showAndWait();
}
}
| CS2103JAN2017-F14-B2/main | src/main/java/seedu/task/ui/HelpWindow.java | Java | mit | 1,518 |
package com.network.gui;
/**
* MainModel.
*
* @author ningzhangnj
*/
public class MainModel {
private int localPort;
private String remoteHost;
private int remotePort;
public int getLocalPort() {
return localPort;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public String getRemoteHost() {
return remoteHost;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public int getRemotePort() {
return remotePort;
}
public void setRemotePort(int remotePort) {
this.remotePort = remotePort;
}
}
| ningzhangnj/NetCapPlay | src/main/java/com/network/gui/MainModel.java | Java | mit | 669 |
'''dossier.fc Feature Collections
:class:`dossier.fc.FeatureCollection` provides
convenience methods for working with collections of features
such as :class:`dossier.fc.StringCounter`.
A feature collection provides ``__add__`` and ``__sub__`` so that
adding/subtracting FeatureCollections does the right thing for its
constituent features.
.. This software is released under an MIT/X11 open source license.
Copyright 2012-2015 Diffeo, Inc.
'''
from __future__ import absolute_import, division, print_function
try:
from collections import Counter
except ImportError:
from backport_collections import Counter
from collections import MutableMapping, Sequence
import copy
from itertools import chain, ifilter, imap
import logging
import operator
import cbor
import pkg_resources
import streamcorpus
from dossier.fc.exceptions import ReadOnlyException, SerializationError
from dossier.fc.feature_tokens import FeatureTokens, FeatureTokensSerializer
from dossier.fc.geocoords import GeoCoords, GeoCoordsSerializer
from dossier.fc.string_counter import StringCounterSerializer, StringCounter, \
NestedStringCounter, NestedStringCounterSerializer
from dossier.fc.vector import SparseVector, DenseVector
logger = logging.getLogger(__name__)
class FeatureCollectionChunk(streamcorpus.CborChunk):
'''
A :class:`FeatureCollectionChunk` provides a way to serialize
a colllection of feature collections to a single blob of data.
Here's an example that writes two feature collections to an existing
file handle::
fc1 = FeatureCollection({'NAME': {'foo': 2, 'baz': 1}})
fc2 = FeatureCollection({'NAME': {'foo': 4, 'baz': 2}})
fh = StringIO()
chunk = FeatureCollectionChunk(file_obj=fh, mode='wb')
chunk.add(fc1)
chunk.add(fc2)
chunk.flush()
And the blob created inside the buffer can be read from to produce
an iterable of the feature collections that were written::
fh = StringIO(fh.getvalue())
chunk = FeatureCollectionChunk(file_obj=fh, mode='rb')
rfc1, rfc2 = list(chunk)
assert fc1 == rfc1
assert fc2 == rfc2
'''
def __init__(self, *args, **kwargs):
kwargs['write_wrapper'] = FeatureCollection.to_dict
kwargs['read_wrapper'] = FeatureCollection.from_dict
kwargs['message'] = lambda x: x
super(FeatureCollectionChunk, self).__init__(*args, **kwargs)
class FeatureCollection(MutableMapping):
'''
A collection of features.
This is a dictionary from feature name to a
:class:`collections.Counter` or similar object. In typical use
callers will not try to instantiate individual dictionary elements,
but will fall back on the collection's default-value behavior::
fc = FeatureCollection()
fc['NAME']['John Smith'] += 1
The default default feature type is
:class:`~dossier.fc.StringCounter`.
**Feature collection construction and serialization:**
.. automethod:: __init__
.. automethod:: loads
.. automethod:: dumps
.. automethod:: from_dict
.. automethod:: to_dict
.. automethod:: register_serializer
**Feature collection values and attributes:**
.. autoattribute:: read_only
.. autoattribute:: generation
.. autoattribute:: DISPLAY_PREFIX
.. autoattribute:: EPHEMERAL_PREFIX
**Feature collection computation:**
.. automethod:: __add__
.. automethod:: __sub__
.. automethod:: __mul__
.. automethod:: __imul__
.. automethod:: total
.. automethod:: merge_with
'''
__slots__ = ['_features', '_read_only']
DISPLAY_PREFIX = '#'
'''Prefix on names of features that are human-readable.
Processing may convert a feature ``name`` to a similar feature
``#name`` that is human-readable, while converting the original
feature to a form that is machine-readable only; for instance,
replacing strings with integers for faster comparison.
'''
EPHEMERAL_PREFIX = '_'
'''Prefix on names of features that are not persisted.
:meth:`to_dict` and :meth:`dumps` will not write out features
that begin with this character.
'''
TOKEN_PREFIX = '@'
'''Prefix on names of features that contain tokens.'''
GEOCOORDS_PREFIX = '!'
'''Prefix on names of features that contain geocoords.'''
NESTED_PREFIX = '%'
'''Prefix on names of features based on NestedStringCounters'''
@staticmethod
def register_serializer(feature_type, obj):
'''
This is a **class** method that lets you define your own
feature type serializers. ``tag`` should be the name of
the feature type that you want to define serialization
for. Currently, the valid values are ``StringCounter``,
``Unicode``, ``SparseVector`` or ``DenseVector``.
Note that this function is not thread safe.
``obj`` must be an object with three attributes defined.
``obj.loads`` is a function that takes a CBOR created
Python data structure and returns a new feature counter.
``obj.dumps`` is a function that takes a feature counter
and returns a Python data structure that can be serialized
by CBOR.
``obj.constructor`` is a function with no parameters that
returns the Python ``type`` that can be used to construct
new features. It should be possible to call
``obj.constructor()`` to get a new and empty feature
counter.
'''
registry.add(feature_type, obj)
def __init__(self, data=None, read_only=False):
'''
Creates a new empty feature collection.
If ``data`` is a dictionary-like object with a structure similar
to that of a feature collection (i.e., a dict of multisets),
then it is used to initialize the feature collection.
'''
self._features = {}
self.read_only = read_only
if data is not None:
self._from_dict_update(data)
@classmethod
def loads(cls, data):
'''Create a feature collection from a CBOR byte string.'''
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')
metadata = rep[0]
if 'v' not in metadata:
raise SerializationError('no version in CBOR metadata')
if metadata['v'] != 'fc01':
raise SerializationError('invalid CBOR version {!r} '
'(expected "fc01")'
.format(metadata['v']))
read_only = metadata.get('ro', False)
contents = rep[1]
return cls.from_dict(contents, read_only=read_only)
def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
rep = [metadata, self.to_dict()]
return cbor.dumps(rep)
@classmethod
def from_dict(cls, data, read_only=False):
'''Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
is instead passed as parameters to this function.
'''
fc = cls(read_only=read_only)
fc._features = {}
fc._from_dict_update(data)
return fc
def _from_dict_update(self, data):
for name, feat in data.iteritems():
if not isinstance(name, unicode):
name = name.decode('utf-8')
if name.startswith(self.EPHEMERAL_PREFIX):
self._features[name] = feat
continue
if isinstance(feat, cbor.Tag):
if feat.tag not in cbor_tags_to_names:
raise SerializationError(
'Unknown CBOR value (tag id: %d): %r'
% (feat.tag, feat.value))
loads = registry.get(cbor_tags_to_names[feat.tag]).loads
feat = feat.value
elif is_native_string_counter(feat):
loads = registry.get('StringCounter').loads
elif isinstance(feat, unicode):
# A Unicode string.
loads = registry.get('Unicode').loads
elif registry.is_serializeable(feat):
loads = lambda x: x
else:
raise SerializationError(
'Unknown CBOR value (type: %r): %r' % (type(feat), feat))
value = loads(feat)
if hasattr(value, 'read_only'):
value.read_only = self.read_only
self._features[name] = value
def to_dict(self):
'''Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats.
'''
def is_non_native_sc(ty, encoded):
return (ty == 'StringCounter'
and not is_native_string_counter(encoded))
fc = {}
native = ('StringCounter', 'Unicode')
for name, feat in self._features.iteritems():
if name.startswith(self.EPHEMERAL_PREFIX):
continue
if not isinstance(name, unicode):
name = name.decode('utf-8')
tyname = registry.feature_type_name(name, feat)
encoded = registry.get(tyname).dumps(feat)
# This tomfoolery is to support *native untagged* StringCounters.
if tyname not in native or is_non_native_sc(tyname, encoded):
encoded = cbor.Tag(cbor_names_to_tags[tyname], encoded)
fc[name] = encoded
return fc
@property
def generation(self):
'''Get the generation number for this feature collection.
This is the highest generation number across all counters
in the collection, if the counters support generation
numbers. This collection has not changed if the generation
number has not changed.
'''
return max(getattr(collection, 'generation', 0)
for collection in self._features.itervalues())
def __repr__(self):
return 'FeatureCollection(%r)' % self._features
def __missing__(self, key):
default_tyname = FeatureTypeRegistry.get_default_feature_type_name(key)
if self.read_only:
# reaturn a read-only instance of the default type, of
# which there is one, because we'll only ever need one,
# because it's read-only.
return registry.get_read_only(default_tyname)
if key.startswith(self.EPHEMERAL_PREFIX):
# When the feature name starts with an ephemeral prefix, then
# we have no idea what it should be---anything goes. Therefore,
# the caller must set the initial value themselves (and we must
# be careful not to get too eager with relying on __missing__).
raise KeyError(key)
default_value = registry.get_constructor(default_tyname)()
self[key] = default_value
return default_value
def __contains__(self, key):
'''
Returns ``True`` if the feature named ``key`` is in this
FeatureCollection.
:type key: unicode
'''
return key in self._features
def merge_with(self, other, multiset_op, other_op=None):
'''Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
feature collections are not modified.
For each feature name in both feature sets, if either feature
collection being merged has a :class:`collections.Counter`
instance as its value, then the two values are merged by
calling `multiset_op` with both values as parameters. If
either feature collection has something other than a
:class:`collections.Counter`, and `other_op` is not
:const:`None`, then `other_op` is called with both values to
merge them. If `other_op` is :const:`None` and a feature
is not present in either feature collection with a counter
value, then the feature will not be present in the result.
:param other: The feature collection to merge into ``self``.
:type other: :class:`FeatureCollection`
:param multiset_op: Function to merge two counters
:type multiset_op: fun(Counter, Counter) -> Counter
:param other_op: Function to merge two non-counters
:type other_op: fun(object, object) -> object
:rtype: :class:`FeatureCollection`
'''
result = FeatureCollection()
for ms_name in set(self._counters()) | set(other._counters()):
c1 = self.get(ms_name, None)
c2 = other.get(ms_name, None)
if c1 is None and c2 is not None:
c1 = c2.__class__()
if c2 is None and c1 is not None:
c2 = c1.__class__()
result[ms_name] = multiset_op(c1, c2)
if other_op is not None:
for o_name in (set(self._not_counters()) |
set(other._not_counters())):
v = other_op(self.get(o_name, None), other.get(o_name, None))
if v is not None:
result[o_name] = v
return result
def __add__(self, other):
'''
Add features from two FeatureCollections.
>>> fc1 = FeatureCollection({'foo': Counter('abbb')})
>>> fc2 = FeatureCollection({'foo': Counter('bcc')})
>>> fc1 + fc2
FeatureCollection({'foo': Counter({'b': 4, 'c': 2, 'a': 1})})
Note that if a feature in either of the collections is not an
instance of :class:`collections.Counter`, then it is ignored.
'''
return self.merge_with(other, operator.add)
def __iadd__(self, other):
'''
In-place add features from two FeatureCollections.
>>> fc1 = FeatureCollection({'foo': Counter('abbb')})
>>> fc2 = FeatureCollection({'foo': Counter('bcc')})
>>> fc1 += fc2
FeatureCollection({'foo': Counter({'b': 4, 'c': 2, 'a': 1})})
Note that if a feature in either of the collections is not an
instance of :class:`collections.Counter`, then it is ignored.
'''
if self.read_only:
raise ReadOnlyException()
fc = self.merge_with(other, operator.iadd)
self._features = fc._features
return self
def __sub__(self, other):
'''
Subtract features from two FeatureCollections.
>>> fc1 = FeatureCollection({'foo': Counter('abbb')})
>>> fc2 = FeatureCollection({'foo': Counter('bcc')})
>>> fc1 - fc2
FeatureCollection({'foo': Counter({'b': 2, 'a': 1})})
Note that if a feature in either of the collections is not an
instance of :class:`collections.Counter`, then it is ignored.
'''
return self.merge_with(other, operator.sub)
def __isub__(self, other):
'''
In-place subtract features from two FeatureCollections.
>>> fc1 = FeatureCollection({'foo': Counter('abbb')})
>>> fc2 = FeatureCollection({'foo': Counter('bcc')})
>>> fc1 -= fc2
FeatureCollection({'foo': Counter({'b': 2, 'a': 1})})
Note that if a feature in either of the collections is not an
instance of :class:`collections.Counter`, then it is ignored.
'''
if self.read_only:
raise ReadOnlyException()
fc = self.merge_with(other, operator.isub)
self._features = fc._features
return self
def __mul__(self, coef):
fc = copy.deepcopy(self)
fc *= coef
return fc
def __imul__(self, coef):
'''In-place multiplication by a scalar.'''
if self.read_only:
raise ReadOnlyException()
if coef == 1:
return self
for name in self._counters():
self[name] *= coef
return self
def total(self):
'''
Returns sum of all counts in all features that are multisets.
'''
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats)))
def __getitem__(self, key):
'''
Returns the feature named ``key``. If ``key`` does not
exist, then a new empty :class:`StringCounter` is created.
Alternatively, a second optional positional argument can
be given that is used as a default value.
Note that traditional indexing is supported too, e.g.::
fc = FeatureCollection({'NAME': {'foo': 1}})
assert fc['NAME'] == StringCounter({'foo': 1})
:type key: unicode
'''
v = self._features.get(key)
if v is not None:
return v
return self.__missing__(key)
def get(self, key, default=None):
if key not in self:
return default
else:
return self._features[key]
def __setitem__(self, key, value):
if self.read_only:
raise ReadOnlyException()
if not isinstance(key, unicode):
if isinstance(key, str):
key = unicode(key)
else:
raise TypeError(key)
if hasattr(value, 'read_only'):
value.read_only = self.read_only
self._features[key] = value
def __delitem__(self, key):
'''
Deletes the feature named ``key`` from this feature collection.
:type key: unicode
'''
if self.read_only:
raise ReadOnlyException()
if key in self._features:
del self._features[key]
else:
raise KeyError(key)
def _counters(self):
'''
Returns a generator of ``feature_name`` where ``feature_name``
corresponds to a feature that is an instance of
:class:`collections.Counter`. This method is useful when you
need to perform operations only on features that are multisets.
'''
return ifilter(lambda n: is_counter(self[n]), self)
def _not_counters(self):
'''
Returns a generator of ``feature_name`` where ``feature_name``
corresponds to a feature that is **not** an instance of
:class:`collections.Counter`. This method is useful when you
need to perform operations only on features that are **not**
multisets.
'''
return ifilter(lambda n: not is_counter(self[n]), self)
def __iter__(self):
return self._features.iterkeys()
def __len__(self):
'''
Returns the number of features in this collection.
'''
return len(set(iter(self)))
@property
def read_only(self):
'''Flag if this feature collection is read-only.
When a feature collection is read-only, no part of it
can be modified. Individual feature counters cannot
be added, deleted, or changed. This attribute is
preserved across serialization and deserialization.
'''
return self._read_only
@read_only.setter
def read_only(self, ro):
self._read_only = ro
for (k, v) in self._features.iteritems():
if hasattr(v, 'read_only'):
v.read_only = ro
class FeatureTypeRegistry (object):
'''
This is a pretty bogus class that has exactly one instance. Its
purpose is to guarantee the correct lazy loading of entry points
into the registry.
'''
ENTRY_POINT_GROUP = 'dossier.fc.feature_types'
DEFAULT_FEATURE_TYPE_NAME = 'StringCounter'
DEFAULT_FEATURE_TYPE_PREFIX_NAMES = {
FeatureCollection.DISPLAY_PREFIX: 'StringCounter',
FeatureCollection.EPHEMERAL_PREFIX: 'StringCounter',
FeatureCollection.TOKEN_PREFIX: 'FeatureTokens',
FeatureCollection.GEOCOORDS_PREFIX: 'GeoCoords',
FeatureCollection.NESTED_PREFIX: 'NestedStringCounter',
}
@classmethod
def get_default_feature_type_name(cls, feature_name):
by_prefix = cls.DEFAULT_FEATURE_TYPE_PREFIX_NAMES.get(feature_name[0])
if by_prefix is None:
return cls.DEFAULT_FEATURE_TYPE_NAME
else:
return by_prefix
def __init__(self):
self._registry = {}
self._inverse = {}
self._entry_points = False
def add(self, name, obj):
'''Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `constructor` is a callable that
creates an empty instance of the representation; `dumps` is
a callable that takes an instance of the representation and
returns a JSON-compatible form made of purely primitive
objects (lists, dictionaries, strings, numbers); and `loads`
is a callable that takes the response from `dumps` and recreates
the original representation.
Note that ``obj.constructor()`` *must* return an
object that is an instance of one of the following
types: ``unicode``, :class:`dossier.fc.StringCounter`,
:class:`dossier.fc.SparseVector` or
:class:`dossier.fc.DenseVector`. If it isn't, a
:exc:`ValueError` is raised.
'''
ro = obj.constructor()
if name not in cbor_names_to_tags:
print(name)
raise ValueError(
'Unsupported feature type name: "%s". '
'Allowed feature type names: %r'
% (name, cbor_names_to_tags.keys()))
if not is_valid_feature_instance(ro):
raise ValueError(
'Constructor for "%s" returned "%r" which has an unknown '
'sub type "%r". (mro: %r). Object must be an instance of '
'one of the allowed types: %r'
% (name, ro, type(ro), type(ro).mro(), ALLOWED_FEATURE_TYPES))
self._registry[name] = {'obj': obj, 'ro': obj.constructor()}
self._inverse[obj.constructor] = name
def feature_type_name(self, feat_name, obj):
ty = type(obj)
if ty not in self._inverse:
raise SerializationError(
'Python type "%s" is not in the feature type registry: %r\n\n'
'The offending feature (%s): %r'
% (ty, self._inverse, feat_name, obj))
return self._inverse[ty]
def is_serializeable(self, obj):
return type(obj) in self._inverse
def _get(self, type_name):
self._load_entry_points()
if type_name not in self._registry:
raise SerializationError(
'Feature type %r not in feature type registry: %r'
% (type_name, self._registry))
return self._registry[type_name]
def get(self, type_name):
return self._get(type_name)['obj']
def get_constructor(self, type_name):
return self._get(type_name)['obj'].constructor
def get_read_only(self, type_name):
return self._get(type_name)['ro']
def types(self):
self._load_entry_points()
return self._registry.keys()
def _load_entry_points(self):
if self._entry_points:
return
self._entry_points = True
for epoint in pkg_resources.iter_entry_points(self.ENTRY_POINT_GROUP):
try:
obj = epoint.load()
except (ImportError, pkg_resources.DistributionNotFound):
import traceback
logger.warn(traceback.format_exc())
continue
self.add(epoint.name, obj)
def _reset(self):
self._entry_points = False
self._registry = {}
self._inverse = {}
self.add('StringCounter', StringCounterSerializer)
self.add('Unicode', UnicodeSerializer)
self.add('GeoCoords', GeoCoordsSerializer)
self.add('FeatureTokens', FeatureTokensSerializer)
self.add('NestedStringCounter', NestedStringCounterSerializer)
def __enter__(self):
return self
def __exit__(self, *args):
self._reset()
class UnicodeSerializer(object):
def __init__(self):
raise NotImplementedError()
# cbor natively supports Unicode, so we can use the identity function.
loads = staticmethod(lambda x: x)
dumps = staticmethod(lambda x: x)
constructor = unicode
cbor_names_to_tags = {
# Tagged just in case someone wants to changed the binary format.
# By default, FeatureCollection will deserialize it as a special case
# into a dict of {unicode |--> int} with no tag.
'StringCounter': 55800,
# Not tagged because CBOR supports it natively.
'Unicode': None,
# These are *always* tagged.
'SparseVector': 55801,
'DenseVector': 55802,
# 55803 was FeatureOffsets
'FeatureTokens': 55804,
'GeoCoords': 55805,
'NestedStringCounter': 55806,
}
cbor_tags_to_names = {}
for k, v in cbor_names_to_tags.items():
if v:
cbor_tags_to_names[v] = k
ALLOWED_FEATURE_TYPES = (
unicode, StringCounter, SparseVector, DenseVector,
FeatureTokens,
GeoCoords, NestedStringCounter,
)
def is_native_string_counter(cbor_data):
return isinstance(cbor_data, dict)
def is_counter(obj):
return isinstance(obj, Counter) \
or getattr(obj, 'is_counter', False)
def is_valid_feature_instance(obj):
return isinstance(obj, ALLOWED_FEATURE_TYPES)
registry = FeatureTypeRegistry()
registry._reset()
| dossier/dossier.fc | python/dossier/fc/feature_collection.py | Python | mit | 26,206 |
<?php
/**
* Template for "My company" page.
*
* @author: Andrii Birev
*/
defined('BEXEC')or die('No direct access!');
?>
<div id="companies_newcompany">
<div class="header">
<h1 class="page-header">Create company</h1>
</div>
<?php $this->breadcrumbs->draw(); ?>
<div>
form
</div>
</div>
| konservs/financello | templates/members/companies.newcompany.d.php | PHP | mit | 302 |
/*
* This file is part of ThaumicSpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) Gabriel Harris-Rouquette
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.gabizou.thaumicsponge.api.entity;
import org.spongepowered.api.entity.Entity;
public interface EldritchMonster extends Entity {
}
| gabizou/ThaumicSpongeAPI | src/main/java/com/gabizou/thaumicsponge/api/entity/EldritchMonster.java | Java | mit | 1,382 |
import { Java } from './java';
import * as path from 'path';
import { ChildProcess } from "child_process";
import { LoggerContext } from './lib/logger-context';
import { Logger } from './lib/logger';
function emitLines(stream): void {
let backlog = '';
stream.on('data', function (data) {
backlog += data;
let n = backlog.indexOf('\n');
// got a \n? emit one or more 'line' events
while (~n) {
stream.emit('line', backlog.substring(0, n));
backlog = backlog.substring(n + 1);
n = backlog.indexOf('\n');
}
});
stream.on('end', function () {
if (backlog) {
stream.emit('line', backlog);
}
});
}
/**
* Class allowing abstract interface for accessing sqflint CLI.
*/
export class SQFLint {
// This is list of waiting results
private waiting: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[filename: string]: ((info: SQFLint.ParseInfo) => any);
} = {};
// Currently running sqflint process
private childProcess: ChildProcess;
private logger: Logger;
constructor(context: LoggerContext) {
this.logger = context.createLogger('sqflint');
}
/**
* Launches sqflint process and assigns basic handlers.
*/
private launchProcess(): void {
this.childProcess = Java.spawn(
path.join(__dirname, "..", "bin", "SQFLint.jar"),
[
"-j"
,"-v"
,"-s"
// ,"-bl"
]
);
// Fix for nodejs issue (see https://gist.github.com/TooTallNate/1785026)
emitLines(this.childProcess.stdout);
this.childProcess.stdout.resume();
this.childProcess.stdout.setEncoding('utf-8');
this.childProcess.stdout.on('line', line => this.processLine(line.toString()));
this.childProcess.stderr.on('data', data => {
let dataStr: string = data.toString().trim();
if (dataStr.startsWith('\n')) {
dataStr = dataStr.substring(1).trim();
}
// benchLog begin with timestamp
// TODO find better filter
this.logger.error(dataStr.startsWith("158") ? "" : "SQFLint: Error message", dataStr);
});
this.childProcess.on('error', msg => {
this.logger.error("SQFLint: Process crashed", msg);
this.childProcess = null;
this.flushWaiters();
});
this.childProcess.on('close', code => {
if (code != 0) {
this.logger.error("SQFLint: Process crashed with code", code);
} else {
this.logger.info('Background server stopped');
}
this.childProcess = null;
this.flushWaiters();
});
}
/**
* Calls all waiters with empty result and clears the waiters list.
*/
private flushWaiters(): void {
for (const i in this.waiting) {
this.waiting[i](new SQFLint.ParseInfo());
}
this.waiting = {};
}
/**
* Processes sqflint server line
* @param line sqflint output line in server mode
*/
private processLine(line: string): void {
// Prepare result info
const info = new SQFLint.ParseInfo();
// Skip empty lines
if (line.replace(/(\r\n|\n|\r)/gm, "").length == 0) {
return;
}
// Parse message
let serverMessage: RawServerMessage;
try {
serverMessage = JSON.parse(line) as RawServerMessage;
} catch (ex) {
console.error("SQFLint: Failed to parse server output.");
console.error(line);
return;
}
// log some bench
info.timeNeededSqfLint = serverMessage.timeneeded;
// Parse messages
for (const l in serverMessage.messages) {
this.processMessage(serverMessage.messages[l], info);
}
// Pass result to waiter
const waiter = this.waiting[serverMessage.file];
if (waiter) {
waiter(info);
delete this.waiting[serverMessage.file];
} else {
console.error("SQFLint: Received unrequested info.");
}
}
/**
* Converts raw sqflint message into specific classes.
* @param message sqflint info message
* @param info used to store parsed messages
*/
private processMessage(message: RawMessage, info: SQFLint.ParseInfo): void {
const errors: SQFLint.Error[] = info.errors;
const warnings: SQFLint.Warning[] = info.warnings;
const variables: SQFLint.VariableInfo[] = info.variables;
const macros: SQFLint.Macroinfo[] = info.macros;
const includes: SQFLint.IncludeInfo[] = info.includes;
// Preload position if present
let position: SQFLint.Range = null;
if (message.line && message.column) {
position = this.parsePosition(message);
}
// Create different wrappers based on type
if (message.type == "error") {
errors.push(new SQFLint.Error(
message.error || message.message,
position
));
} else if (message.type == "warning") {
warnings.push(new SQFLint.Warning(
message.error || message.message,
position,
message.filename
));
} else if (message.type == "variable") {
// Build variable info wrapper
const variable = new SQFLint.VariableInfo();
variable.name = message.variable;
variable.comment = this.parseComment(message.comment);
variable.usage = [];
variable.definitions = [];
// We need to convert raw positions to our format (compatible with vscode format)
for(const i in message.definitions) {
variable.definitions.push(this.parsePosition(message.definitions[i]));
}
for(const i in message.usage) {
variable.usage.push(this.parsePosition(message.usage[i]));
}
variables.push(variable);
} else if (message.type == "macro") {
const macro = new SQFLint.Macroinfo();
macro.name = message.macro;
macro.definitions = [];
if (macro.name.indexOf('(') >= 0) {
macro.arguments = macro.name.substr(macro.name.indexOf('('));
if (macro.arguments.indexOf(')') >= 0) {
macro.arguments = macro.arguments.substr(0, macro.arguments.indexOf(')') + 1);
}
macro.name = macro.name.substr(0, macro.name.indexOf('('));
}
const defs = message.definitions as unknown as { range: RawMessagePosition; value: string; filename: string }[];
for(const i in defs) {
const definition = new SQFLint.MacroDefinition();
definition.position = this.parsePosition(defs[i].range);
definition.value = defs[i].value;
definition.filename = defs[i].filename;
macro.definitions.push(definition);
}
macros.push(macro);
} else if (message.type == "include") {
const include = new SQFLint.IncludeInfo();
include.filename = message.include;
include.expanded = message.expandedInclude;
includes.push(include);
}
}
/**
* Parses content and returns result wrapped in helper classes.
* Warning: This only queues the item, the linting will start after 200ms to prevent fooding.
*/
public parse(filename: string, contents: string, options: SQFLint.Options): Promise<SQFLint.ParseInfo> {
// Cancel previous callback if exists
if (this.waiting[filename]) {
this.waiting[filename](null);
delete(this.waiting[filename]);
}
return new Promise<SQFLint.ParseInfo>((success /*, reject */): void => {
if (!this.childProcess) {
this.logger.info("Starting background server...");
this.launchProcess();
this.logger.info("Background server started");
}
const startTime = new Date();
this.waiting[filename] = (info: SQFLint.ParseInfo): void => {
info.timeNeededMessagePass = new Date().valueOf() - startTime.valueOf();
success(info);
};
this.childProcess.stdin.write(JSON.stringify({ "file": filename, "contents": contents, "options": options }) + "\n");
});
}
/**
* Stops subprocess if running.
*/
public stop(): void {
if (this.childProcess != null) {
this.logger.info('Stopping background server');
this.childProcess.stdin.write(JSON.stringify({ "type": "exit" }) + "\n");
}
}
/**
* Converts raw position to result position.
*/
private parsePosition(position: RawMessagePosition): SQFLint.Range {
return new SQFLint.Range(
new SQFLint.Position(position.line[0] - 1, position.column[0] - 1),
new SQFLint.Position(position.line[1] - 1, position.column[1])
);
}
/**
* Removes comment specific characters and trims the comment.
*/
private parseComment(comment: string): string {
if (comment) {
comment = comment.trim();
if (comment.indexOf("//") == 0) {
comment = comment.substr(2).trim();
}
if (comment.indexOf("/*") == 0) {
const clines = comment.substr(2, comment.length - 4).trim().split("\n");
for(const c in clines) {
let cline = clines[c].trim();
if (cline.indexOf("*") == 0) {
cline = cline.substr(1).trim();
}
clines[c] = cline;
}
comment = clines.filter((i) => !!i).join("\r\n").trim();
}
}
return comment;
}
}
/**
* Raw message received from server.
*/
interface RawServerMessage {
timeneeded?: number;
file: string;
messages: RawMessage[];
}
/**
* Raw position received from sqflint CLI.
*/
interface RawMessagePosition {
line: number[];
column: number[];
}
/**
* Raw message received from sqflint CLI.
*/
interface RawMessage extends RawMessagePosition {
type: string;
error?: string;
message?: string;
macro?: string;
filename?: string;
include?: string;
expandedInclude?: string;
variable?: string;
comment?: string;
usage: RawMessagePosition[];
definitions: RawMessagePosition[];
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace SQFLint {
/**
* Base message.
*/
class Message {
constructor(
public message: string,
public range: Range,
public filename?: string
) {}
}
/**
* Error in code.
*/
export class Error extends Message {}
/**
* Warning in code.
*/
export class Warning extends Message {}
/**
* Contains info about parse result.
*/
export class ParseInfo {
errors: Error[] = [];
warnings: Warning[] = [];
variables: VariableInfo[] = [];
macros: Macroinfo[] = [];
includes: IncludeInfo[] = [];
timeNeededSqfLint?: number;
timeNeededMessagePass?: number;
}
export class IncludeInfo {
filename: string;
expanded: string;
}
/**
* Contains info about variable used in document.
*/
export class VariableInfo {
name: string;
ident: string;
comment: string;
definitions: Range[];
usage: Range[];
public isLocal(): boolean {
return this.name.charAt(0) == '_';
}
}
/**
* Info about macro.
*/
export class Macroinfo {
name: string;
arguments: string = null;
definitions: MacroDefinition[]
}
/**
* Info about one specific macro definition.
*/
export class MacroDefinition {
position: Range;
value: string;
filename: string;
}
/**
* vscode compatible range
*/
export class Range {
constructor(
public start: Position,
public end: Position
) {}
}
/**
* vscode compatible position
*/
export class Position {
constructor(
public line: number,
public character: number
) {}
}
export interface Options {
checkPaths?: boolean;
pathsRoot?: string;
ignoredVariables?: string[];
includePrefixes?: { [key: string]: string };
contextSeparation?: boolean;
}
} | SkaceKamen/vscode-sqflint | server/src/sqflint.ts | TypeScript | mit | 13,048 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "Chapter5.h"
#include "TimeOfDayHandler.h"
#include "Clock.h"
// Sets default values
AClock::AClock()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
RootSceneComponent = CreateDefaultSubobject<USceneComponent>("RootSceneComponent");
ClockFace = CreateDefaultSubobject<UStaticMeshComponent>("ClockFace");
HourHand = CreateDefaultSubobject<UStaticMeshComponent>("HourHand");
MinuteHand = CreateDefaultSubobject<UStaticMeshComponent>("MinuteHand");
HourHandle = CreateDefaultSubobject<USceneComponent>("HourHandle");
MinuteHandle = CreateDefaultSubobject<USceneComponent>("MinuteHandle");
auto MeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Engine/BasicShapes/Cylinder.Cylinder'"));
if (MeshAsset.Object != nullptr)
{
ClockFace->SetStaticMesh(MeshAsset.Object);
HourHand->SetStaticMesh(MeshAsset.Object);
MinuteHand->SetStaticMesh(MeshAsset.Object);
}
RootComponent = RootSceneComponent;
HourHand->AttachTo(HourHandle);
MinuteHand->AttachTo(MinuteHandle);
HourHandle->AttachTo(RootSceneComponent);
MinuteHandle->AttachTo(RootSceneComponent);
ClockFace->AttachTo(RootSceneComponent);
ClockFace->SetRelativeTransform(FTransform(FRotator(90, 0, 0), FVector(10, 0, 0), FVector(2, 2, 0.1)));
HourHand->SetRelativeTransform(FTransform(FRotator(0, 0, 0), FVector(0, 0, 25), FVector(0.1, 0.1, 0.5)));
MinuteHand->SetRelativeTransform(FTransform(FRotator(0, 0, 0), FVector(0, 0, 50), FVector(0.1, 0.1, 1)));
}
// Called when the game starts or when spawned
void AClock::BeginPlay()
{
Super::BeginPlay();
TArray<AActor*> TimeOfDayHandlers;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ATimeOfDayHandler::StaticClass(), TimeOfDayHandlers);
if (TimeOfDayHandlers.Num() != 0)
{
auto TimeOfDayHandler = Cast<ATimeOfDayHandler>(TimeOfDayHandlers[0]);
MyDelegateHandle = TimeOfDayHandler->OnTimeChanged.AddUObject(this, &AClock::TimeChanged);
}
}
// Called every frame
void AClock::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
void AClock::TimeChanged(int32 Hours, int32 Minutes)
{
HourHandle->SetRelativeRotation(FRotator( 0, 0,30 * Hours));
MinuteHandle->SetRelativeRotation(FRotator(0,0,6 * Minutes));
}
| sunithshetty/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook | Chapter05/source/Chapter5/Clock.cpp | C++ | mit | 2,382 |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using C1.WPF.Toolbar;
using Memento.Component.WPF;
namespace Memento.JMS.Toolbar
{
/// <summary>
/// 菜单栏通用组件
/// </summary>
public partial class ToolbarControl : UserControl
{
#region 成员变量
private static Dictionary<string, ICommand> m_AllCommands = new Dictionary<string, ICommand>();
#endregion
#region 构造函数
/// <summary>
/// 菜单栏通用组件
/// </summary>
public ToolbarControl()
{
InitializeComponent();
}
#endregion
#region 公开方法
/// <summary>
/// 注册命令
/// </summary>
/// <param name="command">命令</param>
public void RegisterCommand(ICommand command)
{
CommandAttribute cmdAttr = BaseCommand.GetCommandAttr(command);
if(cmdAttr == null)
{
throw new ArgumentNullException("There is no attribute defined in the command.");
}
if (!m_AllCommands.ContainsKey(cmdAttr.TabItemHeader))
{
// 创建新菜单
m_AllCommands[cmdAttr.TabItemHeader] = command;
C1ToolbarTabItem tabItem = CreateC1ToolbarTabItem(command, cmdAttr.TabItemHeader);
toolbar.ToolbarItems.Add(tabItem);
tabItem.IsSelected = true;
}
else if (command != m_AllCommands[cmdAttr.TabItemHeader])
{
CancelCommand(command);
RegisterCommand(command);
}
}
/// <summary>
/// 注销命令
/// </summary>
/// <param name="command">命令</param>
public void CancelCommand(ICommand command)
{
CommandAttribute cmdAttr = BaseCommand.GetCommandAttr(command);
if (cmdAttr == null)
{
throw new ArgumentNullException("There is no attribute defined in the command.");
}
if (m_AllCommands.ContainsKey(cmdAttr.TabItemHeader))
{
m_AllCommands.Remove(cmdAttr.TabItemHeader);
int toolbarItemsCount = toolbar.ToolbarItems.Count;
for (int i = 0; i < toolbarItemsCount; i++)
{
C1ToolbarTabItem tabItem = toolbar.ToolbarItems[i] as C1ToolbarTabItem;
if (tabItem != null && tabItem.Header.ToString() == cmdAttr.TabItemHeader)
{
toolbar.ToolbarItems.Remove(tabItem);
break;
}
}
}
else
{
throw new Exception("The command is not registered by RegisterCommand method.");
}
}
/// <summary>
/// 注销命令
/// </summary>
/// <param name="tabItemHeader">命令页签标题</param>
public void CancelCommand(string tabItemHeader)
{
if (m_AllCommands.ContainsKey(tabItemHeader))
{
CancelCommand(m_AllCommands[tabItemHeader]);
}
}
/// <summary>
/// 注销某个命令下的某个方法
/// </summary>
/// <param name="command">命令</param>
/// <param name="methodName">方法名称</param>
public void CancelMethod(ICommand command, string methodName)
{
CommandAttribute cmdAttr = BaseCommand.GetCommandAttr(command);
if (cmdAttr == null)
{
throw new ArgumentNullException("There is no attribute defined in the command.");
}
bool flag = false;
foreach (C1ToolbarTabItem tabItem in toolbar.ToolbarItems)
{
if (tabItem != null && tabItem.Header.ToString() == cmdAttr.TabItemHeader)
{
int groupCount = tabItem.Groups.Count;
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++)
{
C1ToolbarGroup group = tabItem.Groups[groupIndex];
int btnCount = group.Items.Count;
for (int btnIndex = 0; btnIndex < btnCount; btnIndex++)
{
C1ToolbarButton button = group.Items[btnIndex] as C1ToolbarButton;
if (button != null && button.Name == "btn" + methodName)
{
flag = true;
group.Items.Remove(button);
break;
}
}
if (flag)
{
// 移除空组
if (group.Items.Count == 0)
{
tabItem.Groups.Remove(group);
}
break;
}
}
break;
}
}
}
/// <summary>
/// 刷新命令
/// </summary>
/// <param name="command">命令</param>
public void RefreshCommand(ICommand command)
{
MethodInfo[] mis = command.GetType().GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach(MethodInfo mi in mis)
{
string key = "cmd" + mi.Name;
C1ToolbarCommand cmd = grid.Resources[key] as C1ToolbarCommand;
bool canExecute = command.EnabledItems.Contains(mi.Name);
if (cmd != null)
{
CommandManager.RegisterClassCommandBinding(
GetType(),
new CommandBinding(
cmd,
(sender, e) =>
{
try
{
mi.Invoke(command, null);
}
catch (Exception ex)
{
MsgBoxHelper.ShowError(ex.InnerException);
}
},
(sender, e) =>
{
e.CanExecute = canExecute;
}));
}
}
}
#endregion
#region 其他方法
// 创建 C1ToolbarTabItem
private C1ToolbarTabItem CreateC1ToolbarTabItem(ICommand command, string tabItemHeader)
{
C1ToolbarTabItem tabItem = new C1ToolbarTabItem();
tabItem.Header = tabItemHeader;
Dictionary<int, List<CommandMethodAttribute>> cmdMethodAttrs = new Dictionary<int, List<CommandMethodAttribute>>();
foreach(MethodInfo mi in command.GetType().GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
{
foreach(object attr in mi.GetCustomAttributes(true))
{
if(attr is CommandMethodAttribute)
{
CommandMethodAttribute cmdMethod = attr as CommandMethodAttribute;
if(cmdMethod != null)
{
if(!cmdMethodAttrs.ContainsKey(cmdMethod.GroupIndex))
{
cmdMethodAttrs[cmdMethod.GroupIndex] = new List<CommandMethodAttribute>();
}
cmdMethodAttrs[cmdMethod.GroupIndex].Add(cmdMethod);
break;
}
}
}
}
foreach(int gourpIndex in cmdMethodAttrs.Keys)
{
C1ToolbarGroup group = CreateC1ToolbarGroup(cmdMethodAttrs[gourpIndex], command.GetType());
tabItem.Groups.Add(group);
}
return tabItem;
}
// 创建 C1ToolbarGroup
private C1ToolbarGroup CreateC1ToolbarGroup(List<CommandMethodAttribute> methods, Type cmdType)
{
C1ToolbarGroup group = new C1ToolbarGroup();
C1ToolbarGroupSizeDefinition groupSizeDef = new C1ToolbarGroupSizeDefinition();
groupSizeDef.ControlSizes.Add(C1ToolbarControlSize.Large);
group.GroupSizeDefinitions.Add(groupSizeDef);
foreach(CommandMethodAttribute cmdMethodAttr in methods)
{
if (cmdMethodAttr.IsEnable)
{
string key = "cmd" + cmdMethodAttr.Name;
C1ToolbarCommand toolbarCmd = null;
if (grid.Resources.Contains(key))
{
grid.Resources.Remove(key);
}
toolbarCmd = new C1ToolbarCommand();
toolbarCmd.LabelTitle = cmdMethodAttr.Title;
toolbarCmd.LargeImageSource = new BitmapImage(new Uri(string.Format("/{0};component/Resources/{1}32.png", cmdType.BaseType.Namespace, cmdMethodAttr.Name), UriKind.Relative));
toolbarCmd.SmallImageSource = new BitmapImage(new Uri(string.Format("/{0};component/Resources/{1}.png", cmdType.BaseType.Namespace, cmdMethodAttr.Name), UriKind.Relative));
grid.Resources.Add(key, toolbarCmd);
C1ToolbarButton button = new C1ToolbarButton();
button.Name = "btn" + cmdMethodAttr.Name;
button.Command = toolbarCmd;
group.Items.Add(button);
}
}
return group;
}
#endregion
}
} | Memento1990/Memento | JMS/JMSToolbar/ToolbarControl.xaml.cs | C# | mit | 10,199 |
'use strict';
angular.module('ucllApp')
.controller('LogoutController', function (Auth) {
Auth.logout();
});
| craftworkz/ucll-workshop-jhipster | jhipster-demo/src/main/webapp/scripts/app/account/logout/logout.controller.js | JavaScript | mit | 126 |
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
unordered_map<string,double> coll { { "tim", 9.9 },
{ "struppi", 11.77 }
};
// square the value of each element:
for (pair<const string,double>& elem : coll) {
elem.second *= elem.second;
}
// print each element (key and value):
for (const auto& elem : coll) {
cout << elem.first << ": " << elem.second << endl;
}
}
| iZhangHui/cppstdlib | stl/unordmap1.cpp | C++ | mit | 1,036 |
/*
* Copyright (C) 2012 David Geary. This code is from the book
* Core HTML5 Canvas, published by Prentice-Hall in 2012.
*
* License:
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* The Software may not be used to create training material of any sort,
* including courses, books, instructional videos, presentations, etc.
* without the express written consent of David Geary.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
CENTROID_RADIUS = 10,
CENTROID_STROKE_STYLE = 'rgba(0, 0, 0, 0.5)',
CENTROID_FILL_STYLE ='rgba(80, 190, 240, 0.6)',
GUIDEWIRE_STROKE_STYLE = 'goldenrod',
GUIDEWIRE_FILL_STYLE = 'rgba(85, 190, 240, 0.6)',
TEXT_FILL_STYLE = 'rgba(100, 130, 240, 0.5)',
TEXT_STROKE_STYLE = 'rgba(200, 0, 0, 0.7)',
TEXT_SIZE = 64,
GUIDEWIRE_STROKE_STYLE = 'goldenrod',
GUIDEWIRE_FILL_STYLE = 'rgba(85, 190, 240, 0.6)',
circle = { x: canvas.width/2,
y: canvas.height/2,
radius: 200
};
// Functions.....................................................
function drawGrid(color, stepx, stepy) {
context.save()
context.shadowColor = undefined;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.strokeStyle = color;
context.fillStyle = '#ffffff';
context.lineWidth = 0.5;
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, context.canvas.height);
context.stroke();
}
for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(context.canvas.width, i);
context.stroke();
}
context.restore();
}
// Drawing functions.............................................
function drawCentroid() {
context.beginPath();
context.save();
context.strokeStyle = CENTROID_STROKE_STYLE;
context.fillStyle = CENTROID_FILL_STYLE;
context.arc(circle.x, circle.y, CENTROID_RADIUS, 0, Math.PI*2, false);
context.stroke();
context.fill();
context.restore();
}
function drawCircularText(string, startAngle, endAngle) {
var radius = circle.radius,
angleDecrement = (startAngle - endAngle)/(string.length-1),
angle = parseFloat(startAngle),
index = 0,
character;
context.save();
context.fillStyle = TEXT_FILL_STYLE;
context.strokeStyle = TEXT_STROKE_STYLE;
context.font = TEXT_SIZE + 'px Lucida Sans';
while (index < string.length) {
character = string.charAt(index);
context.save();
context.beginPath();
context.translate(
circle.x + Math.cos(angle) * radius,
circle.y - Math.sin(angle) * radius);
context.rotate(Math.PI/2 - angle);
context.fillText(character, 0, 0);
context.strokeText(character, 0, 0);
angle -= angleDecrement;
index++;
context.restore();
}
context.restore();
}
// Initialization................................................
if (navigator.userAgent.indexOf('Opera') === -1)
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
context.shadowOffsetX = 2;
context.shadowOffsetY = 2;
context.shadowBlur = 5;
context.textAlign = 'center';
context.textBaseline = 'middle';
drawGrid('lightgray', 10, 10);
drawCentroid();
drawCircularText("Clockwise around the circle", Math.PI*2, Math.PI/8);
| yuesir/HTML5-Canvas | ch03/example-3.9/example.js | JavaScript | mit | 4,545 |
// @flow
import React, { type Node } from 'react';
import classnames from 'classnames';
import { Tooltip as ReactAccessibleTooltip } from 'react-accessible-tooltip';
import './tooltip.scss';
function Tooltip({ label, overlay }: { label: Node, overlay: Node }) {
return (
<ReactAccessibleTooltip
className="tooltip"
label={({ labelAttributes }: { labelAttributes: Object }) => (
<span className="tooltip__label" {...labelAttributes}>
<strong>{label}</strong>
</span>
)}
overlay={({
overlayAttributes,
isHidden,
}: {
overlayAttributes: Object,
isHidden: boolean,
}) => (
<span
className={classnames('tooltip__overlay', {
'tooltip__overlay--hidden': isHidden,
})}
{...overlayAttributes}
>
<span className="tooltip__overlay-inner">{overlay}</span>
</span>
)}
/>
);
}
export default Tooltip;
| ryami333/react-accessible-tooltip | packages/docs/src/components/Tooltip/Tooltip.js | JavaScript | mit | 1,166 |
<?php
namespace Adriatic\PHPAkademija\DesignPattern\FactoryMethod\MailerImplementations;
use Adriatic\PHPAkademija\DesignPattern\FactoryMethod\Newsletter;
class GiveawayNewsletter extends Newsletter
{
public function getContent() : string
{
return $this->recipientName . ', nagradna igra!';
}
}
| adriatichr/php-academy | example/src/DesignPattern/FactoryMethod/MailerImplementations/GiveawayNewsletter.php | PHP | mit | 318 |
<?php
function draw_html(){
set_lang();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="inc/js/kvm-vdi-openstack.js"></script>
</head>
<body>
<style>
.input-group-addon {
min-width:80px;
}
</style>
<form id="new_vm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><?php echo _("Create virtual machine(s)");?></h4>
</div>
<div class="modal-body">
<div class="row targetConfig">
<div class="col-md-6">
<label><?php echo _("Machine type:");?></label>
<select class="form-control selectClass" name="OSMachineType" id="OSMachineType" required tabindex="1">
<option selected value=""><?php echo _("Please select machine type");?></option>
<option value="initialmachine"><?php echo _("Initial machine");?></option>
<option value="sourcemachine"><?php echo _("Source machine");?></option>
<option value="vdimachine"><?php echo _("VDI machine");?></option>
</select>
</div>
<div class="col-md-6">
<label><?php echo _("Machine source:");?></label>
<select class="form-control selectClass" name="OSSource" id="OSSource" required>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label><?php echo _("Networks:");?><i class="fa fa-spinner fa-spin fa-1x fa-fw hide" id="OSNetworkLoad"></i></label>
<select multiple class="form-control osselection" name="OSNetworks" id="OSNetworks" tabindex="3" required type="number">
</select>
</div>
<div class="col-md-6 hide" id="OSVolumeSize">
<label><?php echo _("Volume size GB:");?></label>
<input type="number" name="OSVolumeGB" id="OSVolumeGB" min="1" value="1" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-md-6" id="newmachine-os">
<label><?php echo _("System info:");?></label>
<div class="input-group">
<span class="input-group-addon"><?php echo _("OS type");?></span>
<select class="form-control osselection" name="os_type" id="os_type" tabindex="3" required type="number">
<option selected value=""><?php echo _("Please select OS type");?></option>
<option value="linux"><?php echo _("Linux");?></option>
<option value="windows"><?php echo _("Windows");?></option>
</select>
</div>
</div>
<div class="col-md-6">
<label><?php echo _("Flavors")?><i class="fa fa-spinner fa-spin fa-1x fa-fw hide" id="OSFlavorLoad"></i></label>
<select class="form-control selectClass" name="OSFlavor" id="OSFlavor" required tabindex="1">
</select>
</div>
</div>
<div class="row machineDeployInfo">
<div class="col-md-6">
<label><?php echo _("Machine name:");?></label>
<input type="text" name="machinename" id="machinename" placeholder="somename-" class="form-control" required pattern="[a-zA-Z0-9-_]+" oninvalid="setCustomValidity(<?php echo ("'Illegal characters detected'");?>)" onchange="try{setCustomValidity('')}catch(e){}" >
</div>
<div class="col-md-6 hide" id="OSMachineCount">
<label><?php echo _("Number of machines to create:");?></label>
<input type="number" name="machinecount" id="machinecount" min="1" value="1" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<div class="row">
<div class="col-md-7">
<div class="alert alert-info text-left hide" id="new_vm_creation_info_box"></div>
</div>
<div class="col-md-5">
<button type="button" class="btn btn-default create_vm_buttons" data-dismiss="modal"><?php echo _("Close");?></button>
<button type="button" class="btn btn-primary create_vm_buttons" id="create-vm-button-click"><?php echo _("Create VMs");?></button>
<input type="submit" class="hide">
</div>
</div>
</div>
</div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function () {
loadNetworkList();
loadFlavorList();
});
</script>
</html>
<?php
} | Seitanas/kvm-vdi | inc/modules/OpenStack/NewVM.php | PHP | mit | 5,047 |
var router = new AiRouter();
router.route('/',{
name:'HOME',
action:function(params, query) {
document.getElementById("switch").innerHTML = "Changed to Home page!";
console.log('Home Page');
},
});
router.route('/projects/:projectId/tests/:testId',{
name:'HOME',
action:function(params, query) {
document.getElementById("switch").innerHTML = "Changed to Projects page!";
console.log(params);
console.log(query);
},
});
router.route('/posts/:postId/comments/:commentId',{
name:'HOME',
beforeAction:function(params, query) {
console.log('This function trigger before Action');
console.log(params);
console.log(query);
},
action:function(params, query) {
document.getElementById("switch").innerHTML = "Changed to Blog page!";
console.log('This function trigger Action');
console.log(params);
console.log(query);
},
afterAction:function(params, query) {
console.log('This function triggers after Action');
console.log(params);
console.log(query);
}
});
router.notFound({
action:function() {
document.getElementById("switch").innerHTML = "No Route Found page!";
console.log('No Route Found page');
}
});
function go1() {
router.go('/demo/#/');
}
function go2() {
router.go('/demo/#/projects/123/tests/321');
}
function go3() {
router.go('/demo/#/posts/123/comments/A2516BC');
}
function go4() {
var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
router.go('/demo/#/'+thing);
}
| nedyalkovV/AiRouter | demo/demo/demo.js | JavaScript | mit | 1,653 |
#!/usr/local/bin/python3
import argparse
import gym
import logging
import tensorflow as tf
from dqn_agent import DQNAgent
from network import Network
from replay_memory import ReplayMemory
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--log_level', default='INFO', help='Log verbosity')
# Environment
parser.add_argument('--env', default='CartPole-v0',
help='OpenAI Gym environment name')
parser.add_argument('--monitor', action='store_true',
help='Turn on OpenAI Gym monitor')
parser.add_argument('--monitor_path', default='/tmp/gym',
help='Path for OpenAI Gym monitor logs')
parser.add_argument('--disable_video', action='store_true',
help='Disable video recording while when running the monitor')
# Network
parser.add_argument('--network', default='simple', choices=['simple', 'cnn'],
help='Network architecture type')
parser.add_argument('--lr', default=0.001, type=float, help='Learning rate')
parser.add_argument('--reg_param', default=0.001, type=float,
help='Regularization param')
parser.add_argument('--optimizer', default='sgd',
choices=['adadelta', 'adagrad', 'adam', 'ftrl', 'sgd', 'momentum', 'rmsprop'],
help='Type of optimizer for gradient descent')
parser.add_argument('--momentum', default=0.9, type=float,
help='Momentum value for MomentumOptimizer')
parser.add_argument('--rmsprop_decay', default=0.95, type=float,
help='Decay for RMSPropOptimizer')
# Agent
parser.add_argument('--num_episodes', default=10000, type=int,
help='Number of episodes to train')
parser.add_argument('--max_steps_per_episode', default=1000, type=int,
help='Max steps to train for each episode')
parser.add_argument('--minibatch_size', default=30, type=int,
help='Minibatch size for each training step')
parser.add_argument('--frames_per_state', default=1, type=int,
help='Number of consecutive frames that form a state')
parser.add_argument('--resize_width', default=0, type=int,
help='Resized screen width for frame pre-processing (0 for no resizing)')
parser.add_argument('--resize_height', default=0, type=int,
help='Resized screen height for frame pre-processing (0 for no resizing)')
parser.add_argument('--reward_discount', default=0.9, type=float,
help='Discount factor for future rewards')
parser.add_argument('--replay_memory_capacity', default=10000, type=int,
help='Max size of the memory for experience replay')
parser.add_argument('--replay_start_size', default=0, type=int,
help='Size to prefill the replay memory to based on random actions')
parser.add_argument('--init_random_action_prob', default=0.9, type=float,
help='Initial probability for choosing random actions')
parser.add_argument('--min_random_action_prob', default=0.1, type=float,
help='Threshold at which to stop decaying random action probability')
parser.add_argument('--random_action_explore_steps', default=10000, type=int,
help='Number of steps over which to decay the random action probability')
parser.add_argument('--update_freq', default=1, type=int,
help='Number of actions by the agent between successive learning updates')
parser.add_argument('--target_update_freq', default=10000, type=int,
help='Target network update frequency in terms of number of training steps')
# Distribution
parser.add_argument('--ps_hosts', default='',
help='Parameter Servers. Comma separated list of host:port pairs')
parser.add_argument('--worker_hosts', default='localhost:0',
help='Worker hosts. Comma separated list of host:port pairs')
parser.add_argument('--job', default='worker', choices=['ps', 'worker'],
help='Whether this instance is a param server or a worker')
parser.add_argument('--task_id', default=0, type=int,
help='Index of this task within the job')
parser.add_argument('--gpu_id', default=0, type=int,
help='Index of the GPU to run the training on')
parser.add_argument('--sync', action='store_true',
help='Whether to perform synchronous training')
parser.add_argument('--disable_cpu_param_pinning', action='store_true',
help='If set, param server will not pin the varaibles to CPU, allowing '
'TensorFlow to default to GPU:0 if the host has GPU devices')
parser.add_argument('--disable_target_replication', action='store_true',
help='Unless set, the target params will be replicated on each GPU. '
'Setting the flag defaults to a single set of target params managed '
'by the param server.')
# Summary
parser.add_argument('--logdir', default='/tmp/train_logs',
help='Directory for training summary and logs')
parser.add_argument('--summary_freq', default=100, type=int,
help='Frequency for writing summary (in terms of global steps')
return parser.parse_args()
def run_worker(cluster, server, args):
env = gym.make(args.env)
worker_job = args.job
num_workers = len(cluster.job_tasks(worker_job))
ps_device = None
if num_workers > 1 and not args.disable_cpu_param_pinning:
# If in a distributed setup, have param servers pin params to CPU.
# Otherwise, in a multi-GPU setup, /gpu:0 would be used for params
# by default, and it becomes a communication bottleneck.
ps_device = '/cpu'
# If no GPU devices are found, then allow_soft_placement in the
# config below results in falling back to CPU.
worker_device = '/job:%s/task:%d/gpu:%d' % \
(worker_job, args.task_id, args.gpu_id)
replica_setter = tf.train.replica_device_setter(
worker_device=worker_device,
cluster=cluster,
)
with tf.device(replica_setter):
network = Network.create_network(
config=args,
input_shape=DQNAgent.get_input_shape(env, args),
num_actions=env.action_space.n,
num_replicas=num_workers,
ps_device=ps_device,
worker_device=worker_device,
)
init_op = tf.initialize_all_variables()
# Designate the first worker task as the chief
is_chief = (args.task_id == 0)
# Create a Supervisor that oversees training and co-ordination of workers
sv = tf.train.Supervisor(
is_chief=is_chief,
logdir=args.logdir,
init_op=init_op,
global_step=network.global_step,
summary_op=None, # Explicitly disable as DQNAgent handles summaries
recovery_wait_secs=3,
)
# Start the gym monitor if needed
video = False if args.disable_video else None
if args.monitor:
env.monitor.start(args.monitor_path, resume=True, video_callable=video)
# Initialize memory for experience replay
replay_memory = ReplayMemory(args.replay_memory_capacity)
# Start the session and kick-off the train loop
config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)
with sv.managed_session(server.target, config=config) as session:
dqn_agent = DQNAgent(
env, network, session, replay_memory, args,
enable_summary=is_chief, # Log summaries only from the chief worker
)
dqn_agent.train(args.num_episodes, args.max_steps_per_episode, sv)
# Close the gym monitor
if args.monitor:
env.monitor.close()
# Stop all other services
sv.stop()
if __name__ == '__main__':
args = parse_args()
logging.getLogger().setLevel(args.log_level)
ps_hosts = args.ps_hosts.split(',') if args.ps_hosts else []
worker_hosts = args.worker_hosts.split(',') if args.worker_hosts else []
cluster = tf.train.ClusterSpec({'ps': ps_hosts, 'worker': worker_hosts})
# Create a TensorFlow server that acts either as a param server or
# as a worker. For non-distributed setup, we still create a single
# instance cluster without any --ps_hosts and one item in --worker_hosts
# that corresponds to localhost.
server = tf.train.Server(
cluster,
job_name=args.job,
task_index=args.task_id
)
if args.job == 'ps':
# Param server
server.join()
elif args.job == 'worker':
# Start the worker and run the train loop
run_worker(cluster, server, args)
| viswanathgs/dist-dqn | src/main.py | Python | mit | 7,997 |
User.inject({
statics: {
log: function() {
var str = Array.create(arguments).join(' ');
if (session && session.user)
str = '[' + session.user.name + '] ' + str;
app.log(str);
},
logError: function(title, e) {
var shortDesc = (e.fileName
? 'Error in ' + e.fileName + ', Line ' + e.lineNumber
: 'Error')
+ ' (' + title + '): ' + e;
// In some situations, the global req object might not be available,
// so make sure we check to not produce another error.
if (global.req && req.path)
shortDesc += '\n(' + req.path + ')';
// Generate the stacktrace:
var longDesc = shortDesc;
if (e.javaException) {
var sw = new java.io.StringWriter();
e.javaException.printStackTrace(new java.io.PrintWriter(sw));
longDesc += '\nStacktrace:\n' + sw.toString();
}
User.log(longDesc);
var from = app.properties.errorFromAddress
|| app.properties.serverAddress;
var to = app.properties.errorToAddress;
if (from && to) {
try {
// Send an error mail:
var mail = new Mail();
mail.setFrom(from);
mail.setTo(to);
mail.setSubject('[' + new Date().format(
'yyyy/MM/dd HH:mm:ss') + '] ' + title);
if (session.user != null)
longDesc = '[' + session.user.name + '] ' + longDesc;
mail.addText(longDesc);
mail.send();
} catch (e) {
}
}
return shortDesc;
},
getHost: function() {
var host = req.data.http_remotehost;
var address = java.net.InetAddress.getByName(host);
var name = address && address.getCanonicalHostName();
return name || host;
}
}
}); | lehni/boots | base/helma/User/functions.js | JavaScript | mit | 1,599 |
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http';
import { DestinyGrimoireAppComponent, environment } from './app/';
if (environment.production) {
enableProdMode();
}
bootstrap(DestinyGrimoireAppComponent, [HTTP_PROVIDERS]);
| Foshkey/destiny-grimoire | src/main.ts | TypeScript | mit | 339 |
class CreateTweets < ActiveRecord::Migration
def change
create_table :tweets do |t|
t.string :xid
t.string :name
t.string :screen_name
t.text :text
t.text :media_url
t.text :profile_image_url
t.datetime :tweeted_at
t.timestamps
end
end
end
| cbetta/battlehack-dashboard | db/migrate/20130716134921_create_tweets.rb | Ruby | mit | 301 |
/**
* @since 2019-07-19 14:13
* @author vivaxy
*
* Call simple function. 7.964s
* Call function await promise. 16.687s
* Call function with if logic. 9.612s
*/
let resolved = false;
function request() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(true);
}, 1000);
});
}
const promise = request();
async function callSimpleFunction() {
return 0;
}
async function callFunctionWithAwaitPromise() {
await promise;
return 0;
}
async function callFunctionWithIfLogic() {
if (resolved) {
return 0;
}
await promise;
return 0;
}
function getTime(s) {
return (Date.now() - s) / 1000 + 's';
}
(async function() {
await promise;
resolved = true;
const loopCount = 1e8;
let s = Date.now();
for (let i = 0; i < loopCount; i++) {
await callSimpleFunction();
}
console.log('Call simple function.', getTime(s));
s = Date.now();
for (let i = 0; i < loopCount; i++) {
await callFunctionWithAwaitPromise();
}
console.log('Call function await promise.', getTime(s));
s = Date.now();
for (let i = 0; i < loopCount; i++) {
await callFunctionWithIfLogic();
}
console.log('Call function with if logic.', getTime(s));
})();
| vivaxy/course | benchmark/await-resolved-promise/index.js | JavaScript | mit | 1,223 |
package speedy.model.database.mainmemory.datasource.nodes;
import speedy.model.database.mainmemory.datasource.operators.INodeVisitor;
public class SetNode extends IntermediateNode {
boolean cloned = false;
public SetNode(String label) {
super(label);
}
public SetNode(String label, Object value) {
super(label, value);
}
public boolean isCloned() {
return cloned;
}
public void setCloned(boolean cloned) {
this.cloned = cloned;
}
public boolean isRequiredSet() {
return this.getChild(0).isRequired();
}
public void accept(INodeVisitor visitor) {
visitor.visitSetNode(this);
}
}
| dbunibas/Speedy | src/speedy/model/database/mainmemory/datasource/nodes/SetNode.java | Java | mit | 700 |
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Ng2CompleterModule } from "ng2-completer";
import { AgmCoreModule } from "angular2-google-maps/core";
import { AppComponent } from './app.component';
import { homeComponent } from './components/home/home.component';
import { weathersComponent } from './components/weathers/weathers.component';
import { itemsComponent } from './components/weathers/items.component';
import {WeatherService} from './services/weather.service';
@NgModule({
imports: [ BrowserModule, HttpModule, FormsModule, ReactiveFormsModule, Ng2CompleterModule, AgmCoreModule.forRoot({
apiKey: "AIzaSyDlvJY0jGnu7tHPmLuqVye7V-fu2_-DPCk",
libraries: ["places"]
})],
declarations: [ AppComponent, homeComponent, weathersComponent, itemsComponent ],
providers: [WeatherService],
bootstrap: [ AppComponent ]
})
export class AppModule { }
| pratik-trianz/hello_weather | src/app/app.module.ts | TypeScript | mit | 1,066 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.entity.living.complex;
import org.spongepowered.api.entity.Entity;
/**
* Represents a part of a {@link ComplexLiving}.
* <p>Parts are usually created to have multiple bounding boxes associated
* with a larger entity.</p>
*/
public interface ComplexLivingPart extends Entity {
/**
* Gets the associated parent of this part.
*
* @return The associated parent
*/
ComplexLiving getParent();
}
| Fozie/SpongeAPI | src/main/java/org/spongepowered/api/entity/living/complex/ComplexLivingPart.java | Java | mit | 1,706 |
package com.icharge.newCache;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadQueue {
public static final int PRIORITY_BACKGROUND = 1;
public static final int PRIORITY_LOW = 2;
public static final int PRIORITY_MEDIUM = 3;
public static final int PRIORITY_HIGH = 4;
public static final int PRIORITY_TOP = 5;
ThreadPoolExecutor threadPool;
public boolean commandSortByLatest = true;
private Vector<String> actionList = new Vector<String>();
private ThreadQueue(boolean commandSortByLatest) {
this.commandSortByLatest = commandSortByLatest;
threadPool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS,
new PriorityBlockingQueue<Runnable>(),
new ThreadPoolExecutor.DiscardOldestPolicy());
}
public static ThreadQueue newInstance(boolean commandSortByLatest) {
return new ThreadQueue(commandSortByLatest);
}
public void put(String action, int priority, MockRunnable runnable) {
if (!actionList.contains(action)) {
Command task = new Command(action, priority, runnable);
threadPool.execute(task);
actionList.add(action);
}
}
public void stopQueue() {
removeTasks();
threadPool.shutdown();
}
public void removeTasks() {
BlockingQueue<Runnable> commands = threadPool.getQueue();
synchronized (commands) {
Iterator<Runnable> keys = commands.iterator();
Runnable cmd;
ArrayList<Runnable> buffer = new ArrayList<Runnable>();
while (keys.hasNext()) {
cmd = keys.next();
buffer.add(cmd);
}
commands.removeAll(buffer);
}
}
class Command implements Runnable, Comparable<Command> {
String action;
int priority = PRIORITY_MEDIUM;
MockRunnable runnable;
long time = System.currentTimeMillis();
public Command(String action, int priority, MockRunnable runnable) {
this.action = action;
this.priority = priority;
this.runnable = runnable;
}
public void run() {
try {
runnable.run();
actionList.remove(action);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int compareTo(Command another) {
int result = another.priority - priority;
if (result == 0) {
result = (int) (commandSortByLatest ? (another.time - time)
: (time - another.time));
}
return result;
}
}
}
| jinsen47/iCharge | Client/app/src/main/java/com/icharge/newCache/ThreadQueue.java | Java | mit | 2,652 |
package com.youdevise.hsd;
public enum QueryType {
SELECT("select"),
INSERT("insert"),
UPDATE("update"),
DELETE("delete");
private String keyword;
private QueryType(String keyword) {
this.keyword = keyword;
}
public boolean matches(String sql) {
return sql.trim().toLowerCase().startsWith(keyword);
}
public static QueryType forSql(String sql) {
for (QueryType queryType : QueryType.values()) {
if (queryType.matches(sql)) {
return queryType;
}
}
throw new IllegalArgumentException("Query type not recognised for query: " + sql);
}
} | tim-group/High-Speed-Dirt | src/main/java/com/youdevise/hsd/QueryType.java | Java | mit | 673 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SumArrayElements")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("SumArrayElements")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d4101c9b-8202-469d-ad94-71de67629ad8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| dakh93/ProgrammingFundamentals | Arrays/SimpleArrayProcessing/SumArrayElements/Properties/AssemblyInfo.cs | C# | mit | 1,426 |
class AddOpenAllEntriesToUsers < ActiveRecord::Migration[5.2]
def up
add_column :users, :open_all_entries, :boolean, null: false, default: false
User.all.each do |u|
u.update_column :open_all_entries, false
end
end
def down
change_column :users, :open_all_entries, :boolean
end
end
| amatriain/feedbunch | FeedBunch-app/db/migrate/20131121205700_add_open_all_entries_to_users.rb | Ruby | mit | 314 |
using System;
using System.Collections.Generic;
namespace Puresharp
{
static public partial class Data
{
public class Store<T> : IStore<T>
where T : class
{
private Dictionary<string, T> m_Dictionary;
public Store()
{
this.m_Dictionary = new Dictionary<string, T>();
}
public T this[string name]
{
get
{
this.m_Dictionary.TryGetValue(name, out var _value);
return _value;
}
set { this.m_Dictionary[name] = value; }
}
public void Add(string name, T value)
{
this.m_Dictionary.Add(name, value);
}
public void Remove(string name)
{
this.m_Dictionary.Remove(name);
}
}
}
}
| Virtuoze/Puresharp | Puresharp/Puresharp/Data/Data.Store.cs | C# | mit | 933 |
// Copyright (c) 2014 The Drivercoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypto/hmac_sha256.h"
#include <string.h>
CHMAC_SHA256::CHMAC_SHA256(const unsigned char* key, size_t keylen)
{
unsigned char rkey[64];
if (keylen <= 64) {
memcpy(rkey, key, keylen);
memset(rkey + keylen, 0, 64 - keylen);
} else {
CSHA256().Write(key, keylen).Finalize(rkey);
memset(rkey + 32, 0, 32);
}
for (int n = 0; n < 64; n++)
rkey[n] ^= 0x5c;
outer.Write(rkey, 64);
for (int n = 0; n < 64; n++)
rkey[n] ^= 0x5c ^ 0x36;
inner.Write(rkey, 64);
}
void CHMAC_SHA256::Finalize(unsigned char hash[OUTPUT_SIZE])
{
unsigned char temp[32];
inner.Finalize(temp);
outer.Write(temp, 32).Finalize(hash);
}
| drivercoin/drivercoin | src/crypto/hmac_sha256.cpp | C++ | mit | 900 |
'use strict';
FbFriends.StatsView = Backbone.View.extend({
events: {
},
initialize: function(options) {
_.extend(this, options);
this.friends.on('reset', this.render, this);
},
render: function(event) {
this.showSexRepartition();
// this.showTopVille();
this.showRelationRepartition();
},
showSexRepartition: function() {
var repartition = this.friends.getRepartitionSexe();
this.$el.find(".pie-sexes").highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Sexes',
align: 'center',
verticalAlign: 'middle',
y: 50
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
dataLabels: {
enabled: true,
distance: -50,
style: {
fontWeight: 'bold',
color: 'white',
textShadow: '0px 1px 2px black'
}
},
startAngle: -90,
endAngle: 90,
center: ['50%', '75%']
}
},
series: [{
type: 'pie',
name: 'Sexes',
innerSize: '50%',
data: [
['Homme', repartition["male"] || 0.0],
['Femme', repartition["female"] || 0.0],
['Non défini', repartition[""] || 0.0]
]
}]
});
},
showRelationRepartition: function() {
var repartition = this.friends.getRelationShipPercent();
this.$el.find(".pie-relation").highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Relations'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
data: _.pairs(repartition)
}]
});
},
// not yet implemented
showTopVille: function() {
// var data = this.friends.getTopVillesData();
//
// this.$el.find('.pie-top-villes').highcharts({
// chart: {
// type: 'column'
// },
// title: {
// text: 'Top 10 des villes'
// },
// xAxis: {
// categories: []
// },
// yAxis: {
// min: 0
// },
// tooltip: {
// headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
// pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
// '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
// footerFormat: '</table>',
// shared: true,
// useHTML: true
// },
// plotOptions: {
// column: {
// pointPadding: 0.2,
// borderWidth: 0
// }
// },
// series: [{
// name: 'Tokyo',
// data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
//
// }, {
// name: 'New York',
// data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
//
// }, {
// name: 'London',
// data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
//
// }, {
// name: 'Berlin',
// data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
//
// }]
// });
}
});
| FXHibon/facebook-fun | frontend/app/friends/statistics/StatsView.js | JavaScript | mit | 4,807 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_02_01
module Models
#
# The routes table associated with the ExpressRouteCircuit.
#
class ExpressRouteCircuitRoutesTableSummary
include MsRestAzure
# @return [String] Neighbor
attr_accessor :neighbor
# @return [Integer] BGP version number spoken to the neighbor.
attr_accessor :v
# @return [Integer] Autonomous system number.
attr_accessor :as
# @return [String] The length of time that the BGP session has been in
# the Established state, or the current status if not in the Established
# state.
attr_accessor :up_down
# @return [String] Current state of the BGP session, and the number of
# prefixes that have been received from a neighbor or peer group.
attr_accessor :state_pfx_rcd
#
# Mapper for ExpressRouteCircuitRoutesTableSummary class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ExpressRouteCircuitRoutesTableSummary',
type: {
name: 'Composite',
class_name: 'ExpressRouteCircuitRoutesTableSummary',
model_properties: {
neighbor: {
client_side_validation: true,
required: false,
serialized_name: 'neighbor',
type: {
name: 'String'
}
},
v: {
client_side_validation: true,
required: false,
serialized_name: 'v',
type: {
name: 'Number'
}
},
as: {
client_side_validation: true,
required: false,
serialized_name: 'as',
type: {
name: 'Number'
}
},
up_down: {
client_side_validation: true,
required: false,
serialized_name: 'upDown',
type: {
name: 'String'
}
},
state_pfx_rcd: {
client_side_validation: true,
required: false,
serialized_name: 'statePfxRcd',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2018-02-01/generated/azure_mgmt_network/models/express_route_circuit_routes_table_summary.rb | Ruby | mit | 2,716 |
package com.weixin.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.util.Hash;
import com.weixin.vo.AccessToken;
import com.weixin.vo.NewsVo;
import com.weixin.vo.Oauth2Token;
import com.weixin.vo.UserInfo;
import com.weixin.vo.WxMediaVo;
import net.sf.json.JSONObject;
/**
* @author Jay
*/
@Component
public class WeixinUtil {
private static final Logger log = LoggerFactory.getLogger(WeixinUtil.class);
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static final String GET_USERS_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
private static final String GET_USER_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
private static final String GET_Oauth2AccessToken_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
private static final String GET_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN";
private static final String GET_JSPAI_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
private static final String MEDIA_UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
private static final String GET_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
private static final String MESSAGE_PREVIEW_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN";
/**
* 添加永久素材
*/
private static final String METERIAL_ADD_NEWS = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN";
/**
* 上传图片
*/
private static final String UPLOAD_IMG = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
/**
* 上传永久素材
*/
private static final String MATERIAL_ADD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN";
/**
* 获取素材总数
*/
private static final String GET_METERIALCOUNT_URL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN";
/**
* 获取素材列表
*/
private static final String GET_METERIALLIST_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
/**
* 群发
*/
private static final String SEND_ALL_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";
@Autowired
private RestTemplate restTemplate;
/**
* get请求
*
* @param url
* @return
*/
public static JSONObject doGetStr(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
public static String doGetStr2(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
String result = "";
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* post请求
*
* @param url
* @param outStr
* @return
*/
public static JSONObject doPostStr(String url, String outStr) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
try {
httpost.setEntity(new StringEntity(outStr, "UTF-8"));
HttpResponse response = httpClient.execute(httpost);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
jsonObject = JSONObject.fromObject(result);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* get access_token
*
* @return
*/
public static AccessToken getAccessToken() {
AccessToken token = new AccessToken();
String url = GET_ACCESS_TOKEN_URL.replace("APPID", TokenThread.APPID).replace("APPSECRET",
TokenThread.APPSECRET);
JSONObject jsonObject = doGetStr(url);
System.out.println(jsonObject.toString());
if (jsonObject != null) {
try {
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (Exception e) {
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
System.out.println(errorCode + " | " + errorMsg);
}
}
return token;
}
public static AccessToken getAccessToken(String appId, String appSecret) {
AccessToken token = new AccessToken();
String url = GET_ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
JSONObject jsonObject = doGetStr(url);
System.out.println(jsonObject.toString());
if (jsonObject != null) {
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
}
return token;
}
/*
* Get user list
*/
public static List<UserInfo> getUsers(String token) throws ParseException, IOException {
String url = GET_USERS_URL.replace("ACCESS_TOKEN", token);
JSONObject jsonObject = doGetStr(url);
Object obj = jsonObject.get("data");
Map<String, List<String>> map = (Map<String, List<String>>) obj;
List<String> list = map.get("openid");
List<UserInfo> userList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
UserInfo userInfo = WeixinUtil.getUser(token, list.get(i));
userList.add(userInfo);
}
return userList;
}
/*
* Get user info
*/
public static UserInfo getUser(String token, String openId) throws ParseException, IOException {
String url = GET_USER_URL.replace("ACCESS_TOKEN", token).replace("OPENID", openId);
JSONObject jsonObject = doGetStr(url);
System.out.println("hack");
System.out.println(jsonObject.toString());
UserInfo userInfo = new UserInfo();
if (null != jsonObject) {
try {
userInfo = new UserInfo();
// openId
userInfo.setOpenId(jsonObject.getString("openid"));
// 昵称
userInfo.setNickname(jsonObject.getString("nickname"));
// 性别
userInfo.setSex(jsonObject.getInt("sex"));
// 国家
userInfo.setCountry(jsonObject.getString("country"));
// 省
userInfo.setProvince(jsonObject.getString("province"));
// 城市
userInfo.setCity(jsonObject.getString("city"));
// 图片url
userInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
// privilege
// userInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"),
// List.class));
} catch (Exception e) {
userInfo = null;
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
System.out.println(errorCode + " | " + errorMsg);
}
}
return userInfo;
}
/**
* Get OAuth Access Token
*/
public static Oauth2Token getOauth2AccessToken(String appid, String appsecret, String code) {
String url = GET_Oauth2AccessToken_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE",
code);
JSONObject jsonObject = doGetStr(url);
Oauth2Token oauth2Token = new Oauth2Token();
if (jsonObject != null) {
try {
oauth2Token.setAccessToken(jsonObject.getString("access_token"));
oauth2Token.setExpiresIn(jsonObject.getInt("expires_in"));
oauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
oauth2Token.setOpenId(jsonObject.getString("openid"));
oauth2Token.setScope(jsonObject.getString("scope"));
} catch (Exception e) {
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
System.out.println(errorCode + " :" + errorMsg);
}
}
return oauth2Token;
}
/**
* get OAuth access token
*/
public static Oauth2Token getOauth2AccessToken(String code) {
return getOauth2AccessToken(TokenThread.APPID, TokenThread.APPSECRET, code);
}
/**
* Get material
*/
public void getMaterial(String token,String mediaId) {
String url = GET_MATERIAL_URL.replace("ACCESS_TOKEN", token);
// JSONObject jsonObject = doPostStr(url,
// "{'media_id': 'X-fJF8E32mDZQnq6XgyDBTI7iriawzkKNQv2QzrzrYg");
Map<String, Object> params = new HashMap<>();
params.put("media_id", mediaId);
String result = restTemplate.postForObject(url, params, String.class);
log.info(result.toString());
// System.out.println(jsonObject.toString());
}
/**
* Get JSPAI Token
*/
public static String getJsapiToken(String token) {
String url = GET_JSPAI_URL.replace("ACCESS_TOKEN", token);
JSONObject jsonObject = doGetStr(url);
System.out.println(jsonObject.toString());
return jsonObject.getString("ticket");
}
/**
* media upload
*
* @param token
* @param file
* @param type
* @return
*/
public WxMediaVo mediaUpload(String token, File file, String type) {
String url = MEDIA_UPLOAD_URL.replace("ACCESS_TOKEN", token).replace("TYPE", type);
// JSONObject jsonObject = doPostStr(url, "{'media': file}");
// System.out.println(jsonObject.toString());
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("jarFile", resource);
// WxMediaVo vo = restTemplate.postForObject(url, param,
// WxMediaVo.class);
String str = restTemplate.postForObject(url, param, String.class);
WxMediaVo vo = null;
try {
vo = new ObjectMapper().readValue(str, WxMediaVo.class);
} catch (Exception e) {
e.printStackTrace();
}
log.info(vo.toString());
return vo;
}
/**
* get media
* @param token
* @param mediaId
*/
public void getMedia(String token,String mediaId){
String url = GET_MEDIA_URL.replace("ACCESS_TOKEN", token).replace("MEDIA_ID", mediaId);
HttpHeaders result = restTemplate.headForHeaders(url);
log.info(result.toString());
}
/**
* 添加图文
* @param token
* @param newsVo
*/
public void meterialAddNews(String token,NewsVo newsVo){
String url = METERIAL_ADD_NEWS.replace("ACCESS_TOKEN", token);
String result = restTemplate.postForObject(url, newsVo, String.class);
log.info(result.toString());
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
// X-fJF8E32mDZQnq6XgyDBTI7iriawzkKNQv2QzrzrYg
// 这里的media_id 保存到本地数据库
}
/**
* 获取素材总数
* @param token
* @param newsVo
*/
public void getMeteialCount(String token){
String url = GET_METERIALCOUNT_URL.replace("ACCESS_TOKEN", token);
String result = restTemplate.getForObject(url, String.class);
log.info(result.toString());
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* 获取素材总数
* @param token
* @param newsVo
*/
public String getMeteialList(String token){
String url = GET_METERIALLIST_URL.replace("ACCESS_TOKEN", token);
Map<String, Object> param = new HashMap<>();
param.put("type", "image");
param.put("offset", 0);
param.put("count", 10);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result.toString());
return result;
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* 群发
* user not agree mass-send protocol 没有权限
* @param token
*/
public void sendALL(String token){
String url = SEND_ALL_URL.replace("ACCESS_TOKEN", token);
Map<String, Object> param = new HashMap<>();
Map<String, Object> mpnews = new HashMap<>();
mpnews.put("media_id", "X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"); //test
param.put("mpnews", mpnews);
param.put("msgtype", "mpnews");
Map<String, Object> filter = new HashMap<>();
filter.put("is_to_all", true);
param.put("filter", filter);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result.toString());
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* 预览
* user not agree mass-send protocol 没有权限
* @param token
*/
public String messagePreview(String token,String touser){
String url = MESSAGE_PREVIEW_URL.replace("ACCESS_TOKEN", token);
Map<String, Object> param = new HashMap<>();
Map<String, Object> mpnews = new HashMap<>();
mpnews.put("media_id", "X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"); //test
param.put("mpnews", mpnews);
param.put("msgtype", "mpnews");
param.put("touser", touser);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result.toString());
return result;
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* Upload image
* @param token
* @param file
*/
public void uploadImg(String token,File file){
String url = UPLOAD_IMG.replace("ACCESS_TOKEN", token);
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("jarFile", resource);
String imgUrl = restTemplate.postForObject(url, param, String.class);
log.info(imgUrl);
// http://mmbiz.qpic.cn/mmbiz/NlnaapibtH6EVOVBmPlf1TQI6Mwt6DLO79rhQNHZYE4Q12NN88coMAWcMAibeRaeMqRnQDAR90ibJk4sNqNm2EWkQ/0
// 保存到本地数据库
}
/**
* access_token 是 调用接口凭证
* type 是 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
* media 是 form-data中媒体文件标识,有filename、filelength、content-type等信息
*{"media_id":"X-fJF8E32mDZQnq6XgyDBRGqKvuTPm9YJqFPk7dqcUY","url":"https:\/\/mmbiz.qlogo.cn\/mmbiz\/NlnaapibtH6EVOVBmPlf1TQI6Mwt6DLO79rhQNHZYE4Q12NN88coMAWcMAibeRaeMqRnQDAR90ibJk4sNqNm2EWkQ\/0?wx_fmt=jpeg"}
* @param token
* @param file
* @param type
*/
public void materialAdd(String token,File file,String type){
String url = MATERIAL_ADD_URL.replace("ACCESS_TOKEN", token);
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("media", resource);
param.add("type", type);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result);
JSONObject obj = JSONObject.fromObject(result);
String mediaId = obj.getString("media_id");
log.info(mediaId);
if(type.equals("image")){
String imgUrl = obj.getString("url");
log.info(imgUrl);
}
// 本地是否需要保存
}
}
| ScorpionJay/wechat | src/main/java/com/weixin/util/WeixinUtil.java | Java | mit | 17,181 |
// Copyright (c) 2013-2016 Jae-jun Kang
// See the file LICENSE for details.
using System;
#if XML_CONFIG
using System.Configuration;
#endif
namespace x2
{
/// <summary>
/// Provides the global configuration properties.
/// </summary>
public static class Config
{
/// <summary>
/// Gets or sets the minimum log level.
/// </summary>
public static LogLevel LogLevel { get; set;}
/// <summary>
/// Gets or sets the time interval, in seconds, of built-in heartbeat
/// events.
/// </summary>
public static int HeartbeatInterval { get; set; }
public static class Flow
{
public static class Logging
{
public static class SlowHandler
{
static SlowHandler()
{
// Default values
LogLevel = LogLevel.Warning;
Threshold = 100; // in milliseconds
}
public static LogLevel LogLevel { get; set; }
public static int Threshold { get; set; }
}
public static class SlowScope
{
static SlowScope()
{
// Default values
LogLevel = LogLevel.Warning;
Threshold = 200; // in milliseconds
}
public static LogLevel LogLevel { get; set; }
public static int Threshold { get; set; }
}
public static class LongQueue
{
static LongQueue()
{
// Default values
LogLevel = LogLevel.Error;
Threshold = 1000;
}
public static LogLevel LogLevel { get; set; }
public static int Threshold { get; set; }
}
}
}
public static int MaxLinkHandles { get; set; }
public static class Buffer
{
public static class SizeExponent
{
static SizeExponent()
{
// Default values
// SizeExponent.Chunk >= SizeExponent.Segment
Chunk = 24; // 16MB
Segment = 12; // 4KB
}
/// <summary>
/// Gets or sets the buffer chunk size exponent n in 2^n.
/// </summary>
public static int Chunk { get; set; }
/// <summary>
/// Gets or sets the buffer segment size exponent n in 2^n.
/// </summary>
public static int Segment { get; set; }
}
/// <summary>
/// Gets the buffer chunk size in bytes.
/// </summary>
public static int ChunkSize
{
get { return (1 << SizeExponent.Chunk); }
}
/// <summary>
/// Gets the buffer segment size in bytes.
/// </summary>
public static int SegmentSize
{
get { return (1 << SizeExponent.Segment); }
}
public static class RoomFactor
{
static RoomFactor()
{
// Default values
MinLevel = 0; // x1
MaxLevel = 3; // x8
}
public static int MinLevel { get; set; }
public static int MaxLevel { get; set; }
}
}
public static class Coroutine
{
static Coroutine()
{
// Default values
MaxWaitHandles = 32768;
DefaultTimeout = 30.0; // in seconds
}
/// <summary>
/// Gets or sets the maximum number of wait handles.
/// </summary>
public static int MaxWaitHandles { get; set; }
/// <summary>
/// Gets or sets the default wait timeout in seconds.
/// </summary>
public static double DefaultTimeout { get; set; }
}
static Config()
{
// Default values
LogLevel = LogLevel.Info;
HeartbeatInterval = 5; // in seconds
MaxLinkHandles = 65536;
}
#if XML_CONFIG
/// <summary>
/// Loads the configuration properties from the application
/// configuration.
/// </summary>
public static void Load()
{
ConfigSection section = (ConfigSection)
ConfigurationManager.GetSection("x2clr");
LogLevel = section.Log.Level;
HeartbeatInterval = section.Heartbeat.Interval;
FlowLoggingElement logging = section.Flow.Logging;
Flow.Logging.SlowHandler.LogLevel = logging.SlowHandler.LogLevel;
Flow.Logging.SlowHandler.Threshold = logging.SlowHandler.Threshold;
Flow.Logging.LongQueue.LogLevel = logging.LongQueue.LogLevel;
Flow.Logging.LongQueue.Threshold = logging.LongQueue.Threshold;
MaxLinkHandles = section.Link.MaxHandles;
BufferElement buffer = section.Buffer;
Buffer.SizeExponent.Chunk = buffer.SizeExponent.Chunk;
Buffer.SizeExponent.Segment = buffer.SizeExponent.Segment;
Buffer.RoomFactor.MinLevel = buffer.RoomFactor.MinLevel;
Buffer.RoomFactor.MaxLevel = buffer.RoomFactor.MaxLevel;
Coroutine.MaxWaitHandles = section.Coroutine.MaxWaitHandles;
Coroutine.DefaultTimeout = section.Coroutine.DefaultTimeout;
}
#endif
}
}
| jaykang920/x2clr | x2/Config.cs | C# | mit | 5,917 |
'use strict';
const Perceptron = require('./perceptron');
const PerceptronTrainer = require('./perceptron.trainer');
const trainer = new PerceptronTrainer();
trainer.setLearningRate(2.0);
// and-perceptron: weights: [1,4], bias: -5
const perceptron = new Perceptron();
perceptron.setWeights([-20,-30]);
perceptron.setBias(1);
trainer.train(perceptron, [
{ inputs: [0 ,0], ideal: 0 },
{ inputs: [1 ,0], ideal: 0 },
{ inputs: [0 ,1], ideal: 0 },
{ inputs: [1 ,1], ideal: 1 },
]);
console.log({
perceptron: perceptron.getConnections(),
inputs: [1, 0],
output: perceptron.output()
});
// or-perceptron: weights: [1,2], bias: -1
perceptron.setWeights([-20,-30]);
perceptron.setBias(1);
trainer.train(perceptron, [
{ inputs: [0 ,0], ideal: 0 },
{ inputs: [1 ,0], ideal: 1 },
{ inputs: [0 ,1], ideal: 1 },
{ inputs: [1 ,1], ideal: 1 },
]);
console.log({
perceptron: perceptron.getConnections(),
inputs: [1, 0],
output: perceptron.output()
}); | pascalvree/example-perceptron-implementation | src/example.js | JavaScript | mit | 998 |
require 'rails_helper'
RSpec.describe ComponentsController, type: :controller do
describe "GET a_z" do
before(:each) do
get :a_z
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/a-z")
end
end
describe "GET alert" do
before(:each) do
get :alert
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/alert")
end
end
describe "GET badges" do
before(:each) do
get :badges
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/badges")
end
end
describe "GET banners" do
before(:each) do
get :banners
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/banners")
end
end
describe "GET breadcrumb" do
before(:each) do
get :breadcrumb
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/breadcrumb")
end
end
describe "GET footer" do
before(:each) do
get :footer
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/footer")
end
end
describe "GET header" do
before(:each) do
get :header
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/header")
end
end
describe "GET pagination" do
before(:each) do
get :pagination
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/pagination")
end
end
end
| naseberry/styleguide | spec/controllers/components_controller_spec.rb | Ruby | mit | 2,542 |
/*
*
* DynamicObject
* ledger-core
*
* Created by Pierre Pollastri on 08/03/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "DynamicObject.hpp"
#include <cereal/cereal.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/types/set.hpp>
#include <cereal/types/memory.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
namespace ledger {
namespace core {
optional<std::string> DynamicObject::getString(const std::string &key) {
return get<std::string>(key);
}
optional<int32_t> DynamicObject::getInt(const std::string &key) {
return get<int32_t>(key);
}
optional<int64_t> DynamicObject::getLong(const std::string &key) {
return get<int64_t>(key);
}
optional<double> DynamicObject::getDouble(const std::string &key) {
return get<double>(key);
}
optional<bool> DynamicObject::getBoolean(const std::string &key) {
return get<bool>(key);
}
optional<std::vector<uint8_t>> DynamicObject::getData(const std::string &key) {
return get<std::vector<uint8_t>>(key);
}
std::shared_ptr<api::DynamicObject> DynamicObject::getObject(const std::string &key) {
return get<std::shared_ptr<DynamicObject>>(key).value_or(nullptr);
}
std::shared_ptr<api::DynamicArray> DynamicObject::getArray(const std::string &key) {
return get<std::shared_ptr<DynamicArray>>(key).value_or(nullptr);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putString(const std::string &key, const std::string &value) {
return put(key, value);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putInt(const std::string &key, int32_t value) {
return put(key, value);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putLong(const std::string &key, int64_t value) {
return put(key, value);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putDouble(const std::string &key, double value) {
return put(key, value);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putData(const std::string &key, const std::vector<uint8_t> &value) {
return put(key, value);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putBoolean(const std::string &key, bool value) {
return put(key, value);
}
std::shared_ptr<api::DynamicObject> DynamicObject::putObject(const std::string &key, const std::shared_ptr<api::DynamicObject> &value) {
return put(key, std::static_pointer_cast<DynamicObject>(value));
}
std::shared_ptr<api::DynamicObject>
DynamicObject::putArray(const std::string &key, const std::shared_ptr<api::DynamicArray> &value) {
return put(key, std::static_pointer_cast<DynamicArray>(value));
}
bool DynamicObject::contains(const std::string &key) {
return _values.contains(key);
}
bool DynamicObject::remove(const std::string &key) {
return _values.remove(key);
}
std::vector<std::string> DynamicObject::getKeys() {
return _values.getKeys().getContainer();
}
optional<api::DynamicType> DynamicObject::getType(const std::string &key) {
auto v = _values.lift(key);
if (_values.empty() || !v.hasValue())
return optional<api::DynamicType>();
return optional<api::DynamicType>(v.getValue().getType());
}
std::string DynamicObject::dump() {
std::stringstream ss;
dump(ss, 0);
return ss.str();
}
std::vector<uint8_t> DynamicObject::serialize() {
std::stringstream is;
::cereal::PortableBinaryOutputArchive archive(is);
archive(shared_from_this());
auto savedState = is.str();
return std::vector<uint8_t>((const uint8_t *)savedState.data(),(const uint8_t *)savedState.data() + savedState.length());
}
std::shared_ptr<api::DynamicObject> api::DynamicObject::load(const std::vector<uint8_t> &serialized) {
std::shared_ptr<ledger::core::DynamicObject> object;
boost::iostreams::array_source my_vec_source(reinterpret_cast<const char*>(&serialized[0]), serialized.size());
boost::iostreams::stream<boost::iostreams::array_source> is(my_vec_source);
::cereal::PortableBinaryInputArchive archive(is);
archive(object);
return object;
}
std::shared_ptr<api::DynamicObject> api::DynamicObject::newInstance() {
return std::make_shared<ledger::core::DynamicObject>();
}
std::ostream &DynamicObject::dump(std::ostream &ss, int depth) const {
for (auto& item : _values.getContainer()) {
ss << (" "_S * depth).str() << '"' << item.first << "\" -> ";
item.second.dump(ss, depth);
ss << std::endl;
}
return ss;
}
int64_t DynamicObject::size() {
return _values.getContainer().size();
}
bool DynamicObject::isReadOnly() {
return _readOnly;
}
void DynamicObject::setReadOnly(bool enable) {
_readOnly = enable;
for (auto& v : _values.getContainer()) {
// try to set the read-only attribute on the contained value as an array, and if it
// fails, try to do the same as if it were an object
auto array = v.second.get<std::shared_ptr<DynamicArray>>();
if (array) {
(*array)->setReadOnly(enable);
} else {
auto object = v.second.get<std::shared_ptr<DynamicObject>>();
if (object) {
(*object)->setReadOnly(enable);
}
}
}
}
std::shared_ptr<api::DynamicObject> DynamicObject::updateWithConfiguration(const std::shared_ptr<DynamicObject> &configuration) {
for (auto &key : configuration->getKeys()) {
auto type = configuration->getType(key).value_or(api::DynamicType::UNDEFINED);
switch (type) {
case api::DynamicType::STRING:
put(key, configuration->get<std::string>(key).value());
break;
case api::DynamicType::DATA:
put(key, configuration->get<std::vector<uint8_t>>(key).value());
break;
case api::DynamicType::BOOLEAN:
put(key, configuration->get<bool>(key).value());
break;
case api::DynamicType::INT32:
put(key, configuration->get<int32_t>(key).value());
break;
case api::DynamicType::INT64:
put(key, configuration->get<int64_t>(key).value());
break;
case api::DynamicType::DOUBLE:
put(key, configuration->get<double>(key).value());
break;
case api::DynamicType::ARRAY:
put(key, configuration->get<std::shared_ptr<DynamicArray>>(key).value());
break;
case api::DynamicType::OBJECT:
put(key, configuration->get<std::shared_ptr<DynamicObject>>(key).value());
break;
case api::DynamicType::UNDEFINED:
break;
}
}
return shared_from_this();
}
}
}
| LedgerHQ/lib-ledger-core | core/src/collections/DynamicObject.cpp | C++ | mit | 9,037 |
import { getElementIfNotEmpty } from './getElementIfNotEmpty.js';
export function getStackDataIfNotEmpty(viewportIndex) {
const element = getElementIfNotEmpty(viewportIndex);
if (!element) {
return;
}
const stackToolData = cornerstoneTools.getToolState(element, 'stack');
if (!stackToolData ||
!stackToolData.data ||
!stackToolData.data.length) {
return;
}
const stack = stackToolData.data[0];
if (!stack) {
return;
}
return stack;
}
| NucleusIo/HealthGenesis | viewerApp/Packages/ohif-viewerbase/client/lib/getStackDataIfNotEmpty.js | JavaScript | mit | 518 |
class AddTeamIdToUsersAndBuckets < ActiveRecord::Migration
def change
add_column :users, :team_id, :integer
add_column :buckets, :team_id, :integer
end
end
| jonmagic/i-got-issues | db/migrate/20140608063204_add_team_id_to_users_and_buckets.rb | Ruby | mit | 170 |
<?php
/**
* A simple component which returns a list of controllers plus the corresponding action names.
*
* See also: http://cakebaker.42dh.com/2006/07/21/how-to-list-all-controllers
*
* This code is in the public domain, use it in any way you like ;-)
*/
class ControllerListComponent extends Object {
public function get() {
$controllerClasses = App::objects('controller');
foreach($controllerClasses as $controller) {
if ($controller != 'App') {
App::import('Controller', $controller);
$className = $controller . 'Controller';
$actions = get_class_methods($className);
foreach($actions as $k => $v) {
if ($v{0} == '_') {
unset($actions[$k]);
}
}
$parentActions = get_class_methods('AppController');
$controllers[$controller] = array_diff($actions, $parentActions);
}
}
return $controllers;
}
}
| ambagasdowa/kml | app/controllers/components/controller_list.php | PHP | mit | 1,033 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Wpf.Controls.Demo
{
public class DelegateCommand : ICommand
{
private Action<object> _executeMethod;
private Func<object, bool> _canExecuteMethod;
public DelegateCommand(Action<object> executeMethod, Func<object, bool> canExecuteMethod)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
if (_canExecuteMethod == null)
return true;
return _canExecuteMethod(parameter);
}
public void Execute(object parameter)
{
if (_executeMethod != null)
_executeMethod(parameter);
}
public void RaiseCanExecute()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, null);
}
}
}
| fengdingfeilong/FssControls | Wpf.Controls.Demo/DelegateCommand.cs | C# | mit | 1,265 |
// Markup.cpp: implementation of the CMarkup class.
//
// Markup Release 11.2
// Copyright (C) 2009 First Objective Software, Inc. All rights reserved
// Go to www.firstobject.com for the latest CMarkup and EDOM documentation
// Use in commercial applications requires written permission
// This software is provided "as is", with no warranty.
//
#include <stdio.h>
#include "Markup.h"
#if defined(MCD_STRERROR) // C error routine
#include <errno.h>
#endif // C error routine
#if defined (MARKUP_ICONV)
#include <iconv.h>
#endif
#if defined(MARKUP_STL) && ( defined(MARKUP_WINCONV) || (! defined(MCD_STRERROR)))
#include <windows.h> // for MultiByteToWideChar, WideCharToMultiByte, FormatMessage
#endif // need windows.h when STL and (not setlocale or not strerror), MFC afx.h includes it already
#if defined(MARKUP_MBCS) // MBCS/double byte
#pragma message( "Note: MBCS build (not UTF-8)" )
// For UTF-8, remove MBCS from project settings C/C++ preprocessor definitions
#if defined (MARKUP_WINCONV)
#include <mbstring.h> // for VC++ _mbclen
#endif // WINCONV
#endif // MBCS/double byte
#if defined(_DEBUG) && _MSC_VER > 1000 // VC++ DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#if defined(DEBUG_NEW)
#define new DEBUG_NEW
#endif // DEBUG_NEW
#endif // VC++ DEBUG
// Customization
#define x_EOL MCD_T("\r\n") // can be \r\n or \n or empty
#define x_EOLLEN (sizeof(x_EOL)/sizeof(MCD_CHAR)-1) // string length of x_EOL
#define x_ATTRIBQUOTE '\"' // can be double or single quote
// Disable "while ( 1 )" warning in VC++ 2002
#if _MSC_VER >= 1300 // VC++ 2002 (7.0)
#pragma warning(disable:4127)
#endif // VC++ 2002 (7.0)
//////////////////////////////////////////////////////////////////////
// Internal static utility functions
//
void x_StrInsertReplace( MCD_STR& str, int nLeft, int nReplace, const MCD_STR& strInsert )
{
// Insert strInsert into str at nLeft replacing nReplace chars
// Reduce reallocs on growing string by reserving string space
// If realloc needed, allow for 1.5 times the new length
//
int nStrLength = MCD_STRLENGTH(str);
int nInsLength = MCD_STRLENGTH(strInsert);
int nNewLength = nInsLength + nStrLength - nReplace;
int nAllocLen = MCD_STRCAPACITY(str);
#if defined(MCD_STRINSERTREPLACE) // STL, replace method
if ( nNewLength > nAllocLen )
MCD_BLDRESERVE( str, (nNewLength + nNewLength/2 + 128) );
MCD_STRINSERTREPLACE( str, nLeft, nReplace, strInsert );
#else // MFC, no replace method
int nBufferLen = nNewLength;
if ( nNewLength > nAllocLen )
nBufferLen += nBufferLen/2 + 128;
MCD_CHAR* pDoc = MCD_GETBUFFER( str, nBufferLen );
if ( nInsLength != nReplace && nLeft+nReplace < nStrLength )
memmove( &pDoc[nLeft+nInsLength], &pDoc[nLeft+nReplace], (nStrLength-nLeft-nReplace)*sizeof(MCD_CHAR) );
if ( nInsLength )
memcpy( &pDoc[nLeft], strInsert, nInsLength*sizeof(MCD_CHAR) );
MCD_RELEASEBUFFER( str, pDoc, nNewLength );
#endif // MFC, no replace method
}
int x_Hash( MCD_PCSZ p, int nSize )
{
unsigned int n=0;
while (*p)
n += (unsigned int)(*p++);
return n % nSize;
}
MCD_STR x_IntToStr( int n )
{
MCD_CHAR sz[25];
MCD_SPRINTF(MCD_SSZ(sz),MCD_T("%d"),n);
MCD_STR s=sz;
return s;
}
enum MarkupResultCode
{
MRC_COUNT = 1,
MRC_TYPE = 2,
MRC_NUMBER = 4,
MRC_ENCODING = 8,
MRC_LENGTH = 16,
MRC_MODIFY = 32,
MRC_MSG = 64
};
void x_AddResult( MCD_STR& strResult, MCD_CSTR pszID, MCD_CSTR pszVal = NULL, int nResultCode = 0, int n = -1, int n2 = -1 )
{
// Call this to append an error result to strResult, discard if accumulating too large
if ( MCD_STRLENGTH(strResult) < 1000 )
{
// Use a temporary CMarkup object but keep strResult in a string to minimize memory footprint
CMarkup mResult( strResult );
if ( nResultCode & MRC_MODIFY )
mResult.FindElem( pszID );
else
mResult.AddElem( pszID, MCD_T(""), CMarkup::MNF_WITHNOLINES );
if ( pszVal.pcsz )
{
if ( nResultCode & MRC_TYPE )
mResult.SetAttrib( MCD_T("type"), pszVal );
else if ( nResultCode & MRC_ENCODING )
mResult.SetAttrib( MCD_T("encoding"), pszVal );
else if ( nResultCode & MRC_MSG )
mResult.SetAttrib( MCD_T("msg"), pszVal );
else
mResult.SetAttrib( MCD_T("tagname"), pszVal );
}
if ( nResultCode & MRC_NUMBER )
mResult.SetAttrib( MCD_T("n"), n );
else if ( nResultCode & MRC_COUNT )
mResult.SetAttrib( MCD_T("count"), n );
else if ( nResultCode & MRC_LENGTH )
mResult.SetAttrib( MCD_T("length"), n );
else if ( n != -1 )
mResult.SetAttrib( MCD_T("offset"), n );
if ( n2 != -1 )
mResult.SetAttrib( MCD_T("offset2"), n2 );
strResult = mResult.GetDoc();
}
}
//////////////////////////////////////////////////////////////////////
// Encoding conversion struct and methods
//
struct TextEncoding
{
TextEncoding( MCD_CSTR pszFromEncoding, const void* pFromBuffer, int nFromBufferLen )
{
m_strFromEncoding = pszFromEncoding;
m_pFrom = pFromBuffer;
m_nFromLen = nFromBufferLen;
m_nFailedChars = 0;
m_nToCount = 0;
};
int PerformConversion( void* pTo, MCD_CSTR pszToEncoding = NULL );
bool FindRaggedEnd( int& nTruncBeforeBytes );
#if defined(MARKUP_ICONV)
static const char* IConvName( char* szEncoding, MCD_CSTR pszEncoding );
int IConv( void* pTo, int nToCharSize, int nFromCharSize );
#endif // ICONV
#if ! defined(MARKUP_WCHAR)
static bool CanConvert( MCD_CSTR pszToEncoding, MCD_CSTR pszFromEncoding );
#endif // WCHAR
MCD_STR m_strToEncoding;
MCD_STR m_strFromEncoding;
const void* m_pFrom;
int m_nFromLen;
int m_nToCount;
int m_nFailedChars;
};
// Encoding names
// This is a precompiled ASCII hash table for speed and minimum memory requirement
// Each entry consists of a 2 digit name length, 5 digit code page, and the encoding name
// Each table slot can have multiple entries, table size 155 was chosen for even distribution
//
MCD_PCSZ EncodingNameTable[155] =
{
MCD_T("0800949ksc_5601"),MCD_T("1920932cseucpkdfmtjapanese0920003x-cp20003"),
MCD_T("1250221_iso-2022-jp0228591l10920004x-cp20004"),
MCD_T("0228592l20920005x-cp20005"),
MCD_T("0228593l30600850ibm8501000858ccsid00858"),
MCD_T("0228594l40600437ibm4370701201ucs-2be0600860ibm860"),
MCD_T("0600852ibm8520501250ms-ee0600861ibm8610228599l50751932cp51932"),
MCD_T("0600862ibm8620620127ibm3670700858cp008581010021x-mac-thai0920261x-cp20261"),
MCD_T("0600737ibm7370500869cp-gr1057003x-iscii-be0600863ibm863"),
MCD_T("0750221ms502210628591ibm8190600855ibm8550600864ibm864"),
MCD_T("0600775ibm7751057002x-iscii-de0300949uhc0228605l91028591iso-ir-1000600865ibm865"),
MCD_T("1028594iso-ir-1101028592iso-ir-1010600866ibm8660500861cp-is0600857ibm857"),
MCD_T("0950227x-cp50227"),
MCD_T("0320866koi1628598csisolatinhebrew1057008x-iscii-ka"),
MCD_T("1000950big5-hkscs1220106x-ia5-german0600869ibm869"),
MCD_T("1057009x-iscii-ma0701200ucs-2le0712001utf32be0920269x-cp20269"),
MCD_T("0800708asmo-7080500437cspc81765000unicode-1-1-utf-70612000utf-320920936x-cp20936"),
MCD_T("1200775ebcdic-cp-be0628598hebrew0701201utf16be1765001unicode-1-1-utf-81765001unicode-2-0-utf-80551932x-euc"),
MCD_T("1028595iso-ir-1441028597iso-ir-1260728605latin-90601200utf-161057011x-iscii-pa"),
MCD_T("1028596iso-ir-1271028593iso-ir-1090751932ms51932"),
MCD_T("0801253ms-greek0600949korean1050225iso2022-kr1128605iso_8859-150920949x-cp20949"),
MCD_T("1200775ebcdic-cp-ch1028598iso-ir-1381057006x-iscii-as1450221iso-2022-jp-ms"),
MCD_T("1057004x-iscii-ta1028599iso-ir-148"),
MCD_T("1000949iso-ir-1490820127us-ascii"),MCD_T(""),
MCD_T("1000936gb_2312-801900850cspc850multilingual0712000utf32le"),
MCD_T("1057005x-iscii-te1300949csksc560119871965000x-unicode-2-0-utf-7"),
MCD_T("0701200utf16le1965001x-unicode-2-0-utf-80928591iso8859-1"),
MCD_T("0928592iso8859-21420002x_chinese-eten0520866koi8r1000932x-ms-cp932"),
MCD_T("1320000x-chinese-cns1138598iso8859-8-i1057010x-iscii-gu0928593iso8859-3"),
MCD_T("0928594iso8859-4"),MCD_T("0928595iso8859-51150221csiso2022jp"),
MCD_T("0928596iso8859-60900154csptcp154"),
MCD_T("0928597iso8859-70900932shift_jis1400154cyrillic-asian"),
MCD_T("0928598iso8859-81057007x-iscii-or1150225csiso2022kr"),
MCD_T("0721866koi8-ru0928599iso8859-9"),MCD_T("0910000macintosh"),MCD_T(""),
MCD_T(""),MCD_T(""),
MCD_T("1210004x-mac-arabic0800936gb2312800628598visual1520108x-ia5-norwegian"),
MCD_T(""),MCD_T("0829001x-europa"),MCD_T(""),MCD_T("1510079x-mac-icelandic"),
MCD_T("0800932sjis-win1128591csisolatin1"),MCD_T("1128592csisolatin2"),
MCD_T("1400949ks_c_5601-19871128593csisolatin3"),MCD_T("1128594csisolatin4"),
MCD_T("0400950big51128595csisolatin51400949ks_c_5601-1989"),
MCD_T("0500775cp5001565000csunicode11utf7"),MCD_T("0501361johab"),
MCD_T("1100932windows-9321100437codepage437"),
MCD_T("1800862cspc862latinhebrew1310081x-mac-turkish"),MCD_T(""),
MCD_T("0701256ms-arab0800775csibm5000500154cp154"),
MCD_T("1100936windows-9360520127ascii"),
MCD_T("1528597csisolatingreek1100874windows-874"),MCD_T("0500850cp850"),
MCD_T("0700720dos-7200500950cp9500500932cp9320500437cp4370500860cp8601650222_iso-2022-jp$sio"),
MCD_T("0500852cp8520500861cp8610700949ksc56010812001utf-32be"),
MCD_T("0528597greek0500862cp8620520127cp3670500853cp853"),
MCD_T("0500737cp7371150220iso-2022-jp0801201utf-16be0500863cp863"),
MCD_T("0500936cp9360528591cp8194520932extended_unix_code_packed_format_for_japanese0500855cp8550500864cp864"),
MCD_T("0500775cp7750500874cp8740800860csibm8600500865cp865"),
MCD_T("0500866cp8660800861csibm8611150225iso-2022-kr0500857cp8571101201unicodefffe"),
MCD_T("0700862dos-8620701255ms-hebr0500858cp858"),
MCD_T("1210005x-mac-hebrew0500949cp9490800863csibm863"),
MCD_T("0500869cp8691600437cspc8codepage4370700874tis-6200800855csibm8550800864csibm864"),
MCD_T("0800950x-x-big50420866koi80800932ms_kanji0700874dos-8740800865csibm865"),
MCD_T("0800866csibm8661210003x-mac-korean0800857csibm8570812000utf-32le"),
MCD_T(""),MCD_T("0500932ms9320801200utf-16le1028591iso-8859-10500154pt154"),
MCD_T("1028592iso-8859-20620866koi8-r0800869csibm869"),
MCD_T("1500936csiso58gb2312800828597elot_9281238598iso-8859-8-i1028593iso-8859-30820127iso-ir-6"),
MCD_T("1028594iso-8859-4"),
MCD_T("0800852cspcp8520500936ms9361028595iso-8859-50621866koi8-u0701252ms-ansi"),
MCD_T("1028596iso-8859-60220127us2400858pc-multilingual-850+euro"),
MCD_T("1028597iso-8859-71028603iso8859-13"),
MCD_T("1320000x-chinese_cns1028598iso-8859-8"),
MCD_T("1828595csisolatincyrillic1028605iso8859-151028599iso-8859-9"),
MCD_T("0465001utf8"),MCD_T("1510017x-mac-ukrainian"),MCD_T(""),
MCD_T("0828595cyrillic"),MCD_T("0900936gb2312-80"),MCD_T(""),
MCD_T("0720866cskoi8r1528591iso_8859-1:1987"),MCD_T("1528592iso_8859-2:1987"),
MCD_T("1354936iso-4873:1986"),MCD_T("0700932sjis-ms1528593iso_8859-3:1988"),
MCD_T("1528594iso_8859-4:19880600936gb23120701251ms-cyrl"),
MCD_T("1528596iso_8859-6:19871528595iso_8859-5:1988"),
MCD_T("1528597iso_8859-7:1987"),
MCD_T("1201250windows-12501300932shifft_jis-ms"),
MCD_T("0810029x-mac-ce1201251windows-12511528598iso_8859-8:19880900949ks_c_56011110000csmacintosh"),
MCD_T("0601200cp12001201252windows-1252"),
MCD_T("1052936hz-gb-23121201253windows-12531400949ks_c_5601_19871528599iso_8859-9:19890601201cp1201"),
MCD_T("1201254windows-1254"),MCD_T("1000936csgb2312801201255windows-1255"),
MCD_T("1201256windows-12561100932windows-31j"),
MCD_T("1201257windows-12570601250cp12500601133cp1133"),
MCD_T("0601251cp12511201258windows-12580601125cp1125"),
MCD_T("0701254ms-turk0601252cp1252"),MCD_T("0601253cp12530601361cp1361"),
MCD_T("0800949ks-c56010601254cp1254"),MCD_T("0651936euc-cn0601255cp1255"),
MCD_T("0601256cp1256"),MCD_T("0601257cp12570600950csbig50800858ibm00858"),
MCD_T("0601258cp1258"),MCD_T("0520105x-ia5"),
MCD_T("0801250x-cp12501110006x-mac-greek0738598logical"),
MCD_T("0801251x-cp1251"),MCD_T(""),
MCD_T("1410001x-mac-japanese1200932cswindows31j"),
MCD_T("0700936chinese0720127csascii0620932euc-jp"),
MCD_T("0851936x-euc-cn0501200ucs-2"),MCD_T("0628597greek8"),
MCD_T("0651949euc-kr"),MCD_T(""),MCD_T("0628591latin1"),
MCD_T("0628592latin21100874iso-8859-11"),
MCD_T("0628593latin31420127ansi_x3.4-19681420127ansi_x3.4-19861028591iso_8859-1"),
MCD_T("0628594latin41028592iso_8859-20701200unicode1128603iso-8859-13"),
MCD_T("1028593iso_8859-30628599latin51410082x-mac-croatian"),
MCD_T("1028594iso_8859-41128605iso-8859-150565000utf-70851932x-euc-jp"),
MCD_T("1300775cspc775baltic1028595iso_8859-50565001utf-80512000utf32"),
MCD_T("1028596iso_8859-61710002x-mac-chinesetrad0601252x-ansi"),
MCD_T("1028597iso_8859-70628605latin90501200utf160700154ptcp1541410010x-mac-romanian"),
MCD_T("0900936iso-ir-581028598iso_8859-8"),MCD_T("1028599iso_8859-9"),
MCD_T("1350221iso2022-jp-ms0400932sjis"),MCD_T("0751949cseuckr"),
MCD_T("1420002x-chinese-eten"),MCD_T("1410007x-mac-cyrillic"),
MCD_T("1000932shifft_jis"),MCD_T("0828596ecma-114"),MCD_T(""),
MCD_T("0900932shift-jis"),MCD_T("0701256cp1256 1320107x-ia5-swedish"),
MCD_T("0828597ecma-118"),
MCD_T("1628596csisolatinarabic1710008x-mac-chinesesimp0600932x-sjis"),MCD_T(""),
MCD_T("0754936gb18030"),MCD_T("1350221windows-502210712000cp12000"),
MCD_T("0628596arabic0500936cn-gb0900932sjis-open0712001cp12001"),MCD_T(""),
MCD_T(""),MCD_T("0700950cn-big50920127iso646-us1001133ibm-cp1133"),MCD_T(""),
MCD_T("0800936csgb23120900949ks-c-56010310000mac"),
MCD_T("1001257winbaltrim0750221cp502211020127iso-ir-6us"),
MCD_T("1000932csshiftjis"),MCD_T("0300936gbk0765001cp65001"),
MCD_T("1620127iso_646.irv:19911351932windows-519320920001x-cp20001")
};
int x_GetEncodingCodePage( MCD_CSTR pszEncoding )
{
// redo for completeness, the iconv set, UTF-32, and uppercase
// Lookup strEncoding in EncodingNameTable and return Windows code page
int nCodePage = -1;
int nEncLen = MCD_PSZLEN( pszEncoding );
if ( ! nEncLen )
nCodePage = MCD_ACP;
else if ( MCD_PSZNCMP(pszEncoding,MCD_T("UTF-32"),6) == 0 )
nCodePage = MCD_UTF32;
else if ( nEncLen < 100 )
{
MCD_CHAR szEncodingLower[100];
for ( int nEncChar=0; nEncChar<nEncLen; ++nEncChar )
{
MCD_CHAR cEncChar = pszEncoding[nEncChar];
szEncodingLower[nEncChar] = (cEncChar>='A' && cEncChar<='Z')? (MCD_CHAR)(cEncChar+('a'-'A')) : cEncChar;
}
szEncodingLower[nEncLen] = '\0';
MCD_PCSZ pEntry = EncodingNameTable[x_Hash(szEncodingLower,sizeof(EncodingNameTable)/sizeof(MCD_PCSZ))];
while ( *pEntry )
{
// e.g. entry: 0565001utf-8 means length 05, code page 65001, encoding name utf-8
int nEntryLen = (*pEntry - '0') * 10;
++pEntry;
nEntryLen += (*pEntry - '0');
++pEntry;
MCD_PCSZ pCodePage = pEntry;
pEntry += 5;
if ( nEntryLen == nEncLen && MCD_PSZNCMP(szEncodingLower,pEntry,nEntryLen) == 0 )
{
// Convert digits to integer up to code name which always starts with alpha
nCodePage = MCD_PSZTOL( pCodePage, NULL, 10 );
break;
}
pEntry += nEntryLen;
}
}
return nCodePage;
}
#if ! defined(MARKUP_WCHAR)
bool TextEncoding::CanConvert( MCD_CSTR pszToEncoding, MCD_CSTR pszFromEncoding )
{
// Return true if MB to MB conversion is possible
#if defined(MARKUP_ICONV)
// iconv_open should fail if either encoding not supported or one is alias for other
char szTo[100], szFrom[100];
iconv_t cd = iconv_open( IConvName(szTo,pszToEncoding), IConvName(szFrom,pszFromEncoding) );
if ( cd == (iconv_t)-1 )
return false;
iconv_close(cd);
#else
int nToCP = x_GetEncodingCodePage( pszToEncoding );
int nFromCP = x_GetEncodingCodePage( pszFromEncoding );
if ( nToCP == -1 || nFromCP == -1 )
return false;
#if defined(MARKUP_WINCONV)
if ( nToCP == MCD_ACP || nFromCP == MCD_ACP ) // either ACP ANSI?
{
int nACP = GetACP();
if ( nToCP == MCD_ACP )
nToCP = nACP;
if ( nFromCP == MCD_ACP )
nFromCP = nACP;
}
#else // no conversion API, but we can do AToUTF8 and UTF8ToA
if ( nToCP != MCD_UTF8 && nFromCP != MCD_UTF8 ) // either UTF-8?
return false;
#endif // no conversion API
if ( nToCP == nFromCP )
return false;
#endif // not ICONV
return true;
}
#endif // not WCHAR
#if defined(MARKUP_ICONV)
const char* TextEncoding::IConvName( char* szEncoding, MCD_CSTR pszEncoding )
{
// Make upper case char-based name from strEncoding which consists only of characters in the ASCII range
int nEncChar = 0;
while ( pszEncoding[nEncChar] )
{
char cEncChar = (char)pszEncoding[nEncChar];
szEncoding[nEncChar] = (cEncChar>='a' && cEncChar<='z')? (cEncChar-('a'-'A')) : cEncChar;
++nEncChar;
}
if ( nEncChar == 6 && strncmp(szEncoding,"UTF-16",6) == 0 )
{
szEncoding[nEncChar++] = 'B';
szEncoding[nEncChar++] = 'E';
}
szEncoding[nEncChar] = '\0';
return szEncoding;
}
int TextEncoding::IConv( void* pTo, int nToCharSize, int nFromCharSize )
{
// Converts from m_pFrom to pTo
char szTo[100], szFrom[100];
iconv_t cd = iconv_open( IConvName(szTo,m_strToEncoding), IConvName(szFrom,m_strFromEncoding) );
int nToLenBytes = 0;
if ( cd != (iconv_t)-1 )
{
size_t nFromLenRemaining = (size_t)m_nFromLen * nFromCharSize;
size_t nToCountRemaining = (size_t)m_nToCount * nToCharSize;
size_t nToCountRemainingBefore;
char* pToChar = (char*)pTo;
char* pFromChar = (char*)m_pFrom;
char* pToTempBuffer = NULL;
const size_t nTempBufferSize = 2048;
size_t nResult;
if ( ! pTo )
{
pToTempBuffer = new char[nTempBufferSize];
pToChar = pToTempBuffer;
nToCountRemaining = nTempBufferSize;
}
while ( nFromLenRemaining )
{
nToCountRemainingBefore = nToCountRemaining;
nResult = iconv( cd, &pFromChar, &nFromLenRemaining, &pToChar, &nToCountRemaining );
nToLenBytes += (int)(nToCountRemainingBefore - nToCountRemaining);
if ( nResult == (size_t)-1 )
{
int nErrno = errno;
if ( nErrno == EILSEQ )
{
// Bypass bad char, question mark denotes problem in source string
pFromChar += nFromCharSize;
nFromLenRemaining -= nFromCharSize;
if ( nToCharSize == 1 )
*pToChar = '?';
else if ( nToCharSize == 2 )
*((unsigned short*)pToChar) = (unsigned short)'?';
else if ( nToCharSize == 4 )
*((unsigned int*)pToChar) = (unsigned int)'?';
pToChar += nToCharSize;
nToCountRemaining -= nToCharSize;
}
else if ( nErrno == EINVAL )
break; // incomplete character or shift sequence at end of input
// E2BIG : output buffer full should only happen when using a temp buffer
}
else
m_nFailedChars += nResult;
if ( pToTempBuffer && nToCountRemaining < 10 )
{
nToCountRemaining = nTempBufferSize;
pToChar = pToTempBuffer;
}
}
if ( pToTempBuffer )
delete[] pToTempBuffer;
iconv_close(cd);
}
return nToLenBytes / nToCharSize;
}
#endif
#if defined(MARKUP_WINCONV)
bool x_NoDefaultChar( int nCP )
{
// WideCharToMultiByte fails if lpUsedDefaultChar is non-NULL for these code pages:
return (bool)(nCP == 65000 || nCP == 65001 || nCP == 50220 || nCP == 50221 || nCP == 50222 || nCP == 50225 ||
nCP == 50227 || nCP == 50229 || nCP == 52936 || nCP == 54936 || (nCP >= 57002 && nCP <= 57011) );
}
#endif
int TextEncoding::PerformConversion( void* pTo, MCD_CSTR pszToEncoding/*=NULL*/ )
{
// If pTo is not NULL, it must be large enough to hold result, length of result is returned
// m_nFailedChars will be set to >0 if characters not supported in strToEncoding
int nToLen = 0;
if ( pszToEncoding.pcsz )
m_strToEncoding = pszToEncoding;
int nToCP = x_GetEncodingCodePage( m_strToEncoding );
if ( nToCP == -1 )
nToCP = MCD_ACP;
int nFromCP = x_GetEncodingCodePage( m_strFromEncoding );
if ( nFromCP == -1 )
nFromCP = MCD_ACP;
m_nFailedChars = 0;
#if ! defined(MARKUP_WINCONV) && ! defined(MARKUP_ICONV)
// Only non-Unicode encoding supported is locale charset, must call setlocale
if ( nToCP != MCD_UTF8 && nToCP != MCD_UTF16 && nToCP != MCD_UTF32 )
nToCP = MCD_ACP;
if ( nFromCP != MCD_UTF8 && nFromCP != MCD_UTF16 && nFromCP != MCD_UTF32 )
nFromCP = MCD_ACP;
if ( nFromCP == MCD_ACP )
{
const char* pA = (const char*)m_pFrom;
int nALenRemaining = m_nFromLen;
int nCharLen;
wchar_t wcChar;
char* pU = (char*)pTo;
while ( nALenRemaining )
{
nCharLen = mbtowc( &wcChar, pA, nALenRemaining );
if ( nCharLen < 1 )
{
wcChar = (wchar_t)'?';
nCharLen = 1;
}
pA += nCharLen;
nALenRemaining -= nCharLen;
if ( nToCP == MCD_UTF8 )
CMarkup::EncodeCharUTF8( (int)wcChar, pU, nToLen );
else if ( nToCP == MCD_UTF16 )
CMarkup::EncodeCharUTF16( (int)wcChar, (unsigned short*)pU, nToLen );
else // UTF32
{
if ( pU )
((unsigned int*)pU)[nToLen] = (unsigned int)wcChar;
++nToLen;
}
}
}
else if ( nToCP == MCD_ACP )
{
union pUnicodeUnion { const char* p8; const unsigned short* p16; const unsigned int* p32; } pU;
pU.p8 = (const char*)m_pFrom;
const char* pUEnd = pU.p8 + m_nFromLen;
if ( nFromCP == MCD_UTF16 )
pUEnd = (char*)( pU.p16 + m_nFromLen );
else if ( nFromCP == MCD_UTF32 )
pUEnd = (char*)( pU.p32 + m_nFromLen );
int nCharLen;
char* pA = (char*)pTo;
char szA[8];
int nUChar;
while ( pU.p8 != pUEnd )
{
if ( nFromCP == MCD_UTF8 )
nUChar = CMarkup::DecodeCharUTF8( pU.p8, pUEnd );
else if ( nFromCP == MCD_UTF16 )
nUChar = CMarkup::DecodeCharUTF16( pU.p16, (const unsigned short*)pUEnd );
else // UTF32
nUChar = *(pU.p32)++;
if ( nUChar == -1 )
nCharLen = -2;
else if ( nUChar & ~0xffff )
nCharLen = -1;
else
nCharLen = wctomb( pA?pA:szA, (wchar_t)nUChar );
if ( nCharLen < 0 )
{
if ( nCharLen == -1 )
++m_nFailedChars;
nCharLen = 1;
if ( pA )
*pA = '?';
}
if ( pA )
pA += nCharLen;
nToLen += nCharLen;
}
}
#endif // not WINCONV and not ICONV
if ( nFromCP == MCD_UTF32 )
{
const unsigned int* p32 = (const unsigned int*)m_pFrom;
const unsigned int* p32End = p32 + m_nFromLen;
if ( nToCP == MCD_UTF8 )
{
char* p8 = (char*)pTo;
while ( p32 != p32End )
CMarkup::EncodeCharUTF8( *p32++, p8, nToLen );
}
else if ( nToCP == MCD_UTF16 )
{
unsigned short* p16 = (unsigned short*)pTo;
while ( p32 != p32End )
CMarkup::EncodeCharUTF16( (int)*p32++, p16, nToLen );
}
else // to ANSI
{
// WINCONV not supported for 32To8, since only used for sizeof(wchar_t) == 4
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 1, 4 );
#endif // ICONV
}
}
else if ( nFromCP == MCD_UTF16 )
{
// UTF16To8 will be deprecated since weird output buffer size sensitivity not worth implementing here
const unsigned short* p16 = (const unsigned short*)m_pFrom;
const unsigned short* p16End = p16 + m_nFromLen;
int nUChar;
if ( nToCP == MCD_UTF32 )
{
unsigned int* p32 = (unsigned int*)pTo;
while ( p16 != p16End )
{
nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
if ( nUChar == -1 )
nUChar = '?';
if ( p32 )
p32[nToLen] = (unsigned int)nUChar;
++nToLen;
}
}
#if defined(MARKUP_WINCONV)
else // to UTF-8 or other multi-byte
{
nToLen = WideCharToMultiByte(nToCP,0,(const wchar_t*)m_pFrom,m_nFromLen,(char*)pTo,
m_nToCount?m_nToCount+1:0,NULL,x_NoDefaultChar(nToCP)?NULL:&m_nFailedChars);
}
#else // not WINCONV
else if ( nToCP == MCD_UTF8 )
{
char* p8 = (char*)pTo;
while ( p16 != p16End )
{
nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
if ( nUChar == -1 )
nUChar = '?';
CMarkup::EncodeCharUTF8( nUChar, p8, nToLen );
}
}
else // to ANSI
{
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 1, 2 );
#endif // ICONV
}
#endif // not WINCONV
}
else if ( nToCP == MCD_UTF16 ) // to UTF-16 from UTF-8/ANSI
{
#if defined(MARKUP_WINCONV)
nToLen = MultiByteToWideChar(nFromCP,0,(const char*)m_pFrom,m_nFromLen,(wchar_t*)pTo,m_nToCount);
#else // not WINCONV
if ( nFromCP == MCD_UTF8 )
{
const char* p8 = (const char*)m_pFrom;
const char* p8End = p8 + m_nFromLen;
int nUChar;
unsigned short* p16 = (unsigned short*)pTo;
while ( p8 != p8End )
{
nUChar = CMarkup::DecodeCharUTF8( p8, p8End );
if ( nUChar == -1 )
nUChar = '?';
if ( p16 )
p16[nToLen] = (unsigned short)nUChar;
++nToLen;
}
}
else // from ANSI
{
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 2, 1 );
#endif // ICONV
}
#endif // not WINCONV
}
else if ( nToCP == MCD_UTF32 ) // to UTF-32 from UTF-8/ANSI
{
if ( nFromCP == MCD_UTF8 )
{
const char* p8 = (const char*)m_pFrom;
const char* p8End = p8 + m_nFromLen;
int nUChar;
unsigned int* p32 = (unsigned int*)pTo;
while ( p8 != p8End )
{
nUChar = CMarkup::DecodeCharUTF8( p8, p8End );
if ( nUChar == -1 )
nUChar = '?';
if ( p32 )
p32[nToLen] = (unsigned int)nUChar;
++nToLen;
}
}
else // from ANSI
{
// WINCONV not supported for ATo32, since only used for sizeof(wchar_t) == 4
#if defined(MARKUP_ICONV)
// nToLen = IConv( pTo, 4, 1 );
// Linux: had trouble getting IConv to leave the BOM off of the UTF-32 output stream
// So converting via UTF-16 with native endianness
unsigned short* pwszUTF16 = new unsigned short[m_nFromLen];
MCD_STR strToEncoding = m_strToEncoding;
m_strToEncoding = MCD_T("UTF-16BE");
short nEndianTest = 1;
if ( ((char*)&nEndianTest)[0] ) // Little-endian?
m_strToEncoding = MCD_T("UTF-16LE");
m_nToCount = m_nFromLen;
int nUTF16Len = IConv( pwszUTF16, 2, 1 );
m_strToEncoding = strToEncoding;
const unsigned short* p16 = (const unsigned short*)pwszUTF16;
const unsigned short* p16End = p16 + nUTF16Len;
int nUChar;
unsigned int* p32 = (unsigned int*)pTo;
while ( p16 != p16End )
{
nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
if ( nUChar == -1 )
nUChar = '?';
if ( p32 )
*p32++ = (unsigned int)nUChar;
++nToLen;
}
delete[] pwszUTF16;
#endif // ICONV
}
}
else
{
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 1, 1 );
#elif defined(MARKUP_WINCONV)
wchar_t* pwszUTF16 = new wchar_t[m_nFromLen];
int nUTF16Len = MultiByteToWideChar(nFromCP,0,(const char*)m_pFrom,m_nFromLen,pwszUTF16,m_nFromLen);
nToLen = WideCharToMultiByte(nToCP,0,pwszUTF16,nUTF16Len,(char*)pTo,m_nToCount,NULL,
x_NoDefaultChar(nToCP)?NULL:&m_nFailedChars);
delete[] pwszUTF16;
#endif // WINCONV
}
// Store the length in case this is called again after allocating output buffer to fit
m_nToCount = nToLen;
return nToLen;
}
bool TextEncoding::FindRaggedEnd( int& nTruncBeforeBytes )
{
// Check for ragged end UTF-16 or multi-byte according to m_strToEncoding, expects at least 40 bytes to work with
bool bSuccess = true;
nTruncBeforeBytes = 0;
int nCP = x_GetEncodingCodePage( m_strFromEncoding );
if ( nCP == MCD_UTF16 )
{
unsigned short* pUTF16Buffer = (unsigned short*)m_pFrom;
const unsigned short* pUTF16Last = &pUTF16Buffer[m_nFromLen-1];
if ( CMarkup::DecodeCharUTF16(pUTF16Last,&pUTF16Buffer[m_nFromLen]) == -1 )
nTruncBeforeBytes = 2;
}
else // UTF-8, SBCS DBCS
{
if ( nCP == MCD_UTF8 )
{
char* pUTF8Buffer = (char*)m_pFrom;
char* pUTF8End = &pUTF8Buffer[m_nFromLen];
int nLast = m_nFromLen - 1;
const char* pUTF8Last = &pUTF8Buffer[nLast];
while ( nLast > 0 && CMarkup::DecodeCharUTF8(pUTF8Last,pUTF8End) == -1 )
pUTF8Last = &pUTF8Buffer[--nLast];
nTruncBeforeBytes = (int)(pUTF8End - pUTF8Last);
}
else
{
// Do a conversion-based test unless we can determine it is not multi-byte
// If m_strEncoding="" default code page then GetACP can tell us the code page, otherwise just do the test
#if defined(MARKUP_WINCONV)
if ( nCP == 0 )
nCP = GetACP();
#endif
int nMultibyteCharsToTest = 2;
switch ( nCP )
{
case 54936:
nMultibyteCharsToTest = 4;
case 932: case 51932: case 20932: case 50220: case 50221: case 50222: case 10001: // Japanese
case 949: case 51949: case 50225: case 1361: case 10003: case 20949: // Korean
case 874: case 20001: case 20004: case 10021: case 20003: // Taiwan
case 50930: case 50939: case 50931: case 50933: case 20833: case 50935: case 50937: // EBCDIC
case 936: case 51936: case 20936: case 52936: // Chinese
case 950: case 50227: case 10008: case 20000: case 20002: case 10002: // Chinese
nCP = 0;
break;
}
if ( nMultibyteCharsToTest > m_nFromLen )
nMultibyteCharsToTest = m_nFromLen;
if ( nCP == 0 && nMultibyteCharsToTest )
{
/*
1. convert the piece to Unicode with MultiByteToWideChar
2. Identify at least two Unicode code point boundaries at the end of
the converted piece by stepping backwards from the end and re-
converting the final 2 bytes, 3 bytes, 4 bytes etc, comparing the
converted end string to the end of the entire converted piece to find
a valid code point boundary.
3. Upon finding a code point boundary, I still want to make sure it
will convert the same separately on either side of the divide as it
does together, so separately convert the first byte and the remaining
bytes and see if the result together is the same as the whole end, if
not try the first two bytes and the remaining bytes. etc., until I
find a useable dividing point. If none found, go back to step 2 and
get a longer end string to try.
*/
m_strToEncoding = MCD_T("UTF-16");
m_nToCount = m_nFromLen*2;
unsigned short* pUTF16Buffer = new unsigned short[m_nToCount];
int nUTF16Len = PerformConversion( (void*)pUTF16Buffer );
int nOriginalByteLen = m_nFromLen;
// Guaranteed to have at least MARKUP_FILEBLOCKSIZE/2 bytes to work with
const int nMaxBytesToTry = 40;
unsigned short wsz16End[nMaxBytesToTry*2];
unsigned short wsz16EndDivided[nMaxBytesToTry*2];
const char* pszOriginalBytes = (const char*)m_pFrom;
int nBoundariesFound = 0;
bSuccess = false;
while ( nTruncBeforeBytes < nMaxBytesToTry && ! bSuccess )
{
++nTruncBeforeBytes;
m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes];
m_nFromLen = nTruncBeforeBytes;
m_nToCount = nMaxBytesToTry*2;
int nEndUTF16Len = PerformConversion( (void*)wsz16End );
if ( nEndUTF16Len && memcmp(wsz16End,&pUTF16Buffer[nUTF16Len-nEndUTF16Len],nEndUTF16Len*2) == 0 )
{
++nBoundariesFound;
if ( nBoundariesFound > 2 )
{
int nDivideAt = 1;
while ( nDivideAt < nTruncBeforeBytes )
{
m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes];
m_nFromLen = nDivideAt;
m_nToCount = nMaxBytesToTry*2;
int nDividedUTF16Len = PerformConversion( (void*)wsz16EndDivided );
if ( nDividedUTF16Len )
{
m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes+nDivideAt];
m_nFromLen = nTruncBeforeBytes-nDivideAt;
m_nToCount = nMaxBytesToTry*2-nDividedUTF16Len;
nDividedUTF16Len += PerformConversion( (void*)&wsz16EndDivided[nDividedUTF16Len] );
if ( m_nToCount && nEndUTF16Len == nDividedUTF16Len && memcmp(wsz16End,wsz16EndDivided,nEndUTF16Len) == 0 )
{
nTruncBeforeBytes -= nDivideAt;
bSuccess = true;
break;
}
}
++nDivideAt;
}
}
}
}
delete [] pUTF16Buffer;
}
}
}
return bSuccess;
}
bool x_EndianSwapRequired( int nDocFlags )
{
short nWord = 1;
char cFirstByte = ((char*)&nWord)[0];
if ( cFirstByte ) // LE
{
if ( nDocFlags & CMarkup::MDF_UTF16BEFILE )
return true;
}
else if ( nDocFlags & CMarkup::MDF_UTF16LEFILE )
return true;
return false;
}
void x_EndianSwapUTF16( unsigned short* pBuffer, int nCharLen )
{
unsigned short cChar;
while ( nCharLen-- )
{
cChar = pBuffer[nCharLen];
pBuffer[nCharLen] = (unsigned short)((cChar<<8) | (cChar>>8));
}
}
//////////////////////////////////////////////////////////////////////
// Element position indexes
// This is the primary means of storing the layout of the document
//
struct ElemPos
{
ElemPos() {};
ElemPos( const ElemPos& pos ) { *this = pos; };
int StartTagLen() const { return nStartTagLen; };
void SetStartTagLen( int n ) { nStartTagLen = n; };
void AdjustStartTagLen( int n ) { nStartTagLen += n; };
int EndTagLen() const { return nEndTagLen; };
void SetEndTagLen( int n ) { nEndTagLen = n; };
bool IsEmptyElement() { return (StartTagLen()==nLength)?true:false; };
int StartContent() const { return nStart + StartTagLen(); };
int ContentLen() const { return nLength - StartTagLen() - EndTagLen(); };
int StartAfter() const { return nStart + nLength; };
int Level() const { return nFlags & 0xffff; };
void SetLevel( int nLev ) { nFlags = (nFlags & ~0xffff) | nLev; };
void ClearVirtualParent() { memset(this,0,sizeof(ElemPos)); };
void SetEndTagLenUnparsed() { SetEndTagLen(1); };
bool IsUnparsed() { return EndTagLen() == 1; };
// Memory size: 8 32-bit integers == 32 bytes
int nStart;
int nLength;
unsigned int nStartTagLen : 22; // 4MB limit for start tag
unsigned int nEndTagLen : 10; // 1K limit for end tag
int nFlags; // 16 bits flags, 16 bits level 65536 depth limit
int iElemParent;
int iElemChild; // first child
int iElemNext; // next sibling
int iElemPrev; // if this is first, iElemPrev points to last
};
enum MarkupNodeFlagsInternal2
{
MNF_REPLACE = 0x001000,
MNF_QUOTED = 0x008000,
MNF_EMPTY = 0x010000,
MNF_DELETED = 0x020000,
MNF_FIRST = 0x080000,
MNF_PUBLIC = 0x300000,
MNF_ILLFORMED = 0x800000,
MNF_USER = 0xf000000
};
struct ElemPosTree
{
ElemPosTree() { Clear(); };
~ElemPosTree() { Release(); };
enum { PA_SEGBITS = 16, PA_SEGMASK = 0xffff };
void ReleaseElemPosTree() { Release(); Clear(); };
void Release() { for (int n=0;n<SegsUsed();++n) delete[] (char*)m_pSegs[n]; if (m_pSegs) delete[] (char*)m_pSegs; };
void Clear() { m_nSegs=0; m_nSize=0; m_pSegs=NULL; };
int GetSize() const { return m_nSize; };
int SegsUsed() const { return ((m_nSize-1)>>PA_SEGBITS) + 1; };
ElemPos& GetRefElemPosAt(int i) const { return m_pSegs[i>>PA_SEGBITS][i&PA_SEGMASK]; };
void CopyElemPosTree( ElemPosTree* pOtherTree, int n );
void GrowElemPosTree( int nNewSize );
private:
ElemPos** m_pSegs;
int m_nSize;
int m_nSegs;
};
void ElemPosTree::CopyElemPosTree( ElemPosTree* pOtherTree, int n )
{
ReleaseElemPosTree();
m_nSize = n;
if ( m_nSize < 8 )
m_nSize = 8;
m_nSegs = SegsUsed();
if ( m_nSegs )
{
m_pSegs = (ElemPos**)(new char[m_nSegs*sizeof(char*)]);
int nSegSize = 1 << PA_SEGBITS;
for ( int nSeg=0; nSeg < m_nSegs; ++nSeg )
{
if ( nSeg + 1 == m_nSegs )
nSegSize = m_nSize - (nSeg << PA_SEGBITS);
m_pSegs[nSeg] = (ElemPos*)(new char[nSegSize*sizeof(ElemPos)]);
memcpy( m_pSegs[nSeg], pOtherTree->m_pSegs[nSeg], nSegSize*sizeof(ElemPos) );
}
}
}
void ElemPosTree::GrowElemPosTree( int nNewSize )
{
// Called by x_AllocElemPos when the document is created or the array is filled
// The ElemPosTree class is implemented using segments to reduce contiguous memory requirements
// It reduces reallocations (copying of memory) since this only occurs within one segment
// The "Grow By" algorithm ensures there are no reallocations after 2 segments
//
// Grow By: new size can be at most one more complete segment
int nSeg = (m_nSize?m_nSize-1:0) >> PA_SEGBITS;
int nNewSeg = (nNewSize-1) >> PA_SEGBITS;
if ( nNewSeg > nSeg + 1 )
{
nNewSeg = nSeg + 1;
nNewSize = (nNewSeg+1) << PA_SEGBITS;
}
// Allocate array of segments
if ( m_nSegs <= nNewSeg )
{
int nNewSegments = 4 + nNewSeg * 2;
char* pNewSegments = new char[nNewSegments*sizeof(char*)];
if ( SegsUsed() )
memcpy( pNewSegments, m_pSegs, SegsUsed()*sizeof(char*) );
if ( m_pSegs )
delete[] (char*)m_pSegs;
m_pSegs = (ElemPos**)pNewSegments;
m_nSegs = nNewSegments;
}
// Calculate segment sizes
int nSegSize = m_nSize - (nSeg << PA_SEGBITS);
int nNewSegSize = nNewSize - (nNewSeg << PA_SEGBITS);
// Complete first segment
int nFullSegSize = 1 << PA_SEGBITS;
if ( nSeg < nNewSeg && nSegSize < nFullSegSize )
{
char* pNewFirstSeg = new char[ nFullSegSize * sizeof(ElemPos) ];
if ( nSegSize )
{
// Reallocate
memcpy( pNewFirstSeg, m_pSegs[nSeg], nSegSize * sizeof(ElemPos) );
delete[] (char*)m_pSegs[nSeg];
}
m_pSegs[nSeg] = (ElemPos*)pNewFirstSeg;
}
// New segment
char* pNewSeg = new char[ nNewSegSize * sizeof(ElemPos) ];
if ( nNewSeg == nSeg && nSegSize )
{
// Reallocate
memcpy( pNewSeg, m_pSegs[nSeg], nSegSize * sizeof(ElemPos) );
delete[] (char*)m_pSegs[nSeg];
}
m_pSegs[nNewSeg] = (ElemPos*)pNewSeg;
m_nSize = nNewSize;
}
#define ELEM(i) m_pElemPosTree->GetRefElemPosAt(i)
//////////////////////////////////////////////////////////////////////
// NodePos stores information about an element or node during document creation and parsing
//
struct NodePos
{
NodePos() {};
NodePos( int n ) { nNodeFlags=n; nNodeType=0; nStart=0; nLength=0; };
int nNodeType;
int nStart;
int nLength;
int nNodeFlags;
MCD_STR strMeta;
};
//////////////////////////////////////////////////////////////////////
// Token struct and tokenizing functions
// TokenPos handles parsing operations on a constant text pointer
//
struct TokenPos
{
TokenPos( MCD_CSTR sz, int n, FilePos* p=NULL ) { Clear(); m_pDocText=sz; m_nTokenFlags=n; m_pReaderFilePos=p; };
void Clear() { m_nL=0; m_nR=-1; m_nNext=0; };
int Length() const { return m_nR - m_nL + 1; };
MCD_PCSZ GetTokenPtr() const { return &m_pDocText[m_nL]; };
MCD_STR GetTokenText() const { return MCD_STR( GetTokenPtr(), Length() ); };
int WhitespaceToTag( int n ) { m_nNext = n; if (FindAny()&&m_pDocText[m_nNext]!='<') { m_nNext=n; m_nR=n-1; } return m_nNext; };
void ForwardUntil( MCD_PCSZ szStopChars ) { while ( m_pDocText[m_nNext] && ! MCD_PSZCHR(szStopChars,m_pDocText[m_nNext]) ) m_nNext += MCD_CLEN(&m_pDocText[m_nNext]); }
bool FindAny()
{
// Go to non-whitespace or end
while ( m_pDocText[m_nNext] && MCD_PSZCHR(MCD_T(" \t\n\r"),m_pDocText[m_nNext]) )
++m_nNext;
m_nL = m_nNext;
m_nR = m_nNext-1;
return m_pDocText[m_nNext]!='\0';
};
bool FindName()
{
if ( ! FindAny() ) // go to first non-whitespace
return false;
ForwardUntil(MCD_T(" \t\n\r<>=\\/?!\"';"));
if ( m_nNext == m_nL )
++m_nNext; // it is a special char
m_nR = m_nNext - 1;
return true;
}
static int StrNIACmp( MCD_PCSZ p1, MCD_PCSZ p2, int n )
{
// string compare ignore case
bool bNonAsciiFound = false;
MCD_CHAR c1, c2;
while ( n-- )
{
c1 = *p1++;
c2 = *p2++;
if ( c1 != c2 )
{
if ( bNonAsciiFound )
return c1 - c2;
if ( c1 >= 'a' && c1 <= 'z' )
c1 = (MCD_CHAR)( c1 - ('a'-'A') );
if ( c2 >= 'a' && c2 <= 'z' )
c2 = (MCD_CHAR)( c2 - ('a'-'A') );
if ( c1 != c2 )
return c1 - c2;
}
else if ( (unsigned int)c1 > 127 )
bNonAsciiFound = true;
}
return 0;
}
bool Match( MCD_CSTR szName )
{
int nLen = Length();
if ( m_nTokenFlags & CMarkup::MDF_IGNORECASE )
return ( (StrNIACmp( GetTokenPtr(), szName, nLen ) == 0)
&& ( szName[nLen] == '\0' || MCD_PSZCHR(MCD_T(" =/[]"),szName[nLen]) ) );
else
return ( (MCD_PSZNCMP( GetTokenPtr(), szName, nLen ) == 0)
&& ( szName[nLen] == '\0' || MCD_PSZCHR(MCD_T(" =/[]"),szName[nLen]) ) );
};
bool FindAttrib( MCD_PCSZ pAttrib, int n = 0 );
int ParseNode( NodePos& node );
int m_nL;
int m_nR;
int m_nNext;
MCD_PCSZ m_pDocText;
int m_nTokenFlags;
int m_nPreSpaceStart;
int m_nPreSpaceLength;
FilePos* m_pReaderFilePos;
};
bool TokenPos::FindAttrib( MCD_PCSZ pAttrib, int n/*=0*/ )
{
// Return true if found, otherwise false and token.m_nNext is new insertion point
// If pAttrib is NULL find attrib n and leave token at attrib name
// If pAttrib is given, find matching attrib and leave token at value
// support non-well-formed attributes e.g. href=/advanced_search?hl=en, nowrap
// token also holds start and length of preceeding whitespace to support remove
//
int nTempPreSpaceStart;
int nTempPreSpaceLength;
MCD_CHAR cFirstChar;
int nAttrib = -1; // starts at tag name
int nFoundAttribNameR = 0;
bool bAfterEqual = false;
while ( 1 )
{
// Starting at m_nNext, bypass whitespace and find the next token
nTempPreSpaceStart = m_nNext;
if ( ! FindAny() )
break;
nTempPreSpaceLength = m_nNext - nTempPreSpaceStart;
// Is it an opening quote?
cFirstChar = m_pDocText[m_nNext];
if ( cFirstChar == '\"' || cFirstChar == '\'' )
{
m_nTokenFlags |= MNF_QUOTED;
// Move past opening quote
++m_nNext;
m_nL = m_nNext;
// Look for closing quote
while ( m_pDocText[m_nNext] && m_pDocText[m_nNext] != cFirstChar )
m_nNext += MCD_CLEN( &m_pDocText[m_nNext] );
// Set right to before closing quote
m_nR = m_nNext - 1;
// Set m_nNext past closing quote unless at end of document
if ( m_pDocText[m_nNext] )
++m_nNext;
}
else
{
m_nTokenFlags &= ~MNF_QUOTED;
// Go until special char or whitespace
m_nL = m_nNext;
if ( bAfterEqual )
ForwardUntil(MCD_T(" \t\n\r>"));
else
ForwardUntil(MCD_T("= \t\n\r>/?"));
// Adjust end position if it is one special char
if ( m_nNext == m_nL )
++m_nNext; // it is a special char
m_nR = m_nNext - 1;
}
if ( ! bAfterEqual && ! (m_nTokenFlags&MNF_QUOTED) )
{
// Is it an equal sign?
MCD_CHAR cChar = m_pDocText[m_nL];
if ( cChar == '=' )
{
bAfterEqual = true;
continue;
}
// Is it the right angle bracket?
if ( cChar == '>' || cChar == '/' || cChar == '?' )
{
m_nNext = nTempPreSpaceStart;
break; // attrib not found
}
if ( nFoundAttribNameR )
break;
// Attribute name
if ( nAttrib != -1 )
{
if ( ! pAttrib )
{
if ( nAttrib == n )
return true; // found by number
}
else if ( Match(pAttrib) )
{
// Matched attrib name, go forward to value
nFoundAttribNameR = m_nR;
m_nPreSpaceStart = nTempPreSpaceStart;
m_nPreSpaceLength = nTempPreSpaceLength;
}
}
++nAttrib;
}
else if ( nFoundAttribNameR )
break;
bAfterEqual = false;
}
if ( nFoundAttribNameR )
{
if ( ! bAfterEqual )
{
// when attribute has no value the value is the attribute name
m_nL = m_nPreSpaceStart + m_nPreSpaceLength;
m_nR = nFoundAttribNameR;
m_nNext = nFoundAttribNameR + 1;
}
return true; // found by name
}
return false; // not found
}
//////////////////////////////////////////////////////////////////////
// Element tag stack: an array of TagPos structs to track nested elements
// This is used during parsing to match end tags with corresponding start tags
// For x_ParseElem only ElemStack::iTop is used with PushIntoLevel, PopOutOfLevel, and Current
// For file mode then the full capabilities are used to track counts of sibling tag names for path support
//
struct TagPos
{
TagPos() { Init(); };
void SetTagName( MCD_PCSZ pName, int n ) { MCD_STRASSIGN(strTagName,pName,n); };
void Init( int i=0, int n=1 ) { nCount=1; nTagNames=n; iNext=i; iPrev=0; nSlot=-1; iSlotPrev=0; iSlotNext=0; };
void IncCount() { if (nCount) ++nCount; };
MCD_STR strTagName;
int nCount;
int nTagNames;
int iParent;
int iNext;
int iPrev;
int nSlot;
int iSlotNext;
int iSlotPrev;
};
struct ElemStack
{
enum { LS_TABLESIZE = 23 };
ElemStack() { iTop=0; iUsed=0; iPar=0; nLevel=0; nSize=0; pL=NULL; Alloc(7); pL[0].Init(); InitTable(); };
~ElemStack() { if (pL) delete [] pL; };
TagPos& Current() { return pL[iTop]; };
void InitTable() { memset(anTable,0,sizeof(int)*LS_TABLESIZE); };
TagPos& NextParent( int& i ) { int iCur=i; i=pL[i].iParent; return pL[iCur]; };
TagPos& GetRefTagPosAt( int i ) { return pL[i]; };
void Push( MCD_PCSZ pName, int n ) { ++iUsed; if (iUsed==nSize) Alloc(nSize*2); pL[iUsed].SetTagName(pName,n); pL[iUsed].iParent=iPar; iTop=iUsed; };
void IntoLevel() { iPar = iTop; ++nLevel; };
void OutOfLevel() { if (iPar!=iTop) Pop(); iPar = pL[iTop].iParent; --nLevel; };
void PushIntoLevel( MCD_PCSZ pName, int n ) { ++iTop; if (iTop==nSize) Alloc(nSize*2); pL[iTop].SetTagName(pName,n); };
void PopOutOfLevel() { --iTop; };
void Pop() { iTop = iPar; while (iUsed && pL[iUsed].iParent==iPar) { if (pL[iUsed].nSlot!=-1) Unslot(pL[iUsed]); --iUsed; } };
void Slot( int n ) { pL[iUsed].nSlot=n; int i=anTable[n]; anTable[n]=iUsed; pL[iUsed].iSlotNext=i; if (i) pL[i].iSlotPrev=iUsed; };
void Unslot( TagPos& lp ) { int n=lp.iSlotNext,p=lp.iSlotPrev; if (n) pL[n].iSlotPrev=p; if (p) pL[p].iSlotNext=n; else anTable[lp.nSlot]=n; };
static int CalcSlot( MCD_PCSZ pName, int n, bool bIC );
void PushTagAndCount( TokenPos& token );
int iTop;
int nLevel;
int iPar;
protected:
void Alloc( int nNewSize ) { TagPos* pLNew = new TagPos[nNewSize]; Copy(pLNew); nSize=nNewSize; };
void Copy( TagPos* pLNew ) { for(int n=0;n<nSize;++n) pLNew[n]=pL[n]; if (pL) delete [] pL; pL=pLNew; };
TagPos* pL;
int iUsed;
int nSize;
int anTable[LS_TABLESIZE];
};
int ElemStack::CalcSlot( MCD_PCSZ pName, int n, bool bIC )
{
// If bIC (ASCII ignore case) then return an ASCII case insensitive hash
unsigned int nHash = 0;
MCD_PCSZ pEnd = pName + n;
while ( pName != pEnd )
{
nHash += (unsigned int)(*pName);
if ( bIC && *pName >= 'A' && *pName <= 'Z' )
nHash += ('a'-'A');
++pName;
}
return nHash%LS_TABLESIZE;
}
void ElemStack::PushTagAndCount( TokenPos& token )
{
// Check for a matching tag name at the top level and set current if found or add new one
// Calculate hash of tag name, support ignore ASCII case for MDF_IGNORECASE
int nSlot = -1;
int iNext = 0;
MCD_PCSZ pTagName = token.GetTokenPtr();
if ( iTop != iPar )
{
// See if tag name is already used, first try previous sibling (almost always)
iNext = iTop;
if ( token.Match(Current().strTagName) )
{
iNext = -1;
Current().IncCount();
}
else
{
nSlot = CalcSlot( pTagName, token.Length(), (token.m_nTokenFlags & CMarkup::MDF_IGNORECASE)?true:false );
int iLookup = anTable[nSlot];
while ( iLookup )
{
TagPos& tag = pL[iLookup];
if ( tag.iParent == iPar && token.Match(tag.strTagName) )
{
pL[tag.iPrev].iNext = tag.iNext;
if ( tag.iNext )
pL[tag.iNext].iPrev = tag.iPrev;
tag.nTagNames = Current().nTagNames;
tag.iNext = iTop;
tag.IncCount();
iTop = iLookup;
iNext = -1;
break;
}
iLookup = tag.iSlotNext;
}
}
}
if ( iNext != -1 )
{
// Turn off in the rare case where a document uses unique tag names like record1, record2, etc, more than 256
int nTagNames = 0;
if ( iNext )
nTagNames = Current().nTagNames;
if ( nTagNames == 256 )
{
MCD_STRASSIGN( (Current().strTagName), pTagName, (token.Length()) );
Current().nCount = 0;
Unslot( Current() );
}
else
{
Push( pTagName, token.Length() );
Current().Init( iNext, nTagNames+1 );
}
if ( nSlot == -1 )
nSlot = CalcSlot( pTagName, token.Length(), (token.m_nTokenFlags & CMarkup::MDF_IGNORECASE)?true:false );
Slot( nSlot );
}
}
//////////////////////////////////////////////////////////////////////
// FilePos is created for a file while it is open
// In file mode the file stays open between CMarkup calls and is stored in m_pFilePos
//
struct FilePos
{
FilePos()
{
m_fp=NULL; m_nDocFlags=0; m_nFileByteLen=0; m_nFileByteOffset=0; m_nOpFileByteLen=0; m_nBlockSizeBasis=MARKUP_FILEBLOCKSIZE;
m_nFileCharUnitSize=0; m_nOpFileTextLen=0; m_pstrBuffer=NULL; m_nReadBufferStart=0; m_nReadBufferRemoved=0; m_nReadGatherStart=-1;
};
bool FileOpen( MCD_CSTR_FILENAME szFileName );
bool FileRead( void* pBuffer );
bool FileReadText( MCD_STR& strDoc );
bool FileCheckRaggedEnd( void* pBuffer );
bool FileReadNextBuffer();
void FileGatherStart( int nStart );
int FileGatherEnd( MCD_STR& strSubDoc );
bool FileWrite( void* pBuffer, const void* pConstBuffer = NULL );
bool FileWriteText( const MCD_STR& strDoc, int nWriteStrLen = -1 );
bool FileFlush( MCD_STR& strBuffer, int nWriteStrLen = -1, bool bFflush = false );
bool FileClose();
void FileSpecifyEncoding( MCD_STR* pstrEncoding );
bool FileAtTop();
bool FileErrorAddResult();
FILE* m_fp;
int m_nDocFlags;
int m_nOpFileByteLen;
int m_nBlockSizeBasis;
MCD_INTFILEOFFSET m_nFileByteLen;
MCD_INTFILEOFFSET m_nFileByteOffset;
int m_nFileCharUnitSize;
int m_nOpFileTextLen;
MCD_STR m_strIOResult;
MCD_STR m_strEncoding;
MCD_STR* m_pstrBuffer;
ElemStack m_elemstack;
int m_nReadBufferStart;
int m_nReadBufferRemoved;
int m_nReadGatherStart;
MCD_STR m_strReadGatherMarkup;
};
struct BomTableStruct { const char* pszBom; int nBomLen; MCD_PCSZ pszBomEnc; int nBomFlag; } BomTable[] =
{
{ "\xef\xbb\xbf", 3, MCD_T("UTF-8"), CMarkup::MDF_UTF8PREAMBLE },
{ "\xff\xfe", 2, MCD_T("UTF-16LE"), CMarkup::MDF_UTF16LEFILE },
{ "\xfe\xff", 2, MCD_T("UTF-16BE"), CMarkup::MDF_UTF16BEFILE },
{ NULL,0,NULL,0 }
};
bool FilePos::FileErrorAddResult()
{
// strerror has difficulties cross-platform
// VC++ leaves MCD_STRERROR undefined and uses FormatMessage
// Non-VC++ use strerror (even for MARKUP_WCHAR and convert)
// additional notes:
// _WIN32_WCE (Windows CE) has no strerror (Embedded VC++ uses FormatMessage)
// _MSC_VER >= 1310 (VC++ 2003/7.1) has _wcserror (but not used)
//
const int nErrorBufferSize = 100;
int nErr = 0;
MCD_CHAR szError[nErrorBufferSize+1];
#if defined(MCD_STRERROR) // C error routine
nErr = (int)errno;
#if defined(MARKUP_WCHAR)
char szMBError[nErrorBufferSize+1];
strncpy( szMBError, MCD_STRERROR, nErrorBufferSize );
szMBError[nErrorBufferSize] = '\0';
TextEncoding textencoding( MCD_T(""), (const void*)szMBError, strlen(szMBError) );
textencoding.m_nToCount = nErrorBufferSize;
int nWideLen = textencoding.PerformConversion( (void*)szError, MCD_ENC );
szError[nWideLen] = '\0';
#else
MCD_PSZNCPY( szError, MCD_STRERROR, nErrorBufferSize );
szError[nErrorBufferSize] = '\0';
#endif
#else // no C error routine, use Windows API
DWORD dwErr = ::GetLastError();
if ( ::FormatMessage(0x1200,0,dwErr,0,szError,nErrorBufferSize,0) < 1 )
szError[0] = '\0';
nErr = (int)dwErr;
#endif // no C error routine
MCD_STR strError = szError;
for ( int nChar=0; nChar<MCD_STRLENGTH(strError); ++nChar )
if ( strError[nChar] == '\r' || strError[nChar] == '\n' )
{
strError = MCD_STRMID( strError, 0, nChar ); // no trailing newline
break;
}
x_AddResult( m_strIOResult, MCD_T("file_error"), strError, MRC_MSG|MRC_NUMBER, nErr );
return false;
}
void FilePos::FileSpecifyEncoding( MCD_STR* pstrEncoding )
{
// In ReadTextFile, WriteTextFile and Open, the pstrEncoding argument can override or return the detected encoding
if ( pstrEncoding && m_strEncoding != *pstrEncoding )
{
if ( m_nFileCharUnitSize == 1 && *pstrEncoding != MCD_T("") )
m_strEncoding = *pstrEncoding; // override the encoding
else // just report the encoding
*pstrEncoding = m_strEncoding;
}
}
bool FilePos::FileAtTop()
{
// Return true if in the first block of file mode, max BOM < 5 bytes
if ( ((m_nDocFlags & CMarkup::MDF_READFILE) && m_nFileByteOffset < (MCD_INTFILEOFFSET)m_nOpFileByteLen + 5 )
|| ((m_nDocFlags & CMarkup::MDF_WRITEFILE) && m_nFileByteOffset < 5) )
return true;
return false;
}
bool FilePos::FileOpen( MCD_CSTR_FILENAME szFileName )
{
MCD_STRCLEAR( m_strIOResult );
// Open file
MCD_PCSZ_FILENAME pMode = MCD_T_FILENAME("rb");
if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
pMode = MCD_T_FILENAME("ab");
else if ( m_nDocFlags & CMarkup::MDF_WRITEFILE )
pMode = MCD_T_FILENAME("wb");
m_fp = NULL;
MCD_FOPEN( m_fp, szFileName, pMode );
if ( ! m_fp )
return FileErrorAddResult();
// Prepare file
bool bSuccess = true;
int nBomLen = 0;
m_nFileCharUnitSize = 1; // unless UTF-16 BOM
if ( m_nDocFlags & CMarkup::MDF_READFILE )
{
// Get file length
MCD_FSEEK( m_fp, 0, SEEK_END );
m_nFileByteLen = MCD_FTELL( m_fp );
MCD_FSEEK( m_fp, 0, SEEK_SET );
// Read the top of the file to check BOM and encoding
int nReadTop = 1024;
if ( m_nFileByteLen < nReadTop )
nReadTop = (int)m_nFileByteLen;
if ( nReadTop )
{
char* pFileTop = new char[nReadTop];
if ( nReadTop )
bSuccess = ( fread( pFileTop, nReadTop, 1, m_fp ) == 1 );
if ( bSuccess )
{
// Check for Byte Order Mark (preamble)
int nBomCheck = 0;
m_nDocFlags &= ~( CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF8PREAMBLE );
while ( BomTable[nBomCheck].pszBom )
{
while ( nBomLen < BomTable[nBomCheck].nBomLen )
{
if ( nBomLen >= nReadTop || pFileTop[nBomLen] != BomTable[nBomCheck].pszBom[nBomLen] )
break;
++nBomLen;
}
if ( nBomLen == BomTable[nBomCheck].nBomLen )
{
m_nDocFlags |= BomTable[nBomCheck].nBomFlag;
if ( nBomLen == 2 )
m_nFileCharUnitSize = 2;
m_strEncoding = BomTable[nBomCheck].pszBomEnc;
break;
}
++nBomCheck;
nBomLen = 0;
}
if ( nReadTop > nBomLen )
MCD_FSEEK( m_fp, nBomLen, SEEK_SET );
// Encoding check
if ( ! nBomLen )
{
MCD_STR strDeclCheck;
#if defined(MARKUP_WCHAR) // WCHAR
TextEncoding textencoding( MCD_T("UTF-8"), (const void*)pFileTop, nReadTop );
MCD_CHAR* pWideBuffer = MCD_GETBUFFER(strDeclCheck,nReadTop);
textencoding.m_nToCount = nReadTop;
int nDeclWideLen = textencoding.PerformConversion( (void*)pWideBuffer, MCD_ENC );
MCD_RELEASEBUFFER(strDeclCheck,pWideBuffer,nDeclWideLen);
#else // not WCHAR
MCD_STRASSIGN(strDeclCheck,pFileTop,nReadTop);
#endif // not WCHAR
m_strEncoding = CMarkup::GetDeclaredEncoding( strDeclCheck );
}
// Assume markup files starting with < sign are UTF-8 if otherwise unknown
if ( MCD_STRISEMPTY(m_strEncoding) && pFileTop[0] == '<' )
m_strEncoding = MCD_T("UTF-8");
}
delete [] pFileTop;
}
}
else if ( m_nDocFlags & CMarkup::MDF_WRITEFILE )
{
if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
{
// fopen for append does not move the file pointer to the end until first I/O operation
MCD_FSEEK( m_fp, 0, SEEK_END );
m_nFileByteLen = MCD_FTELL( m_fp );
}
int nBomCheck = 0;
while ( BomTable[nBomCheck].pszBom )
{
if ( m_nDocFlags & BomTable[nBomCheck].nBomFlag )
{
nBomLen = BomTable[nBomCheck].nBomLen;
if ( nBomLen == 2 )
m_nFileCharUnitSize = 2;
m_strEncoding = BomTable[nBomCheck].pszBomEnc;
if ( m_nFileByteLen ) // append
nBomLen = 0;
else // write BOM
bSuccess = ( fwrite(BomTable[nBomCheck].pszBom,nBomLen,1,m_fp) == 1 );
break;
}
++nBomCheck;
}
}
if ( ! bSuccess )
return FileErrorAddResult();
if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
m_nFileByteOffset = m_nFileByteLen;
else
m_nFileByteOffset = (MCD_INTFILEOFFSET)nBomLen;
if ( nBomLen )
x_AddResult( m_strIOResult, MCD_T("bom") );
return bSuccess;
}
bool FilePos::FileRead( void* pBuffer )
{
bool bSuccess = ( fread( pBuffer,m_nOpFileByteLen,1,m_fp) == 1 );
m_nOpFileTextLen = m_nOpFileByteLen / m_nFileCharUnitSize;
if ( bSuccess )
{
m_nFileByteOffset += m_nOpFileByteLen;
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, m_nOpFileTextLen );
// Microsoft components can produce apparently valid docs with some nulls at ends of values
int nNullCount = 0;
int nNullCheckCharsRemaining = m_nOpFileTextLen;
char* pAfterNull = NULL;
char* pNullScan = (char*)pBuffer;
bool bSingleByteChar = m_nFileCharUnitSize == 1;
while ( nNullCheckCharsRemaining-- )
{
if ( bSingleByteChar? (! *pNullScan) : (! (*(unsigned short*)pNullScan)) )
{
if ( pAfterNull && pNullScan != pAfterNull )
memmove( pAfterNull - (nNullCount*m_nFileCharUnitSize), pAfterNull, pNullScan - pAfterNull );
pAfterNull = pNullScan + m_nFileCharUnitSize;
++nNullCount;
}
pNullScan += m_nFileCharUnitSize;
}
if ( pAfterNull && pNullScan != pAfterNull )
memmove( pAfterNull - (nNullCount*m_nFileCharUnitSize), pAfterNull, pNullScan - pAfterNull );
if ( nNullCount )
{
x_AddResult( m_strIOResult, MCD_T("nulls_removed"), NULL, MRC_COUNT, nNullCount );
m_nOpFileTextLen -= nNullCount;
}
// Big endian/little endian conversion
if ( m_nFileCharUnitSize > 1 && x_EndianSwapRequired(m_nDocFlags) )
{
x_EndianSwapUTF16( (unsigned short*)pBuffer, m_nOpFileTextLen );
x_AddResult( m_strIOResult, MCD_T("endian_swap") );
}
}
if ( ! bSuccess )
FileErrorAddResult();
return bSuccess;
}
bool FilePos::FileCheckRaggedEnd( void* pBuffer )
{
// In file read mode, piece of file text in memory must end on a character boundary
// This check must happen after the encoding has been decided, so after UTF-8 autodetection
// If ragged, adjust file position, m_nOpFileTextLen and m_nOpFileByteLen
int nTruncBeforeBytes = 0;
TextEncoding textencoding( m_strEncoding, pBuffer, m_nOpFileTextLen );
if ( ! textencoding.FindRaggedEnd(nTruncBeforeBytes) )
{
// Input must be garbled? decoding error before potentially ragged end, add error result and continue
MCD_STR strEncoding = m_strEncoding;
if ( MCD_STRISEMPTY(strEncoding) )
strEncoding = MCD_T("ANSI");
x_AddResult( m_strIOResult, MCD_T("truncation_error"), strEncoding, MRC_ENCODING );
}
else if ( nTruncBeforeBytes )
{
nTruncBeforeBytes *= -1;
m_nFileByteOffset += nTruncBeforeBytes;
MCD_FSEEK( m_fp, m_nFileByteOffset, SEEK_SET );
m_nOpFileByteLen += nTruncBeforeBytes;
m_nOpFileTextLen += nTruncBeforeBytes / m_nFileCharUnitSize;
x_AddResult( m_strIOResult, MCD_T("read"), NULL, MRC_MODIFY|MRC_LENGTH, m_nOpFileTextLen );
}
return true;
}
bool FilePos::FileReadText( MCD_STR& strDoc )
{
bool bSuccess = true;
MCD_STRCLEAR( m_strIOResult );
if ( ! m_nOpFileByteLen )
{
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, 0 );
return bSuccess;
}
// Only read up to end of file (a single read byte length cannot be over the capacity of int)
bool bCheckRaggedEnd = true;
MCD_INTFILEOFFSET nBytesRemaining = m_nFileByteLen - m_nFileByteOffset;
if ( (MCD_INTFILEOFFSET)m_nOpFileByteLen >= nBytesRemaining )
{
m_nOpFileByteLen = (int)nBytesRemaining;
bCheckRaggedEnd = false;
}
if ( m_nDocFlags & (CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF16BEFILE) )
{
int nUTF16Len = m_nOpFileByteLen / 2;
#if defined(MARKUP_WCHAR) // WCHAR
int nBufferSizeForGrow = nUTF16Len + nUTF16Len/100; // extra 1%
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
unsigned short* pUTF16Buffer = new unsigned short[nUTF16Len+1];
bSuccess = FileRead( pUTF16Buffer );
if ( bSuccess )
{
if ( bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pUTF16Buffer );
TextEncoding textencoding( MCD_T("UTF-16"), (const void*)pUTF16Buffer, m_nOpFileTextLen );
textencoding.m_nToCount = nBufferSizeForGrow;
MCD_CHAR* pUTF32Buffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
int nUTF32Len = textencoding.PerformConversion( (void*)pUTF32Buffer, MCD_T("UTF-32") );
MCD_RELEASEBUFFER(strDoc,pUTF32Buffer,nUTF32Len);
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_T("UTF-32"), MRC_ENCODING|MRC_LENGTH, nUTF32Len );
}
#else // sizeof(wchar_t) == 2
MCD_CHAR* pUTF16Buffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
bSuccess = FileRead( pUTF16Buffer );
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pUTF16Buffer );
MCD_RELEASEBUFFER(strDoc,pUTF16Buffer,m_nOpFileTextLen);
#endif // sizeof(wchar_t) == 2
#else // not WCHAR
// Convert file from UTF-16; it needs to be in memory as UTF-8 or MBCS
unsigned short* pUTF16Buffer = new unsigned short[nUTF16Len+1];
bSuccess = FileRead( pUTF16Buffer );
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pUTF16Buffer );
TextEncoding textencoding( MCD_T("UTF-16"), (const void*)pUTF16Buffer, m_nOpFileTextLen );
int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
int nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
MCD_CHAR* pMBBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pMBBuffer );
delete [] pUTF16Buffer;
MCD_RELEASEBUFFER(strDoc,pMBBuffer,nMBLen);
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
#endif // not WCHAR
}
else // single or multibyte file (i.e. not UTF-16)
{
#if defined(MARKUP_WCHAR) // WCHAR
char* pBuffer = new char[m_nOpFileByteLen];
bSuccess = FileRead( pBuffer );
if ( MCD_STRISEMPTY(m_strEncoding) )
{
int nNonASCII;
bool bErrorAtEnd;
if ( CMarkup::DetectUTF8(pBuffer,m_nOpFileByteLen,&nNonASCII,&bErrorAtEnd) || (bCheckRaggedEnd && bErrorAtEnd) )
{
m_strEncoding = MCD_T("UTF-8");
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_MODIFY|MRC_ENCODING );
}
x_AddResult( m_strIOResult, MCD_T("utf8_detection") );
}
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pBuffer );
TextEncoding textencoding( m_strEncoding, (const void*)pBuffer, m_nOpFileTextLen );
int nWideLen = textencoding.PerformConversion( NULL, MCD_ENC );
int nBufferSizeForGrow = nWideLen + nWideLen/100; // extra 1%
MCD_CHAR* pWideBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pWideBuffer );
MCD_RELEASEBUFFER( strDoc, pWideBuffer, nWideLen );
delete [] pBuffer;
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWideLen );
#else // not WCHAR
// After loading a file with unknown multi-byte encoding
bool bAssumeUnknownIsNative = false;
if ( MCD_STRISEMPTY(m_strEncoding) )
{
bAssumeUnknownIsNative = true;
m_strEncoding = MCD_ENC;
}
if ( TextEncoding::CanConvert(MCD_ENC,m_strEncoding) )
{
char* pBuffer = new char[m_nOpFileByteLen];
bSuccess = FileRead( pBuffer );
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pBuffer );
TextEncoding textencoding( m_strEncoding, (const void*)pBuffer, m_nOpFileTextLen );
int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
int nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
MCD_CHAR* pMBBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pMBBuffer );
MCD_RELEASEBUFFER( strDoc, pMBBuffer, nMBLen );
delete [] pBuffer;
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
}
else // load directly into string
{
int nBufferSizeForGrow = m_nOpFileByteLen + m_nOpFileByteLen/100; // extra 1%
MCD_CHAR* pBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
bSuccess = FileRead( pBuffer );
bool bConvertMB = false;
if ( bAssumeUnknownIsNative )
{
// Might need additional conversion if we assumed an encoding
int nNonASCII;
bool bErrorAtEnd;
bool bIsUTF8 = CMarkup::DetectUTF8( pBuffer, m_nOpFileByteLen, &nNonASCII, &bErrorAtEnd ) || (bCheckRaggedEnd && bErrorAtEnd);
MCD_STR strDetectedEncoding = bIsUTF8? MCD_T("UTF-8"): MCD_T("");
if ( nNonASCII && m_strEncoding != strDetectedEncoding ) // only need to convert non-ASCII
bConvertMB = true;
m_strEncoding = strDetectedEncoding;
if ( bIsUTF8 )
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_MODIFY|MRC_ENCODING );
}
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pBuffer );
MCD_RELEASEBUFFER( strDoc, pBuffer, m_nOpFileTextLen );
if ( bConvertMB )
{
TextEncoding textencoding( m_strEncoding, MCD_2PCSZ(strDoc), m_nOpFileTextLen );
int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
MCD_STR strConvDoc;
pBuffer = MCD_GETBUFFER(strConvDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pBuffer );
MCD_RELEASEBUFFER( strConvDoc, pBuffer, nMBLen );
strDoc = strConvDoc;
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
}
if ( bAssumeUnknownIsNative )
x_AddResult( m_strIOResult, MCD_T("utf8_detection") );
}
#endif // not WCHAR
}
return bSuccess;
}
bool FilePos::FileWrite( void* pBuffer, const void* pConstBuffer /*=NULL*/ )
{
m_nOpFileByteLen = m_nOpFileTextLen * m_nFileCharUnitSize;
if ( ! pConstBuffer )
pConstBuffer = pBuffer;
unsigned short* pTempEndianBuffer = NULL;
if ( x_EndianSwapRequired(m_nDocFlags) )
{
if ( ! pBuffer )
{
pTempEndianBuffer = new unsigned short[m_nOpFileTextLen];
memcpy( pTempEndianBuffer, pConstBuffer, m_nOpFileTextLen * 2 );
pBuffer = pTempEndianBuffer;
pConstBuffer = pTempEndianBuffer;
}
x_EndianSwapUTF16( (unsigned short*)pBuffer, m_nOpFileTextLen );
x_AddResult( m_strIOResult, MCD_T("endian_swap") );
}
bool bSuccess = ( fwrite( pConstBuffer, m_nOpFileByteLen, 1, m_fp ) == 1 );
if ( pTempEndianBuffer )
delete [] pTempEndianBuffer;
if ( bSuccess )
{
m_nFileByteOffset += m_nOpFileByteLen;
x_AddResult( m_strIOResult, MCD_T("write"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, m_nOpFileTextLen );
}
else
FileErrorAddResult();
return bSuccess;
}
bool FilePos::FileWriteText( const MCD_STR& strDoc, int nWriteStrLen/*=-1*/ )
{
bool bSuccess = true;
MCD_STRCLEAR( m_strIOResult );
MCD_PCSZ pDoc = MCD_2PCSZ(strDoc);
if ( nWriteStrLen == -1 )
nWriteStrLen = MCD_STRLENGTH(strDoc);
if ( ! nWriteStrLen )
{
x_AddResult( m_strIOResult, MCD_T("write"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, 0 );
return bSuccess;
}
if ( m_nDocFlags & (CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF16BEFILE) )
{
#if defined(MARKUP_WCHAR) // WCHAR
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
TextEncoding textencoding( MCD_T("UTF-32"), (const void*)pDoc, nWriteStrLen );
m_nOpFileTextLen = textencoding.PerformConversion( NULL, MCD_T("UTF-16") );
unsigned short* pUTF16Buffer = new unsigned short[m_nOpFileTextLen];
textencoding.PerformConversion( (void*)pUTF16Buffer );
x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_T("UTF-32"), MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
bSuccess = FileWrite( pUTF16Buffer );
delete [] pUTF16Buffer;
#else // sizeof(wchar_t) == 2
m_nOpFileTextLen = nWriteStrLen;
bSuccess = FileWrite( NULL, pDoc );
#endif
#else // not WCHAR
TextEncoding textencoding( MCD_ENC, (const void*)pDoc, nWriteStrLen );
m_nOpFileTextLen = textencoding.PerformConversion( NULL, MCD_T("UTF-16") );
unsigned short* pUTF16Buffer = new unsigned short[m_nOpFileTextLen];
textencoding.PerformConversion( (void*)pUTF16Buffer );
x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
bSuccess = FileWrite( pUTF16Buffer );
delete [] pUTF16Buffer;
#endif // not WCHAR
}
else // single or multibyte file (i.e. not UTF-16)
{
#if ! defined(MARKUP_WCHAR) // not WCHAR
if ( ! TextEncoding::CanConvert(m_strEncoding,MCD_ENC) )
{
// Same or unsupported multi-byte to multi-byte, so save directly from string
m_nOpFileTextLen = nWriteStrLen;
bSuccess = FileWrite( NULL, pDoc );
return bSuccess;
}
#endif // not WCHAR
TextEncoding textencoding( MCD_ENC, (const void*)pDoc, nWriteStrLen );
m_nOpFileTextLen = textencoding.PerformConversion( NULL, m_strEncoding );
char* pMBBuffer = new char[m_nOpFileTextLen];
textencoding.PerformConversion( (void*)pMBBuffer );
x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
bSuccess = FileWrite( pMBBuffer );
delete [] pMBBuffer;
}
return bSuccess;
}
bool FilePos::FileClose()
{
if ( m_fp )
{
if ( fclose(m_fp) )
FileErrorAddResult();
m_fp = NULL;
m_nDocFlags &= ~(CMarkup::MDF_WRITEFILE|CMarkup::MDF_READFILE|CMarkup::MDF_APPENDFILE);
return true;
}
return false;
}
bool FilePos::FileReadNextBuffer()
{
// If not end of file, returns amount to subtract from offsets
if ( m_nFileByteOffset < m_nFileByteLen )
{
// Prepare to put this node at beginning
MCD_STR& str = *m_pstrBuffer;
int nDocLength = MCD_STRLENGTH( str );
int nRemove = m_nReadBufferStart;
m_nReadBufferRemoved = nRemove;
// Gather
if ( m_nReadGatherStart != -1 )
{
if ( m_nReadBufferStart > m_nReadGatherStart )
{
// In case it is a large subdoc, reduce reallocs by using x_StrInsertReplace
MCD_STR strAppend = MCD_STRMID( str, m_nReadGatherStart, m_nReadBufferStart - m_nReadGatherStart );
x_StrInsertReplace( m_strReadGatherMarkup, MCD_STRLENGTH(m_strReadGatherMarkup), 0, strAppend );
}
m_nReadGatherStart = 0;
}
// Increase capacity if already at the beginning keeping more than half
int nKeepLength = nDocLength - nRemove;
int nEstimatedKeepBytes = m_nBlockSizeBasis * nKeepLength / nDocLength; // block size times fraction of doc kept
if ( nRemove == 0 || nKeepLength > nDocLength / 2 )
m_nBlockSizeBasis *= 2;
if ( nRemove )
x_StrInsertReplace( str, 0, nRemove, MCD_STR() );
MCD_STR strRead;
m_nOpFileByteLen = m_nBlockSizeBasis - nEstimatedKeepBytes;
m_nOpFileByteLen += 4 - m_nOpFileByteLen % 4;
FileReadText( strRead );
x_StrInsertReplace( str, nKeepLength, 0, strRead );
m_nReadBufferStart = 0; // next time just elongate/increase capacity
return true;
}
return false;
}
void FilePos::FileGatherStart( int nStart )
{
m_nReadGatherStart = nStart;
}
int FilePos::FileGatherEnd( MCD_STR& strMarkup )
{
int nStart = m_nReadGatherStart;
m_nReadGatherStart = -1;
strMarkup = m_strReadGatherMarkup;
MCD_STRCLEAR( m_strReadGatherMarkup );
return nStart;
}
bool FilePos::FileFlush( MCD_STR& strBuffer, int nWriteStrLen/*=-1*/, bool bFflush/*=false*/ )
{
bool bSuccess = true;
MCD_STRCLEAR( m_strIOResult );
if ( nWriteStrLen == -1 )
nWriteStrLen = MCD_STRLENGTH( strBuffer );
if ( nWriteStrLen )
{
if ( (! m_nFileByteOffset) && MCD_STRISEMPTY(m_strEncoding) && ! MCD_STRISEMPTY(strBuffer) )
{
m_strEncoding = CMarkup::GetDeclaredEncoding( strBuffer );
if ( MCD_STRISEMPTY(m_strEncoding) )
m_strEncoding = MCD_T("UTF-8");
}
bSuccess = FileWriteText( strBuffer, nWriteStrLen );
if ( bSuccess )
x_StrInsertReplace( strBuffer, 0, nWriteStrLen, MCD_STR() );
}
if ( bFflush && bSuccess )
{
if ( fflush(m_fp) )
bSuccess = FileErrorAddResult();
}
return bSuccess;
}
//////////////////////////////////////////////////////////////////////
// PathPos encapsulates parsing of the path string used in Find methods
//
struct PathPos
{
PathPos( MCD_PCSZ pszPath, bool b ) { p=pszPath; bReader=b; i=0; iPathAttribName=0; iSave=0; nPathType=0; if (!ParsePath()) nPathType=-1; };
int GetTypeAndInc() { i=-1; if (p) { if (p[0]=='/') { if (p[1]=='/') i=2; else i=1; } else if (p[0]) i=0; } nPathType=i+1; return nPathType; };
int GetNumAndInc() { int n=0; while (p[i]>='0'&&p[i]<='9') n=n*10+(int)p[i++]-(int)'0'; return n; };
MCD_PCSZ GetValAndInc() { ++i; MCD_CHAR cEnd=']'; if (p[i]=='\''||p[i]=='\"') cEnd=p[i++]; int iVal=i; IncWord(cEnd); nLen=i-iVal; if (cEnd!=']') ++i; return &p[iVal]; };
int GetValOrWordLen() { return nLen; };
MCD_CHAR GetChar() { return p[i]; };
bool IsAtPathEnd() { return ((!p[i])||(iPathAttribName&&i+2>=iPathAttribName))?true:false; };
MCD_PCSZ GetPtr() { return &p[i]; };
void SaveOffset() { iSave=i; };
void RevertOffset() { i=iSave; };
void RevertOffsetAsName() { i=iSave; nPathType=1; };
MCD_PCSZ GetWordAndInc() { int iWord=i; IncWord(); nLen=i-iWord; return &p[iWord]; };
void IncWord() { while (p[i]&&!MCD_PSZCHR(MCD_T(" =/[]"),p[i])) i+=MCD_CLEN(&p[i]); };
void IncWord( MCD_CHAR c ) { while (p[i]&&p[i]!=c) i+=MCD_CLEN(&p[i]); };
void IncChar() { ++i; };
void Inc( int n ) { i+=n; };
bool IsAnywherePath() { return nPathType == 3; };
bool IsAbsolutePath() { return nPathType == 2; };
bool IsPath() { return nPathType > 0; };
bool ValidPath() { return nPathType != -1; };
MCD_PCSZ GetPathAttribName() { if (iPathAttribName) return &p[iPathAttribName]; return NULL; };
bool AttribPredicateMatch( TokenPos& token );
private:
bool ParsePath();
int nPathType; // -1 invalid, 0 empty, 1 name, 2 absolute path, 3 anywhere path
bool bReader;
MCD_PCSZ p;
int i;
int iPathAttribName;
int iSave;
int nLen;
};
bool PathPos::ParsePath()
{
// Determine if the path seems to be in a valid format before attempting to find
if ( GetTypeAndInc() )
{
SaveOffset();
while ( 1 )
{
if ( ! GetChar() )
return false;
IncWord(); // Tag name
if ( GetChar() == '[' ) // predicate
{
IncChar(); // [
if ( GetChar() >= '1' && GetChar() <= '9' )
GetNumAndInc();
else // attrib or child tag name
{
if ( GetChar() == '@' )
{
IncChar(); // @
IncWord(); // attrib name
if ( GetChar() == '=' )
GetValAndInc();
}
else
{
if ( bReader )
return false;
IncWord();
}
}
if ( GetChar() != ']' )
return false;
IncChar(); // ]
}
// Another level of path
if ( GetChar() == '/' )
{
if ( IsAnywherePath() )
return false; // multiple levels not supported for // path
IncChar();
if ( GetChar() == '@' )
{
// FindGetData and FindSetData support paths ending in attribute
IncChar(); // @
iPathAttribName = i;
IncWord(); // attrib name
if ( GetChar() )
return false; // it should have ended with attribute name
break;
}
}
else
{
if ( GetChar() )
return false; // not a slash, so it should have ended here
break;
}
}
RevertOffset();
}
return true;
}
bool PathPos::AttribPredicateMatch( TokenPos& token )
{
// Support attribute predicate matching in regular and file read mode
// token.m_nNext must already be set to node.nStart + 1 or ELEM(i).nStart + 1
IncChar(); // @
if ( token.FindAttrib(GetPtr()) )
{
IncWord();
if ( GetChar() == '=' )
{
MCD_PCSZ pszVal = GetValAndInc();
MCD_STR strPathValue = CMarkup::UnescapeText( pszVal, GetValOrWordLen() );
MCD_STR strAttribValue = CMarkup::UnescapeText( token.GetTokenPtr(), token.Length() );
if ( strPathValue != strAttribValue )
return false;
}
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
// A map is a table of SavedPos structs
//
struct SavedPos
{
// SavedPos is an entry in the SavedPosMap hash table
SavedPos() { nSavedPosFlags=0; iPos=0; };
MCD_STR strName;
int iPos;
enum { SPM_MAIN = 1, SPM_CHILD = 2, SPM_USED = 4, SPM_LAST = 8 };
int nSavedPosFlags;
};
struct SavedPosMap
{
// SavedPosMap is only created if SavePos/RestorePos are used
SavedPosMap( int nSize ) { nMapSize=nSize; pTable = new SavedPos*[nSize]; memset(pTable,0,nSize*sizeof(SavedPos*)); };
~SavedPosMap() { if (pTable) { for (int n=0;n<nMapSize;++n) if (pTable[n]) delete[] pTable[n]; delete[] pTable; } };
SavedPos** pTable;
int nMapSize;
};
struct SavedPosMapArray
{
// SavedPosMapArray keeps pointers to SavedPosMap instances
SavedPosMapArray() { m_pMaps = NULL; };
~SavedPosMapArray() { ReleaseMaps(); };
void ReleaseMaps() { SavedPosMap**p = m_pMaps; if (p) { while (*p) delete *p++; delete[] m_pMaps; m_pMaps=NULL; } };
bool GetMap( SavedPosMap*& pMap, int nMap, int nMapSize = 7 );
void CopySavedPosMaps( SavedPosMapArray* pOtherMaps );
SavedPosMap** m_pMaps; // NULL terminated array
};
bool SavedPosMapArray::GetMap( SavedPosMap*& pMap, int nMap, int nMapSize /*=7*/ )
{
// Find or create map, returns true if map(s) created
SavedPosMap** pMapsExisting = m_pMaps;
int nMapIndex = 0;
if ( pMapsExisting )
{
// Length of array is unknown, so loop through maps
while ( nMapIndex <= nMap )
{
pMap = pMapsExisting[nMapIndex];
if ( ! pMap )
break;
if ( nMapIndex == nMap )
return false; // not created
++nMapIndex;
}
nMapIndex = 0;
}
// Create map(s)
// If you access map 1 before map 0 created, then 2 maps will be created
m_pMaps = new SavedPosMap*[nMap+2];
if ( pMapsExisting )
{
while ( pMapsExisting[nMapIndex] )
{
m_pMaps[nMapIndex] = pMapsExisting[nMapIndex];
++nMapIndex;
}
delete[] pMapsExisting;
}
while ( nMapIndex <= nMap )
{
m_pMaps[nMapIndex] = new SavedPosMap( nMapSize );
++nMapIndex;
}
m_pMaps[nMapIndex] = NULL;
pMap = m_pMaps[nMap];
return true; // map(s) created
}
void SavedPosMapArray::CopySavedPosMaps( SavedPosMapArray* pOtherMaps )
{
ReleaseMaps();
if ( pOtherMaps->m_pMaps )
{
int nMap = 0;
SavedPosMap* pMap = NULL;
while ( pOtherMaps->m_pMaps[nMap] )
{
SavedPosMap* pMapSrc = pOtherMaps->m_pMaps[nMap];
GetMap( pMap, nMap, pMapSrc->nMapSize );
for ( int nSlot=0; nSlot < pMap->nMapSize; ++nSlot )
{
SavedPos* pCopySavedPos = pMapSrc->pTable[nSlot];
if ( pCopySavedPos )
{
int nCount = 0;
while ( pCopySavedPos[nCount].nSavedPosFlags & SavedPos::SPM_USED )
{
++nCount;
if ( pCopySavedPos[nCount-1].nSavedPosFlags & SavedPos::SPM_LAST )
break;
}
if ( nCount )
{
SavedPos* pNewSavedPos = new SavedPos[nCount];
for ( int nCopy=0; nCopy<nCount; ++nCopy )
pNewSavedPos[nCopy] = pCopySavedPos[nCopy];
pNewSavedPos[nCount-1].nSavedPosFlags |= SavedPos::SPM_LAST;
pMap->pTable[nSlot] = pNewSavedPos;
}
}
}
++nMap;
}
}
}
//////////////////////////////////////////////////////////////////////
// Core parser function
//
int TokenPos::ParseNode( NodePos& node )
{
// Call this with m_nNext set to the start of the node or tag
// Upon return m_nNext points to the char after the node or tag
// m_nL and m_nR are set to name location if it is a tag with a name
// node members set to node location, strMeta used for parse error
//
// <!--...--> comment
// <!DOCTYPE ...> dtd
// <?target ...?> processing instruction
// <![CDATA[...]]> cdata section
// <NAME ...> element start tag
// </NAME ...> element end tag
//
// returns the nodetype or
// 0 for end tag
// -1 for bad node
// -2 for end of document
//
enum ParseBits
{
PD_OPENTAG = 1,
PD_BANG = 2,
PD_DASH = 4,
PD_BRACKET = 8,
PD_TEXTORWS = 16,
PD_DOCTYPE = 32,
PD_INQUOTE_S = 64,
PD_INQUOTE_D = 128,
PD_EQUALS = 256
};
int nParseFlags = 0;
MCD_PCSZ pFindEnd = NULL;
int nNodeType = -1;
int nEndLen = 0;
int nName = 0;
int nNameLen = 0;
unsigned int cDminus1 = 0, cDminus2 = 0;
#define FINDNODETYPE(e,t) { pFindEnd=e; nEndLen=(sizeof(e)-1)/sizeof(MCD_CHAR); nNodeType=t; }
#define FINDNODETYPENAME(e,t,n) { FINDNODETYPE(e,t) nName=(int)(pD-m_pDocText)+n; }
#define FINDNODEBAD(e) { pFindEnd=MCD_T(">"); nEndLen=1; x_AddResult(node.strMeta,e,NULL,0,m_nNext); nNodeType=-1; }
node.nStart = m_nNext;
node.nNodeFlags = 0;
MCD_PCSZ pD = &m_pDocText[m_nNext];
unsigned int cD;
while ( 1 )
{
cD = (unsigned int)*pD;
if ( ! cD )
{
m_nNext = (int)(pD - m_pDocText);
if ( m_pReaderFilePos ) // read file mode
{
int nRemovedAlready = m_pReaderFilePos->m_nReadBufferRemoved;
if ( m_pReaderFilePos->FileReadNextBuffer() ) // more text in file?
{
int nNodeLength = m_nNext - node.nStart;
int nRemove = m_pReaderFilePos->m_nReadBufferRemoved - nRemovedAlready;
if ( nRemove )
{
node.nStart -= nRemove;
if ( nName )
nName -= nRemove;
else if ( nNameLen )
{
m_nL -= nRemove;
m_nR -= nRemove;
}
m_nNext -= nRemove;
}
int nNewOffset = node.nStart + nNodeLength;
MCD_STR& str = *m_pReaderFilePos->m_pstrBuffer;
m_pDocText = MCD_2PCSZ( str );
pD = &m_pDocText[nNewOffset];
cD = (unsigned int)*pD; // loaded char replaces null terminator
}
}
if ( ! cD )
{
if ( m_nNext == node.nStart )
{
node.nLength = 0;
node.nNodeType = 0;
return -2; // end of document
}
if ( nNodeType != CMarkup::MNT_WHITESPACE && nNodeType != CMarkup::MNT_TEXT )
{
MCD_PCSZ pType = MCD_T("tag");
if ( (nParseFlags & PD_DOCTYPE) || nNodeType == CMarkup::MNT_DOCUMENT_TYPE )
pType = MCD_T("document_type");
else if ( nNodeType == CMarkup::MNT_ELEMENT )
pType = MCD_T("start_tag");
else if ( nNodeType == 0 )
pType = MCD_T("end_tag");
else if ( nNodeType == CMarkup::MNT_CDATA_SECTION )
pType = MCD_T("cdata_section");
else if ( nNodeType == CMarkup::MNT_PROCESSING_INSTRUCTION )
pType = MCD_T("processing_instruction");
else if ( nNodeType == CMarkup::MNT_COMMENT )
pType = MCD_T("comment");
nNodeType = -1;
x_AddResult(node.strMeta,MCD_T("unterminated_tag_syntax"),pType,MRC_TYPE,node.nStart);
}
break;
}
}
if ( nName )
{
if ( MCD_PSZCHR(MCD_T(" \t\n\r/>"),(MCD_CHAR)cD) )
{
nNameLen = (int)(pD - m_pDocText) - nName;
m_nL = nName;
m_nR = nName + nNameLen - 1;
nName = 0;
cDminus2 = 0;
cDminus1 = 0;
}
else
{
pD += MCD_CLEN( pD );
continue;
}
}
if ( pFindEnd )
{
if ( cD == '>' && ! (nParseFlags & (PD_INQUOTE_S|PD_INQUOTE_D)) )
{
m_nNext = (int)(pD - m_pDocText) + 1;
if ( nEndLen == 1 )
{
pFindEnd = NULL;
if ( nNodeType == CMarkup::MNT_ELEMENT && cDminus1 == '/' )
{
if ( (! cDminus2) || MCD_PSZCHR(MCD_T(" \t\n\r\'\""),(MCD_CHAR)cDminus2) )
node.nNodeFlags |= MNF_EMPTY;
}
}
else if ( m_nNext - 1 > nEndLen )
{
// Test for end of PI or comment
MCD_PCSZ pEnd = pD - nEndLen + 1;
MCD_PCSZ pInFindEnd = pFindEnd;
int nLen = nEndLen;
while ( --nLen && *pEnd++ == *pInFindEnd++ );
if ( nLen == 0 )
pFindEnd = NULL;
}
if ( ! pFindEnd && ! (nParseFlags & PD_DOCTYPE) )
break;
}
else if ( cD == '<' && (nNodeType == CMarkup::MNT_TEXT || nNodeType == -1) )
{
m_nNext = (int)(pD - m_pDocText);
break;
}
else if ( nNodeType & CMarkup::MNT_ELEMENT )
{
if ( (nParseFlags & (PD_INQUOTE_S|PD_INQUOTE_D)) )
{
if ( cD == '\"' && (nParseFlags&PD_INQUOTE_D) )
nParseFlags ^= PD_INQUOTE_D; // off
else if ( cD == '\'' && (nParseFlags&PD_INQUOTE_S) )
nParseFlags ^= PD_INQUOTE_S; // off
}
else // not in quotes
{
// Only set INQUOTE status when preceeded by equal sign
if ( cD == '\"' && (nParseFlags&PD_EQUALS) )
nParseFlags ^= PD_INQUOTE_D|PD_EQUALS; // D on, equals off
else if ( cD == '\'' && (nParseFlags&PD_EQUALS) )
nParseFlags ^= PD_INQUOTE_S|PD_EQUALS; // S on, equals off
else if ( cD == '=' && cDminus1 != '=' && ! (nParseFlags&PD_EQUALS) )
nParseFlags ^= PD_EQUALS; // on
else if ( (nParseFlags&PD_EQUALS) && ! MCD_PSZCHR(MCD_T(" \t\n\r"),(MCD_CHAR)cD) )
nParseFlags ^= PD_EQUALS; // off
}
cDminus2 = cDminus1;
cDminus1 = cD;
}
else if ( nNodeType & CMarkup::MNT_DOCUMENT_TYPE )
{
if ( cD == '\"' && ! (nParseFlags&PD_INQUOTE_S) )
nParseFlags ^= PD_INQUOTE_D; // toggle
else if ( cD == '\'' && ! (nParseFlags&PD_INQUOTE_D) )
nParseFlags ^= PD_INQUOTE_S; // toggle
}
}
else if ( nParseFlags )
{
if ( nParseFlags & PD_TEXTORWS )
{
if ( cD == '<' )
{
m_nNext = (int)(pD - m_pDocText);
nNodeType = CMarkup::MNT_WHITESPACE;
break;
}
else if ( ! MCD_PSZCHR(MCD_T(" \t\n\r"),(MCD_CHAR)cD) )
{
nParseFlags ^= PD_TEXTORWS;
FINDNODETYPE( MCD_T("<"), CMarkup::MNT_TEXT )
}
}
else if ( nParseFlags & PD_OPENTAG )
{
nParseFlags ^= PD_OPENTAG;
if ( cD > 0x60 || ( cD > 0x40 && cD < 0x5b ) || cD == 0x5f || cD == 0x3a )
FINDNODETYPENAME( MCD_T(">"), CMarkup::MNT_ELEMENT, 0 )
else if ( cD == '/' )
FINDNODETYPENAME( MCD_T(">"), 0, 1 )
else if ( cD == '!' )
nParseFlags |= PD_BANG;
else if ( cD == '?' )
FINDNODETYPENAME( MCD_T("?>"), CMarkup::MNT_PROCESSING_INSTRUCTION, 1 )
else
FINDNODEBAD( MCD_T("first_tag_syntax") )
}
else if ( nParseFlags & PD_BANG )
{
nParseFlags ^= PD_BANG;
if ( cD == '-' )
nParseFlags |= PD_DASH;
else if ( nParseFlags & PD_DOCTYPE )
{
if ( MCD_PSZCHR(MCD_T("EAN"),(MCD_CHAR)cD) ) // <!ELEMENT ATTLIST ENTITY NOTATION
FINDNODETYPE( MCD_T(">"), CMarkup::MNT_DOCUMENT_TYPE )
else
FINDNODEBAD( MCD_T("doctype_tag_syntax") )
}
else
{
if ( cD == '[' )
nParseFlags |= PD_BRACKET;
else if ( cD == 'D' )
nParseFlags |= PD_DOCTYPE;
else
FINDNODEBAD( MCD_T("exclamation_tag_syntax") )
}
}
else if ( nParseFlags & PD_DASH )
{
nParseFlags ^= PD_DASH;
if ( cD == '-' )
FINDNODETYPE( MCD_T("-->"), CMarkup::MNT_COMMENT )
else
FINDNODEBAD( MCD_T("comment_tag_syntax") )
}
else if ( nParseFlags & PD_BRACKET )
{
nParseFlags ^= PD_BRACKET;
if ( cD == 'C' )
FINDNODETYPE( MCD_T("]]>"), CMarkup::MNT_CDATA_SECTION )
else
FINDNODEBAD( MCD_T("cdata_section_syntax") )
}
else if ( nParseFlags & PD_DOCTYPE )
{
if ( cD == '<' )
nParseFlags |= PD_OPENTAG;
else if ( cD == '>' )
{
m_nNext = (int)(pD - m_pDocText) + 1;
nNodeType = CMarkup::MNT_DOCUMENT_TYPE;
break;
}
}
}
else if ( cD == '<' )
{
nParseFlags |= PD_OPENTAG;
}
else
{
nNodeType = CMarkup::MNT_WHITESPACE;
if ( MCD_PSZCHR(MCD_T(" \t\n\r"),(MCD_CHAR)cD) )
nParseFlags |= PD_TEXTORWS;
else
FINDNODETYPE( MCD_T("<"), CMarkup::MNT_TEXT )
}
pD += MCD_CLEN( pD );
}
node.nLength = m_nNext - node.nStart;
node.nNodeType = nNodeType;
return nNodeType;
}
//////////////////////////////////////////////////////////////////////
// CMarkup public methods
//
CMarkup::~CMarkup()
{
delete m_pSavedPosMaps;
delete m_pElemPosTree;
}
void CMarkup::operator=( const CMarkup& markup )
{
// Copying not supported during file mode because of file pointer
if ( (m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) || (markup.m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) )
return;
m_iPosParent = markup.m_iPosParent;
m_iPos = markup.m_iPos;
m_iPosChild = markup.m_iPosChild;
m_iPosFree = markup.m_iPosFree;
m_iPosDeleted = markup.m_iPosDeleted;
m_nNodeType = markup.m_nNodeType;
m_nNodeOffset = markup.m_nNodeOffset;
m_nNodeLength = markup.m_nNodeLength;
m_strDoc = markup.m_strDoc;
m_strResult = markup.m_strResult;
m_nDocFlags = markup.m_nDocFlags;
m_pElemPosTree->CopyElemPosTree( markup.m_pElemPosTree, m_iPosFree );
m_pSavedPosMaps->CopySavedPosMaps( markup.m_pSavedPosMaps );
MARKUP_SETDEBUGSTATE;
}
bool CMarkup::SetDoc( MCD_PCSZ pDoc )
{
// pDoc is markup text, not a filename!
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Set document text
if ( pDoc )
m_strDoc = pDoc;
else
{
MCD_STRCLEARSIZE( m_strDoc );
m_pElemPosTree->ReleaseElemPosTree();
}
MCD_STRCLEAR(m_strResult);
return x_ParseDoc();
}
bool CMarkup::SetDoc( const MCD_STR& strDoc )
{
// strDoc is markup text, not a filename!
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
m_strDoc = strDoc;
MCD_STRCLEAR(m_strResult);
return x_ParseDoc();
}
bool CMarkup::IsWellFormed()
{
if ( m_nDocFlags & MDF_WRITEFILE )
return true;
if ( m_nDocFlags & MDF_READFILE )
{
if ( ! (ELEM(0).nFlags & MNF_ILLFORMED) )
return true;
}
else if ( m_pElemPosTree->GetSize()
&& ! (ELEM(0).nFlags & MNF_ILLFORMED)
&& ELEM(0).iElemChild
&& ! ELEM(ELEM(0).iElemChild).iElemNext )
return true;
return false;
}
MCD_STR CMarkup::GetError() const
{
// For backwards compatibility, return a readable English string built from m_strResult
// In release 11.0 you can use GetResult and examine result in XML format
CMarkup mResult( m_strResult );
MCD_STR strError;
int nSyntaxErrors = 0;
while ( mResult.FindElem() )
{
MCD_STR strItem;
MCD_STR strID = mResult.GetTagName();
// Parse result
if ( strID == MCD_T("root_has_sibling") )
strItem = MCD_T("root element has sibling");
else if ( strID == MCD_T("no_root_element") )
strItem = MCD_T("no root element");
else if ( strID == MCD_T("lone_end_tag") )
strItem = MCD_T("lone end tag '") + mResult.GetAttrib(MCD_T("tagname")) + MCD_T("' at offset ")
+ mResult.GetAttrib(MCD_T("offset"));
else if ( strID == MCD_T("unended_start_tag") )
strItem = MCD_T("start tag '") + mResult.GetAttrib(MCD_T("tagname")) + MCD_T("' at offset ")
+ mResult.GetAttrib(MCD_T("offset")) + MCD_T(" expecting end tag at offset ") + mResult.GetAttrib(MCD_T("offset2"));
else if ( strID == MCD_T("first_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting tag name / ! or ?");
else if ( strID == MCD_T("exclamation_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting 'DOCTYPE' [ or -");
else if ( strID == MCD_T("doctype_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting markup declaration"); // ELEMENT ATTLIST ENTITY NOTATION
else if ( strID == MCD_T("comment_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting - to begin comment");
else if ( strID == MCD_T("cdata_section_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting 'CDATA'");
else if ( strID == MCD_T("unterminated_tag_syntax") )
strItem = MCD_T("unterminated tag at offset ") + mResult.GetAttrib(MCD_T("offset"));
// Report only the first syntax or well-formedness error
if ( ! MCD_STRISEMPTY(strItem) )
{
++nSyntaxErrors;
if ( nSyntaxErrors > 1 )
continue;
}
// I/O results
if ( strID == MCD_T("file_error") )
strItem = mResult.GetAttrib(MCD_T("msg"));
else if ( strID == MCD_T("bom") )
strItem = MCD_T("BOM +");
else if ( strID == MCD_T("read") || strID == MCD_T("write") || strID == MCD_T("converted_to") || strID == MCD_T("converted_from") )
{
if ( strID == MCD_T("converted_to") )
strItem = MCD_T("to ");
MCD_STR strEncoding = mResult.GetAttrib( MCD_T("encoding") );
if ( ! MCD_STRISEMPTY(strEncoding) )
strItem += strEncoding + MCD_T(" ");
strItem += MCD_T("length ") + mResult.GetAttrib(MCD_T("length"));
if ( strID == MCD_T("converted_from") )
strItem += MCD_T(" to");
}
else if ( strID == MCD_T("nulls_removed") )
strItem = MCD_T("removed ") + mResult.GetAttrib(MCD_T("count")) + MCD_T(" nulls");
else if ( strID == MCD_T("conversion_loss") )
strItem = MCD_T("(chars lost in conversion!)");
else if ( strID == MCD_T("utf8_detection") )
strItem = MCD_T("(used UTF-8 detection)");
else if ( strID == MCD_T("endian_swap") )
strItem = MCD_T("endian swap");
else if ( strID == MCD_T("truncation_error") )
strItem = MCD_T("encoding ") + mResult.GetAttrib(MCD_T("encoding")) + MCD_T(" adjustment error");
// Concatenate result item to error string
if ( ! MCD_STRISEMPTY(strItem) )
{
if ( ! MCD_STRISEMPTY(strError) )
strError += MCD_T(" ");
strError += strItem;
}
}
return strError;
}
bool CMarkup::Load( MCD_CSTR_FILENAME szFileName )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
if ( ! ReadTextFile(szFileName, m_strDoc, &m_strResult, &m_nDocFlags) )
return false;
return x_ParseDoc();
}
bool CMarkup::ReadTextFile( MCD_CSTR_FILENAME szFileName, MCD_STR& strDoc, MCD_STR* pstrResult, int* pnDocFlags, MCD_STR* pstrEncoding )
{
// Static utility method to load text file into strDoc
//
FilePos file;
file.m_nDocFlags = (pnDocFlags?*pnDocFlags:0) | MDF_READFILE;
bool bSuccess = file.FileOpen( szFileName );
if ( pstrResult )
*pstrResult = file.m_strIOResult;
MCD_STRCLEAR(strDoc);
if ( bSuccess )
{
file.FileSpecifyEncoding( pstrEncoding );
file.m_nOpFileByteLen = (int)((MCD_INTFILEOFFSET)(file.m_nFileByteLen - file.m_nFileByteOffset));
bSuccess = file.FileReadText( strDoc );
file.FileClose();
if ( pstrResult )
*pstrResult += file.m_strIOResult;
if ( pnDocFlags )
*pnDocFlags = file.m_nDocFlags;
}
return bSuccess;
}
bool CMarkup::Save( MCD_CSTR_FILENAME szFileName )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
return WriteTextFile( szFileName, m_strDoc, &m_strResult, &m_nDocFlags );
}
bool CMarkup::WriteTextFile( MCD_CSTR_FILENAME szFileName, const MCD_STR& strDoc, MCD_STR* pstrResult, int* pnDocFlags, MCD_STR* pstrEncoding )
{
// Static utility method to save strDoc to text file
//
FilePos file;
file.m_nDocFlags = (pnDocFlags?*pnDocFlags:0) | MDF_WRITEFILE;
bool bSuccess = file.FileOpen( szFileName );
if ( pstrResult )
*pstrResult = file.m_strIOResult;
if ( bSuccess )
{
if ( MCD_STRISEMPTY(file.m_strEncoding) && ! MCD_STRISEMPTY(strDoc) )
{
file.m_strEncoding = GetDeclaredEncoding( strDoc );
if ( MCD_STRISEMPTY(file.m_strEncoding) )
file.m_strEncoding = MCD_T("UTF-8"); // to do: MDF_ANSIFILE
}
file.FileSpecifyEncoding( pstrEncoding );
bSuccess = file.FileWriteText( strDoc );
file.FileClose();
if ( pstrResult )
*pstrResult += file.m_strIOResult;
if ( pnDocFlags )
*pnDocFlags = file.m_nDocFlags;
}
return bSuccess;
}
bool CMarkup::FindElem( MCD_CSTR szName )
{
if ( m_nDocFlags & MDF_WRITEFILE )
return false;
if ( m_pElemPosTree->GetSize() )
{
// Change current position only if found
PathPos path( szName, false );
int iPos = x_FindElem( m_iPosParent, m_iPos, path );
if ( iPos )
{
// Assign new position
x_SetPos( ELEM(iPos).iElemParent, iPos, 0 );
return true;
}
}
return false;
}
bool CMarkup::FindChildElem( MCD_CSTR szName )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Shorthand: if no current main position, find first child under parent element
if ( ! m_iPos )
FindElem();
// Change current child position only if found
PathPos path( szName, false );
int iPosChild = x_FindElem( m_iPos, m_iPosChild, path );
if ( iPosChild )
{
// Assign new position
int iPos = ELEM(iPosChild).iElemParent;
x_SetPos( ELEM(iPos).iElemParent, iPos, iPosChild );
return true;
}
return false;
}
MCD_STR CMarkup::EscapeText( MCD_CSTR szText, int nFlags )
{
// Convert text as seen outside XML document to XML friendly
// replacing special characters with ampersand escape codes
// E.g. convert "6>7" to "6>7"
//
// < less than
// & ampersand
// > greater than
//
// and for attributes:
//
// ' apostrophe or single quote
// " double quote
//
static MCD_PCSZ apReplace[] = { MCD_T("<"),MCD_T("&"),MCD_T(">"),MCD_T("'"),MCD_T(""") };
MCD_PCSZ pFind = (nFlags&MNF_ESCAPEQUOTES)?MCD_T("<&>\'\""):MCD_T("<&>");
MCD_STR strText;
MCD_PCSZ pSource = szText;
int nDestSize = MCD_PSZLEN(pSource);
nDestSize += nDestSize / 10 + 7;
MCD_BLDRESERVE(strText,nDestSize);
MCD_CHAR cSource = *pSource;
MCD_PCSZ pFound;
int nCharLen;
while ( cSource )
{
MCD_BLDCHECK(strText,nDestSize,6);
if ( (pFound=MCD_PSZCHR(pFind,cSource)) != NULL )
{
bool bIgnoreAmpersand = false;
if ( (nFlags&MNF_WITHREFS) && *pFound == '&' )
{
// Do not replace ampersand if it is start of any entity reference
// &[#_:A-Za-zU][_:-.A-Za-z0-9U]*; where U is > 0x7f
MCD_PCSZ pCheckEntity = pSource;
++pCheckEntity;
MCD_CHAR c = *pCheckEntity;
if ( (c>='A'&&c<='Z') || (c>='a'&&c<='z')
|| c=='#' || c=='_' || c==':' || ((unsigned int)c)>0x7f )
{
while ( 1 )
{
pCheckEntity += MCD_CLEN( pCheckEntity );
c = *pCheckEntity;
if ( c == ';' )
{
int nEntityLen = (int)(pCheckEntity - pSource) + 1;
MCD_BLDAPPENDN(strText,pSource,nEntityLen);
pSource = pCheckEntity;
bIgnoreAmpersand = true;
}
else if ( (c>='A'&&c<='Z') || (c>='a'&&c<='z') || (c>='0'&&c<='9')
|| c=='_' || c==':' || c=='-' || c=='.' || ((unsigned int)c)>0x7f )
continue;
break;
}
}
}
if ( ! bIgnoreAmpersand )
{
pFound = apReplace[pFound-pFind];
MCD_BLDAPPEND(strText,pFound);
}
++pSource; // ASCII, so 1 byte
}
else
{
nCharLen = MCD_CLEN( pSource );
MCD_BLDAPPENDN(strText,pSource,nCharLen);
pSource += nCharLen;
}
cSource = *pSource;
}
MCD_BLDRELEASE(strText);
return strText;
}
// Predefined character entities
// By default UnescapeText will decode standard HTML entities as well as the 5 in XML
// To unescape only the 5 standard XML entities, use this short table instead:
// MCD_PCSZ PredefEntityTable[4] =
// { MCD_T("20060lt"),MCD_T("40034quot"),MCD_T("30038amp"),MCD_T("20062gt40039apos") };
//
// This is a precompiled ASCII hash table for speed and minimum memory requirement
// Each entry consists of a 1 digit code name length, 4 digit code point, and the code name
// Each table slot can have multiple entries, table size 130 was chosen for even distribution
//
MCD_PCSZ PredefEntityTable[130] =
{
MCD_T("60216oslash60217ugrave60248oslash60249ugrave"),
MCD_T("50937omega60221yacute58968lceil50969omega60253yacute"),
MCD_T("50916delta50206icirc50948delta50238icirc68472weierp"),MCD_T("40185sup1"),
MCD_T("68970lfloor40178sup2"),
MCD_T("50922kappa60164curren50954kappa58212mdash40179sup3"),
MCD_T("59830diams58211ndash"),MCD_T("68855otimes58969rceil"),
MCD_T("50338oelig50212ocirc50244ocirc50339oelig58482trade"),
MCD_T("50197aring50931sigma50229aring50963sigma"),
MCD_T("50180acute68971rfloor50732tilde"),MCD_T("68249lsaquo"),
MCD_T("58734infin68201thinsp"),MCD_T("50161iexcl"),
MCD_T("50920theta50219ucirc50952theta50251ucirc"),MCD_T("58254oline"),
MCD_T("58260frasl68727lowast"),MCD_T("59827clubs60191iquest68250rsaquo"),
MCD_T("58629crarr50181micro"),MCD_T("58222bdquo"),MCD_T(""),
MCD_T("58243prime60177plusmn58242prime"),MCD_T("40914beta40946beta"),MCD_T(""),
MCD_T(""),MCD_T(""),MCD_T("50171laquo50215times"),MCD_T("40710circ"),
MCD_T("49001lang"),MCD_T("58220ldquo40175macr"),
MCD_T("40182para50163pound48476real"),MCD_T(""),MCD_T("58713notin50187raquo"),
MCD_T("48773cong50223szlig50978upsih"),
MCD_T("58776asymp58801equiv49002rang58218sbquo"),
MCD_T("50222thorn48659darr48595darr40402fnof58221rdquo50254thorn"),
MCD_T("40162cent58722minus"),MCD_T("58707exist40170ordf"),MCD_T(""),
MCD_T("40921iota58709empty48660harr48596harr40953iota"),MCD_T(""),
MCD_T("40196auml40228auml48226bull40167sect48838sube"),MCD_T(""),
MCD_T("48656larr48592larr58853oplus"),MCD_T("30176deg58216lsquo40186ordm"),
MCD_T("40203euml40039apos40235euml48712isin40160nbsp"),
MCD_T("40918zeta40950zeta"),MCD_T("38743and48195emsp48719prod"),
MCD_T("30935chi38745cap30967chi48194ensp"),
MCD_T("40207iuml40239iuml48706part48869perp48658rarr48594rarr"),
MCD_T("38736ang48836nsub58217rsquo"),MCD_T(""),
MCD_T("48901sdot48657uarr48593uarr"),MCD_T("40169copy48364euro"),
MCD_T("30919eta30951eta"),MCD_T("40214ouml40246ouml48839supe"),MCD_T(""),
MCD_T(""),MCD_T("30038amp30174reg"),MCD_T("48733prop"),MCD_T(""),
MCD_T("30208eth30934phi40220uuml30240eth30966phi40252uuml"),MCD_T(""),MCD_T(""),
MCD_T(""),MCD_T("40376yuml40255yuml"),MCD_T(""),MCD_T("40034quot48204zwnj"),
MCD_T("38746cup68756there4"),MCD_T("30929rho30961rho38764sim"),
MCD_T("30932tau38834sub30964tau"),MCD_T("38747int38206lrm38207rlm"),
MCD_T("30936psi30968psi30165yen"),MCD_T(""),MCD_T("28805ge30168uml"),
MCD_T("30982piv"),MCD_T(""),MCD_T("30172not"),MCD_T(""),MCD_T("28804le"),
MCD_T("30173shy"),MCD_T("39674loz28800ne38721sum"),MCD_T(""),MCD_T(""),
MCD_T("38835sup"),MCD_T("28715ni"),MCD_T(""),MCD_T("20928pi20960pi38205zwj"),
MCD_T(""),MCD_T("60923lambda20062gt60955lambda"),MCD_T(""),MCD_T(""),
MCD_T("60199ccedil60231ccedil"),MCD_T(""),MCD_T("20060lt"),
MCD_T("20926xi28744or20958xi"),MCD_T("20924mu20956mu"),MCD_T("20925nu20957nu"),
MCD_T("68225dagger68224dagger"),MCD_T("80977thetasym"),MCD_T(""),MCD_T(""),
MCD_T(""),MCD_T("78501alefsym"),MCD_T(""),MCD_T(""),MCD_T(""),
MCD_T("60193aacute60195atilde60225aacute60227atilde"),MCD_T(""),
MCD_T("70927omicron60247divide70959omicron"),MCD_T("60192agrave60224agrave"),
MCD_T("60201eacute60233eacute60962sigmaf"),MCD_T("70917epsilon70949epsilon"),
MCD_T(""),MCD_T("60200egrave60232egrave"),MCD_T("60205iacute60237iacute"),
MCD_T(""),MCD_T(""),MCD_T("60204igrave68230hellip60236igrave"),
MCD_T("60166brvbar"),
MCD_T("60209ntilde68704forall58711nabla60241ntilde69824spades"),
MCD_T("60211oacute60213otilde60189frac1260183middot60243oacute60245otilde"),
MCD_T(""),MCD_T("50184cedil60188frac14"),
MCD_T("50198aelig50194acirc60210ograve50226acirc50230aelig60242ograve"),
MCD_T("50915gamma60190frac3450947gamma58465image58730radic"),
MCD_T("60352scaron60353scaron"),MCD_T("60218uacute69829hearts60250uacute"),
MCD_T("50913alpha50202ecirc70933upsilon50945alpha50234ecirc70965upsilon"),
MCD_T("68240permil")
};
MCD_STR CMarkup::UnescapeText( MCD_CSTR szText, int nTextLength /*=-1*/ )
{
// Convert XML friendly text to text as seen outside XML document
// ampersand escape codes replaced with special characters e.g. convert "6>7" to "6>7"
// ampersand numeric codes replaced with character e.g. convert < to <
// Conveniently the result is always the same or shorter in byte length
//
MCD_STR strText;
MCD_PCSZ pSource = szText;
if ( nTextLength == -1 )
nTextLength = MCD_PSZLEN(szText);
MCD_BLDRESERVE(strText,nTextLength);
MCD_CHAR szCodeName[10];
int nCharLen;
int nChar = 0;
while ( nChar < nTextLength )
{
if ( pSource[nChar] == '&' )
{
// Get corresponding unicode code point
int nUnicode = 0;
// Look for terminating semi-colon within 9 ASCII characters
int nCodeLen = 0;
MCD_CHAR cCodeChar = pSource[nChar+1];
while ( nCodeLen < 9 && ((unsigned int)cCodeChar) < 128 && cCodeChar != ';' )
{
if ( cCodeChar >= 'A' && cCodeChar <= 'Z') // upper case?
cCodeChar += ('a' - 'A'); // make lower case
szCodeName[nCodeLen] = cCodeChar;
++nCodeLen;
cCodeChar = pSource[nChar+1+nCodeLen];
}
if ( cCodeChar == ';' ) // found semi-colon?
{
// Decode szCodeName
szCodeName[nCodeLen] = '\0';
if ( *szCodeName == '#' ) // numeric character reference?
{
// Is it a hex number?
int nBase = 10; // decimal
int nNumberOffset = 1; // after #
if ( szCodeName[1] == 'x' )
{
nNumberOffset = 2; // after #x
nBase = 16; // hex
}
nUnicode = MCD_PSZTOL( &szCodeName[nNumberOffset], NULL, nBase );
}
else // does not start with #
{
// Look for matching code name in PredefEntityTable
MCD_PCSZ pEntry = PredefEntityTable[x_Hash(szCodeName,sizeof(PredefEntityTable)/sizeof(MCD_PCSZ))];
while ( *pEntry )
{
// e.g. entry: 40039apos means length 4, code point 0039, code name apos
int nEntryLen = (*pEntry - '0');
++pEntry;
MCD_PCSZ pCodePoint = pEntry;
pEntry += 4;
if ( nEntryLen == nCodeLen && MCD_PSZNCMP(szCodeName,pEntry,nEntryLen) == 0 )
{
// Convert digits to integer up to code name which always starts with alpha
nUnicode = MCD_PSZTOL( pCodePoint, NULL, 10 );
break;
}
pEntry += nEntryLen;
}
}
}
// If a code point found, encode it into text
if ( nUnicode )
{
MCD_CHAR szChar[5];
nCharLen = 0;
#if defined(MARKUP_WCHAR) // WCHAR
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
szChar[0] = (MCD_CHAR)nUnicode;
nCharLen = 1;
#else // sizeof(wchar_t) == 2
EncodeCharUTF16( nUnicode, (unsigned short*)szChar, nCharLen );
#endif
#elif defined(MARKUP_MBCS) // MBCS/double byte
#if defined(MARKUP_WINCONV)
int nUsedDefaultChar = 0;
wchar_t wszUTF16[2];
EncodeCharUTF16( nUnicode, (unsigned short*)wszUTF16, nCharLen );
nCharLen = WideCharToMultiByte( CP_ACP, 0, wszUTF16, nCharLen, szChar, 5, NULL, &nUsedDefaultChar );
if ( nUsedDefaultChar || nCharLen <= 0 )
nUnicode = 0;
#else // not WINCONV
wchar_t wcUnicode = (wchar_t)nUnicode;
nCharLen = wctomb( szChar, wcUnicode );
if ( nCharLen <= 0 )
nUnicode = 0;
#endif // not WINCONV
#else // not WCHAR and not MBCS/double byte
EncodeCharUTF8( nUnicode, szChar, nCharLen );
#endif // not WCHAR and not MBCS/double byte
// Increment index past ampersand semi-colon
if ( nUnicode ) // must check since MBCS case can clear it
{
MCD_BLDAPPENDN(strText,szChar,nCharLen);
nChar += nCodeLen + 2;
}
}
if ( ! nUnicode )
{
// If the code is not converted, leave it as is
MCD_BLDAPPEND1(strText,'&');
++nChar;
}
}
else // not &
{
nCharLen = MCD_CLEN(&pSource[nChar]);
MCD_BLDAPPENDN(strText,&pSource[nChar],nCharLen);
nChar += nCharLen;
}
}
MCD_BLDRELEASE(strText);
return strText;
}
bool CMarkup::DetectUTF8( const char* pText, int nTextLen, int* pnNonASCII/*=NULL*/, bool* bErrorAtEnd/*=NULL*/ )
{
// return true if ASCII or all non-ASCII byte sequences are valid UTF-8 pattern:
// ASCII 0xxxxxxx
// 2-byte 110xxxxx 10xxxxxx
// 3-byte 1110xxxx 10xxxxxx 10xxxxxx
// 4-byte 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// *pnNonASCII is set (if pnNonASCII is not NULL) to the number of non-ASCII UTF-8 sequences
// or if an invalid UTF-8 sequence is found, to 1 + the valid non-ASCII sequences up to the invalid sequence
// *bErrorAtEnd is set (if bErrorAtEnd is not NULL) to true if the UTF-8 was cut off at the end in mid valid sequence
int nUChar;
if ( pnNonASCII )
*pnNonASCII = 0;
const char* pTextEnd = pText + nTextLen;
while ( *pText && pText != pTextEnd )
{
if ( (unsigned char)(*pText) & 0x80 )
{
if ( pnNonASCII )
++(*pnNonASCII);
nUChar = DecodeCharUTF8( pText, pTextEnd );
if ( nUChar == -1 )
{
if ( bErrorAtEnd )
*bErrorAtEnd = (pTextEnd == pText)? true:false;
return false;
}
}
else
++pText;
}
if ( bErrorAtEnd )
*bErrorAtEnd = false;
return true;
}
int CMarkup::DecodeCharUTF8( const char*& pszUTF8, const char* pszUTF8End/*=NULL*/ )
{
// Return Unicode code point and increment pszUTF8 past 1-4 bytes
// pszUTF8End can be NULL if pszUTF8 is null terminated
int nUChar = (unsigned char)*pszUTF8;
++pszUTF8;
if ( nUChar & 0x80 )
{
int nExtraChars;
if ( ! (nUChar & 0x20) )
{
nExtraChars = 1;
nUChar &= 0x1f;
}
else if ( ! (nUChar & 0x10) )
{
nExtraChars = 2;
nUChar &= 0x0f;
}
else if ( ! (nUChar & 0x08) )
{
nExtraChars = 3;
nUChar &= 0x07;
}
else
return -1;
while ( nExtraChars-- )
{
if ( pszUTF8 == pszUTF8End || ! (*pszUTF8 & 0x80) )
return -1;
nUChar = nUChar<<6;
nUChar |= *pszUTF8 & 0x3f;
++pszUTF8;
}
}
return nUChar;
}
void CMarkup::EncodeCharUTF16( int nUChar, unsigned short* pwszUTF16, int& nUTF16Len )
{
// Write UTF-16 sequence to pwszUTF16 for Unicode code point nUChar and update nUTF16Len
// Be sure pwszUTF16 has room for up to 2 wide chars
if ( nUChar & ~0xffff )
{
if ( pwszUTF16 )
{
// Surrogate pair
nUChar -= 0x10000;
pwszUTF16[nUTF16Len++] = (unsigned short)(((nUChar>>10) & 0x3ff) | 0xd800); // W1
pwszUTF16[nUTF16Len++] = (unsigned short)((nUChar & 0x3ff) | 0xdc00); // W2
}
else
nUTF16Len += 2;
}
else
{
if ( pwszUTF16 )
pwszUTF16[nUTF16Len++] = (unsigned short)nUChar;
else
++nUTF16Len;
}
}
int CMarkup::DecodeCharUTF16( const unsigned short*& pwszUTF16, const unsigned short* pszUTF16End/*=NULL*/ )
{
// Return Unicode code point and increment pwszUTF16 past 1 or 2 (if surrogrates) UTF-16 code points
// pszUTF16End can be NULL if pszUTF16 is zero terminated
int nUChar = *pwszUTF16;
++pwszUTF16;
if ( (nUChar & ~0x000007ff) == 0xd800 ) // W1
{
if ( pwszUTF16 == pszUTF16End || ! (*pwszUTF16) ) // W2
return -1; // incorrect UTF-16
nUChar = (((nUChar & 0x3ff) << 10) | (*pwszUTF16 & 0x3ff)) + 0x10000;
++pwszUTF16;
}
return nUChar;
}
void CMarkup::EncodeCharUTF8( int nUChar, char* pszUTF8, int& nUTF8Len )
{
// Write UTF-8 sequence to pszUTF8 for Unicode code point nUChar and update nUTF8Len
// Be sure pszUTF8 has room for up to 4 bytes
if ( ! (nUChar & ~0x0000007f) ) // < 0x80
{
if ( pszUTF8 )
pszUTF8[nUTF8Len++] = (char)nUChar;
else
++nUTF8Len;
}
else if ( ! (nUChar & ~0x000007ff) ) // < 0x800
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x7c0)>>6)|0xc0);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 2;
}
else if ( ! (nUChar & ~0x0000ffff) ) // < 0x10000
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xf000)>>12)|0xe0);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 3;
}
else // < 0x110000
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x1c0000)>>18)|0xf0);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x3f000)>>12)|0x80);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 4;
}
}
int CMarkup::UTF16To8( char* pszUTF8, const unsigned short* pwszUTF16, int nUTF8Count )
{
// Supports the same arguments as wcstombs
// the pwszUTF16 source must be a NULL-terminated UTF-16 string
// if pszUTF8 is NULL, the number of bytes required is returned and nUTF8Count is ignored
// otherwise pszUTF8 is filled with the result string and NULL-terminated if nUTF8Count allows
// nUTF8Count is the byte size of pszUTF8 and must be large enough for the NULL if NULL desired
// and the number of bytes (excluding NULL) is returned
//
int nUChar, nUTF8Len = 0;
while ( *pwszUTF16 )
{
// Decode UTF-16
nUChar = DecodeCharUTF16( pwszUTF16, NULL );
if ( nUChar == -1 )
nUChar = '?';
// Encode UTF-8
if ( pszUTF8 && nUTF8Len + 4 > nUTF8Count )
{
int nUTF8LenSoFar = nUTF8Len;
EncodeCharUTF8( nUChar, NULL, nUTF8Len );
if ( nUTF8Len > nUTF8Count )
return nUTF8LenSoFar;
nUTF8Len = nUTF8LenSoFar;
}
EncodeCharUTF8( nUChar, pszUTF8, nUTF8Len );
}
if ( pszUTF8 && nUTF8Len < nUTF8Count )
pszUTF8[nUTF8Len] = 0;
return nUTF8Len;
}
int CMarkup::UTF8To16( unsigned short* pwszUTF16, const char* pszUTF8, int nUTF8Count )
{
// Supports the same arguments as mbstowcs
// the pszUTF8 source must be a UTF-8 string which will be processed up to NULL-terminator or nUTF8Count
// if pwszUTF16 is NULL, the number of UTF-16 chars required is returned
// nUTF8Count is maximum UTF-8 bytes to convert and should include NULL if NULL desired in result
// if pwszUTF16 is not NULL it is filled with the result string and it must be large enough
// result will be NULL-terminated if NULL encountered in pszUTF8 before nUTF8Count
// and the number of UTF-8 bytes converted is returned
//
const char* pszPosUTF8 = pszUTF8;
const char* pszUTF8End = pszUTF8 + nUTF8Count;
int nUChar, nUTF8Len = 0, nUTF16Len = 0;
while ( pszPosUTF8 != pszUTF8End )
{
nUChar = DecodeCharUTF8( pszPosUTF8, pszUTF8End );
if ( ! nUChar )
{
if ( pwszUTF16 )
pwszUTF16[nUTF16Len] = 0;
break;
}
else if ( nUChar == -1 )
nUChar = '?';
// Encode UTF-16
EncodeCharUTF16( nUChar, pwszUTF16, nUTF16Len );
}
nUTF8Len = (int)(pszPosUTF8 - pszUTF8);
if ( ! pwszUTF16 )
return nUTF16Len;
return nUTF8Len;
}
#if ! defined(MARKUP_WCHAR) // not WCHAR
MCD_STR CMarkup::UTF8ToA( MCD_CSTR pszUTF8, int* pnFailed/*=NULL*/ )
{
// Converts from UTF-8 to locale ANSI charset
MCD_STR strANSI;
int nMBLen = (int)MCD_PSZLEN( pszUTF8 );
if ( pnFailed )
*pnFailed = 0;
if ( nMBLen )
{
TextEncoding textencoding( MCD_T("UTF-8"), (const void*)pszUTF8, nMBLen );
textencoding.m_nToCount = nMBLen;
MCD_CHAR* pANSIBuffer = MCD_GETBUFFER(strANSI,textencoding.m_nToCount);
nMBLen = textencoding.PerformConversion( (void*)pANSIBuffer );
MCD_RELEASEBUFFER(strANSI,pANSIBuffer,nMBLen);
if ( pnFailed )
*pnFailed = textencoding.m_nFailedChars;
}
return strANSI;
}
MCD_STR CMarkup::AToUTF8( MCD_CSTR pszANSI )
{
// Converts locale ANSI charset to UTF-8
MCD_STR strUTF8;
int nMBLen = (int)MCD_PSZLEN( pszANSI );
if ( nMBLen )
{
TextEncoding textencoding( MCD_T(""), (const void*)pszANSI, nMBLen );
textencoding.m_nToCount = nMBLen * 4;
MCD_CHAR* pUTF8Buffer = MCD_GETBUFFER(strUTF8,textencoding.m_nToCount);
nMBLen = textencoding.PerformConversion( (void*)pUTF8Buffer, MCD_T("UTF-8") );
MCD_RELEASEBUFFER(strUTF8,pUTF8Buffer,nMBLen);
}
return strUTF8;
}
#endif // not WCHAR
MCD_STR CMarkup::GetDeclaredEncoding( MCD_CSTR szDoc )
{
// Extract encoding attribute from XML Declaration, or HTML meta charset
MCD_STR strEncoding;
TokenPos token( szDoc, MDF_IGNORECASE );
NodePos node;
bool bHtml = false;
int nTypeFound = 0;
while ( nTypeFound >= 0 )
{
nTypeFound = token.ParseNode( node );
int nNext = token.m_nNext;
if ( nTypeFound == MNT_PROCESSING_INSTRUCTION && node.nStart == 0 )
{
token.m_nNext = node.nStart + 2; // after <?
if ( token.FindName() && token.Match(MCD_T("xml")) )
{
// e.g. <?xml version="1.0" encoding="UTF-8"?>
if ( token.FindAttrib(MCD_T("encoding")) )
strEncoding = token.GetTokenText();
break;
}
}
else if ( nTypeFound == 0 ) // end tag
{
// Check for end of HTML head
token.m_nNext = node.nStart + 2; // after </
if ( token.FindName() && token.Match(MCD_T("head")) )
break;
}
else if ( nTypeFound == MNT_ELEMENT )
{
token.m_nNext = node.nStart + 1; // after <
token.FindName();
if ( ! bHtml )
{
if ( ! token.Match(MCD_T("html")) )
break;
bHtml = true;
}
else if ( token.Match(MCD_T("meta")) )
{
// e.g. <META http-equiv=Content-Type content="text/html; charset=UTF-8">
int nAttribOffset = node.nStart + 1;
token.m_nNext = nAttribOffset;
if ( token.FindAttrib(MCD_T("http-equiv")) && token.Match(MCD_T("Content-Type")) )
{
token.m_nNext = nAttribOffset;
if ( token.FindAttrib(MCD_T("content")) )
{
int nContentEndOffset = token.m_nNext;
token.m_nNext = token.m_nL;
while ( token.m_nNext < nContentEndOffset && token.FindName() )
{
if ( token.Match(MCD_T("charset")) && token.FindName() && token.Match(MCD_T("=")) )
{
token.FindName();
strEncoding = token.GetTokenText();
break;
}
}
}
break;
}
}
}
token.m_nNext = nNext;
}
return strEncoding;
}
int CMarkup::GetEncodingCodePage( MCD_CSTR pszEncoding )
{
return x_GetEncodingCodePage( pszEncoding );
}
int CMarkup::FindNode( int nType )
{
// Change current node position only if a node is found
// If nType is 0 find any node, otherwise find node of type nType
// Return type of node or 0 if not found
// Determine where in document to start scanning for node
int nNodeOffset = m_nNodeOffset;
if ( m_nNodeType > MNT_ELEMENT )
{
// By-pass current node
nNodeOffset += m_nNodeLength;
}
else // element or no current main position
{
// Set position to begin looking for node
if ( m_iPos )
{
// After element
nNodeOffset = ELEM(m_iPos).StartAfter();
}
else if ( m_iPosParent )
{
// Immediately after start tag of parent
if ( ELEM(m_iPosParent).IsEmptyElement() )
return 0;
else
nNodeOffset = ELEM(m_iPosParent).StartContent();
}
}
// Get nodes until we find what we're looking for
int nTypeFound = 0;
int iPosNew = m_iPos;
TokenPos token( m_strDoc, m_nDocFlags );
NodePos node;
token.m_nNext = nNodeOffset;
do
{
nNodeOffset = token.m_nNext;
nTypeFound = token.ParseNode( node );
if ( nTypeFound == 0 )
{
// Check if we have reached the end of the parent element
if ( m_iPosParent && nNodeOffset == ELEM(m_iPosParent).StartContent()
+ ELEM(m_iPosParent).ContentLen() )
return 0;
nTypeFound = MNT_LONE_END_TAG; // otherwise it is a lone end tag
}
else if ( nTypeFound < 0 )
{
if ( nTypeFound == -2 ) // end of document
return 0;
// -1 is node error
nTypeFound = MNT_NODE_ERROR;
}
else if ( nTypeFound == MNT_ELEMENT )
{
if ( iPosNew )
iPosNew = ELEM(iPosNew).iElemNext;
else
iPosNew = ELEM(m_iPosParent).iElemChild;
if ( ! iPosNew )
return 0;
if ( ! nType || (nType & nTypeFound) )
{
// Found element node, move position to this element
x_SetPos( m_iPosParent, iPosNew, 0 );
return m_nNodeType;
}
token.m_nNext = ELEM(iPosNew).StartAfter();
}
}
while ( nType && ! (nType & nTypeFound) );
m_iPos = iPosNew;
m_iPosChild = 0;
m_nNodeOffset = node.nStart;
m_nNodeLength = node.nLength;
m_nNodeType = nTypeFound;
MARKUP_SETDEBUGSTATE;
return m_nNodeType;
}
bool CMarkup::RemoveNode()
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
if ( m_iPos || m_nNodeLength )
{
x_RemoveNode( m_iPosParent, m_iPos, m_nNodeType, m_nNodeOffset, m_nNodeLength );
m_iPosChild = 0;
MARKUP_SETDEBUGSTATE;
return true;
}
return false;
}
MCD_STR CMarkup::GetTagName() const
{
// Return the tag name at the current main position
MCD_STR strTagName;
// This method is primarily for elements, however
// it does return something for certain other nodes
if ( m_nNodeLength )
{
switch ( m_nNodeType )
{
case MNT_PROCESSING_INSTRUCTION:
case MNT_LONE_END_TAG:
{
// <?target or </tagname
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = m_nNodeOffset + 2;
if ( token.FindName() )
strTagName = token.GetTokenText();
}
break;
case MNT_COMMENT:
strTagName = MCD_T("#comment");
break;
case MNT_CDATA_SECTION:
strTagName = MCD_T("#cdata-section");
break;
case MNT_DOCUMENT_TYPE:
{
// <!DOCTYPE name
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = m_nNodeOffset + 2;
if ( token.FindName() && token.FindName() )
strTagName = token.GetTokenText();
}
break;
case MNT_TEXT:
case MNT_WHITESPACE:
strTagName = MCD_T("#text");
break;
}
return strTagName;
}
if ( m_iPos )
strTagName = x_GetTagName( m_iPos );
return strTagName;
}
bool CMarkup::IntoElem()
{
// Make current element the parent
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
{
x_SetPos( m_iPos, m_iPosChild, 0 );
return true;
}
return false;
}
bool CMarkup::OutOfElem()
{
// Go to parent element
if ( m_iPosParent )
{
x_SetPos( ELEM(m_iPosParent).iElemParent, m_iPosParent, m_iPos );
return true;
}
return false;
}
MCD_STR CMarkup::GetAttribName( int n ) const
{
// Return nth attribute name of main position
TokenPos token( m_strDoc, m_nDocFlags );
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
token.m_nNext = ELEM(m_iPos).nStart + 1;
else if ( m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
token.m_nNext = m_nNodeOffset + 2;
else
return MCD_T("");
if ( token.FindAttrib(NULL,n) )
return token.GetTokenText();
return MCD_T("");
}
bool CMarkup::SavePos( MCD_CSTR szPosName /*=""*/, int nMap /*=0*/ )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Save current element position in saved position map
if ( szPosName )
{
SavedPosMap* pMap;
m_pSavedPosMaps->GetMap( pMap, nMap );
SavedPos savedpos;
if ( szPosName )
savedpos.strName = szPosName;
if ( m_iPosChild )
{
savedpos.iPos = m_iPosChild;
savedpos.nSavedPosFlags |= SavedPos::SPM_CHILD;
}
else if ( m_iPos )
{
savedpos.iPos = m_iPos;
savedpos.nSavedPosFlags |= SavedPos::SPM_MAIN;
}
else
{
savedpos.iPos = m_iPosParent;
}
savedpos.nSavedPosFlags |= SavedPos::SPM_USED;
int nSlot = x_Hash( szPosName, pMap->nMapSize);
SavedPos* pSavedPos = pMap->pTable[nSlot];
int nOffset = 0;
if ( ! pSavedPos )
{
pSavedPos = new SavedPos[2];
pSavedPos[1].nSavedPosFlags = SavedPos::SPM_LAST;
pMap->pTable[nSlot] = pSavedPos;
}
else
{
while ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
{
if ( pSavedPos[nOffset].strName == (MCD_PCSZ)szPosName )
break;
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
{
int nNewSize = (nOffset + 6) * 2;
SavedPos* pNewSavedPos = new SavedPos[nNewSize];
for ( int nCopy=0; nCopy<=nOffset; ++nCopy )
pNewSavedPos[nCopy] = pSavedPos[nCopy];
pNewSavedPos[nOffset].nSavedPosFlags ^= SavedPos::SPM_LAST;
pNewSavedPos[nNewSize-1].nSavedPosFlags = SavedPos::SPM_LAST;
delete [] pSavedPos;
pSavedPos = pNewSavedPos;
pMap->pTable[nSlot] = pSavedPos;
++nOffset;
break;
}
++nOffset;
}
}
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
savedpos.nSavedPosFlags |= SavedPos::SPM_LAST;
pSavedPos[nOffset] = savedpos;
/*
// To review hash table balance, uncomment and watch strBalance
MCD_STR strBalance, strSlot;
for ( nSlot=0; nSlot < pMap->nMapSize; ++nSlot )
{
pSavedPos = pMap->pTable[nSlot];
int nCount = 0;
while ( pSavedPos && pSavedPos->nSavedPosFlags & SavedPos::SPM_USED )
{
++nCount;
if ( pSavedPos->nSavedPosFlags & SavedPos::SPM_LAST )
break;
++pSavedPos;
}
strSlot.Format( MCD_T("%d "), nCount );
strBalance += strSlot;
}
*/
return true;
}
return false;
}
bool CMarkup::RestorePos( MCD_CSTR szPosName /*=""*/, int nMap /*=0*/ )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Restore element position if found in saved position map
if ( szPosName )
{
SavedPosMap* pMap;
m_pSavedPosMaps->GetMap( pMap, nMap );
int nSlot = x_Hash( szPosName, pMap->nMapSize );
SavedPos* pSavedPos = pMap->pTable[nSlot];
if ( pSavedPos )
{
int nOffset = 0;
while ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
{
if ( pSavedPos[nOffset].strName == (MCD_PCSZ)szPosName )
{
int i = pSavedPos[nOffset].iPos;
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_CHILD )
x_SetPos( ELEM(ELEM(i).iElemParent).iElemParent, ELEM(i).iElemParent, i );
else if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_MAIN )
x_SetPos( ELEM(i).iElemParent, i, 0 );
else
x_SetPos( i, 0, 0 );
return true;
}
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
break;
++nOffset;
}
}
}
return false;
}
bool CMarkup::SetMapSize( int nSize, int nMap /*=0*/ )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Set saved position map hash table size before using it
// Returns false if map already exists
// Some prime numbers: 53, 101, 211, 503, 1009, 2003, 10007, 20011, 50021, 100003, 200003, 500009
SavedPosMap* pNewMap;
return m_pSavedPosMaps->GetMap( pNewMap, nMap, nSize );
}
bool CMarkup::RemoveElem()
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Remove current main position element
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
{
int iPos = x_RemoveElem( m_iPos );
x_SetPos( m_iPosParent, iPos, 0 );
return true;
}
return false;
}
bool CMarkup::RemoveChildElem()
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Remove current child position element
if ( m_iPosChild )
{
int iPosChild = x_RemoveElem( m_iPosChild );
x_SetPos( m_iPosParent, m_iPos, iPosChild );
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
// CMarkup private methods
//
void CMarkup::x_InitMarkup()
{
// Only called from CMarkup constructors
m_pFilePos = NULL;
m_pSavedPosMaps = new SavedPosMapArray;
m_pElemPosTree = new ElemPosTree;
// To always ignore case, define MARKUP_IGNORECASE
#if defined(MARKUP_IGNORECASE) // ignore case
m_nDocFlags = MDF_IGNORECASE;
#else // not ignore case
m_nDocFlags = 0;
#endif // not ignore case
}
int CMarkup::x_GetParent( int i )
{
return ELEM(i).iElemParent;
}
void CMarkup::x_SetPos( int iPosParent, int iPos, int iPosChild )
{
m_iPosParent = iPosParent;
m_iPos = iPos;
m_iPosChild = iPosChild;
m_nNodeOffset = 0;
m_nNodeLength = 0;
m_nNodeType = iPos?MNT_ELEMENT:0;
MARKUP_SETDEBUGSTATE;
}
#if defined(_DEBUG) // DEBUG
void CMarkup::x_SetDebugState()
{
// Set m_pDebugCur and m_pDebugPos to point into document
MCD_PCSZ pD = MCD_2PCSZ(m_strDoc);
// Node (non-element) position is determined differently in file mode
if ( m_nNodeLength || (m_nNodeOffset && !m_pFilePos)
|| (m_pFilePos && (!m_iPos) && (!m_iPosParent) && ! m_pFilePos->FileAtTop()) )
{
if ( ! m_nNodeLength )
m_pDebugCur = MCD_T("main position offset"); // file mode only
else
m_pDebugCur = MCD_T("main position node");
m_pDebugPos = &pD[m_nNodeOffset];
}
else
{
if ( m_iPosChild )
{
m_pDebugCur = MCD_T("child position element");
m_pDebugPos = &pD[ELEM(m_iPosChild).nStart];
}
else if ( m_iPos )
{
m_pDebugCur = MCD_T("main position element");
m_pDebugPos = &pD[ELEM(m_iPos).nStart];
}
else if ( m_iPosParent )
{
m_pDebugCur = MCD_T("parent position element");
m_pDebugPos = &pD[ELEM(m_iPosParent).nStart];
}
else
{
m_pDebugCur = MCD_T("top of document");
m_pDebugPos = pD;
}
}
}
#endif // DEBUG
int CMarkup::x_GetFreePos()
{
if ( m_iPosFree == m_pElemPosTree->GetSize() )
x_AllocElemPos();
return m_iPosFree++;
}
bool CMarkup::x_AllocElemPos( int nNewSize /*=0*/ )
{
// Resize m_aPos when the document is created or the array is filled
if ( ! nNewSize )
nNewSize = m_iPosFree + (m_iPosFree>>1); // Grow By: multiply size by 1.5
if ( m_pElemPosTree->GetSize() < nNewSize )
m_pElemPosTree->GrowElemPosTree( nNewSize );
return true;
}
bool CMarkup::x_ParseDoc()
{
// Reset indexes
ResetPos();
m_pSavedPosMaps->ReleaseMaps();
// Starting size of position array: 1 element per 64 bytes of document
// Tight fit when parsing small doc, only 0 to 2 reallocs when parsing large doc
// Start at 8 when creating new document
int nDocLen = MCD_STRLENGTH(m_strDoc);
m_iPosFree = 1;
x_AllocElemPos( nDocLen / 64 + 8 );
m_iPosDeleted = 0;
// Parse document
ELEM(0).ClearVirtualParent();
if ( nDocLen )
{
TokenPos token( m_strDoc, m_nDocFlags );
int iPos = x_ParseElem( 0, token );
ELEM(0).nLength = nDocLen;
if ( iPos > 0 )
{
ELEM(0).iElemChild = iPos;
if ( ELEM(iPos).iElemNext )
x_AddResult( m_strResult, MCD_T("root_has_sibling") );
}
else
x_AddResult( m_strResult, MCD_T("no_root_element") );
}
ResetPos();
return IsWellFormed();
}
int CMarkup::x_ParseElem( int iPosParent, TokenPos& token )
{
// This is either called by x_ParseDoc or x_AddSubDoc or x_SetElemContent
// Returns index of the first element encountered or zero if no elements
//
int iPosRoot = 0;
int iPos = iPosParent;
int iVirtualParent = iPosParent;
int nRootDepth = ELEM(iPos).Level();
int nMatchLevel;
int iPosMatch;
int iTag;
int nTypeFound;
int iPosFirst;
int iPosLast;
ElemPos* pElem;
ElemPos* pElemParent;
ElemPos* pElemChild;
// Loop through the nodes of the document
ElemStack elemstack;
NodePos node;
token.m_nNext = 0;
while ( 1 )
{
nTypeFound = token.ParseNode( node );
nMatchLevel = 0;
if ( nTypeFound == MNT_ELEMENT ) // start tag
{
iPos = x_GetFreePos();
if ( ! iPosRoot )
iPosRoot = iPos;
pElem = &ELEM(iPos);
pElem->iElemParent = iPosParent;
pElem->iElemNext = 0;
pElemParent = &ELEM(iPosParent);
if ( pElemParent->iElemChild )
{
iPosFirst = pElemParent->iElemChild;
pElemChild = &ELEM(iPosFirst);
iPosLast = pElemChild->iElemPrev;
ELEM(iPosLast).iElemNext = iPos;
pElem->iElemPrev = iPosLast;
pElemChild->iElemPrev = iPos;
pElem->nFlags = 0;
}
else
{
pElemParent->iElemChild = iPos;
pElem->iElemPrev = iPos;
pElem->nFlags = MNF_FIRST;
}
pElem->SetLevel( nRootDepth + elemstack.iTop );
pElem->iElemChild = 0;
pElem->nStart = node.nStart;
pElem->SetStartTagLen( node.nLength );
if ( node.nNodeFlags & MNF_EMPTY )
{
iPos = iPosParent;
pElem->SetEndTagLen( 0 );
pElem->nLength = node.nLength;
}
else
{
iPosParent = iPos;
elemstack.PushIntoLevel( token.GetTokenPtr(), token.Length() );
}
}
else if ( nTypeFound == 0 ) // end tag
{
iPosMatch = iPos;
iTag = elemstack.iTop;
nMatchLevel = iTag;
while ( nMatchLevel && ! token.Match(elemstack.GetRefTagPosAt(iTag--).strTagName) )
{
--nMatchLevel;
iPosMatch = ELEM(iPosMatch).iElemParent;
}
if ( nMatchLevel == 0 )
{
// Not matched at all, it is a lone end tag, a non-element node
ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
ELEM(iPos).nFlags |= MNF_ILLDATA;
x_AddResult( m_strResult, MCD_T("lone_end_tag"), token.GetTokenText(), 0, node.nStart );
}
else
{
pElem = &ELEM(iPosMatch);
pElem->nLength = node.nStart - pElem->nStart + node.nLength;
pElem->SetEndTagLen( node.nLength );
}
}
else if ( nTypeFound == -1 )
{
ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
ELEM(iPos).nFlags |= MNF_ILLDATA;
m_strResult += node.strMeta;
}
// Matched end tag, or end of document
if ( nMatchLevel || nTypeFound == -2 )
{
if ( elemstack.iTop > nMatchLevel )
ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
// Process any non-ended elements
while ( elemstack.iTop > nMatchLevel )
{
// Element with no end tag
pElem = &ELEM(iPos);
int iPosChild = pElem->iElemChild;
iPosParent = pElem->iElemParent;
pElem->SetEndTagLen( 0 );
pElem->nFlags |= MNF_NONENDED;
pElem->iElemChild = 0;
pElem->nLength = pElem->StartTagLen();
if ( pElem->nFlags & MNF_ILLDATA )
{
pElem->nFlags ^= MNF_ILLDATA;
ELEM(iPosParent).nFlags |= MNF_ILLDATA;
}
while ( iPosChild )
{
ELEM(iPosChild).iElemParent = iPosParent;
ELEM(iPosChild).iElemPrev = iPos;
ELEM(iPos).iElemNext = iPosChild;
iPos = iPosChild;
iPosChild = ELEM(iPosChild).iElemNext;
}
// If end tag did not match, top node is end tag that did not match pElem
// if end of document, any nodes below top have no end tag
// second offset represents location where end tag was expected but end of document or other end tag was found
// end tag that was found is token.GetTokenText() but not reported in error
int nOffset2 = (nTypeFound==0)? token.m_nL-1: MCD_STRLENGTH(m_strDoc);
x_AddResult( m_strResult, MCD_T("unended_start_tag"), elemstack.Current().strTagName, 0, pElem->nStart, nOffset2 );
iPos = iPosParent;
elemstack.PopOutOfLevel();
}
if ( nTypeFound == -2 )
break;
iPosParent = ELEM(iPos).iElemParent;
iPos = iPosParent;
elemstack.PopOutOfLevel();
}
}
return iPosRoot;
}
int CMarkup::x_FindElem( int iPosParent, int iPos, PathPos& path ) const
{
// If pPath is NULL or empty, go to next sibling element
// Otherwise go to next sibling element with matching path
//
if ( ! path.ValidPath() )
return 0;
// Paths other than simple tag name are only supported in the developer version
if ( path.IsAnywherePath() || path.IsAbsolutePath() )
return 0;
if ( iPos )
iPos = ELEM(iPos).iElemNext;
else
iPos = ELEM(iPosParent).iElemChild;
// Finished here if pPath not specified
if ( ! path.IsPath() )
return iPos;
// Search
TokenPos token( m_strDoc, m_nDocFlags );
while ( iPos )
{
// Compare tag name
token.m_nNext = ELEM(iPos).nStart + 1;
token.FindName(); // Locate tag name
if ( token.Match(path.GetPtr()) )
return iPos;
iPos = ELEM(iPos).iElemNext;
}
return 0;
}
MCD_STR CMarkup::x_GetPath( int iPos ) const
{
// In file mode, iPos is an index into m_pFilePos->m_elemstack or zero
MCD_STR strPath;
while ( iPos )
{
MCD_STR strTagName;
int iPosParent;
int nCount = 0;
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
{
TagPos& tag = m_pFilePos->m_elemstack.GetRefTagPosAt(iPos);
strTagName = tag.strTagName;
nCount = tag.nCount;
iPosParent = tag.iParent;
}
else
{
strTagName = x_GetTagName( iPos );
PathPos path( MCD_2PCSZ(strTagName), false );
iPosParent = ELEM(iPos).iElemParent;
int iPosSib = 0;
while ( iPosSib != iPos )
{
path.RevertOffset();
iPosSib = x_FindElem( iPosParent, iPosSib, path );
++nCount;
}
}
if ( nCount == 1 )
strPath = MCD_T("/") + strTagName + strPath;
else
{
MCD_CHAR szPred[25];
MCD_SPRINTF( MCD_SSZ(szPred), MCD_T("[%d]"), nCount );
strPath = MCD_T("/") + strTagName + szPred + strPath;
}
iPos = iPosParent;
}
return strPath;
}
MCD_STR CMarkup::x_GetTagName( int iPos ) const
{
// Return the tag name at specified element
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = ELEM(iPos).nStart + 1;
if ( ! iPos || ! token.FindName() )
return MCD_T("");
// Return substring of document
return token.GetTokenText();
}
MCD_STR CMarkup::x_GetAttrib( int iPos, MCD_PCSZ pAttrib ) const
{
// Return the value of the attrib
TokenPos token( m_strDoc, m_nDocFlags );
if ( iPos && m_nNodeType == MNT_ELEMENT )
token.m_nNext = ELEM(iPos).nStart + 1;
else if ( iPos == m_iPos && m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
token.m_nNext = m_nNodeOffset + 2;
else
return MCD_T("");
if ( pAttrib && token.FindAttrib(pAttrib) )
return UnescapeText( token.GetTokenPtr(), token.Length() );
return MCD_T("");
}
bool CMarkup::x_SetAttrib( int iPos, MCD_PCSZ pAttrib, int nValue, int nFlags /*=0*/ )
{
// Convert integer to string
MCD_CHAR szVal[25];
MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
return x_SetAttrib( iPos, pAttrib, szVal, nFlags );
}
bool CMarkup::x_SetAttrib( int iPos, MCD_PCSZ pAttrib, MCD_PCSZ pValue, int nFlags /*=0*/ )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
int nNodeStart = 0;
if ( iPos && m_nNodeType == MNT_ELEMENT )
nNodeStart = ELEM(iPos).nStart;
else if ( iPos == m_iPos && m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
nNodeStart = m_nNodeOffset;
else
return false;
// Create insertion text depending on whether attribute already exists
// Decision: for empty value leaving attrib="" instead of removing attrib
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = nNodeStart + ((m_nNodeType == MNT_ELEMENT)?1:2);
int nReplace = 0;
int nInsertAt;
MCD_STR strEscapedValue = EscapeText( pValue, MNF_ESCAPEQUOTES|nFlags );
int nEscapedValueLen = MCD_STRLENGTH( strEscapedValue );
MCD_STR strInsert;
if ( token.FindAttrib(pAttrib) )
{
// Replace value
MCD_BLDRESERVE( strInsert, nEscapedValueLen + 2 );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDAPPENDN( strInsert, MCD_2PCSZ(strEscapedValue), nEscapedValueLen );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDRELEASE( strInsert );
nInsertAt = token.m_nL - ((token.m_nTokenFlags&MNF_QUOTED)?1:0);
nReplace = token.Length() + ((token.m_nTokenFlags&MNF_QUOTED)?2:0);
}
else
{
// Insert string name value pair
int nAttribNameLen = MCD_PSZLEN( pAttrib );
MCD_BLDRESERVE( strInsert, nAttribNameLen + nEscapedValueLen + 4 );
MCD_BLDAPPEND1( strInsert, ' ' );
MCD_BLDAPPENDN( strInsert, pAttrib, nAttribNameLen );
MCD_BLDAPPEND1( strInsert, '=' );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDAPPENDN( strInsert, MCD_2PCSZ(strEscapedValue), nEscapedValueLen );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDRELEASE( strInsert );
nInsertAt = token.m_nNext;
}
int nAdjust = MCD_STRLENGTH(strInsert) - nReplace;
if ( m_nDocFlags & MDF_WRITEFILE )
{
int nNewDocLength = MCD_STRLENGTH(m_strDoc) + nAdjust;
MCD_STRCLEAR( m_strResult );
if ( nNodeStart && nNewDocLength > m_pFilePos->m_nBlockSizeBasis )
{
int nDocCapacity = MCD_STRCAPACITY(m_strDoc);
if ( nNewDocLength > nDocCapacity )
{
m_pFilePos->FileFlush( *m_pFilePos->m_pstrBuffer, nNodeStart );
m_strResult = m_pFilePos->m_strIOResult;
nInsertAt -= nNodeStart;
m_nNodeOffset = 0;
if ( m_nNodeType == MNT_ELEMENT )
ELEM(iPos).nStart = 0;
}
}
}
x_DocChange( nInsertAt, nReplace, strInsert );
if ( m_nNodeType == MNT_PROCESSING_INSTRUCTION )
{
x_AdjustForNode( m_iPosParent, m_iPos, nAdjust );
m_nNodeLength += nAdjust;
}
else
{
ELEM(iPos).AdjustStartTagLen( nAdjust );
ELEM(iPos).nLength += nAdjust;
x_Adjust( iPos, nAdjust );
}
MARKUP_SETDEBUGSTATE;
return true;
}
bool CMarkup::x_CreateNode( MCD_STR& strNode, int nNodeType, MCD_PCSZ pText )
{
// Set strNode based on nNodeType and szData
// Return false if szData would jeopardize well-formed document
//
switch ( nNodeType )
{
case MNT_PROCESSING_INSTRUCTION:
strNode = MCD_T("<?");
strNode += pText;
strNode += MCD_T("?>");
break;
case MNT_COMMENT:
strNode = MCD_T("<!--");
strNode += pText;
strNode += MCD_T("-->");
break;
case MNT_ELEMENT:
strNode = MCD_T("<");
strNode += pText;
strNode += MCD_T("/>");
break;
case MNT_TEXT:
case MNT_WHITESPACE:
strNode = EscapeText( pText );
break;
case MNT_DOCUMENT_TYPE:
strNode = pText;
break;
case MNT_LONE_END_TAG:
strNode = MCD_T("</");
strNode += pText;
strNode += MCD_T(">");
break;
case MNT_CDATA_SECTION:
if ( MCD_PSZSTR(pText,MCD_T("]]>")) != NULL )
return false;
strNode = MCD_T("<![CDATA[");
strNode += pText;
strNode += MCD_T("]]>");
break;
}
return true;
}
MCD_STR CMarkup::x_EncodeCDATASection( MCD_PCSZ szData )
{
// Split CDATA Sections if there are any end delimiters
MCD_STR strData = MCD_T("<![CDATA[");
MCD_PCSZ pszNextStart = szData;
MCD_PCSZ pszEnd = MCD_PSZSTR( szData, MCD_T("]]>") );
while ( pszEnd )
{
strData += MCD_STR( pszNextStart, (int)(pszEnd - pszNextStart) );
strData += MCD_T("]]]]><![CDATA[>");
pszNextStart = pszEnd + 3;
pszEnd = MCD_PSZSTR( pszNextStart, MCD_T("]]>") );
}
strData += pszNextStart;
strData += MCD_T("]]>");
return strData;
}
bool CMarkup::x_SetData( int iPos, int nValue )
{
// Convert integer to string
MCD_CHAR szVal[25];
MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
return x_SetData( iPos, szVal, 0 );
}
bool CMarkup::x_SetData( int iPos, MCD_PCSZ szData, int nFlags )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
MCD_STR strInsert;
if ( m_nDocFlags & MDF_WRITEFILE )
{
if ( ! iPos || m_nNodeType != 1 || ! ELEM(iPos).IsEmptyElement() )
return false; // only set data on current empty element (no other kinds of nodes)
}
if ( iPos == m_iPos && m_nNodeLength )
{
// Not an element
if ( ! x_CreateNode(strInsert, m_nNodeType, szData) )
return false;
x_DocChange( m_nNodeOffset, m_nNodeLength, strInsert );
x_AdjustForNode( m_iPosParent, iPos, MCD_STRLENGTH(strInsert) - m_nNodeLength );
m_nNodeLength = MCD_STRLENGTH(strInsert);
MARKUP_SETDEBUGSTATE;
return true;
}
// Set data in iPos element
if ( ! iPos || ELEM(iPos).iElemChild )
return false;
// Build strInsert from szData based on nFlags
if ( nFlags & MNF_WITHCDATA )
strInsert = x_EncodeCDATASection( szData );
else
strInsert = EscapeText( szData, nFlags );
// Insert
NodePos node( MNF_WITHNOLINES|MNF_REPLACE );
node.strMeta = strInsert;
int iPosBefore = 0;
int nReplace = x_InsertNew( iPos, iPosBefore, node );
int nAdjust = MCD_STRLENGTH(node.strMeta) - nReplace;
x_Adjust( iPos, nAdjust );
ELEM(iPos).nLength += nAdjust;
if ( ELEM(iPos).nFlags & MNF_ILLDATA )
ELEM(iPos).nFlags &= ~MNF_ILLDATA;
MARKUP_SETDEBUGSTATE;
return true;
}
MCD_STR CMarkup::x_GetData( int iPos )
{
if ( iPos == m_iPos && m_nNodeLength )
{
if ( m_nNodeType == MNT_COMMENT )
return MCD_STRMID( m_strDoc, m_nNodeOffset+4, m_nNodeLength-7 );
else if ( m_nNodeType == MNT_PROCESSING_INSTRUCTION )
return MCD_STRMID( m_strDoc, m_nNodeOffset+2, m_nNodeLength-4 );
else if ( m_nNodeType == MNT_CDATA_SECTION )
return MCD_STRMID( m_strDoc, m_nNodeOffset+9, m_nNodeLength-12 );
else if ( m_nNodeType == MNT_TEXT )
return UnescapeText( &(MCD_2PCSZ(m_strDoc))[m_nNodeOffset], m_nNodeLength );
else if ( m_nNodeType == MNT_LONE_END_TAG )
return MCD_STRMID( m_strDoc, m_nNodeOffset+2, m_nNodeLength-3 );
return MCD_STRMID( m_strDoc, m_nNodeOffset, m_nNodeLength );
}
// Return a string representing data between start and end tag
// Return empty string if there are any children elements
MCD_STR strData;
if ( iPos && ! ELEM(iPos).IsEmptyElement() )
{
ElemPos* pElem = &ELEM(iPos);
int nStartContent = pElem->StartContent();
if ( pElem->IsUnparsed() )
{
TokenPos token( m_strDoc, m_nDocFlags, m_pFilePos );
token.m_nNext = nStartContent;
NodePos node;
m_pFilePos->m_nReadBufferStart = pElem->nStart;
while ( 1 )
{
m_pFilePos->m_nReadBufferRemoved = 0; // will be non-zero after ParseNode if read buffer shifted
token.ParseNode( node );
if ( m_pFilePos->m_nReadBufferRemoved )
{
pElem->nStart = 0;
MARKUP_SETDEBUGSTATE;
}
if ( node.nNodeType == MNT_TEXT )
strData += UnescapeText( &token.m_pDocText[node.nStart], node.nLength );
else if ( node.nNodeType == MNT_CDATA_SECTION )
strData += MCD_STRMID( m_strDoc, node.nStart+9, node.nLength-12 );
else if ( node.nNodeType == MNT_ELEMENT )
{
MCD_STRCLEAR(strData);
break;
}
else if ( node.nNodeType == 0 )
{
if ( token.Match(m_pFilePos->m_elemstack.Current().strTagName) )
{
pElem->SetEndTagLen( node.nLength );
pElem->nLength = node.nStart + node.nLength - pElem->nStart;
m_pFilePos->m_elemstack.OutOfLevel();
}
else
{
MCD_STRCLEAR(strData);
}
break;
}
}
}
else if ( ! pElem->iElemChild )
{
// Quick scan for any tags inside content
int nContentLen = pElem->ContentLen();
MCD_PCSZ pszContent = &(MCD_2PCSZ(m_strDoc))[nStartContent];
MCD_PCSZ pszTag = MCD_PSZCHR( pszContent, '<' );
if ( pszTag && ((int)(pszTag-pszContent) < nContentLen) )
{
// Concatenate all CDATA Sections and text nodes, ignore other nodes
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = nStartContent;
NodePos node;
while ( token.m_nNext < nStartContent + nContentLen )
{
token.ParseNode( node );
if ( node.nNodeType == MNT_TEXT )
strData += UnescapeText( &token.m_pDocText[node.nStart], node.nLength );
else if ( node.nNodeType == MNT_CDATA_SECTION )
strData += MCD_STRMID( m_strDoc, node.nStart+9, node.nLength-12 );
}
}
else // no tags
strData = UnescapeText( &(MCD_2PCSZ(m_strDoc))[nStartContent], nContentLen );
}
}
return strData;
}
MCD_STR CMarkup::x_GetElemContent( int iPos ) const
{
if ( ! (m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) )
{
ElemPos* pElem = &ELEM(iPos);
if ( iPos && pElem->ContentLen() )
return MCD_STRMID( m_strDoc, pElem->StartContent(), pElem->ContentLen() );
}
return MCD_T("");
}
bool CMarkup::x_SetElemContent( MCD_PCSZ szContent )
{
MCD_STRCLEAR(m_strResult);
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Set data in iPos element only
if ( ! m_iPos )
return false;
if ( m_nNodeLength )
return false; // not an element
// Unlink all children
int iPos = m_iPos;
int iPosChild = ELEM(iPos).iElemChild;
bool bHadChild = (iPosChild != 0);
while ( iPosChild )
iPosChild = x_ReleaseSubDoc( iPosChild );
if ( bHadChild )
x_CheckSavedPos();
// Parse content
bool bWellFormed = true;
TokenPos token( szContent, m_nDocFlags );
int iPosVirtual = x_GetFreePos();
ELEM(iPosVirtual).ClearVirtualParent();
ELEM(iPosVirtual).SetLevel( ELEM(iPos).Level() + 1 );
iPosChild = x_ParseElem( iPosVirtual, token );
if ( ELEM(iPosVirtual).nFlags & MNF_ILLFORMED )
bWellFormed = false;
ELEM(iPos).nFlags = (ELEM(iPos).nFlags & ~MNF_ILLDATA) | (ELEM(iPosVirtual).nFlags & MNF_ILLDATA);
// Prepare insert and adjust offsets
NodePos node( MNF_WITHNOLINES|MNF_REPLACE );
node.strMeta = szContent;
int iPosBefore = 0;
int nReplace = x_InsertNew( iPos, iPosBefore, node );
// Adjust and link in the inserted elements
x_Adjust( iPosChild, node.nStart );
ELEM(iPosChild).nStart += node.nStart;
ELEM(iPos).iElemChild = iPosChild;
while ( iPosChild )
{
ELEM(iPosChild).iElemParent = iPos;
iPosChild = ELEM(iPosChild).iElemNext;
}
x_ReleasePos( iPosVirtual );
int nAdjust = MCD_STRLENGTH(node.strMeta) - nReplace;
x_Adjust( iPos, nAdjust, true );
ELEM(iPos).nLength += nAdjust;
x_SetPos( m_iPosParent, m_iPos, 0 );
return bWellFormed;
}
void CMarkup::x_DocChange( int nLeft, int nReplace, const MCD_STR& strInsert )
{
x_StrInsertReplace( m_strDoc, nLeft, nReplace, strInsert );
}
void CMarkup::x_Adjust( int iPos, int nShift, bool bAfterPos /*=false*/ )
{
// Loop through affected elements and adjust indexes
// Algorithm:
// 1. update children unless bAfterPos
// (if no children or bAfterPos is true, length of iPos not affected)
// 2. update starts of next siblings and their children
// 3. go up until there is a next sibling of a parent and update starts
// 4. step 2
int iPosTop = ELEM(iPos).iElemParent;
bool bPosFirst = bAfterPos; // mark as first to skip its children
// Stop when we've reached the virtual parent (which has no tags)
while ( ELEM(iPos).StartTagLen() )
{
// Were we at containing parent of affected position?
bool bPosTop = false;
if ( iPos == iPosTop )
{
// Move iPosTop up one towards root
iPosTop = ELEM(iPos).iElemParent;
bPosTop = true;
}
// Traverse to the next update position
if ( ! bPosTop && ! bPosFirst && ELEM(iPos).iElemChild )
{
// Depth first
iPos = ELEM(iPos).iElemChild;
}
else if ( ELEM(iPos).iElemNext )
{
iPos = ELEM(iPos).iElemNext;
}
else
{
// Look for next sibling of a parent of iPos
// When going back up, parents have already been done except iPosTop
while ( 1 )
{
iPos = ELEM(iPos).iElemParent;
if ( iPos == iPosTop )
break;
if ( ELEM(iPos).iElemNext )
{
iPos = ELEM(iPos).iElemNext;
break;
}
}
}
bPosFirst = false;
// Shift indexes at iPos
if ( iPos != iPosTop )
ELEM(iPos).nStart += nShift;
else
ELEM(iPos).nLength += nShift;
}
}
int CMarkup::x_InsertNew( int iPosParent, int& iPosRel, NodePos& node )
{
// Parent empty tag or tags with no content?
bool bEmptyParentTag = iPosParent && ELEM(iPosParent).IsEmptyElement();
bool bNoContentParentTags = iPosParent && ! ELEM(iPosParent).ContentLen();
if ( iPosRel && ! node.nLength ) // current position element?
{
node.nStart = ELEM(iPosRel).nStart;
if ( ! (node.nNodeFlags & MNF_INSERT) ) // follow iPosRel
node.nStart += ELEM(iPosRel).nLength;
}
else if ( bEmptyParentTag ) // parent has no separate end tag?
{
// Split empty parent element
if ( ELEM(iPosParent).nFlags & MNF_NONENDED )
node.nStart = ELEM(iPosParent).StartContent();
else
node.nStart = ELEM(iPosParent).StartContent() - 1;
}
else if ( node.nLength || (m_nDocFlags&MDF_WRITEFILE) ) // non-element node or a file mode zero length position?
{
if ( ! (node.nNodeFlags & MNF_INSERT) )
node.nStart += node.nLength; // after node or file mode position
}
else // no current node
{
// Insert relative to parent's content
if ( node.nNodeFlags & (MNF_INSERT|MNF_REPLACE) )
node.nStart = ELEM(iPosParent).StartContent(); // beginning of parent's content
else // in front of parent's end tag
node.nStart = ELEM(iPosParent).StartAfter() - ELEM(iPosParent).EndTagLen();
}
// Go up to start of next node, unless its splitting an empty element
if ( ! (node.nNodeFlags&(MNF_WITHNOLINES|MNF_REPLACE)) && ! bEmptyParentTag )
{
TokenPos token( m_strDoc, m_nDocFlags );
node.nStart = token.WhitespaceToTag( node.nStart );
}
// Is insert relative to element position? (i.e. not other kind of node)
if ( ! node.nLength )
{
// Modify iPosRel to reflect position before
if ( iPosRel )
{
if ( node.nNodeFlags & MNF_INSERT )
{
if ( ! (ELEM(iPosRel).nFlags & MNF_FIRST) )
iPosRel = ELEM(iPosRel).iElemPrev;
else
iPosRel = 0;
}
}
else if ( ! (node.nNodeFlags & MNF_INSERT) )
{
// If parent has a child, add after last child
if ( ELEM(iPosParent).iElemChild )
iPosRel = ELEM(ELEM(iPosParent).iElemChild).iElemPrev;
}
}
// Get node length (needed for x_AddNode and x_AddSubDoc in file write mode)
node.nLength = MCD_STRLENGTH(node.strMeta);
// Prepare end of lines
if ( (! (node.nNodeFlags & MNF_WITHNOLINES)) && (bEmptyParentTag || bNoContentParentTags) )
node.nStart += x_EOLLEN;
if ( ! (node.nNodeFlags & MNF_WITHNOLINES) )
node.strMeta += x_EOL;
// Calculate insert offset and replace length
int nReplace = 0;
int nInsertAt = node.nStart;
if ( bEmptyParentTag )
{
MCD_STR strTagName = x_GetTagName( iPosParent );
MCD_STR strFormat;
if ( node.nNodeFlags & MNF_WITHNOLINES )
strFormat = MCD_T(">");
else
strFormat = MCD_T(">") x_EOL;
strFormat += node.strMeta;
strFormat += MCD_T("</");
strFormat += strTagName;
node.strMeta = strFormat;
if ( ELEM(iPosParent).nFlags & MNF_NONENDED )
{
nInsertAt = ELEM(iPosParent).StartAfter() - 1;
nReplace = 0;
ELEM(iPosParent).nFlags ^= MNF_NONENDED;
}
else
{
nInsertAt = ELEM(iPosParent).StartAfter() - 2;
nReplace = 1;
ELEM(iPosParent).AdjustStartTagLen( -1 );
}
ELEM(iPosParent).SetEndTagLen( 3 + MCD_STRLENGTH(strTagName) );
}
else
{
if ( node.nNodeFlags & MNF_REPLACE )
{
nInsertAt = ELEM(iPosParent).StartContent();
nReplace = ELEM(iPosParent).ContentLen();
}
else if ( bNoContentParentTags )
{
node.strMeta = x_EOL + node.strMeta;
nInsertAt = ELEM(iPosParent).StartContent();
}
}
if ( m_nDocFlags & MDF_WRITEFILE )
{
// Check if buffer is full
int nNewDocLength = MCD_STRLENGTH(m_strDoc) + MCD_STRLENGTH(node.strMeta) - nReplace;
int nFlushTo = node.nStart;
MCD_STRCLEAR( m_strResult );
if ( bEmptyParentTag )
nFlushTo = ELEM(iPosParent).nStart;
if ( nFlushTo && nNewDocLength > m_pFilePos->m_nBlockSizeBasis )
{
int nDocCapacity = MCD_STRCAPACITY(m_strDoc);
if ( nNewDocLength > nDocCapacity )
{
if ( bEmptyParentTag )
ELEM(iPosParent).nStart = 0;
node.nStart -= nFlushTo;
nInsertAt -= nFlushTo;
m_pFilePos->FileFlush( m_strDoc, nFlushTo );
m_strResult = m_pFilePos->m_strIOResult;
}
}
}
x_DocChange( nInsertAt, nReplace, node.strMeta );
return nReplace;
}
bool CMarkup::x_AddElem( MCD_PCSZ pName, int nValue, int nFlags )
{
// Convert integer to string
MCD_CHAR szVal[25];
MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
return x_AddElem( pName, szVal, nFlags );
}
bool CMarkup::x_AddElem( MCD_PCSZ pName, MCD_PCSZ pValue, int nFlags )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
if ( nFlags & MNF_CHILD )
{
// Adding a child element under main position
if ( ! m_iPos || (m_nDocFlags & MDF_WRITEFILE) )
return false;
}
// Cannot have data in non-ended element
if ( (nFlags&MNF_WITHNOEND) && pValue && pValue[0] )
return false;
// Node and element structures
NodePos node( nFlags );
int iPosParent = 0, iPosBefore = 0;
int iPos = x_GetFreePos();
ElemPos* pElem = &ELEM(iPos);
// Locate where to add element relative to current node
if ( nFlags & MNF_CHILD )
{
iPosParent = m_iPos;
iPosBefore = m_iPosChild;
}
else
{
iPosParent = m_iPosParent;
iPosBefore = m_iPos;
node.nStart = m_nNodeOffset;
node.nLength = m_nNodeLength;
}
// Create string for insert
// If no pValue is specified, an empty element is created
// i.e. either <NAME>value</NAME> or <NAME/>
//
int nLenName = MCD_PSZLEN(pName);
if ( ! pValue || ! pValue[0] )
{
// <NAME/> empty element
MCD_BLDRESERVE( node.strMeta, nLenName + 4 );
MCD_BLDAPPEND1( node.strMeta, '<' );
MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
if ( nFlags & MNF_WITHNOEND )
{
MCD_BLDAPPEND1( node.strMeta, '>' );
}
else
{
if ( nFlags & MNF_WITHXHTMLSPACE )
{
MCD_BLDAPPENDN( node.strMeta, MCD_T(" />"), 3 );
}
else
{
MCD_BLDAPPENDN( node.strMeta, MCD_T("/>"), 2 );
}
}
MCD_BLDRELEASE( node.strMeta );
pElem->nLength = MCD_STRLENGTH( node.strMeta );
pElem->SetStartTagLen( pElem->nLength );
pElem->SetEndTagLen( 0 );
}
else
{
// <NAME>value</NAME>
MCD_STR strValue;
if ( nFlags & MNF_WITHCDATA )
strValue = x_EncodeCDATASection( pValue );
else
strValue = EscapeText( pValue, nFlags );
int nLenValue = MCD_STRLENGTH(strValue);
pElem->nLength = nLenName * 2 + nLenValue + 5;
MCD_BLDRESERVE( node.strMeta, pElem->nLength );
MCD_BLDAPPEND1( node.strMeta, '<' );
MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
MCD_BLDAPPEND1( node.strMeta, '>' );
MCD_BLDAPPENDN( node.strMeta, MCD_2PCSZ(strValue), nLenValue );
MCD_BLDAPPENDN( node.strMeta, MCD_T("</"), 2 );
MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
MCD_BLDAPPEND1( node.strMeta, '>' );
MCD_BLDRELEASE( node.strMeta );
pElem->SetEndTagLen( nLenName + 3 );
pElem->SetStartTagLen( nLenName + 2 );
}
// Insert
int nReplace = x_InsertNew( iPosParent, iPosBefore, node );
pElem->nStart = node.nStart;
pElem->iElemChild = 0;
if ( nFlags & MNF_WITHNOEND )
pElem->nFlags = MNF_NONENDED;
else
pElem->nFlags = 0;
if ( m_nDocFlags & MDF_WRITEFILE )
{
iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, iPos );
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nL = pElem->nStart + 1;
token.m_nR = pElem->nStart + nLenName;
m_pFilePos->m_elemstack.PushTagAndCount( token );
}
else
{
x_LinkElem( iPosParent, iPosBefore, iPos );
x_Adjust( iPos, MCD_STRLENGTH(node.strMeta) - nReplace );
}
if ( nFlags & MNF_CHILD )
x_SetPos( m_iPosParent, iPosParent, iPos );
else
x_SetPos( iPosParent, iPos, 0 );
return true;
}
MCD_STR CMarkup::x_GetSubDoc( int iPos )
{
if ( iPos && ! (m_nDocFlags&MDF_WRITEFILE) )
{
if ( ! (m_nDocFlags&MDF_READFILE) )
{
TokenPos token( m_strDoc, m_nDocFlags );
token.WhitespaceToTag( ELEM(iPos).StartAfter() );
token.m_nL = ELEM(iPos).nStart;
return token.GetTokenText();
}
}
return MCD_T("");
}
bool CMarkup::x_AddSubDoc( MCD_PCSZ pSubDoc, int nFlags )
{
if ( m_nDocFlags & MDF_READFILE || ((nFlags & MNF_CHILD) && (m_nDocFlags & MDF_WRITEFILE)) )
return false;
MCD_STRCLEAR(m_strResult);
NodePos node( nFlags );
int iPosParent, iPosBefore;
if ( nFlags & MNF_CHILD )
{
// Add a subdocument under main position, before or after child
if ( ! m_iPos )
return false;
iPosParent = m_iPos;
iPosBefore = m_iPosChild;
}
else
{
// Add a subdocument under parent position, before or after main
iPosParent = m_iPosParent;
iPosBefore = m_iPos;
node.nStart = m_nNodeOffset;
node.nLength = m_nNodeLength;
}
// Parse subdocument, generating indexes based on the subdocument string to be offset later
bool bWellFormed = true;
TokenPos token( pSubDoc, m_nDocFlags );
int iPosVirtual = x_GetFreePos();
ELEM(iPosVirtual).ClearVirtualParent();
ELEM(iPosVirtual).SetLevel( ELEM(iPosParent).Level() + 1 );
int iPos = x_ParseElem( iPosVirtual, token );
if ( (!iPos) || ELEM(iPosVirtual).nFlags & MNF_ILLFORMED )
bWellFormed = false;
if ( ELEM(iPosVirtual).nFlags & MNF_ILLDATA )
ELEM(iPosParent).nFlags |= MNF_ILLDATA;
// File write mode handling
bool bBypassSubDoc = false;
if ( m_nDocFlags & MDF_WRITEFILE )
{
// Current position will bypass subdoc unless well-formed single element
if ( (! bWellFormed) || ELEM(iPos).iElemChild || ELEM(iPos).iElemNext )
bBypassSubDoc = true;
// Count tag names of top level elements (usually one) in given markup
int iPosTop = iPos;
while ( iPosTop )
{
token.m_nNext = ELEM(iPosTop).nStart + 1;
token.FindName();
m_pFilePos->m_elemstack.PushTagAndCount( token );
iPosTop = ELEM(iPosTop).iElemNext;
}
}
// Extract subdocument without leading/trailing nodes
int nExtractStart = 0;
int iPosLast = ELEM(iPos).iElemPrev;
if ( bWellFormed )
{
nExtractStart = ELEM(iPos).nStart;
int nExtractLength = ELEM(iPos).nLength;
if ( iPos != iPosLast )
{
nExtractLength = ELEM(iPosLast).nStart - nExtractStart + ELEM(iPosLast).nLength;
bWellFormed = false; // treat as subdoc here, but return not well-formed
}
MCD_STRASSIGN(node.strMeta,&pSubDoc[nExtractStart],nExtractLength);
}
else
{
node.strMeta = pSubDoc;
node.nNodeFlags |= MNF_WITHNOLINES;
}
// Insert
int nReplace = x_InsertNew( iPosParent, iPosBefore, node );
// Clean up indexes
if ( m_nDocFlags & MDF_WRITEFILE )
{
if ( bBypassSubDoc )
{
// Release indexes used in parsing the subdocument
m_iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, 0 );
m_iPosFree = 1;
m_iPosDeleted = 0;
m_iPos = 0;
m_nNodeOffset = node.nStart + node.nLength;
m_nNodeLength = 0;
m_nNodeType = 0;
MARKUP_SETDEBUGSTATE;
return bWellFormed;
}
else // single element added
{
m_iPos = iPos;
ElemPos* pElem = &ELEM(iPos);
pElem->nStart = node.nStart;
m_iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, iPos );
x_ReleasePos( iPosVirtual );
}
}
else
{
// Adjust and link in the inserted elements
// iPosVirtual will stop it from affecting rest of document
int nAdjust = node.nStart - nExtractStart;
if ( iPos && nAdjust )
{
x_Adjust( iPos, nAdjust );
ELEM(iPos).nStart += nAdjust;
}
int iPosChild = iPos;
while ( iPosChild )
{
int iPosNext = ELEM(iPosChild).iElemNext;
x_LinkElem( iPosParent, iPosBefore, iPosChild );
iPosBefore = iPosChild;
iPosChild = iPosNext;
}
x_ReleasePos( iPosVirtual );
// Now adjust remainder of document
x_Adjust( iPosLast, MCD_STRLENGTH(node.strMeta) - nReplace, true );
}
// Set position to top element of subdocument
if ( nFlags & MNF_CHILD )
x_SetPos( m_iPosParent, iPosParent, iPos );
else // Main
x_SetPos( m_iPosParent, iPos, 0 );
return bWellFormed;
}
int CMarkup::x_RemoveElem( int iPos )
{
// Determine whether any whitespace up to next tag
TokenPos token( m_strDoc, m_nDocFlags );
int nAfterEnd = token.WhitespaceToTag( ELEM(iPos).StartAfter() );
// Remove from document, adjust affected indexes, and unlink
int nLen = nAfterEnd - ELEM(iPos).nStart;
x_DocChange( ELEM(iPos).nStart, nLen, MCD_STR() );
x_Adjust( iPos, - nLen, true );
int iPosPrev = x_UnlinkElem( iPos );
x_CheckSavedPos();
return iPosPrev; // new position
}
void CMarkup::x_LinkElem( int iPosParent, int iPosBefore, int iPos )
{
// Update links between elements and initialize nFlags
ElemPos* pElem = &ELEM(iPos);
if ( m_nDocFlags & MDF_WRITEFILE )
{
// In file write mode, only keep virtual parent 0 plus one element
if ( iPosParent )
x_ReleasePos( iPosParent );
else if ( iPosBefore )
x_ReleasePos( iPosBefore );
iPosParent = 0;
ELEM(iPosParent).iElemChild = iPos;
pElem->iElemParent = iPosParent;
pElem->iElemPrev = iPos;
pElem->iElemNext = 0;
pElem->nFlags |= MNF_FIRST;
}
else
{
pElem->iElemParent = iPosParent;
if ( iPosBefore )
{
// Link in after iPosBefore
pElem->nFlags &= ~MNF_FIRST;
pElem->iElemNext = ELEM(iPosBefore).iElemNext;
if ( pElem->iElemNext )
ELEM(pElem->iElemNext).iElemPrev = iPos;
else
ELEM(ELEM(iPosParent).iElemChild).iElemPrev = iPos;
ELEM(iPosBefore).iElemNext = iPos;
pElem->iElemPrev = iPosBefore;
}
else
{
// Link in as first child
pElem->nFlags |= MNF_FIRST;
if ( ELEM(iPosParent).iElemChild )
{
pElem->iElemNext = ELEM(iPosParent).iElemChild;
pElem->iElemPrev = ELEM(pElem->iElemNext).iElemPrev;
ELEM(pElem->iElemNext).iElemPrev = iPos;
ELEM(pElem->iElemNext).nFlags ^= MNF_FIRST;
}
else
{
pElem->iElemNext = 0;
pElem->iElemPrev = iPos;
}
ELEM(iPosParent).iElemChild = iPos;
}
if ( iPosParent )
pElem->SetLevel( ELEM(iPosParent).Level() + 1 );
}
}
int CMarkup::x_UnlinkElem( int iPos )
{
// Fix links to remove element and mark as deleted
// return previous position or zero if none
ElemPos* pElem = &ELEM(iPos);
// Find previous sibling and bypass removed element
int iPosPrev = 0;
if ( pElem->nFlags & MNF_FIRST )
{
if ( pElem->iElemNext ) // set next as first child
{
ELEM(pElem->iElemParent).iElemChild = pElem->iElemNext;
ELEM(pElem->iElemNext).iElemPrev = pElem->iElemPrev;
ELEM(pElem->iElemNext).nFlags |= MNF_FIRST;
}
else // no children remaining
ELEM(pElem->iElemParent).iElemChild = 0;
}
else
{
iPosPrev = pElem->iElemPrev;
ELEM(iPosPrev).iElemNext = pElem->iElemNext;
if ( pElem->iElemNext )
ELEM(pElem->iElemNext).iElemPrev = iPosPrev;
else
ELEM(ELEM(pElem->iElemParent).iElemChild).iElemPrev = iPosPrev;
}
x_ReleaseSubDoc( iPos );
return iPosPrev;
}
int CMarkup::x_UnlinkPrevElem( int iPosParent, int iPosBefore, int iPos )
{
// In file write mode, only keep virtual parent 0 plus one element if currently at element
if ( iPosParent )
{
x_ReleasePos( iPosParent );
iPosParent = 0;
}
else if ( iPosBefore )
x_ReleasePos( iPosBefore );
ELEM(iPosParent).iElemChild = iPos;
ELEM(iPosParent).nLength = MCD_STRLENGTH(m_strDoc);
if ( iPos )
{
ElemPos* pElem = &ELEM(iPos);
pElem->iElemParent = iPosParent;
pElem->iElemPrev = iPos;
pElem->iElemNext = 0;
pElem->nFlags |= MNF_FIRST;
}
return iPosParent;
}
int CMarkup::x_ReleasePos( int iPos )
{
int iPosNext = ELEM(iPos).iElemNext;
ELEM(iPos).iElemNext = m_iPosDeleted;
ELEM(iPos).nFlags = MNF_DELETED;
m_iPosDeleted = iPos;
return iPosNext;
}
int CMarkup::x_ReleaseSubDoc( int iPos )
{
// Mark position structures as deleted by depth first traversal
// Tricky because iElemNext used in traversal is overwritten for linked list of deleted
// Return value is what iElemNext was before being overwritten
//
int iPosNext = 0, iPosTop = iPos;
while ( 1 )
{
if ( ELEM(iPos).iElemChild )
iPos = ELEM(iPos).iElemChild;
else
{
while ( 1 )
{
iPosNext = x_ReleasePos( iPos );
if ( iPosNext || iPos == iPosTop )
break;
iPos = ELEM(iPos).iElemParent;
}
if ( iPos == iPosTop )
break;
iPos = iPosNext;
}
}
return iPosNext;
}
void CMarkup::x_CheckSavedPos()
{
// Remove any saved positions now pointing to deleted elements
// Must be done as part of element removal before position reassigned
if ( m_pSavedPosMaps->m_pMaps )
{
int nMap = 0;
while ( m_pSavedPosMaps->m_pMaps[nMap] )
{
SavedPosMap* pMap = m_pSavedPosMaps->m_pMaps[nMap];
for ( int nSlot = 0; nSlot < pMap->nMapSize; ++nSlot )
{
SavedPos* pSavedPos = pMap->pTable[nSlot];
if ( pSavedPos )
{
int nOffset = 0;
int nSavedPosCount = 0;
while ( 1 )
{
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
{
int iPos = pSavedPos[nOffset].iPos;
if ( ! (ELEM(iPos).nFlags & MNF_DELETED) )
{
if ( nSavedPosCount < nOffset )
{
pSavedPos[nSavedPosCount] = pSavedPos[nOffset];
pSavedPos[nSavedPosCount].nSavedPosFlags &= ~SavedPos::SPM_LAST;
}
++nSavedPosCount;
}
}
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
{
while ( nSavedPosCount <= nOffset )
pSavedPos[nSavedPosCount++].nSavedPosFlags &= ~SavedPos::SPM_USED;
break;
}
++nOffset;
}
}
}
++nMap;
}
}
}
void CMarkup::x_AdjustForNode( int iPosParent, int iPos, int nShift )
{
// Adjust affected indexes
bool bAfterPos = true;
if ( ! iPos )
{
// Change happened before or at first element under iPosParent
// If there are any children of iPosParent, adjust from there
// otherwise start at parent and adjust from there
iPos = ELEM(iPosParent).iElemChild;
if ( iPos )
{
ELEM(iPos).nStart += nShift;
bAfterPos = false;
}
else
{
iPos = iPosParent;
ELEM(iPos).nLength += nShift;
}
}
x_Adjust( iPos, nShift, bAfterPos );
}
bool CMarkup::x_AddNode( int nNodeType, MCD_PCSZ pText, int nNodeFlags )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
// Comments, DTDs, and processing instructions are followed by CRLF
// Other nodes are usually concerned with mixed content, so no CRLF
if ( ! (nNodeType & (MNT_PROCESSING_INSTRUCTION|MNT_COMMENT|MNT_DOCUMENT_TYPE)) )
nNodeFlags |= MNF_WITHNOLINES;
// Add node of nNodeType after current node position
NodePos node( nNodeFlags );
if ( ! x_CreateNode(node.strMeta, nNodeType, pText) )
return false;
// Insert the new node relative to current node
node.nStart = m_nNodeOffset;
node.nLength = m_nNodeLength;
node.nNodeType = nNodeType;
int iPosBefore = m_iPos;
int nReplace = x_InsertNew( m_iPosParent, iPosBefore, node );
// If its a new element, create an ElemPos
int iPos = iPosBefore;
ElemPos* pElem = NULL;
if ( nNodeType == MNT_ELEMENT )
{
// Set indexes
iPos = x_GetFreePos();
pElem = &ELEM(iPos);
pElem->nStart = node.nStart;
pElem->SetStartTagLen( node.nLength );
pElem->SetEndTagLen( 0 );
pElem->nLength = node.nLength;
node.nStart = 0;
node.nLength = 0;
pElem->iElemChild = 0;
pElem->nFlags = 0;
x_LinkElem( m_iPosParent, iPosBefore, iPos );
}
if ( m_nDocFlags & MDF_WRITEFILE )
{
m_iPosParent = x_UnlinkPrevElem( m_iPosParent, iPosBefore, iPos );
if ( nNodeType == MNT_ELEMENT )
{
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nL = pElem->nStart + 1;
token.m_nR = pElem->nStart + pElem->nLength - 3;
m_pFilePos->m_elemstack.PushTagAndCount( token );
}
}
else // need to adjust element positions after iPos
x_AdjustForNode( m_iPosParent, iPos, MCD_STRLENGTH(node.strMeta) - nReplace );
// Store current position
m_iPos = iPos;
m_iPosChild = 0;
m_nNodeOffset = node.nStart;
m_nNodeLength = node.nLength;
m_nNodeType = nNodeType;
MARKUP_SETDEBUGSTATE;
return true;
}
void CMarkup::x_RemoveNode( int iPosParent, int& iPos, int& nNodeType, int& nNodeOffset, int& nNodeLength )
{
int iPosPrev = iPos;
// Removing an element?
if ( nNodeType == MNT_ELEMENT )
{
nNodeOffset = ELEM(iPos).nStart;
nNodeLength = ELEM(iPos).nLength;
iPosPrev = x_UnlinkElem( iPos );
x_CheckSavedPos();
}
// Find previous node type, offset and length
int nPrevOffset = 0;
if ( iPosPrev )
nPrevOffset = ELEM(iPosPrev).StartAfter();
else if ( iPosParent )
nPrevOffset = ELEM(iPosParent).StartContent();
TokenPos token( m_strDoc, m_nDocFlags );
NodePos node;
token.m_nNext = nPrevOffset;
int nPrevType = 0;
while ( token.m_nNext < nNodeOffset )
{
nPrevOffset = token.m_nNext;
nPrevType = token.ParseNode( node );
}
int nPrevLength = nNodeOffset - nPrevOffset;
if ( ! nPrevLength )
{
// Previous node is iPosPrev element
nPrevOffset = 0;
if ( iPosPrev )
nPrevType = MNT_ELEMENT;
}
// Remove node from document
x_DocChange( nNodeOffset, nNodeLength, MCD_STR() );
x_AdjustForNode( iPosParent, iPosPrev, - nNodeLength );
// Was removed node a lone end tag?
if ( nNodeType == MNT_LONE_END_TAG )
{
// See if we can unset parent MNF_ILLDATA flag
token.m_nNext = ELEM(iPosParent).StartContent();
int nEndOfContent = token.m_nNext + ELEM(iPosParent).ContentLen();
int iPosChild = ELEM(iPosParent).iElemChild;
while ( token.m_nNext < nEndOfContent )
{
if ( token.ParseNode(node) <= 0 )
break;
if ( node.nNodeType == MNT_ELEMENT )
{
token.m_nNext = ELEM(iPosChild).StartAfter();
iPosChild = ELEM(iPosChild).iElemNext;
}
}
if ( token.m_nNext == nEndOfContent )
ELEM(iPosParent).nFlags &= ~MNF_ILLDATA;
}
nNodeType = nPrevType;
nNodeOffset = nPrevOffset;
nNodeLength = nPrevLength;
iPos = iPosPrev;
}
| Bam4d/Neuretix | CMarkup/Markup.cpp | C++ | mit | 172,274 |
<?php
namespace Craft;
use Cake\Utility\Hash as Hash;
class VzAddressFeedMeFieldType extends BaseFeedMeFieldType
{
// Templates
// =========================================================================
public function getMappingTemplate()
{
return 'vzaddresshelper/_integrations/feedme/fields/vzaddress';
}
// Public Methods
// =========================================================================
public function prepFieldData($element, $field, $fieldData, $handle, $options)
{
// Initialize content array
$content = array();
$data = Hash::get($fieldData, 'data');
foreach ($data as $subfieldHandle => $subfieldData) {
// Set value to subfield of correct address array
$content[$subfieldHandle] = Hash::get($subfieldData, 'data');
}
// Return data
return $content;
}
} | engram-design/FeedMe-Helpers | vzaddresshelper/integrations/feedme/fields/VzAddressFeedMeFieldType.php | PHP | mit | 923 |
using AxosoftAPI.NET.Core.Interfaces;
using AxosoftAPI.NET.Models;
namespace AxosoftAPI.NET.Interfaces
{
public interface IFeatures : IItemResource<Item>
{
}
}
| Axosoft/AxosoftAPI.NET | AxosoftAPI.NET/Interfaces/IFeatures.cs | C# | mit | 167 |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# password_digest :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
require 'spec_helper'
describe User do
it "is valid with a username and confirmed password" do
user = User.new(
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
expect(user).to be_valid
end
it "is invalid without a username" do
expect(User.new(name: nil)).to have(1).errors_on(:name)
end
it "is invalid without a password" do
expect(User.new(password: nil)).to have(1).errors_on(:password)
end
it "is invalid without a password confirmation" do
expect(User.new(password_confirmation: nil)).to have(1).errors_on(:password_confirmation)
end
it "is invalid if it is a duplicate" do
user = User.new(
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
user.save
duplicate_user = User.new(
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
expect(duplicate_user).to be_invalid
end
it "always has at least one admin user remaining" do
user1 = User.create(
# create first user
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
# create second user
user2 = User.create(
name: 'Username2',
password: 'Password2',
password_confirmation: 'Password2')
user1.save
user2.save
user1.destroy
expect{ user2.destroy }.to raise_error
end
end
| trackingtrain/spoonfeeder | spec/models/user_spec.rb | Ruby | mit | 1,692 |
#!/usr/bin/env ruby
require "minitest/autorun"
require 'rlisp'
##
# Passes if +expected+.eql?(+actual).
#
# Note that the ordering of arguments is important, since a helpful
# error message is generated when this one fails that tells you the
# values of expected and actual.
#
# Example:
# assert_eql 'MY STRING', 'my string'.upcase
# assert_eql 1.0, 1 # fails
module Minitest::Assertions
public
def assert_eql(expected, actual, message=nil)
full_message = build_message(message, <<EOT, expected, actual)
<?> expected but was
<?>.
EOT
assert_block(full_message) { expected.eql?(actual) }
end
end
class Test_Parser < Minitest::Test
def assert_parses(rlisp, ast)
assert_eql(ast, RLispGrammar.new(rlisp).expr)
end
def test_symbols
assert_parses("a", :a)
assert_parses("A", :A)
assert_parses("foo-bar", :"foo-bar")
assert_parses("az_AZ09!", :"az_AZ09!")
assert_parses("_a?", :"_a?")
assert_parses("[]", :[])
assert_parses("[]=", :[]=)
end
def test_numbers
assert_parses("1", 1)
assert_parses("1.0", 1.0)
assert_parses("-1", -1)
assert_parses("-1.0", -1.0)
assert_parses("(1 1.0 -1 -1.0 0 0.0 -0 -0.0)", [1, 1.0, -1, -1.0, 0, 0.0, -0, -0.0])
end
def test_lists
assert_parses("()", [])
assert_parses("(a)", [:a])
assert_parses("(a b)", [:a, :b])
assert_parses("((a) (b) (c))", [[:a], [:b], [:c]])
assert_parses("((((()))) ((())) (()) ())", [[[[[]]]], [[[]]], [[]], []])
end
def test_reader_macros
assert_parses("'a", [:quote, :a])
assert_parses("[a b c]", [:send, :a, [:quote, :b], :c])
assert_parses("`a", [:quasiquote, :a])
assert_parses(",a", [:unquote, :a])
assert_parses(",@a", [:"unquote-splicing", :a])
end
def test_strings
assert_parses('""', "")
assert_parses('"foo"', "foo")
assert_parses('"foo \\" bar"', "foo \" bar")
assert_parses(%Q["\\\\\\r\\n"], "\\\r\n")
end
end
class Test_Debug_Info < Minitest::Test
def test_debug_info
fh = File.open("tests/adder.rl")
parser = RLispGrammar.new(fh, "tests/adder.rl")
assert_eql(["tests/adder.rl", 1, 0], parser.expr.debug_info)
assert_eql(["tests/adder.rl", 4, 0], parser.expr.debug_info)
assert_eql(["tests/adder.rl", 5, 0], parser.expr.debug_info)
assert_eql(["tests/adder.rl", 6, 0], parser.expr.debug_info)
assert_eql(["tests/adder.rl", 7, 0], parser.expr.debug_info)
end
def test_debug_info_precompile
code = "(let foo (fn () (bar)))"
parser = RLispGrammar.new(code)
expr = parser.expr
assert_eql(["example.rl", 1, 0], expr.debug_info)
assert_eql(["example.rl", 1, 9], expr[2].debug_info)
assert_eql(["example.rl", 1, 16], expr[2][2].debug_info)
rlisp = RLispCompiler.new
pexpr = rlisp.precompile(expr)
assert_eql(["example.rl", 1, 0], pexpr.debug_info)
assert_eql(["example.rl", 1, 9, :foo], pexpr[2].debug_info)
assert_eql(["example.rl", 1, 16, :foo], pexpr[2][2].debug_info)
end
def test_debug_info_defun
code = "(defun foo () (bar))"
parser = RLispGrammar.new(code)
expr = parser.expr
assert_eql(["example.rl", 1, 0], expr.debug_info)
assert_eql(["example.rl", 1, 14], expr[3].debug_info)
rlisp = RLispCompiler.new
rlisp.run_file('stdlib.rl')
pexpr = rlisp.precompile(expr)
assert_eql(["example.rl", 1, 0], pexpr.debug_info)
assert_eql(["example.rl", 1, 0, :foo], pexpr[2].debug_info)
assert_eql(["example.rl", 1, 14, :foo], pexpr[2][2].debug_info)
end
end
| taw/rlisp | tests/test_parser.rb | Ruby | mit | 3,497 |
using System;
using System.Media;
namespace AnimalHierarchy
{
class Kitten : Cat
{
public Kitten()
{
}
public Kitten(int age, string name)
: base(age,name)
{
this.Sex = "Female";
}
public override void ProduceSound()
{
SoundPlayer Sound = new SoundPlayer(@"../../Files/cat_kitten.wav");
Sound.PlaySync();
}
}
}
| siderisltd/Telerik-Academy | All Courses Homeworks/OOP/4. PrinciplesOne - OOP/AnimalHierarchy/Kitten.cs | C# | mit | 450 |
import asynctest
from asynctest.mock import patch
import json
class TestRundeckJob(asynctest.TestCase):
def setUp(self):
patcher1 = patch('charlesbot_rundeck.rundeck_job.http_get_request')
self.addCleanup(patcher1.stop)
self.mock_http_get_request = patcher1.start()
from charlesbot_rundeck.rundeck_job import RundeckJob
self.rd_job = RundeckJob()
def test_invalid_rundeck_json_response(self):
self.mock_http_get_request.side_effect = ["{}"]
success = yield from self.rd_job.retrieve_rundeck_job_info(
"token",
"baseurl",
"project name",
"job name"
)
self.assertFalse(success)
def test_empty_rundeck_response(self):
self.mock_http_get_request.side_effect = ["[]"]
success = yield from self.rd_job.retrieve_rundeck_job_info(
"token",
"baseurl",
"project name",
"job name"
)
self.assertFalse(success)
def test_single_rundeck_response(self):
response = [
{
"id": "rd1",
"name": "rundeckone",
}
]
self.mock_http_get_request.side_effect = [json.dumps(response)]
success = yield from self.rd_job.retrieve_rundeck_job_info(
"token",
"baseurl",
"project name",
"job name"
)
self.assertTrue(success)
self.assertEqual(self.rd_job.id, "rd1")
self.assertEqual(self.rd_job.name, "rundeckone")
self.assertEqual(self.rd_job.friendly_name, "")
def test_multiple_rundeck_responses(self):
response = [
{
"id": "rd1",
"name": "rundeckone",
},
{
"id": "rd2",
"name": "rundecktwo",
}
]
self.mock_http_get_request.side_effect = [json.dumps(response)]
success = yield from self.rd_job.retrieve_rundeck_job_info(
"token",
"baseurl",
"project name",
"job name"
)
self.assertFalse(success)
| marvinpinto/charlesbot-rundeck | tests/test_rundeck_job.py | Python | mit | 2,175 |
package com.tyrfing.games.tyrlib3.util;
public interface IErrorHandler {
public void onError();
}
| TyrfingX/TyrLib | com.tyrfing.games.tyrlib3/src/com/tyrfing/games/tyrlib3/util/IErrorHandler.java | Java | mit | 105 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06. RemoveNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. RemoveNumbers")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("21ba0d6d-2b60-47d5-8cd2-04f04492d771")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| niki-funky/Telerik_Academy | Programming/Data Structures and Algorithms/01. Algo/06. RemoveNumbers/Properties/AssemblyInfo.cs | C# | mit | 1,410 |
package com.dpaulenk.webproxy.common;
import com.dpaulenk.webproxy.inbound.InboundHandlerState;
import com.dpaulenk.webproxy.utils.ChannelUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpObject;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
public abstract class AbstractProxyHandler<R extends HttpMessage, S> extends SimpleChannelInboundHandler<Object> {
protected volatile ChannelHandlerContext ctx;
protected volatile Channel channel;
protected S currentState;
protected boolean tunneling = false;
public S getCurrentState() {
return currentState;
}
public void setCurrentState(S currentState) {
this.currentState = currentState;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpObject) {
channelReadHttpObject(ctx, (HttpObject) msg);
} else {
channelReadBytes(ctx, (ByteBuf) msg);
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
this.channel = ctx.channel();
super.channelRegistered(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
disconnect();
}
protected abstract void channelReadBytes(ChannelHandlerContext ctx, ByteBuf msg);
protected abstract void channelReadHttpObject(ChannelHandlerContext ctx, HttpObject msg);
public ChannelFuture writeToChannel(Object msg) {
ReferenceCountUtil.retain(msg);
return channel.writeAndFlush(msg);
}
public void disconnect() {
if (channel != null) {
ChannelUtils.closeOnFlush(channel);
}
}
public void stopReading() {
channel.config().setAutoRead(false);
}
public void startReading() {
channel.config().setAutoRead(true);
}
}
| Fantast/simple-web-proxy-server | src/main/java/com/dpaulenk/webproxy/common/AbstractProxyHandler.java | Java | mit | 2,222 |
// Load the test base
const reload = require('require-reload')(require);
const tests = reload('../base/tests');
module.exports = function promiseTestRunner (qb) {
Object.keys(tests).forEach(describeName => {
describe(describeName, async () => {
let currentSuite = tests[describeName];
Object.keys(currentSuite).forEach(testDesc => {
it(testDesc, done => {
const methodObj = currentSuite[testDesc];
const methodNames = Object.keys(methodObj);
let results = [];
methodNames.forEach(name => {
const args = methodObj[name];
const method = qb[name];
if (args[0] === 'multiple') {
args.shift();
args.forEach(argSet => {
results.push(method.apply(qb, argSet));
});
} else {
results.push(method.apply(qb, args));
}
});
const promise = results.pop();
promise.then(result => {
// expect(result.rows).is.an('array');
expect(result.rowCount()).toEqual(expect.anything());
expect(result.columnCount()).toEqual(expect.anything());
return done();
}).catch(e => done(e));
});
});
});
});
describe('DB update tests -', () => {
beforeAll(done => {
let sql = qb.driver.truncate('create_test');
qb.query(sql).then(() => done())
.catch(err => done(err));
});
it('Test Insert', async () => {
const promise = await qb.set('id', 98)
.set('key', '84')
.set('val', Buffer.from('120'))
.insert('create_test');
expect(promise).toEqual(expect.anything());
});
it('Test Insert Object', async () => {
const promise = await qb.insert('create_test', {
id: 587,
key: 1,
val: Buffer.from('2')
});
expect(promise).toEqual(expect.anything());
});
it('Test Update', async () => {
const promise = await qb.where('id', 7)
.update('create_test', {
id: 7,
key: 'gogle',
val: Buffer.from('non-word')
});
expect(promise).toEqual(expect.anything());
});
it('Test set Array Update', async () => {
let object = {
id: 22,
key: 'gogle',
val: Buffer.from('non-word')
};
const promise = await qb.set(object)
.where('id', 22)
.update('create_test');
expect(promise).toEqual(expect.anything());
});
it('Test where set update', async () => {
const promise = await qb.where('id', 36)
.set('id', 36)
.set('key', 'gogle')
.set('val', Buffer.from('non-word'))
.update('create_test');
expect(promise).toEqual(expect.anything());
});
it('Test delete', async () => {
const promise = await qb.delete('create_test', {id: 5});
expect(promise).toEqual(expect.anything());
});
it('Delete with where', async () => {
const promise = await qb.where('id', 5)
.delete('create_test');
expect(promise).toEqual(expect.anything());
});
it('Delete multiple where values', async () => {
const promise = await qb.delete('create_test', {
id: 5,
key: 'gogle'
});
expect(promise).toEqual(expect.anything());
});
});
describe('Batch tests -', () => {
it('Test Insert Batch', async () => {
const data = [
{
id: 544,
key: 3,
val: Buffer.from('7')
}, {
id: 89,
key: 34,
val: Buffer.from('10 o\'clock')
}, {
id: 48,
key: 403,
val: Buffer.from('97')
}
];
const promise = await qb.insertBatch('create_test', data);
expect(promise).toEqual(expect.anything());
});
it('Test Update Batch', async () => {
const data = [{
id: 480,
key: 49,
val: '7x7'
}, {
id: 890,
key: 100,
val: '10x10'
}];
const affectedRows = qb.updateBatch('create_test', data, 'id');
expect(affectedRows).toBe(2);
});
});
describe('Grouping tests -', () => {
it('Using grouping method', async () => {
const promise = await qb.select('id, key as k, val')
.from('create_test')
.groupStart()
.where('id >', 1)
.where('id <', 900)
.groupEnd()
.limit(2, 1)
.get();
expect(promise).toEqual(expect.anything());
});
it('Using where first grouping', async () => {
const promise = await qb.select('id, key as k, val')
.from('create_test')
.where('id !=', 5)
.groupStart()
.where('id >', 1)
.where('id <', 900)
.groupEnd()
.limit(2, 1)
.get();
expect(promise).toEqual(expect.anything());
});
it('Using or grouping method', async () => {
const promise = await qb.select('id, key as k, val')
.from('create_test')
.groupStart()
.where('id >', 1)
.where('id <', 900)
.groupEnd()
.orGroupStart()
.where('id', 0)
.groupEnd()
.limit(2, 1)
.get();
expect(promise).toEqual(expect.anything());
});
it('Using or not grouping method', async () => {
const promise = await qb.select('id, key as k, val')
.from('create_test')
.groupStart()
.where('id >', 1)
.where('id <', 900)
.groupEnd()
.orNotGroupStart()
.where('id', 0)
.groupEnd()
.limit(2, 1)
.get();
expect(promise).toEqual(expect.anything());
});
});
describe('Get compiled - ', () => {
it('getCompiledSelect', () => {
const sql = qb.select('id, key as k, val')
.from('create_test')
.groupStart()
.where('id >', 1)
.where('id <', 900)
.groupEnd()
.limit(2, 1)
.getCompiledSelect();
expect(sql).toMatchSnapshot();
});
it('getCompiledSelect 2', () => {
const sql = qb.select('id, key as k, val')
.groupStart()
.where('id >', 1)
.where('id <', 900)
.groupEnd()
.limit(2, 1)
.getCompiledSelect('create_test');
expect(sql).toMatchSnapshot();
});
it('getCompiledInsert', () => {
const sql = qb.set({
id: 587,
key: 1,
val: Buffer.from('2')
}).getCompiledInsert('create_test');
expect(sql).toMatchSnapshot();
});
it('getCompiledUpdate', () => {
const sql = qb.where('id', 36)
.set('id', 36)
.set('key', 'gogle')
.set('val', Buffer.from('non-word'))
.getCompiledUpdate('create_test');
expect(sql).toMatchSnapshot();
});
it('getCompiledDelete', () => {
const sql = qb.where({id: 5}).getCompiledDelete('create_test');
expect(sql).toMatchSnapshot();
});
});
};
| timw4mail/node-query | test/base/adapterPromiseTestRunner.js | JavaScript | mit | 6,181 |
package com.parikls.movieland.web.dao;
import com.parikls.movieland.web.controller.dto.movie.MovieSearchRequestDTO;
import com.parikls.movieland.web.dao.entity.Movie;
import com.parikls.movieland.web.dao.rowmapper.MovieRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class MovieDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private QueryGenerator queryGenerator;
private RowMapper<Movie> mapper = new MovieRowMapper();
private static final String QUERY_BY_ID = "SELECT * FROM movieland.movie m WHERE id=?";
private static final String QUERY_GENRES_BY_MOVIE_ID = "SELECT genre_id FROM movieland.movie_to_genre where movie_id = ?";
private static final String QUERY_COUNTRIES_BY_MOVIE_ID = "SELECT country_id FROM movieland.movie_to_country where movie_id = ?";
public List<Movie> queryAll(String ratingOrder, String priceOrder, int limitFrom, int limitTo){
return queryAll(queryGenerator.movieSorting(ratingOrder, priceOrder, limitFrom, limitTo));
}
public List<Movie> queryAll(MovieSearchRequestDTO searchRequestDTO){
return queryAll(queryGenerator.movieSearch(searchRequestDTO));
}
public List<Movie> queryAll(String query) {
return jdbcTemplate.query(query, mapper);
}
public Movie queryById(Long id) {
return jdbcTemplate.queryForObject(QUERY_BY_ID, mapper, id);
}
public List<Long> queryGenresByMovieId(Long movieID){
return jdbcTemplate.queryForList(QUERY_GENRES_BY_MOVIE_ID, Long.class, movieID);
}
public List<Long> queryCountryByMovieId(Long movieID){
return jdbcTemplate.queryForList(QUERY_COUNTRIES_BY_MOVIE_ID, Long.class, movieID);
}
}
| parikls/movieland | src/main/java/com/parikls/movieland/web/dao/MovieDAO.java | Java | mit | 1,925 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://localhost/hijabaisyahshop/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| http://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = 'joker';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| edisetiawan/hijabaisyahshop | application/config/config.php | PHP | mit | 18,152 |
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$ci =& get_instance();
require_once __DIR__ . '/Validations/Site_validation.php';
/*$config = [
// Users
'user' => [
[
'field' => 'company',
'label' => 'lang:company',
'rules' => 'trim|required'
],
[
'field' => 'first_name',
'label' => 'lang:first_name',
'rules' => 'trim|required'
],
[
'field' => 'last_name',
'label' => 'lang:last_name',
'rules' => 'trim'
],
[
'field' => 'username',
'label' => 'lang:username',
'rules' => 'trim'
],
[
'field' => 'email',
'label' => 'lang:email',
'rules' => 'trim|required|valid_email|is_unique[users.email.'.$ci->uri->segment(4).']'
],
[
'field' => 'password',
'label' => 'lang:password',
'rules' => ($ci->router->fetch_method() == 'create') ? 'trim|required|min_length[6]|max_length[20]' : 'trim|min_length[6]|max_length[20]'
],
[
'field' => 'confirm_password',
'label' => 'lang:confirm_password',
'rules' => 'trim|matches[password]'
]
],
];*/
//require_once __DIR__ . '/Validations/Group_validation.php';
/*$config = [
'site/edit' => [
[
'field' => 'short_name',
'label' => 'Short Name',
'rules' => 'trim|required'
],
[
'field' => 'full_name',
'label' => 'Full Name',
'rules' => 'trim|required'
],
[
'field' => 'logo',
'label' => 'Logo',
'rules' => 'trim'
],
[
'field' => 'website',
'label' => 'Website',
'rules' => 'trim|required|valid_url'
],
[
'field' => 'contact_email',
'label' => 'Contact Email',
'rules' => 'trim|required|valid_email'
]
]
];*/ | normeno/codeigniter-base | application/modules/admin/config/form_validation.php | PHP | mit | 2,111 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 17006 : 17007;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop High5coin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "High5coin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: high5coin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: high5coin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: high5coin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use high5coind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=high5coinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"High5coin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| high5coin/high5coin | src/bitcoinrpc.cpp | C++ | mit | 48,577 |
/**
* This software is released as part of the Pumpernickel project.
*
* All com.pump resources in the Pumpernickel project are distributed under the
* MIT License:
* https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
*
* More information about the Pumpernickel project is available here:
* https://mickleness.github.io/pumpernickel/
*/
package com.pump.io.location;
public interface SearchResults {
/** This may return null. */
public IOLocation getSearchDirectory();
/** Return the text the user is searching by. */
public String getSearchText();
} | mickleness/pumpernickel | src/main/java/com/pump/io/location/SearchResults.java | Java | mit | 594 |
var Quad = Class.create(Renderable, {
initialize: function($super, width, height, position) {
this.width = width;
this.height = height;
$super();
if (position) this.orientation.setPosition(position);
},
setWidth: function(width) { this.setSize(width, this.height); },
setHeight: function(height) { this.setSize(this.width, height); },
setSize: function(width, height) {
this.width = width;
this.height = height;
this.rebuildAll();
},
init: function(vertices, colors, textureCoords) {
this.draw_mode = GL_TRIANGLE_STRIP;
var width = this.width, height = this.height;
vertices.push(-width/2, -height/2, 0);
vertices.push(-width/2, height/2, 0);
vertices.push( width/2, -height/2, 0);
vertices.push( width/2, height/2, 0);
textureCoords.push(0, 1);
textureCoords.push(0, 0);
textureCoords.push(1, 1);
textureCoords.push(1, 0);
colors.push(1,1,1,1);
colors.push(1,1,1,1);
colors.push(1,1,1,1);
colors.push(1,1,1,1);
}
});
| sinisterchipmunk/rails-webgl | public/javascripts/objects/quad.js | JavaScript | mit | 1,039 |
<?php
/* EverFailMainBundle:Vendor:edit.html.twig */
class __TwigTemplate_a12efb1d848d1c6d16be064b9c9d634d8c4a329fc5fa3d7cb6d00bf19fafeb3b extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("::base.html.twig");
$this->blocks = array(
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "::base.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_body($context, array $blocks = array())
{
// line 4
echo "<h1>Vendor edit</h1>
";
// line 6
echo $this->env->getExtension('form')->renderer->renderBlock($this->getContext($context, "edit_form"), 'form');
echo "
<ul class=\"record_actions\">
<li>
<a href=\"";
// line 10
echo $this->env->getExtension('routing')->getPath("vendor");
echo "\">
Back to the list
</a>
</li>
<li>";
// line 14
echo $this->env->getExtension('form')->renderer->renderBlock($this->getContext($context, "delete_form"), 'form');
echo "</li>
</ul>
";
}
public function getTemplateName()
{
return "EverFailMainBundle:Vendor:edit.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 49 => 14, 42 => 10, 35 => 6, 31 => 4, 28 => 3,);
}
}
| Bhathiya90/EverfailRepo | app/cache/dev/twig/a1/2e/fb1d848d1c6d16be064b9c9d634d8c4a329fc5fa3d7cb6d00bf19fafeb3b.php | PHP | mit | 1,732 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dbFontAwesome.Test
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmExample());
}
}
}
| diegobittencourt/dbFontAwesome | dbFontAwesome.Test/Program.cs | C# | mit | 524 |
/*
* SpriteContainer
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// namespace:
//this.createjs = this.createjs||{};
(function() {
"use strict";
/**
* A SpriteContainer is a nestable display list that enables aggressively optimized rendering of bitmap content.
* In order to accomplish these optimizations, SpriteContainer enforces a few restrictions on its content.
*
* Restrictions:
* - only Sprite, SpriteContainer, BitmapText and DOMElement are allowed to be added as children.
* - a spriteSheet MUST be either be passed into the constructor or defined on the first child added.
* - all children (with the exception of DOMElement) MUST use the same spriteSheet.
*
* <h4>Example</h4>
*
* var data = {
* images: ["sprites.jpg"],
* frames: {width:50, height:50},
* animations: {run:[0,4], jump:[5,8,"run"]}
* };
* var spriteSheet = new createjs.SpriteSheet(data);
* var container = new createjs.SpriteContainer(spriteSheet);
* container.addChild(spriteInstance, spriteInstance2);
* container.x = 100;
*
* <strong>Note:</strong> SpriteContainer is not included in the minified version of EaselJS.
*
* @class SpriteContainer
* @extends Container
* @constructor
* @param {SpriteSheet} [spriteSheet] The spriteSheet to use for this SpriteContainer and its children.
**/
function SpriteContainer(spriteSheet) {
this.Container_constructor();
// public properties:
/**
* The SpriteSheet that this container enforces use of.
* @property spriteSheet
* @type {SpriteSheet}
* @readonly
**/
this.spriteSheet = spriteSheet;
}
var p = createjs.extend(SpriteContainer, createjs.Container);
/**
* <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// public methods:
/**
* Adds a child to the top of the display list.
* Only children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement are allowed.
* The child must have the same spritesheet as this container (unless it's a DOMElement).
* If a spritesheet hasn't been defined, this container uses this child's spritesheet.
*
* <h4>Example</h4>
* container.addChild(bitmapInstance);
*
* You can also add multiple children at once:
*
* container.addChild(bitmapInstance, shapeInstance, textInstance);
*
* @method addChild
* @param {DisplayObject} child The display object to add.
* @return {DisplayObject} The child that was added, or the last child if multiple children were added.
**/
p.addChild = function(child) {
if (child == null) { return child; }
if (arguments.length > 1) {
return this.addChildAt.apply(this, Array.prototype.slice.call(arguments).concat([this.children.length]));
} else {
return this.addChildAt(child, this.children.length);
}
};
/**
* Adds a child to the display list at the specified index, bumping children at equal or greater indexes up one, and
* setting its parent to this Container.
* Only children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement are allowed.
* The child must have the same spritesheet as this container (unless it's a DOMElement).
* If a spritesheet hasn't been defined, this container uses this child's spritesheet.
*
* <h4>Example</h4>
* addChildAt(child1, index);
*
* You can also add multiple children, such as:
*
* addChildAt(child1, child2, ..., index);
*
* The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list,
* you could use:
*
* container.addChildAt(myShape, container.getChildIndex(otherShape));
*
* This would also bump otherShape's index up by one. Fails silently if the index is out of range.
*
* @method addChildAt
* @param {DisplayObject} child The display object to add.
* @param {Number} index The index to add the child at.
* @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added.
**/
p.addChildAt = function(child, index) {
var l = arguments.length;
var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1]
if (indx < 0 || indx > this.children.length) { return arguments[l-2]; }
if (l > 2) {
for (var i=0; i<l-1; i++) { this.addChildAt(arguments[i], indx+i); }
return arguments[l-2];
}
if (child._spritestage_compatibility >= 1) {
// The child is compatible with SpriteStage/SpriteContainer.
} else {
console && console.log("Error: You can only add children of type SpriteContainer, Sprite, BitmapText, or DOMElement [" + child.toString() + "]");
return child;
}
if (child._spritestage_compatibility <= 4) {
var spriteSheet = child.spriteSheet;
if ((!spriteSheet || !spriteSheet._images || spriteSheet._images.length > 1) || (this.spriteSheet && this.spriteSheet !== spriteSheet)) {
console && console.log("Error: A child's spriteSheet must be equal to its parent spriteSheet and only use one image. [" + child.toString() + "]");
return child;
}
this.spriteSheet = spriteSheet;
}
if (child.parent) { child.parent.removeChild(child); }
child.parent = this;
this.children.splice(index, 0, child);
return child;
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[SpriteContainer (name="+ this.name +")]";
};
createjs.SpriteContainer = createjs.promote(SpriteContainer, "Container");
}());
| iwangx/createjs | src/easeljs/display/SpriteContainer.js | JavaScript | mit | 7,122 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QuizFactory.Mvc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuizFactory.Mvc")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97bb970b-ddd4-4a54-be05-eebc21f2bb9e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| dpesheva/QuizFactory | QuizFactory/QuizFactory.MVC/Properties/AssemblyInfo.cs | C# | mit | 1,361 |
package com.reason.ide.highlight;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static com.intellij.psi.TokenType.BAD_CHARACTER;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import com.reason.lang.core.type.ORTypes;
import com.reason.lang.napkin.ResLexer;
import com.reason.lang.napkin.ResTypes;
import com.reason.lang.ocaml.OclLexer;
import com.reason.lang.ocaml.OclTypes;
import com.reason.lang.reason.RmlLexer;
import com.reason.lang.reason.RmlTypes;
import java.util.*;
import org.jetbrains.annotations.NotNull;
public class ORSyntaxHighlighter extends SyntaxHighlighterBase {
private static final Set<IElementType> RML_KEYWORD_TYPES =
of(
RmlTypes.INSTANCE.OPEN,
RmlTypes.INSTANCE.MODULE,
RmlTypes.INSTANCE.FUN,
RmlTypes.INSTANCE.LET,
RmlTypes.INSTANCE.TYPE,
RmlTypes.INSTANCE.INCLUDE,
RmlTypes.INSTANCE.EXTERNAL,
RmlTypes.INSTANCE.IF,
RmlTypes.INSTANCE.ELSE,
RmlTypes.INSTANCE.ENDIF,
RmlTypes.INSTANCE.SWITCH,
RmlTypes.INSTANCE.TRY,
RmlTypes.INSTANCE.RAISE,
RmlTypes.INSTANCE.FOR,
RmlTypes.INSTANCE.IN,
RmlTypes.INSTANCE.TO,
RmlTypes.INSTANCE.BOOL_VALUE,
RmlTypes.INSTANCE.REF,
RmlTypes.INSTANCE.EXCEPTION,
RmlTypes.INSTANCE.WHEN,
RmlTypes.INSTANCE.AND,
RmlTypes.INSTANCE.REC,
RmlTypes.INSTANCE.WHILE,
RmlTypes.INSTANCE.ASR,
RmlTypes.INSTANCE.CLASS,
RmlTypes.INSTANCE.CONSTRAINT,
RmlTypes.INSTANCE.DOWNTO,
RmlTypes.INSTANCE.FUNCTOR,
RmlTypes.INSTANCE.INHERIT,
RmlTypes.INSTANCE.INITIALIZER,
RmlTypes.INSTANCE.LAND,
RmlTypes.INSTANCE.LOR,
RmlTypes.INSTANCE.LSL,
RmlTypes.INSTANCE.LSR,
RmlTypes.INSTANCE.LXOR,
RmlTypes.INSTANCE.METHOD,
RmlTypes.INSTANCE.MOD,
RmlTypes.INSTANCE.NEW,
RmlTypes.INSTANCE.NONREC,
RmlTypes.INSTANCE.OR,
RmlTypes.INSTANCE.PRIVATE,
RmlTypes.INSTANCE.VIRTUAL,
RmlTypes.INSTANCE.VAL,
RmlTypes.INSTANCE.PUB,
RmlTypes.INSTANCE.PRI,
RmlTypes.INSTANCE.OBJECT,
RmlTypes.INSTANCE.MUTABLE,
RmlTypes.INSTANCE.UNIT,
RmlTypes.INSTANCE.WITH,
RmlTypes.INSTANCE.DIRECTIVE_IF,
RmlTypes.INSTANCE.DIRECTIVE_ELSE,
RmlTypes.INSTANCE.DIRECTIVE_ELIF,
RmlTypes.INSTANCE.DIRECTIVE_END,
RmlTypes.INSTANCE.DIRECTIVE_ENDIF);
private static final Set<IElementType> RML_OPERATION_SIGN_TYPES =
of(
RmlTypes.INSTANCE.L_AND,
RmlTypes.INSTANCE.L_OR,
RmlTypes.INSTANCE.SHORTCUT,
RmlTypes.INSTANCE.ARROW,
RmlTypes.INSTANCE.PIPE_FIRST,
RmlTypes.INSTANCE.PIPE_FORWARD,
RmlTypes.INSTANCE.EQEQEQ,
RmlTypes.INSTANCE.EQEQ,
RmlTypes.INSTANCE.EQ,
RmlTypes.INSTANCE.NOT_EQEQ,
RmlTypes.INSTANCE.NOT_EQ,
RmlTypes.INSTANCE.DIFF,
RmlTypes.INSTANCE.COLON,
RmlTypes.INSTANCE.SINGLE_QUOTE,
RmlTypes.INSTANCE.DOUBLE_QUOTE,
RmlTypes.INSTANCE.CARRET,
RmlTypes.INSTANCE.PLUSDOT,
RmlTypes.INSTANCE.MINUSDOT,
RmlTypes.INSTANCE.SLASHDOT,
RmlTypes.INSTANCE.STARDOT,
RmlTypes.INSTANCE.PLUS,
RmlTypes.INSTANCE.MINUS,
RmlTypes.INSTANCE.SLASH,
RmlTypes.INSTANCE.STAR,
RmlTypes.INSTANCE.PERCENT,
RmlTypes.INSTANCE.PIPE,
RmlTypes.INSTANCE.ARROBASE,
RmlTypes.INSTANCE.SHARP,
RmlTypes.INSTANCE.SHARPSHARP,
RmlTypes.INSTANCE.QUESTION_MARK,
RmlTypes.INSTANCE.EXCLAMATION_MARK,
RmlTypes.INSTANCE.LT_OR_EQUAL,
RmlTypes.INSTANCE.GT_OR_EQUAL,
RmlTypes.INSTANCE.AMPERSAND,
RmlTypes.INSTANCE.LEFT_ARROW,
RmlTypes.INSTANCE.RIGHT_ARROW,
RmlTypes.INSTANCE.COLON_EQ,
RmlTypes.INSTANCE.COLON_GT,
RmlTypes.INSTANCE.GT,
RmlTypes.INSTANCE.GT_BRACE,
RmlTypes.INSTANCE.GT_BRACKET,
RmlTypes.INSTANCE.BRACKET_GT,
RmlTypes.INSTANCE.BRACKET_LT,
RmlTypes.INSTANCE.BRACE_LT,
RmlTypes.INSTANCE.DOTDOT);
private static final Set<IElementType> RML_OPTIONS_TYPES =
of(RmlTypes.INSTANCE.NONE, RmlTypes.INSTANCE.SOME);
private static final Set<IElementType> NS_KEYWORD_TYPES =
of(
ResTypes.INSTANCE.OPEN,
ResTypes.INSTANCE.MODULE,
ResTypes.INSTANCE.FUN,
ResTypes.INSTANCE.LET,
ResTypes.INSTANCE.TYPE,
ResTypes.INSTANCE.INCLUDE,
ResTypes.INSTANCE.EXTERNAL,
ResTypes.INSTANCE.IF,
ResTypes.INSTANCE.ELSE,
ResTypes.INSTANCE.ENDIF,
ResTypes.INSTANCE.SWITCH,
ResTypes.INSTANCE.TRY,
ResTypes.INSTANCE.RAISE,
ResTypes.INSTANCE.FOR,
ResTypes.INSTANCE.IN,
ResTypes.INSTANCE.TO,
ResTypes.INSTANCE.BOOL_VALUE,
ResTypes.INSTANCE.REF,
ResTypes.INSTANCE.EXCEPTION,
ResTypes.INSTANCE.WHEN,
ResTypes.INSTANCE.AND,
ResTypes.INSTANCE.REC,
ResTypes.INSTANCE.WHILE,
ResTypes.INSTANCE.ASR,
ResTypes.INSTANCE.CLASS,
ResTypes.INSTANCE.CONSTRAINT,
ResTypes.INSTANCE.DOWNTO,
ResTypes.INSTANCE.FUNCTOR,
ResTypes.INSTANCE.INHERIT,
ResTypes.INSTANCE.INITIALIZER,
ResTypes.INSTANCE.LAND,
ResTypes.INSTANCE.LOR,
ResTypes.INSTANCE.LSL,
ResTypes.INSTANCE.LSR,
ResTypes.INSTANCE.LXOR,
ResTypes.INSTANCE.METHOD,
ResTypes.INSTANCE.MOD,
ResTypes.INSTANCE.NEW,
ResTypes.INSTANCE.NONREC,
ResTypes.INSTANCE.OR,
ResTypes.INSTANCE.PRIVATE,
ResTypes.INSTANCE.VIRTUAL,
ResTypes.INSTANCE.VAL,
ResTypes.INSTANCE.PUB,
ResTypes.INSTANCE.PRI,
ResTypes.INSTANCE.OBJECT,
ResTypes.INSTANCE.MUTABLE,
ResTypes.INSTANCE.UNIT,
ResTypes.INSTANCE.WITH,
ResTypes.INSTANCE.DIRECTIVE_IF,
ResTypes.INSTANCE.DIRECTIVE_ELSE,
ResTypes.INSTANCE.DIRECTIVE_ELIF,
ResTypes.INSTANCE.DIRECTIVE_END,
ResTypes.INSTANCE.DIRECTIVE_ENDIF);
private static final Set<IElementType> NS_OPERATION_SIGN_TYPES =
of(
ResTypes.INSTANCE.L_AND,
ResTypes.INSTANCE.L_OR,
ResTypes.INSTANCE.SHORTCUT,
ResTypes.INSTANCE.ARROW,
ResTypes.INSTANCE.PIPE_FIRST,
ResTypes.INSTANCE.PIPE_FORWARD,
ResTypes.INSTANCE.EQEQEQ,
ResTypes.INSTANCE.EQEQ,
ResTypes.INSTANCE.EQ,
ResTypes.INSTANCE.NOT_EQEQ,
ResTypes.INSTANCE.NOT_EQ,
ResTypes.INSTANCE.DIFF,
ResTypes.INSTANCE.COLON,
ResTypes.INSTANCE.SINGLE_QUOTE,
ResTypes.INSTANCE.DOUBLE_QUOTE,
ResTypes.INSTANCE.CARRET,
ResTypes.INSTANCE.PLUSDOT,
ResTypes.INSTANCE.MINUSDOT,
ResTypes.INSTANCE.SLASHDOT,
ResTypes.INSTANCE.STARDOT,
ResTypes.INSTANCE.PLUS,
ResTypes.INSTANCE.MINUS,
ResTypes.INSTANCE.SLASH,
ResTypes.INSTANCE.STAR,
ResTypes.INSTANCE.PERCENT,
ResTypes.INSTANCE.PIPE,
ResTypes.INSTANCE.ARROBASE,
ResTypes.INSTANCE.SHARP,
ResTypes.INSTANCE.SHARPSHARP,
ResTypes.INSTANCE.QUESTION_MARK,
ResTypes.INSTANCE.EXCLAMATION_MARK,
ResTypes.INSTANCE.LT_OR_EQUAL,
ResTypes.INSTANCE.GT_OR_EQUAL,
ResTypes.INSTANCE.AMPERSAND,
ResTypes.INSTANCE.LEFT_ARROW,
ResTypes.INSTANCE.RIGHT_ARROW,
ResTypes.INSTANCE.COLON_EQ,
ResTypes.INSTANCE.COLON_GT,
ResTypes.INSTANCE.GT,
ResTypes.INSTANCE.GT_BRACE,
ResTypes.INSTANCE.GT_BRACKET,
ResTypes.INSTANCE.BRACKET_GT,
ResTypes.INSTANCE.BRACKET_LT,
ResTypes.INSTANCE.BRACE_LT,
ResTypes.INSTANCE.DOTDOT);
private static final Set<IElementType> NS_OPTIONS_TYPES =
of(ResTypes.INSTANCE.NONE, ResTypes.INSTANCE.SOME);
private static final Set<IElementType> OCL_KEYWORD_TYPES =
of(
OclTypes.INSTANCE.OPEN,
OclTypes.INSTANCE.MODULE,
OclTypes.INSTANCE.FUN,
OclTypes.INSTANCE.LET,
OclTypes.INSTANCE.TYPE,
OclTypes.INSTANCE.INCLUDE,
OclTypes.INSTANCE.EXTERNAL,
OclTypes.INSTANCE.IF,
OclTypes.INSTANCE.ELSE,
OclTypes.INSTANCE.ENDIF,
OclTypes.INSTANCE.SWITCH,
OclTypes.INSTANCE.TRY,
OclTypes.INSTANCE.RAISE,
OclTypes.INSTANCE.FOR,
OclTypes.INSTANCE.IN,
OclTypes.INSTANCE.TO,
OclTypes.INSTANCE.BOOL_VALUE,
OclTypes.INSTANCE.REF,
OclTypes.INSTANCE.EXCEPTION,
OclTypes.INSTANCE.WHEN,
OclTypes.INSTANCE.AND,
OclTypes.INSTANCE.REC,
OclTypes.INSTANCE.WHILE,
OclTypes.INSTANCE.ASR,
OclTypes.INSTANCE.CLASS,
OclTypes.INSTANCE.CONSTRAINT,
OclTypes.INSTANCE.DOWNTO,
OclTypes.INSTANCE.FUNCTOR,
OclTypes.INSTANCE.INHERIT,
OclTypes.INSTANCE.INITIALIZER,
OclTypes.INSTANCE.LAND,
OclTypes.INSTANCE.LOR,
OclTypes.INSTANCE.LSL,
OclTypes.INSTANCE.LSR,
OclTypes.INSTANCE.LXOR,
OclTypes.INSTANCE.METHOD,
OclTypes.INSTANCE.MOD,
OclTypes.INSTANCE.NEW,
OclTypes.INSTANCE.NONREC,
OclTypes.INSTANCE.OR,
OclTypes.INSTANCE.PRIVATE,
OclTypes.INSTANCE.VIRTUAL,
OclTypes.INSTANCE.AS,
OclTypes.INSTANCE.MUTABLE,
OclTypes.INSTANCE.OF,
OclTypes.INSTANCE.VAL,
OclTypes.INSTANCE.PRI,
// OCaml
OclTypes.INSTANCE.MATCH,
OclTypes.INSTANCE.WITH,
OclTypes.INSTANCE.DO,
OclTypes.INSTANCE.DONE,
OclTypes.INSTANCE.RECORD,
OclTypes.INSTANCE.BEGIN,
OclTypes.INSTANCE.END,
OclTypes.INSTANCE.LAZY,
OclTypes.INSTANCE.ASSERT,
OclTypes.INSTANCE.THEN,
OclTypes.INSTANCE.FUNCTION,
OclTypes.INSTANCE.STRUCT,
OclTypes.INSTANCE.SIG,
OclTypes.INSTANCE.OBJECT,
OclTypes.INSTANCE.DIRECTIVE_IF,
OclTypes.INSTANCE.DIRECTIVE_ELSE,
OclTypes.INSTANCE.DIRECTIVE_ELIF,
OclTypes.INSTANCE.DIRECTIVE_END,
OclTypes.INSTANCE.DIRECTIVE_ENDIF);
private static final Set<IElementType> OCL_OPERATION_SIGN_TYPES =
of(
OclTypes.INSTANCE.L_AND,
OclTypes.INSTANCE.L_OR,
OclTypes.INSTANCE.SHORTCUT,
OclTypes.INSTANCE.ARROW,
OclTypes.INSTANCE.PIPE_FIRST,
OclTypes.INSTANCE.PIPE_FORWARD,
OclTypes.INSTANCE.EQEQEQ,
OclTypes.INSTANCE.EQEQ,
OclTypes.INSTANCE.EQ,
OclTypes.INSTANCE.NOT_EQEQ,
OclTypes.INSTANCE.NOT_EQ,
OclTypes.INSTANCE.DIFF,
OclTypes.INSTANCE.COLON,
OclTypes.INSTANCE.SINGLE_QUOTE,
OclTypes.INSTANCE.DOUBLE_QUOTE,
OclTypes.INSTANCE.CARRET,
OclTypes.INSTANCE.PLUSDOT,
OclTypes.INSTANCE.MINUSDOT,
OclTypes.INSTANCE.SLASHDOT,
OclTypes.INSTANCE.STARDOT,
OclTypes.INSTANCE.PLUS,
OclTypes.INSTANCE.MINUS,
OclTypes.INSTANCE.SLASH,
OclTypes.INSTANCE.STAR,
OclTypes.INSTANCE.PERCENT,
OclTypes.INSTANCE.PIPE,
OclTypes.INSTANCE.ARROBASE,
OclTypes.INSTANCE.SHARP,
OclTypes.INSTANCE.SHARPSHARP,
OclTypes.INSTANCE.QUESTION_MARK,
OclTypes.INSTANCE.EXCLAMATION_MARK,
OclTypes.INSTANCE.LT_OR_EQUAL,
OclTypes.INSTANCE.GT_OR_EQUAL,
OclTypes.INSTANCE.AMPERSAND,
OclTypes.INSTANCE.LEFT_ARROW,
OclTypes.INSTANCE.RIGHT_ARROW,
OclTypes.INSTANCE.COLON_EQ,
OclTypes.INSTANCE.COLON_GT,
OclTypes.INSTANCE.GT,
OclTypes.INSTANCE.GT_BRACE,
OclTypes.INSTANCE.GT_BRACKET,
OclTypes.INSTANCE.BRACKET_GT,
OclTypes.INSTANCE.BRACKET_LT,
OclTypes.INSTANCE.BRACE_LT,
OclTypes.INSTANCE.DOTDOT);
private static final Set<IElementType> OCL_OPTIONS_TYPES =
of(OclTypes.INSTANCE.NONE, OclTypes.INSTANCE.SOME);
private static final TextAttributesKey TYPE_ARGUMENT_KEY =
TextAttributesKey.createTextAttributesKey("TYPE_ARGUMENT");
public static final TextAttributesKey ANNOTATION_ =
createTextAttributesKey("REASONML_ANNOTATION", DefaultLanguageHighlighterColors.METADATA);
public static final TextAttributesKey BRACES_ =
createTextAttributesKey("REASONML_BRACES", DefaultLanguageHighlighterColors.BRACES);
public static final TextAttributesKey BRACKETS_ =
createTextAttributesKey("REASONML_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS);
public static final TextAttributesKey CODE_LENS_ =
createTextAttributesKey("REASONML_CODE_LENS", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD_ =
createTextAttributesKey("REASONML_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey MARKUP_TAG_ =
createTextAttributesKey("REASONML_MARKUP_TAG", DefaultLanguageHighlighterColors.MARKUP_TAG);
public static final TextAttributesKey MARKUP_ATTRIBUTE_ =
createTextAttributesKey(
"REASONML_MARKUP_ATTRIBUTE", DefaultLanguageHighlighterColors.MARKUP_ATTRIBUTE);
public static final TextAttributesKey MODULE_NAME_ =
createTextAttributesKey("REASONML_MODULE_NAME", DefaultLanguageHighlighterColors.CLASS_NAME);
public static final TextAttributesKey NUMBER_ =
createTextAttributesKey("REASONML_NUMBER", DefaultLanguageHighlighterColors.NUMBER);
public static final TextAttributesKey OPERATION_SIGN_ =
createTextAttributesKey(
"REASONML_OPERATION_SIGN", DefaultLanguageHighlighterColors.OPERATION_SIGN);
public static final TextAttributesKey OPTION_ =
createTextAttributesKey("REASONML_OPTION", DefaultLanguageHighlighterColors.STATIC_FIELD);
public static final TextAttributesKey PARENS_ =
createTextAttributesKey("REASONML_PARENS", DefaultLanguageHighlighterColors.PARENTHESES);
public static final TextAttributesKey POLY_VARIANT_ =
createTextAttributesKey(
"REASONML_POLY_VARIANT", DefaultLanguageHighlighterColors.STATIC_FIELD);
public static final TextAttributesKey RML_COMMENT_ =
createTextAttributesKey("REASONML_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey SEMICOLON_ =
createTextAttributesKey("REASONML_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON);
public static final TextAttributesKey STRING_ =
createTextAttributesKey("REASONML_STRING", DefaultLanguageHighlighterColors.STRING);
public static final TextAttributesKey TYPE_ARGUMENT_ =
createTextAttributesKey("REASONML_TYPE_ARGUMENT", TYPE_ARGUMENT_KEY);
public static final TextAttributesKey VARIANT_NAME_ =
createTextAttributesKey(
"REASONML_VARIANT_NAME", DefaultLanguageHighlighterColors.STATIC_FIELD);
private static final TextAttributesKey BAD_CHAR_ =
createTextAttributesKey("REASONML_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER);
private static final TextAttributesKey[] NUMBER_KEYS = new TextAttributesKey[]{NUMBER_};
private static final TextAttributesKey[] COMMENT_KEYS = new TextAttributesKey[]{RML_COMMENT_};
private static final TextAttributesKey[] STRING_KEYS = new TextAttributesKey[]{STRING_};
private static final TextAttributesKey[] TYPE_ARGUMENT_KEYS = new TextAttributesKey[]{TYPE_ARGUMENT_};
private static final TextAttributesKey[] POLY_VARIANT_KEYS = new TextAttributesKey[]{POLY_VARIANT_};
private static final TextAttributesKey[] BRACKET_KEYS = new TextAttributesKey[]{BRACKETS_};
private static final TextAttributesKey[] BRACE_KEYS = new TextAttributesKey[]{BRACES_};
private static final TextAttributesKey[] PAREN_KEYS = new TextAttributesKey[]{PARENS_};
private static final TextAttributesKey[] OPTION_KEYS = new TextAttributesKey[]{OPTION_};
private static final TextAttributesKey[] KEYWORD_KEYS = new TextAttributesKey[]{KEYWORD_};
private static final TextAttributesKey[] SEMICOLON_KEYS = new TextAttributesKey[]{SEMICOLON_};
private static final TextAttributesKey[] DOT_KEYS = new TextAttributesKey[]{OPERATION_SIGN_};
private static final TextAttributesKey[] COMMA_KEYS = new TextAttributesKey[]{OPERATION_SIGN_};
private static final TextAttributesKey[] OPERATION_SIGN_KEYS = new TextAttributesKey[]{OPERATION_SIGN_};
private static final TextAttributesKey[] BAD_CHAR_KEYS = new TextAttributesKey[]{BAD_CHAR_};
private static final TextAttributesKey[] EMPTY_KEYS = new TextAttributesKey[0];
private final ORTypes m_types;
public ORSyntaxHighlighter(ORTypes types) {
m_types = types;
}
@Override
public @NotNull Lexer getHighlightingLexer() {
return m_types instanceof RmlTypes
? new RmlLexer()
: m_types instanceof ResTypes ? new ResLexer() : new OclLexer();
}
@Override
public @NotNull TextAttributesKey[] getTokenHighlights(@NotNull IElementType tokenType) {
if (tokenType.equals(m_types.MULTI_COMMENT) || tokenType.equals(m_types.SINGLE_COMMENT)) {
return COMMENT_KEYS;
} else if (tokenType.equals(m_types.LBRACE) || tokenType.equals(m_types.RBRACE)) {
return BRACE_KEYS;
} else if (tokenType.equals(m_types.LBRACKET)
|| tokenType.equals(m_types.RBRACKET)
|| tokenType.equals(m_types.LARRAY)
|| tokenType.equals(m_types.RARRAY)
|| tokenType.equals(m_types.ML_STRING_OPEN)
|| tokenType.equals(m_types.ML_STRING_CLOSE)
|| tokenType.equals(m_types.JS_STRING_OPEN)
|| tokenType.equals(m_types.JS_STRING_CLOSE)) {
return BRACKET_KEYS;
} else if (tokenType.equals(m_types.LPAREN) || tokenType.equals(m_types.RPAREN)) {
return PAREN_KEYS;
} else if (tokenType.equals(m_types.INT_VALUE) || tokenType.equals(m_types.FLOAT_VALUE)) {
return NUMBER_KEYS;
} else if (m_types.DOT.equals(tokenType)) {
return DOT_KEYS;
} else if (m_types.TYPE_ARGUMENT.equals(tokenType)) {
return TYPE_ARGUMENT_KEYS;
} else if (m_types.POLY_VARIANT.equals(tokenType)) {
return POLY_VARIANT_KEYS;
} else if (m_types.COMMA.equals(tokenType)) {
return COMMA_KEYS;
} else if (m_types.SEMI.equals(tokenType) || m_types.SEMISEMI.equals(tokenType)) {
return SEMICOLON_KEYS;
} else if (m_types.STRING_VALUE.equals(tokenType) || m_types.CHAR_VALUE.equals(tokenType)) {
return STRING_KEYS;
} else if (m_types == RmlTypes.INSTANCE) {
if (RML_KEYWORD_TYPES.contains(tokenType)) {
return KEYWORD_KEYS;
} else if (RML_OPERATION_SIGN_TYPES.contains(tokenType)) {
return OPERATION_SIGN_KEYS;
} else if (RML_OPTIONS_TYPES.contains(tokenType)) {
return OPTION_KEYS;
}
} else if (m_types == ResTypes.INSTANCE) {
if (NS_KEYWORD_TYPES.contains(tokenType)) {
return KEYWORD_KEYS;
} else if (NS_OPERATION_SIGN_TYPES.contains(tokenType)) {
return OPERATION_SIGN_KEYS;
} else if (NS_OPTIONS_TYPES.contains(tokenType)) {
return OPTION_KEYS;
}
} else if (m_types == OclTypes.INSTANCE) {
if (OCL_KEYWORD_TYPES.contains(tokenType)) {
return KEYWORD_KEYS;
} else if (OCL_OPERATION_SIGN_TYPES.contains(tokenType)) {
return OPERATION_SIGN_KEYS;
} else if (OCL_OPTIONS_TYPES.contains(tokenType)) {
return OPTION_KEYS;
}
} else if (BAD_CHARACTER.equals(tokenType)) {
return BAD_CHAR_KEYS;
}
return EMPTY_KEYS;
}
@NotNull
private static Set<IElementType> of(IElementType... types) {
Set<IElementType> result = new HashSet<>();
Collections.addAll(result, types);
return result;
}
}
| reasonml-editor/reasonml-idea-plugin | src/com/reason/ide/highlight/ORSyntaxHighlighter.java | Java | mit | 24,489 |
/**
* Babel plugin for removing specific properties that match a given regular expression.
*
*/
"use strict";
exports.default = function() {
return {
visitor: {
// ObjectProperty Visitor
ObjectProperty: function ObjectProperty(path, state) {
/**
* Define a visitor for nodes of type `ObjectProperty`.
* Nodes w/ property names that match a specified regex will be removed.
*
* :param path: the path of the visited node
* :param state: options that are passed to the plugin
*
*/
const regexp = new RegExp(state.opts.regexp);
if (regexp.test(path.node.key.name) || regexp.test(path.node.key.value)) {
// Oh sheet, found a match, remove dis beech
path.remove();
}
}
}
};
};
module.exports = exports["default"];
| bdupharm/babel-plugin-remove-object-properties | lib/plugin.js | JavaScript | mit | 998 |
using System;
using System.Reflection;
namespace AssemblyLoader
{
/// <summary>
/// Cross platform AssemblyLoader implementations
/// </summary>
public static class Loader
{
/// <summary>
/// Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly
/// is loaded into the application domain of the caller.
/// </summary>
/// <param name="rawAssembly"></param>
public static Assembly LoadAssembly(byte[] rawAssembly)
{
throw NotImplementedInReferenceAssembly();
}
/// <summary>
/// Returns true if the environment you are running under supports assembly load at runtime.
/// </summary>
public static bool RuntimeLoadAvailable
{
get { return false; }
}
internal static Exception NotImplementedInReferenceAssembly()
{
return new NotImplementedException("The portable implementation of AssemblyLoader was called. Either you are running on a supported platform but haven't installed the AssemblyLoader package into the platform project, or you are trying to use AssemblyLoader on an unsupported (i.e. WinRT) platform.");
}
}
} | rdavisau/loadassembly-for-pcl | AssemblyLoader/AssemblyLoader.Plugin/AssemblyLoader.cs | C# | mit | 1,294 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Response;
use Symfony\Component\HttpClient\Chunk\DataChunk;
use Symfony\Component\HttpClient\Chunk\ErrorChunk;
use Symfony\Component\HttpClient\Chunk\FirstChunk;
use Symfony\Component\HttpClient\Chunk\LastChunk;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\Exception\JsonException;
use Symfony\Component\HttpClient\Exception\RedirectionException;
use Symfony\Component\HttpClient\Exception\ServerException;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\Internal\ClientState;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* Implements the common logic for response classes.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait ResponseTrait
{
private $logger;
private $headers = [];
/**
* @var callable|null A callback that initializes the two previous properties
*/
private $initializer;
/**
* @var resource A php://temp stream typically
*/
private $content;
private $info = [
'response_headers' => [],
'http_code' => 0,
'error' => null,
'canceled' => false,
];
/** @var resource */
private $handle;
private $id;
private $timeout = 0;
private $finalInfo;
private $offset = 0;
private $jsonData;
/**
* {@inheritdoc}
*/
public function getStatusCode(): int
{
if ($this->initializer) {
($this->initializer)($this);
$this->initializer = null;
}
return $this->info['http_code'];
}
/**
* {@inheritdoc}
*/
public function getHeaders(bool $throw = true): array
{
if ($this->initializer) {
($this->initializer)($this);
$this->initializer = null;
}
if ($throw) {
$this->checkStatusCode();
}
return $this->headers;
}
/**
* {@inheritdoc}
*/
public function getContent(bool $throw = true): string
{
if ($this->initializer) {
($this->initializer)($this);
$this->initializer = null;
}
if ($throw) {
$this->checkStatusCode();
}
if (null === $this->content) {
$content = null;
foreach (self::stream([$this]) as $chunk) {
if (!$chunk->isLast()) {
$content .= $chunk->getContent();
}
}
if (null !== $content) {
return $content;
}
if ('HEAD' === $this->info['http_method'] || \in_array($this->info['http_code'], [204, 304], true)) {
return '';
}
throw new TransportException('Cannot get the content of the response twice: buffering is disabled.');
}
foreach (self::stream([$this]) as $chunk) {
// Chunks are buffered in $this->content already
}
rewind($this->content);
return stream_get_contents($this->content);
}
/**
* {@inheritdoc}
*/
public function toArray(bool $throw = true): array
{
if ('' === $content = $this->getContent($throw)) {
throw new TransportException('Response body is empty.');
}
if (null !== $this->jsonData) {
return $this->jsonData;
}
$contentType = $this->headers['content-type'][0] ?? 'application/json';
if (!preg_match('/\bjson\b/i', $contentType)) {
throw new JsonException(sprintf('Response content-type is "%s" while a JSON-compatible one was expected.', $contentType));
}
try {
$content = json_decode($content, true, 512, JSON_BIGINT_AS_STRING | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0));
} catch (\JsonException $e) {
throw new JsonException($e->getMessage(), $e->getCode());
}
if (\PHP_VERSION_ID < 70300 && JSON_ERROR_NONE !== json_last_error()) {
throw new JsonException(json_last_error_msg(), json_last_error());
}
if (!\is_array($content)) {
throw new JsonException(sprintf('JSON content was expected to decode to an array, %s returned.', \gettype($content)));
}
if (null !== $this->content) {
// Option "buffer" is true
return $this->jsonData = $content;
}
return $content;
}
/**
* {@inheritdoc}
*/
public function cancel(): void
{
$this->info['canceled'] = true;
$this->info['error'] = 'Response has been canceled.';
$this->close();
}
/**
* Casts the response to a PHP stream resource.
*
* @return resource
*
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function toStream(bool $throw = true)
{
if ($throw) {
// Ensure headers arrived
$this->getHeaders($throw);
}
$stream = StreamWrapper::createResource($this);
stream_get_meta_data($stream)['wrapper_data']
->bindHandles($this->handle, $this->content);
return $stream;
}
/**
* Closes the response and all its network handles.
*/
abstract protected function close(): void;
/**
* Adds pending responses to the activity list.
*/
abstract protected static function schedule(self $response, array &$runningResponses): void;
/**
* Performs all pending non-blocking operations.
*/
abstract protected static function perform(ClientState $multi, array &$responses): void;
/**
* Waits for network activity.
*/
abstract protected static function select(ClientState $multi, float $timeout): int;
private static function addResponseHeaders(array $responseHeaders, array &$info, array &$headers, string &$debug = ''): void
{
foreach ($responseHeaders as $h) {
if (11 <= \strlen($h) && '/' === $h[4] && preg_match('#^HTTP/\d+(?:\.\d+)? ([12345]\d\d) .*#', $h, $m)) {
if ($headers) {
$debug .= "< \r\n";
$headers = [];
}
$info['http_code'] = (int) $m[1];
} elseif (2 === \count($m = explode(':', $h, 2))) {
$headers[strtolower($m[0])][] = ltrim($m[1]);
}
$debug .= "< {$h}\r\n";
$info['response_headers'][] = $h;
}
$debug .= "< \r\n";
if (!$info['http_code']) {
throw new TransportException('Invalid or missing HTTP status line.');
}
}
private function checkStatusCode()
{
if (500 <= $this->info['http_code']) {
throw new ServerException($this);
}
if (400 <= $this->info['http_code']) {
throw new ClientException($this);
}
if (300 <= $this->info['http_code']) {
throw new RedirectionException($this);
}
}
/**
* Ensures the request is always sent and that the response code was checked.
*/
private function doDestruct()
{
if ($this->initializer && null === $this->info['error']) {
($this->initializer)($this);
$this->initializer = null;
$this->checkStatusCode();
}
}
/**
* Implements an event loop based on a buffer activity queue.
*
* @internal
*/
public static function stream(iterable $responses, float $timeout = null): \Generator
{
$runningResponses = [];
foreach ($responses as $response) {
self::schedule($response, $runningResponses);
}
$lastActivity = microtime(true);
$isTimeout = false;
while (true) {
$hasActivity = false;
$timeoutMax = 0;
$timeoutMin = $timeout ?? INF;
/** @var ClientState $multi */
foreach ($runningResponses as $i => [$multi]) {
$responses = &$runningResponses[$i][1];
self::perform($multi, $responses);
foreach ($responses as $j => $response) {
$timeoutMax = $timeout ?? max($timeoutMax, $response->timeout);
$timeoutMin = min($timeoutMin, $response->timeout, 1);
$chunk = false;
if (isset($multi->handlesActivity[$j])) {
// no-op
} elseif (!isset($multi->openHandles[$j])) {
unset($responses[$j]);
continue;
} elseif ($isTimeout) {
$multi->handlesActivity[$j] = [new ErrorChunk($response->offset, sprintf('Idle timeout reached for "%s".', $response->getInfo('url')))];
} else {
continue;
}
while ($multi->handlesActivity[$j] ?? false) {
$hasActivity = true;
$isTimeout = false;
if (\is_string($chunk = array_shift($multi->handlesActivity[$j]))) {
$response->offset += \strlen($chunk);
$chunk = new DataChunk($response->offset, $chunk);
} elseif (null === $chunk) {
$e = $multi->handlesActivity[$j][0];
unset($responses[$j], $multi->handlesActivity[$j]);
$response->close();
if (null !== $e) {
$response->info['error'] = $e->getMessage();
if ($e instanceof \Error) {
throw $e;
}
$chunk = new ErrorChunk($response->offset, $e);
} else {
$chunk = new LastChunk($response->offset);
}
} elseif ($chunk instanceof ErrorChunk) {
unset($responses[$j]);
$isTimeout = true;
} elseif ($chunk instanceof FirstChunk) {
if ($response->logger) {
$info = $response->getInfo();
$response->logger->info(sprintf('Response: "%s %s"', $info['http_code'], $info['url']));
}
yield $response => $chunk;
if ($response->initializer && null === $response->info['error']) {
// Ensure the HTTP status code is always checked
$response->getHeaders(true);
}
continue;
}
yield $response => $chunk;
}
unset($multi->handlesActivity[$j]);
if ($chunk instanceof ErrorChunk && !$chunk->didThrow()) {
// Ensure transport exceptions are always thrown
$chunk->getContent();
}
}
if (!$responses) {
unset($runningResponses[$i]);
}
// Prevent memory leaks
$multi->handlesActivity = $multi->handlesActivity ?: [];
$multi->openHandles = $multi->openHandles ?: [];
}
if (!$runningResponses) {
break;
}
if ($hasActivity) {
$lastActivity = microtime(true);
continue;
}
switch (self::select($multi, $timeoutMin)) {
case -1: usleep(min(500, 1E6 * $timeoutMin)); break;
case 0: $isTimeout = microtime(true) - $lastActivity > $timeoutMax; break;
}
}
}
}
| shieldo/symfony | src/Symfony/Component/HttpClient/Response/ResponseTrait.php | PHP | mit | 12,832 |
module Meta
module Filelib
def self.create_directory(name)
unless name.nil?
if File.directory?(name)
puts "directory already exists".yellow
else
FileUtils.mkdir_p(name)
puts "directory #{name} created".green
end
end
end
def self.create_file( text, filename, ext, dest, overwrite=false )
filename = File.basename( filename, File.extname(filename) ) + ext
filename = dest + SLASH + filename
reply = false
write = false
if File.exists?(filename)
reply = agree("file #{filename} exists, overwrite?".red) {
|q| q.default = "n" } unless overwrite
else
write = true
end
if overwrite or reply or write
f = File.open( filename, "w" )
f.write(text)
f.close
if overwrite or reply
puts "file #{filename} overwritten".green
else
puts "file #{filename} created".green
end
end
end
def self.get_templates(pattern)
return Dir.glob( pattern, File::FNM_CASEFOLD )
end
def self.get_contents
return Dir.glob( Meta::MARKDOWN, File::FNM_CASEFOLD )
end
end
end
| stephenhu/meta | lib/meta/filelib.rb | Ruby | mit | 1,226 |