diff
stringlengths
41
2.03M
msg
stringlengths
1
1.5k
repo
stringlengths
5
40
sha
stringlengths
40
40
time
stringlengths
20
20
mmm a / scripts / global_metadata . json <nl> ppp b / scripts / global_metadata . json <nl> <nl> " updated " : " 18 - 05 - 2019 08 : 11 : 06 " <nl> } <nl> } , <nl> + " min_lateness " : { <nl> + " location " : " code / greedy_algorithms / src / min_lateness " , <nl> + " opengenus_discuss " : " " , <nl> + " opengenus_iq " : " https : / / iq . opengenus . org / scheduling - to - minimize - lateness / " , <nl> + " files " : [ <nl> + " README . md " , <nl> + " min_lateness . cpp " <nl> + ] , <nl> + " updated " : " 18 - 04 - 2020 08 : 11 : 06 " <nl> + } , <nl> " theory_of_computation " : { <nl> " nondeterministic_finite_atomaton " : { <nl> " location " : " code / theory_of_computation / src / nondeterministic_finite_atomaton " , <nl>
Merge pull request from BhardwajShweta25 / patch - 9
OpenGenus/cosmos
2ebe311c92d4cdb0057fe5f825244abfff6d5127
2020-05-27T15:05:29Z
mmm a / README . md <nl> ppp b / README . md <nl> The main advantage of Cmder is portability . It is designed to be totally self - co <nl> <nl> # # Integration <nl> <nl> - So you ' ve experimented with cmder a little and want to give it a shot in a more permanent home ; <nl> + So you ' ve experimented with Cmder a little and want to give it a shot in a more permanent home ; <nl> <nl> # # # Shortcut to open Cmder in a chosen folder <nl> <nl> All aliases will be saved in ` / config / aliases ` file <nl> <nl> # # # SSH Agent <nl> <nl> - To start SSH agent simply call ` agent ` , which is in the ` bin ` folder . <nl> + To start SSH agent simply call ` start - ssh - agent ` , which is in the ` vendor / git - for - windows / cmd ` folder . <nl> <nl> - If you want to run SSH agent on startup , uncomment the line in ` / vendor / init . bat ` so it says ` @ call " % CMDER_ROOT % / bin / agent . cmd " ` . <nl> + If you want to run SSH agent on startup , uncomment the line in ` / vendor / init . bat ` so it says ` @ call " % GIT_INSTALL_ROOT % / cmd / start - ssh - agent . cmd " ` . <nl> <nl> # # Todo <nl> <nl> deleted file mode 100644 <nl> index 4eaa6141 . . 00000000 <nl> mmm a / bin / agent . cmd <nl> ppp / dev / null <nl> <nl> - @ ECHO OFF <nl> - <nl> - REM Set default sock file <nl> - SET SSH_AUTH_SOCK = / tmp / ssh - agent . sock <nl> - <nl> - REM Check socket is available <nl> - IF NOT EXIST " % TMP % \ ssh - agent . sock " GOTO : RUNAGENT <nl> - <nl> - REM Check if an ssh - agent is running <nl> - FOR / f " tokens = * " % % I IN ( ' ps ^ | grep ssh - agent ^ | sed " s / ^ * \ ( [ 0 - 9 ] \ + \ ) . * / \ 1 / " ' ) DO SET VAR = % % I <nl> - IF " % VAR % " = = " " GOTO : RUNAGENT <nl> - <nl> - REM Check if socket file is valid <nl> - ssh - add - l 1 > NUL 2 > & 1 <nl> - IF ERRORLEVEL 1 GOTO : RUNAGENT <nl> - GOTO : ADDKEYS <nl> - <nl> - : RUNAGENT <nl> - REM Remove old socket file <nl> - rm - f / tmp / ssh - agent . sock <nl> - <nl> - REM Run ssh - agent and save ( last ) PID in VAR <nl> - SET VAR = <nl> - FOR / f " tokens = * " % % J IN ( ' ssh - agent - a / tmp / ssh - agent . sock ' ) DO FOR / f " tokens = * " % % K IN ( ' echo % % J ^ | grep " SSH_AGENT_PID " ^ | sed " s / ^ SSH_AGENT_PID = \ ( [ 0 - 9 ] \ + \ ) ; . * / \ 1 / " ' ) DO SET VAR = % % K <nl> - <nl> - : ADDKEYS <nl> - SET SSH_AUTH_PID = % VAR % <nl> - <nl> - REM Check if ssh keys are known <nl> - SET KEYS = <nl> - FOR / f " tokens = * " % % I IN ( ' DIR / B " % HOME % \ . ssh \ * _rsa " ' ) DO CALL : CHECKKEY % % I <nl> - <nl> - REM Add missing ssh keys at once <nl> - IF NOT " % KEYS % " = = " " ssh - add % KEYS % <nl> - GOTO : END <nl> - <nl> - REM Functions <nl> - REM Check if ssh key has to be added <nl> - : CHECKKEY <nl> - SET VAR = <nl> - FOR / f " tokens = * " % % J IN ( ' ssh - add - l ^ | grep " % 1 " ' ) DO SET VAR = % % J <nl> - IF " % VAR % " = = " " SET KEYS = ' % HOME % \ . ssh \ % 1 ' % KEYS % <nl> - GOTO : EOF <nl> - <nl> - : END <nl> - @ ECHO ON <nl> mmm a / config / ConEmu . xml <nl> ppp b / config / ConEmu . xml <nl> <nl> < value name = " Name " type = " string " data = " { git sh } " / > <nl> < value name = " Hotkey " type = " dword " data = " 00000000 " / > <nl> < value name = " GuiArgs " type = " string " data = " / icon & quot ; % CMDER_ROOT % \ cmder . exe & quot ; " / > <nl> - < value name = " Cmd1 " type = " string " data = " cmd / k & quot ; % ConEmuDir % \ . . \ init . bat & amp ; % CMDER_ROOT % \ vendor \ msysgit \ bin \ bash - - login - i & quot ; - new_console : d : % USERPROFILE % " / > <nl> - < value name = " Cmd2 " type = " string " data = " % CMDER_ROOT % \ vendor \ msysgit \ git - bash . bat " / > <nl> + < value name = " Cmd1 " type = " string " data = " cmd / k & quot ; % ConEmuDir % \ . . \ init . bat & amp ; % CMDER_ROOT % \ vendor \ git - for - windows \ bin \ bash - - login - i & quot ; - new_console : d : % USERPROFILE % " / > <nl> + < value name = " Cmd2 " type = " string " data = " % CMDER_ROOT % \ vendor \ git - for - windows \ git - bash . exe " / > <nl> < value name = " Active " type = " dword " data = " 00000000 " / > <nl> < value name = " Count " type = " dword " data = " 00000001 " / > <nl> < / key > <nl> mmm a / scripts / build . ps1 <nl> ppp b / scripts / build . ps1 <nl> <nl> . EXAMPLE <nl> . \ build . ps1 <nl> <nl> - Executes the default build for cmder ; Conemu , clink . This is equivalent to the " minimum " style package in the releases <nl> + Executes the default build for Cmder ; Conemu , clink . This is equivalent to the " minimum " style package in the releases <nl> . EXAMPLE <nl> . \ build . ps1 - Full <nl> <nl> - Executes a full build for cmder , including git . This is equivalent to the " full " style package in the releases <nl> + Executes a full build for Cmder , including git . This is equivalent to the " full " style package in the releases <nl> . EXAMPLE <nl> . \ build - verbose <nl> <nl> if ( $ config - ne " " ) { <nl> <nl> <nl> foreach ( $ s in $ sources ) { <nl> - if ( $ Full - eq $ false - and $ s . name - eq " msysgit " ) { <nl> + if ( $ Full - eq $ false - and $ s . name - eq " git - for - windows " ) { <nl> Continue <nl> } <nl> <nl> mmm a / scripts / pack . ps1 <nl> ppp b / scripts / pack . ps1 <nl> Ensure - Executable " 7z " <nl> $ targets = @ { <nl> " cmder . zip " = $ null ; <nl> " cmder . 7z " = $ null ; <nl> - " cmder_mini . zip " = " - x ! ` " vendor \ msysgit ` " " ; <nl> + " cmder_mini . zip " = " - x ! ` " vendor \ git - for - windows ` " " ; <nl> } <nl> <nl> Delete - Existing " . . \ Version * " <nl> mmm a / vendor / init . bat <nl> ppp b / vendor / init . bat <nl> <nl> : : Run clink <nl> @ " % CMDER_ROOT % \ vendor \ clink \ clink_x % architecture % . exe " inject - - quiet - - profile " % CMDER_ROOT % \ config " <nl> <nl> - : : Prepare for msysgit <nl> + : : Prepare for git - for - windows <nl> <nl> : : I do not even know , copypasted from their . bat <nl> @ set PLINK_PROTOCOL = ssh <nl> <nl> ) else if exist " % ProgramFiles ( x86 ) % \ Git " ( <nl> set " GIT_INSTALL_ROOT = % ProgramFiles ( x86 ) % \ Git " <nl> ) else if exist " % CMDER_ROOT % \ vendor " ( <nl> - set " GIT_INSTALL_ROOT = % CMDER_ROOT % \ vendor \ msysgit " <nl> + set " GIT_INSTALL_ROOT = % CMDER_ROOT % \ vendor \ git - for - windows " <nl> ) <nl> <nl> : : Add git to the path <nl> @ if defined GIT_INSTALL_ROOT ( <nl> - set " PATH = % GIT_INSTALL_ROOT % \ bin ; % GIT_INSTALL_ROOT % \ share \ vim \ vim74 ; % PATH % " <nl> + set " PATH = % GIT_INSTALL_ROOT % \ bin ; % GIT_INSTALL_ROOT % \ usr \ bin ; % GIT_INSTALL_ROOT % \ share \ vim \ vim74 ; % PATH % " <nl> : : define SVN_SSH so we can use git svn with ssh svn repositories <nl> if not defined SVN_SSH set " SVN_SSH = % GIT_INSTALL_ROOT : \ = \ \ % \ \ bin \ \ ssh . exe " <nl> ) <nl> <nl> ) <nl> ) <nl> <nl> - : : @ call " % CMDER_ROOT % / bin / agent . cmd " <nl> + : : @ call " % GIT_INSTALL_ROOT % / cmd / start - ssh - agent . cmd " <nl> mmm a / vendor / profile . ps1 <nl> ppp b / vendor / profile . ps1 <nl> try { <nl> # Check if git is on PATH , i . e . Git already installed on system <nl> Get - command - Name " git " - ErrorAction Stop > $ null <nl> } catch { <nl> - $ env : Path + = " ; $ env : CMDER_ROOT \ vendor \ msysgit \ bin " <nl> + $ env : Path + = " ; $ env : CMDER_ROOT \ vendor \ git - for - windows \ bin " <nl> } <nl> <nl> try { <nl> mmm a / vendor / sources . json <nl> ppp b / vendor / sources . json <nl> <nl> [ <nl> { <nl> - " name " : " msysgit " , <nl> - " version " : " 1 . 9 . 5 - preview20150319 " , <nl> - " url " : " https : / / github . com / msysgit / msysgit / releases / download / Git - 1 . 9 . 5 - preview20150319 / PortableGit - 1 . 9 . 5 - preview20150319 . 7z " <nl> + " name " : " git - for - windows " , <nl> + " version " : " v2 . 6 . 1 . windows . 1 " , <nl> + " url " : " https : / / github . com / git - for - windows / git / releases / download / v2 . 6 . 1 . windows . 1 / PortableGit - 2 . 6 . 1 - 32 - bit . 7z . exe " <nl> } , <nl> { <nl> " name " : " clink " , <nl>
Merge pull request from Stanzilla / bumpgit
cmderdev/cmder
1f75f85b7c9a8887b1582875825424e3b89c068a
2015-10-12T11:23:06Z
mmm a / modules / features2d / src / matchers . cpp <nl> ppp b / modules / features2d / src / matchers . cpp <nl> const Mat DescriptorMatcher : : DescriptorCollection : : getDescriptor ( int globalDesc <nl> <nl> void DescriptorMatcher : : DescriptorCollection : : getLocalIdx ( int globalDescIdx , int & imgIdx , int & localDescIdx ) const <nl> { <nl> - imgIdx = - 1 ; <nl> - CV_Assert ( globalDescIdx < size ( ) ) ; <nl> - for ( size_t i = 1 ; i < startIdxs . size ( ) ; i + + ) <nl> - { <nl> - if ( globalDescIdx < startIdxs [ i ] ) <nl> - { <nl> - imgIdx = ( int ) ( i - 1 ) ; <nl> - break ; <nl> - } <nl> - } <nl> - imgIdx = imgIdx = = - 1 ? ( int ) ( startIdxs . size ( ) - 1 ) : imgIdx ; <nl> - localDescIdx = globalDescIdx - startIdxs [ imgIdx ] ; <nl> + CV_Assert ( ( globalDescIdx > = 0 ) & & ( globalDescIdx < size ( ) ) ) ; <nl> + std : : vector < int > : : const_iterator img_it = std : : upper_bound ( startIdxs . begin ( ) , startIdxs . end ( ) , globalDescIdx ) ; <nl> + - - img_it ; <nl> + imgIdx = img_it - startIdxs . begin ( ) ; <nl> + localDescIdx = globalDescIdx - ( * img_it ) ; <nl> } <nl> <nl> int DescriptorMatcher : : DescriptorCollection : : size ( ) const <nl>
- replace the linear search in a sorted list by the appropriate algorithm
opencv/opencv
28c2d3b89ff3ada3188c2d5b856962fda1b0445b
2011-03-13T00:31:17Z
new file mode 100644 <nl> index 0000000000000 . . f4c93a4328eb5 <nl> mmm / dev / null <nl> ppp b / tensorflow / g3doc / api_docs / python / functions_and_classes / shard1 / tf . nn . conv1d . md <nl> <nl> + # # # ` tf . nn . conv1d ( value , filters , stride , padding , use_cudnn_on_gpu = None , data_format = None , name = None ) ` { # conv1d } <nl> + <nl> + Computes a 1 - D convolution given 3 - D input and filter tensors . <nl> + <nl> + Given an input tensor of shape [ batch , in_width , in_channels ] <nl> + and a filter / kernel tensor of shape <nl> + [ filter_width , in_channels , out_channels ] , this op reshapes <nl> + the arguments to pass them to conv2d to perform the equivalent <nl> + convolution operation . <nl> + <nl> + Internally , this op reshapes the input tensors and invokes <nl> + ` tf . nn . conv2d ` . A tensor of shape [ batch , in_width , in_channels ] <nl> + is reshaped to [ batch , 1 , in_width , in_channels ] , and the filter <nl> + is reshaped to [ 1 , filter_width , in_channels , out_channels ] . <nl> + The result is then reshaped back to [ batch , out_width , out_channels ] <nl> + ( where out_width is a function of the stride and padding as in <nl> + conv2d ) and returned to the caller . <nl> + <nl> + # # # # # Args : <nl> + <nl> + <nl> + * < b > ` value ` < / b > : A 3D ` Tensor ` . Must be of type ` float32 ` or ` float64 ` . <nl> + * < b > ` filters ` < / b > : A 3D ` Tensor ` . Must have the same type as ` input ` . <nl> + * < b > ` stride ` < / b > : An ` integer ` . The number of entries by which <nl> + the filter is moved right at each step . <nl> + * < b > ` padding ` < / b > : ' SAME ' or ' VALID ' <nl> + * < b > ` use_cudnn_on_gpu ` < / b > : An optional ` bool ` . Defaults to ` True ` . <nl> + * < b > ` data_format ` < / b > : An optional ` string ` from ` " NHWC " , " NCHW " ` . Defaults <nl> + to ` " NHWC " ` , the data is stored in the order of <nl> + [ batch , in_width , in_channels ] . The ` " NCHW " ` format stores <nl> + data as [ batch , in_channels , in_width ] . <nl> + * < b > ` name ` < / b > : A name for the operation ( optional ) . <nl> + <nl> + # # # # # Returns : <nl> + <nl> + A ` Tensor ` . Has the same type as input . <nl> + <nl> mmm a / tensorflow / g3doc / api_docs / python / index . md <nl> ppp b / tensorflow / g3doc / api_docs / python / index . md <nl> <nl> * [ ` bias_add ` ] ( . . / . . / api_docs / python / nn . md # bias_add ) <nl> * [ ` bidirectional_rnn ` ] ( . . / . . / api_docs / python / nn . md # bidirectional_rnn ) <nl> * [ ` compute_accidental_hits ` ] ( . . / . . / api_docs / python / nn . md # compute_accidental_hits ) <nl> + * [ ` conv1d ` ] ( . . / . . / api_docs / python / nn . md # conv1d ) <nl> * [ ` conv2d ` ] ( . . / . . / api_docs / python / nn . md # conv2d ) <nl> * [ ` conv2d_transpose ` ] ( . . / . . / api_docs / python / nn . md # conv2d_transpose ) <nl> * [ ` conv3d ` ] ( . . / . . / api_docs / python / nn . md # conv3d ) <nl> mmm a / tensorflow / g3doc / api_docs / python / nn . md <nl> ppp b / tensorflow / g3doc / api_docs / python / nn . md <nl> deconvolution . <nl> padding is other than ` ' VALID ' ` or ` ' SAME ' ` . <nl> <nl> <nl> + - - - <nl> + <nl> + # # # ` tf . nn . conv1d ( value , filters , stride , padding , use_cudnn_on_gpu = None , data_format = None , name = None ) ` { # conv1d } <nl> + <nl> + Computes a 1 - D convolution given 3 - D input and filter tensors . <nl> + <nl> + Given an input tensor of shape [ batch , in_width , in_channels ] <nl> + and a filter / kernel tensor of shape <nl> + [ filter_width , in_channels , out_channels ] , this op reshapes <nl> + the arguments to pass them to conv2d to perform the equivalent <nl> + convolution operation . <nl> + <nl> + Internally , this op reshapes the input tensors and invokes <nl> + ` tf . nn . conv2d ` . A tensor of shape [ batch , in_width , in_channels ] <nl> + is reshaped to [ batch , 1 , in_width , in_channels ] , and the filter <nl> + is reshaped to [ 1 , filter_width , in_channels , out_channels ] . <nl> + The result is then reshaped back to [ batch , out_width , out_channels ] <nl> + ( where out_width is a function of the stride and padding as in <nl> + conv2d ) and returned to the caller . <nl> + <nl> + # # # # # Args : <nl> + <nl> + <nl> + * < b > ` value ` < / b > : A 3D ` Tensor ` . Must be of type ` float32 ` or ` float64 ` . <nl> + * < b > ` filters ` < / b > : A 3D ` Tensor ` . Must have the same type as ` input ` . <nl> + * < b > ` stride ` < / b > : An ` integer ` . The number of entries by which <nl> + the filter is moved right at each step . <nl> + * < b > ` padding ` < / b > : ' SAME ' or ' VALID ' <nl> + * < b > ` use_cudnn_on_gpu ` < / b > : An optional ` bool ` . Defaults to ` True ` . <nl> + * < b > ` data_format ` < / b > : An optional ` string ` from ` " NHWC " , " NCHW " ` . Defaults <nl> + to ` " NHWC " ` , the data is stored in the order of <nl> + [ batch , in_width , in_channels ] . The ` " NCHW " ` format stores <nl> + data as [ batch , in_channels , in_width ] . <nl> + * < b > ` name ` < / b > : A name for the operation ( optional ) . <nl> + <nl> + # # # # # Returns : <nl> + <nl> + A ` Tensor ` . Has the same type as input . <nl> + <nl> + <nl> - - - <nl> <nl> # # # ` tf . nn . conv3d ( input , filter , strides , padding , name = None ) ` { # conv3d } <nl>
Update generated Python Op docs .
tensorflow/tensorflow
a7fd4350e4c7228a24b51aa9287ecdc402983f3e
2016-08-12T23:18:06Z
mmm a / README . md <nl> ppp b / README . md <nl> sudo apt - get install \ <nl> pkg - config <nl> ` ` ` <nl> <nl> - If advanced debugging functionality is required <nl> + If advanced debugging functionality is required , use : <nl> <nl> ` ` ` <nl> sudo apt - get install \ <nl>
Wording nit in README . md ( )
facebook/folly
794ea600e9f0eb2ebf67d90c2df79fc7441f8987
2018-08-03T20:06:13Z
mmm a / gRPC - Core . podspec <nl> ppp b / gRPC - Core . podspec <nl> Pod : : Spec . new do | s | <nl> ss . dependency " # { s . name } / Interface " , version <nl> ss . dependency ' BoringSSL ' , ' ~ > 4 . 0 ' <nl> <nl> + # To save you from scrolling , this is the last part of the podspec . <nl> ss . source_files = ' src / core / lib / profiling / timers . h ' , <nl> ' src / core / lib / support / backoff . h ' , <nl> ' src / core / lib / support / block_annotate . h ' , <nl> Pod : : Spec . new do | s | <nl> ' src / core / ext / census / mlog . h ' , <nl> ' src / core / ext / census / rpc_metric_id . h ' <nl> end <nl> - <nl> + <nl> s . subspec ' Cronet - Interface ' do | ss | <nl> ss . header_mappings_dir = ' include / grpc ' <nl> ss . source_files = ' include / grpc / grpc_cronet . h ' <nl> mmm a / src / core / ext / client_config / channel_connectivity . c <nl> ppp b / src / core / ext / client_config / channel_connectivity . c <nl> grpc_connectivity_state grpc_channel_check_connectivity_state ( <nl> } <nl> gpr_log ( GPR_ERROR , <nl> " grpc_channel_check_connectivity_state called on something that is " <nl> - " not a client channel , but ' % s ' " , client_channel_elem - > filter - > name ) ; <nl> + " not a client channel , but ' % s ' " , <nl> + client_channel_elem - > filter - > name ) ; <nl> grpc_exec_ctx_finish ( & exec_ctx ) ; <nl> return GRPC_CHANNEL_SHUTDOWN ; <nl> } <nl>
Sanitizing master .
grpc/grpc
20b8333efaa2bc76fbb3d03c62fd8d27b37117a6
2016-07-21T17:28:38Z
mmm a / Jenkinsfile <nl> ppp b / Jenkinsfile <nl> def python3_gpu_ut ( docker_container_name ) { <nl> } <nl> } <nl> <nl> + / / Python 3 NOCUDNN <nl> + def python3_gpu_ut_nocudnn ( docker_container_name ) { <nl> + timeout ( time : max_time , unit : ' MINUTES ' ) { <nl> + docker_run ( docker_container_name , ' unittest_ubuntu_python3_gpu_nocudnn ' , true ) <nl> + } <nl> + } <nl> + <nl> try { <nl> stage ( ' Sanity Check ' ) { <nl> parallel ' Lint ' : { <nl> try { <nl> } <nl> } <nl> } , <nl> + ' GPU : MKLDNN_CUDNNOFF ' : { <nl> + node ( ' mxnetlinux - cpu ' ) { <nl> + ws ( ' workspace / build - mkldnn - gpu - nocudnn ' ) { <nl> + timeout ( time : max_time , unit : ' MINUTES ' ) { <nl> + init_git ( ) <nl> + docker_run ( ' ubuntu_build_cuda ' , ' build_ubuntu_gpu_mkldnn_nocudnn ' , false ) <nl> + pack_lib ( ' mkldnn_gpu_nocudnn ' , mx_mkldnn_lib ) <nl> + } <nl> + } <nl> + } <nl> + } , <nl> ' GPU : CUDA9 . 1 + cuDNN7 ' : { <nl> node ( ' mxnetlinux - cpu ' ) { <nl> ws ( ' workspace / build - gpu ' ) { <nl> try { <nl> } <nl> } <nl> } , <nl> + ' Python3 : MKLDNN - GPU - NOCUDNN ' : { <nl> + node ( ' mxnetlinux - gpu ' ) { <nl> + ws ( ' workspace / ut - python3 - mkldnn - gpu - nocudnn ' ) { <nl> + try { <nl> + init_git ( ) <nl> + unpack_lib ( ' mkldnn_gpu_nocudnn ' , mx_mkldnn_lib ) <nl> + python3_gpu_ut_nocudnn ( ' ubuntu_gpu ' ) <nl> + publish_test_coverage ( ) <nl> + } finally { <nl> + collect_test_results_unix ( ' nosetests_gpu . xml ' , ' nosetests_python3_mkldnn_gpu_nocudnn . xml ' ) <nl> + } <nl> + } <nl> + } <nl> + } , <nl> ' Python3 : CentOS 7 CPU ' : { <nl> node ( ' mxnetlinux - cpu ' ) { <nl> ws ( ' workspace / build - centos7 - cpu ' ) { <nl> mmm a / ci / docker / runtime_functions . sh <nl> ppp b / ci / docker / runtime_functions . sh <nl> build_ubuntu_gpu_mkldnn ( ) { <nl> report_ccache_usage <nl> } <nl> <nl> + build_ubuntu_gpu_mkldnn_nocudnn ( ) { <nl> + set - ex <nl> + <nl> + build_ccache_wrappers <nl> + <nl> + make \ <nl> + DEV = 1 \ <nl> + USE_BLAS = openblas \ <nl> + USE_MKLDNN = 1 \ <nl> + USE_CUDA = 1 \ <nl> + USE_CUDA_PATH = / usr / local / cuda \ <nl> + USE_CUDNN = 0 \ <nl> + - j $ ( nproc ) <nl> + <nl> + report_ccache_usage <nl> + } <nl> + <nl> build_ubuntu_gpu_cuda91_cudnn7 ( ) { <nl> set - ex <nl> # unfortunately this build has problems in 3rdparty dependencies with ccache and make <nl> unittest_ubuntu_python3_gpu ( ) { <nl> nosetests - 3 . 4 $ NOSE_COVERAGE_ARGUMENTS - - with - xunit - - xunit - file nosetests_gpu . xml - - verbose tests / python / gpu <nl> } <nl> <nl> + unittest_ubuntu_python3_gpu_nocudnn ( ) { <nl> + set - ex <nl> + export PYTHONPATH = . / python / <nl> + export MXNET_STORAGE_FALLBACK_LOG_VERBOSE = 0 <nl> + export CUDNN_OFF_TEST_ONLY = true <nl> + nosetests - 3 . 4 $ NOSE_COVERAGE_ARGUMENTS - - with - xunit - - xunit - file nosetests_gpu . xml - - verbose tests / python / gpu <nl> + } <nl> + <nl> # quantization gpu currently only runs on P3 instances <nl> # need to separte it from unittest_ubuntu_python2_gpu ( ) <nl> unittest_ubuntu_python2_quantization_gpu ( ) { <nl> mmm a / src / c_api / c_api . cc <nl> ppp b / src / c_api / c_api . cc <nl> int MXRtcCudaKernelCall ( CudaKernelHandle handle , int dev_id , void * * args , <nl> API_END ( ) ; <nl> } <nl> <nl> - <nl> int MXNDArrayGetSharedMemHandle ( NDArrayHandle handle , int * shared_pid , int * shared_id ) { <nl> API_BEGIN ( ) ; <nl> NDArray * arr = reinterpret_cast < NDArray * > ( handle ) ; <nl> mmm a / src / operator / nn / convolution . cu <nl> ppp b / src / operator / nn / convolution . cu <nl> void ConvolutionCompute < gpu > ( const nnvm : : NodeAttrs & attrs , <nl> int dtype = inputs [ conv : : kData ] . type_flag_ ; <nl> <nl> # if CUDNN_MAJOR < 5 <nl> - if ( param_ . layout . value ( ) ! = kNCW & & <nl> - param_ . layout . value ( ) ! = kNCHW & & <nl> - param_ . layout . value ( ) ! = kNCDHW ) { <nl> + if ( param . layout . value ( ) ! = kNCW & & <nl> + param . layout . value ( ) ! = kNCHW & & <nl> + param . layout . value ( ) ! = kNCDHW ) { <nl> / / Need CuDNN > 5 . 0 for layout support . use MXNet implementation <nl> MSHADOW_REAL_TYPE_SWITCH ( dtype , DType , { <nl> ConvolutionOp < gpu , DType > op ; <nl> void ConvolutionGradCompute < gpu > ( const nnvm : : NodeAttrs & attrs , <nl> int dtype = out_grad . type_flag_ ; <nl> <nl> # if CUDNN_MAJOR < 5 <nl> - if ( param_ . layout . value ( ) ! = kNCW & & <nl> - param_ . layout . value ( ) ! = kNCHW & & <nl> - param_ . layout . value ( ) ! = kNCDHW ) { <nl> + if ( param . layout . value ( ) ! = kNCW & & <nl> + param . layout . value ( ) ! = kNCHW & & <nl> + param . layout . value ( ) ! = kNCDHW ) { <nl> / / Need CuDNN > 5 . 0 for layout support . use MXNet implementation <nl> MSHADOW_REAL_TYPE_SWITCH ( dtype , DType , { <nl> ConvolutionOp < gpu , DType > op ; <nl> mmm a / tests / python / gpu / test_operator_gpu . py <nl> ppp b / tests / python / gpu / test_operator_gpu . py <nl> <nl> <nl> curr_path = os . path . dirname ( os . path . abspath ( os . path . expanduser ( __file__ ) ) ) <nl> sys . path . insert ( 0 , os . path . join ( curr_path , ' . . / unittest ' ) ) <nl> - from common import setup_module , with_seed , teardown <nl> + from common import setup_module , with_seed , teardown , assert_raises_cudnn_disabled <nl> from test_operator import * <nl> from test_optimizer import * <nl> from test_random import * <nl> def test_3d_batchnorm ( fix_gamma , use_global_stats ) : <nl> <nl> <nl> @ with_seed ( 1234 ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_convolution_with_type ( ) : <nl> sym1 = mx . sym . Convolution ( num_filter = 3 , kernel = ( 3 , 3 ) , name = ' conv ' ) <nl> <nl> def check_rnn_consistency ( cell1 , cell2 ) : <nl> assert_allclose ( mod1 . get_outputs ( ) [ 0 ] . asnumpy ( ) , mod2 . get_outputs ( ) [ 0 ] . asnumpy ( ) , rtol = 1e - 2 , atol = 1e - 4 ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnn ( ) : <nl> fused = mx . rnn . FusedRNNCell ( 100 , num_layers = 2 , mode = ' rnn_relu ' , prefix = ' ' ) <nl> <nl> def test_rnn ( ) : <nl> check_rnn_consistency ( stack , fused ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_lstm_forget_bias ( ) : <nl> forget_bias = 2 . 0 <nl> fused = mx . rnn . FusedRNNCell ( 10 , forget_bias = forget_bias , num_layers = 2 , mode = ' lstm ' , prefix = ' ' ) <nl> def test_lstm_forget_bias ( ) : <nl> assert_allclose ( args [ bias_name ] . asnumpy ( ) , expected_bias ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_gru ( ) : <nl> fused = mx . rnn . FusedRNNCell ( 100 , num_layers = 2 , mode = ' gru ' , prefix = ' ' ) <nl> <nl> def test_gru ( ) : <nl> check_rnn_consistency ( stack , fused ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_bidirectional ( ) : <nl> fused = mx . rnn . FusedRNNCell ( 100 , num_layers = 2 , mode = ' gru ' , prefix = ' ' , <nl> bidirectional = True ) <nl> def test_bidirectional ( ) : <nl> check_rnn_consistency ( stack , fused ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_unfuse ( ) : <nl> for mode in [ ' rnn_tanh ' , ' rnn_relu ' , ' lstm ' , ' gru ' ] : <nl> fused = mx . rnn . FusedRNNCell ( <nl> def test_deformable_convolution_options ( ) : <nl> name = ' deformable_conv ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_residual_fused ( ) : <nl> cell = mx . rnn . ResidualCell ( <nl> mx . rnn . FusedRNNCell ( 50 , num_layers = 3 , mode = ' lstm ' , <nl> def check_rnn_layer_w_rand_inputs ( layer ) : <nl> assert_almost_equal ( g . asnumpy ( ) , c . asnumpy ( ) , rtol = 1e - 2 , atol = 1e - 6 ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnn_layer ( ) : <nl> check_rnn_layer ( gluon . rnn . RNN ( 100 , num_layers = 3 ) ) <nl> check_rnn_layer ( gluon . rnn . RNN ( 100 , activation = ' tanh ' , num_layers = 3 ) ) <nl> mmm a / tests / python / unittest / common . py <nl> ppp b / tests / python / unittest / common . py <nl> <nl> import numpy as np <nl> import random <nl> import shutil <nl> + from mxnet . base import MXNetError <nl> curr_path = os . path . dirname ( os . path . abspath ( os . path . expanduser ( __file__ ) ) ) <nl> sys . path . append ( os . path . join ( curr_path , ' . . / common / ' ) ) <nl> sys . path . insert ( 0 , os . path . join ( curr_path , ' . . / . . / . . / python ' ) ) <nl> <nl> import models <nl> from contextlib import contextmanager <nl> - from nose . tools import make_decorator <nl> + from nose . tools import make_decorator , assert_raises <nl> import tempfile <nl> <nl> def assertRaises ( expected_exception , func , * args , * * kwargs ) : <nl> def random_seed ( seed = None ) : <nl> random . seed ( next_seed ) <nl> <nl> <nl> + def assert_raises_cudnn_disabled ( assertion_error = False ) : <nl> + def test_helper ( orig_test ) : <nl> + @ make_decorator ( orig_test ) <nl> + def test_new ( * args , * * kwargs ) : <nl> + cudnn_disabled = ( os . getenv ( ' CUDNN_OFF_TEST_ONLY ' ) = = " true " ) <nl> + if not cudnn_disabled or mx . context . current_context ( ) . device_type = = ' cpu ' : <nl> + orig_test ( * args , * * kwargs ) <nl> + else : <nl> + if assertion_error : <nl> + errors = ( MXNetError , RuntimeError , AssertionError ) <nl> + else : <nl> + errors = ( MXNetError , RuntimeError ) <nl> + assert_raises ( errors , orig_test , * args , * * kwargs ) <nl> + return test_new <nl> + return test_helper <nl> + <nl> + <nl> def with_seed ( seed = None ) : <nl> " " " <nl> A decorator for nosetests test functions that manages rng seeds . <nl> mmm a / tests / python / unittest / test_gluon . py <nl> ppp b / tests / python / unittest / test_gluon . py <nl> <nl> from mxnet . gluon import nn <nl> from mxnet . test_utils import assert_almost_equal <nl> from mxnet . ndarray . ndarray import _STORAGE_TYPE_STR_TO_ID <nl> - from common import setup_module , with_seed , assertRaises , teardown <nl> + from common import setup_module , with_seed , assertRaises , teardown , assert_raises_cudnn_disabled <nl> import numpy as np <nl> from numpy . testing import assert_array_equal <nl> from nose . tools import raises , assert_raises <nl> def record_name ( block ) : <nl> <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_summary ( ) : <nl> net = gluon . model_zoo . vision . resnet50_v1 ( ) <nl> net . initialize ( ) <nl> mmm a / tests / python / unittest / test_gluon_rnn . py <nl> ppp b / tests / python / unittest / test_gluon_rnn . py <nl> <nl> from numpy . testing import assert_allclose <nl> import unittest <nl> from mxnet . test_utils import almost_equal , assert_almost_equal <nl> + from common import assert_raises_cudnn_disabled <nl> <nl> <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnn ( ) : <nl> cell = gluon . rnn . RNNCell ( 100 , prefix = ' rnn_ ' ) <nl> inputs = [ mx . sym . Variable ( ' rnn_t % d_data ' % i ) for i in range ( 3 ) ] <nl> def test_lstm ( ) : <nl> assert outs = = [ ( 10 , 100 ) , ( 10 , 100 ) , ( 10 , 100 ) ] <nl> <nl> <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_lstm_forget_bias ( ) : <nl> forget_bias = 2 . 0 <nl> stack = gluon . rnn . SequentialRNNCell ( ) <nl> def test_lstm_forget_bias ( ) : <nl> forget_bias * np . ones ( 100 , ) , np . zeros ( ( 2 * 100 , ) ) ] ) <nl> assert_allclose ( mod . get_params ( ) [ 0 ] [ bias_argument ] . asnumpy ( ) , expected_bias ) <nl> <nl> + <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_lstm_cpu_inference ( ) : <nl> # should behave the same as lstm cell <nl> EXPECTED_LSTM_OUTPUT = np . array ( [ [ [ 0 . 72045636 , 0 . 72045636 , 0 . 95215213 , 0 . 95215213 ] , <nl> def test_lstm_cpu_inference ( ) : <nl> rtol = 1e - 3 , atol = 1e - 5 ) <nl> <nl> <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_gru ( ) : <nl> cell = gluon . rnn . GRUCell ( 100 , prefix = ' rnn_ ' ) <nl> inputs = [ mx . sym . Variable ( ' rnn_t % d_data ' % i ) for i in range ( 3 ) ] <nl> def check_rnn_layer_forward ( layer , inputs , states = None , run_only = False ) : <nl> mx . test_utils . assert_almost_equal ( np_dx , inputs . grad . asnumpy ( ) , rtol = 1e - 3 , atol = 1e - 5 ) <nl> <nl> <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnn_layers ( ) : <nl> check_rnn_layer_forward ( gluon . rnn . RNN ( 10 , 2 ) , mx . nd . ones ( ( 8 , 3 , 20 ) ) ) <nl> check_rnn_layer_forward ( gluon . rnn . RNN ( 10 , 2 , bidirectional = True ) , mx . nd . ones ( ( 8 , 3 , 20 ) ) , mx . nd . ones ( ( 4 , 3 , 10 ) ) ) <nl> def test_cell_fill_shape ( ) : <nl> check_rnn_forward ( cell , mx . nd . ones ( ( 2 , 3 , 7 ) ) ) <nl> assert cell . i2h_weight . shape [ 1 ] = = 7 , cell . i2h_weight . shape [ 1 ] <nl> <nl> + <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_layer_fill_shape ( ) : <nl> layer = gluon . rnn . LSTM ( 10 ) <nl> layer . hybridize ( ) <nl> mmm a / tests / python / unittest / test_operator . py <nl> ppp b / tests / python / unittest / test_operator . py <nl> <nl> from numpy . testing import assert_allclose , assert_array_equal <nl> from mxnet . test_utils import * <nl> from mxnet . base import py_str , MXNetError , _as_list <nl> - from common import setup_module , with_seed , teardown <nl> + from common import setup_module , with_seed , teardown , assert_raises_cudnn_disabled <nl> import unittest <nl> <nl> def check_rnn_consistency ( cell1 , cell2 , T , N , I , H , grad_req ) : <nl> def check_rnn_consistency ( cell1 , cell2 , T , N , I , H , grad_req ) : <nl> <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_lstm_sym ( ) : <nl> T , N , I , H = 5 , 32 , 800 , 800 <nl> fused = mx . rnn . FusedRNNCell ( H , num_layers = 3 , mode = ' lstm ' , get_next_state = True , prefix = ' ' ) <nl> def test_lstm_sym ( ) : <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' null ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_lstm_bidirectional ( ) : <nl> T , N , I , H = 5 , 20 , 800 , 800 <nl> fused = mx . rnn . FusedRNNCell ( H , num_layers = 2 , mode = ' lstm ' , <nl> def test_lstm_bidirectional ( ) : <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' null ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_gru_sym ( ) : <nl> T , N , I , H = 5 , 32 , 800 , 800 <nl> fused = mx . rnn . FusedRNNCell ( H , num_layers = 3 , mode = ' gru ' , get_next_state = True , prefix = ' ' ) <nl> def test_gru_sym ( ) : <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' null ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_gru_bidirectional ( ) : <nl> T , N , I , H = 5 , 20 , 800 , 800 <nl> <nl> def test_gru_bidirectional ( ) : <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' null ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnntanh_sym ( ) : <nl> T , N , I , H = 5 , 32 , 800 , 800 <nl> <nl> def test_rnntanh_sym ( ) : <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' null ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnntanh_bidirectional ( ) : <nl> T , N , I , H = 5 , 20 , 800 , 800 <nl> <nl> fused = mx . rnn . FusedRNNCell ( H , num_layers = 2 , mode = ' rnn_tanh ' , <nl> bidirectional = True , get_next_state = True , prefix = ' ' ) <nl> - <nl> + <nl> stack = mx . rnn . SequentialRNNCell ( ) <nl> stack . add ( mx . rnn . BidirectionalCell ( <nl> mx . rnn . RNNCell ( H , activation = ' tanh ' , prefix = ' l0_ ' ) , <nl> mx . rnn . RNNCell ( H , activation = ' tanh ' , prefix = ' r0_ ' ) , <nl> - output_prefix = ' bi_rnntanh_0_ ' ) ) <nl> + output_prefix = ' bi_rnntanh_0_ ' ) ) <nl> stack . add ( mx . rnn . BidirectionalCell ( <nl> mx . rnn . RNNCell ( H , activation = ' tanh ' , prefix = ' l1_ ' ) , <nl> mx . rnn . RNNCell ( H , activation = ' tanh ' , prefix = ' r1_ ' ) , <nl> output_prefix = ' bi_rnntanh_1_ ' ) ) <nl> - <nl> + <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' write ' ) <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' add ' ) <nl> check_rnn_consistency ( fused , stack , T , N , I , H , ' null ' ) <nl> <nl> @ with_seed ( ) <nl> + @ assert_raises_cudnn_disabled ( ) <nl> def test_rnnrelu_sym ( ) : <nl> T , N , I , H = 5 , 32 , 200 , 200 <nl> <nl> def test_rnnrelu_bidirectional ( ) : <nl> <nl> fused = mx . rnn . FusedRNNCell ( H , num_layers = 2 , mode = ' rnn_relu ' , <nl> bidirectional = True , get_next_state = True , prefix = ' ' ) <nl> - <nl> + <nl> stack = mx . rnn . SequentialRNNCell ( ) <nl> stack . add ( mx . rnn . BidirectionalCell ( <nl> mx . rnn . RNNCell ( H , activation = ' relu ' , prefix = ' l0_ ' ) , <nl> mx . rnn . RNNCell ( H , activation = ' relu ' , prefix = ' r0_ ' ) , <nl> - output_prefix = ' bi_rnnrelu_0_ ' ) ) <nl> + output_prefix = ' bi_rnnrelu_0_ ' ) ) <nl> stack . add ( mx . rnn . BidirectionalCell ( <nl> mx . rnn . RNNCell ( H , activation = ' relu ' , prefix = ' l1_ ' ) , <nl> mx . rnn . RNNCell ( H , activation = ' relu ' , prefix = ' r1_ ' ) , <nl> def test_flip ( ) : <nl> <nl> <nl> @ with_seed ( ) <nl> + # The test is disabled with USE_CUDA = ON and USE_CUDNN = OFF because of failures with the SpatialTransformer op . <nl> + # Tracked at https : / / github . com / apache / incubator - mxnet / issues / 11568 <nl> + @ assert_raises_cudnn_disabled ( assertion_error = True ) <nl> def test_stn ( ) : <nl> np . set_printoptions ( threshold = np . nan ) <nl> num_filter = 2 # conv of loc net <nl>
Fix build issue with USE_CUDNN = 0 ( )
apache/incubator-mxnet
5b631444974b72238a5d0a6929cf7a10ff532643
2018-07-12T23:40:24Z
mmm a / xbmc / video / VideoDatabase . cpp <nl> ppp b / xbmc / video / VideoDatabase . cpp <nl> bool CVideoDatabase : : GetResumePoint ( CVideoInfoTag & tag ) const <nl> CVideoInfoTag CVideoDatabase : : GetDetailsForMovie ( auto_ptr < Dataset > & pDS , bool needsCast / * = false * / ) <nl> { <nl> CVideoInfoTag details ; <nl> - details . Reset ( ) ; <nl> <nl> DWORD time = XbmcThreads : : SystemClockMillis ( ) ; <nl> int idMovie = pDS - > fv ( 0 ) . get_asInt ( ) ; <nl> mmm a / xbmc / video / windows / GUIWindowVideoBase . cpp <nl> ppp b / xbmc / video / windows / GUIWindowVideoBase . cpp <nl> bool CGUIWindowVideoBase : : ShowIMDB ( CFileItem * item , const ScraperPtr & info2 ) <nl> bool bHasInfo = false ; <nl> <nl> CVideoInfoTag movieDetails ; <nl> - movieDetails . Reset ( ) ; <nl> if ( info ) <nl> { <nl> m_database . Open ( ) ; / / since we can be called from the music library <nl>
Remove unneeded Reset ( ) calls .
xbmc/xbmc
4520939a29e761aaff45c5c2528b8bc2f7c8f1ef
2012-04-04T09:11:36Z
mmm a / dbms / tests / queries / 0_stateless / 01065_if_not_finite . reference <nl> ppp b / dbms / tests / queries / 0_stateless / 01065_if_not_finite . reference <nl> <nl> 2 <nl> \ N <nl> - 42 <nl> + 1 <nl> mmm a / dbms / tests / queries / 0_stateless / 01065_if_not_finite . sql <nl> ppp b / dbms / tests / queries / 0_stateless / 01065_if_not_finite . sql <nl> SELECT ifNotFinite ( - 1 / 0 , 2 ) ; <nl> SELECT ifNotFinite ( log ( 0 ) , NULL ) ; <nl> SELECT ifNotFinite ( sqrt ( - 1 ) , - 42 ) ; <nl> SELECT ifNotFinite ( 1234567890123456789 , - 1234567890123456789 ) ; - - { serverError 386 } <nl> + <nl> + SELECT ifNotFinite ( NULL , 1 ) ; <nl>
Added test
ClickHouse/ClickHouse
eeea89e0a4e5fa828c531a82bc06db6b7f65a566
2020-01-18T13:06:19Z
mmm a / plugins / mongo_db_plugin / mongo_db_plugin . cpp <nl> ppp b / plugins / mongo_db_plugin / mongo_db_plugin . cpp <nl> void handle_mongo_exception ( const std : : string & desc , int line_num ) { <nl> } <nl> } <nl> <nl> + / / custom oid to avoid monotonic throttling <nl> + / / https : / / docs . mongodb . com / master / core / bulk - write - operations / # avoid - monotonic - throttling <nl> + bsoncxx : : oid make_custom_oid ( ) { <nl> + bsoncxx : : oid x = bsoncxx : : oid ( ) ; <nl> + const char * p = x . bytes ( ) ; <nl> + std : : swap ( ( short & ) p [ 0 ] , ( short & ) p [ 10 ] ) ; <nl> + return x ; <nl> + } <nl> + <nl> } / / anonymous namespace <nl> <nl> void mongo_db_plugin_impl : : purge_abi_cache ( ) { <nl> mongo_db_plugin_impl : : add_action_trace ( mongocxx : : bulk_write & bulk_action_traces <nl> auto action_traces_doc = bsoncxx : : builder : : basic : : document { } ; <nl> const chain : : base_action_trace & base = atrace ; / / without inline action traces <nl> <nl> + / / improve data distributivity when using mongodb sharding <nl> + action_traces_doc . append ( kvp ( " _id " , make_custom_oid ( ) ) ) ; <nl> + <nl> auto v = to_variant_with_abi ( base ) ; <nl> string json = fc : : json : : to_string ( v ) ; <nl> try { <nl>
fix issue 5488
EOSIO/eos
649289df8e1f19de6a421c04cd545cca5be09279
2018-12-18T08:59:18Z
mmm a / docs - translations / es / README . md <nl> ppp b / docs - translations / es / README . md <nl> <nl> # # Guías <nl> <nl> - * [ Distribución de aplicaciones ] ( tutorial / application - distribution . md ) <nl> - * [ Empaquetamiento de aplicaciones ] ( tutorial / application - packaging . md ) <nl> - * [ Utilizando módulos nativos ] ( tutorial / using - native - node - modules . md ) <nl> - * [ Depurando el proceso principal ] ( tutorial / debugging - main - process . md ) <nl> + * [ Platfaformas Soportadas ] ( tutorial / supported - platforms . md ) <nl> + * [ Distribución de la Aplicacion ] ( tutorial / application - distribution . md ) <nl> + * [ Empaquetamiento de la Aplicacion ] ( tutorial / application - packaging . md ) <nl> + * [ Utilizando Módulos Node Nativos ] ( tutorial / using - native - node - modules . md ) <nl> + * [ Depurando el Proceso Principal ] ( tutorial / debugging - main - process . md ) <nl> * [ Utilizando Selenium y WebDriver ] ( tutorial / using - selenium - and - webdriver . md ) <nl> * [ Extensión DevTools ] ( tutorial / devtools - extension . md ) <nl> - * [ Utilizando el plugin pepper flash ] ( tutorial / using - pepper - flash - plugin . md ) <nl> + * [ Utilizando el plugin Pepper Flash ] ( tutorial / using - pepper - flash - plugin . md ) <nl> <nl> # # Tutoriales <nl> <nl> <nl> * [ Integración con el entorno de escritorio ] ( tutorial / desktop - environment - integration . md ) <nl> * [ Detección del evento en línea / fuera de línea ] ( tutorial / online - offline - events . md ) <nl> <nl> - # # API <nl> + # # Referencias a la API <nl> <nl> * [ Sinopsis ] ( api / synopsis . md ) <nl> * [ Proceso ] ( api / process . md ) <nl> * [ Parámetros CLI soportados ( Chrome ) ] ( api / chrome - command - line - switches . md ) <nl> <nl> - Elementos DOM customizados : <nl> + # # # Elementos DOM personalizados : <nl> <nl> * [ Objeto ` File ` ] ( . . / . . / docs / api / file - object . md ) <nl> * [ Etiqueta ` < webview > ` ] ( . . / . . / docs / api / web - view - tag . md ) <nl> * [ Función ` window . open ` ] ( . . / . . / docs / api / window - open . md ) <nl> <nl> - Módulos del proceso principal : <nl> + # # # Módulos del Proceso Principal : <nl> <nl> * [ app ] ( . . / . . / docs / api / app . md ) <nl> * [ auto - updater ] ( . . / . . / docs / api / auto - updater . md ) <nl> Módulos del proceso principal : <nl> * [ content - tracing ] ( . . / . . / docs / api / content - tracing . md ) <nl> * [ dialog ] ( . . / . . / docs / api / dialog . md ) <nl> * [ global - shortcut ] ( . . / . . / docs / api / global - shortcut . md ) <nl> - * [ ipc ( main process ) ] ( . . / . . / docs / api / ipc - main - process . md ) <nl> + * [ ipc ( proceso principal ) ] ( . . / . . / docs / api / ipc - main - process . md ) <nl> * [ menu ] ( . . / . . / docs / api / menu . md ) <nl> * [ menu - item ] ( . . / . . / docs / api / menu - item . md ) <nl> * [ power - monitor ] ( . . / . . / docs / api / power - monitor . md ) <nl> * [ power - save - blocker ] ( . . / . . / docs / api / power - save - blocker . md ) <nl> * [ protocol ] ( . . / . . / docs / api / protocol . md ) <nl> + * [ session ] ( . . / . . / docs / api / session . md ) <nl> + * [ web - contents ] ( . . / . . / docs / api / web - contents . md ) <nl> * [ tray ] ( . . / . . / docs / api / tray . md ) <nl> <nl> - Módulos del renderer ( página web ) : <nl> + # # # Módulos del proceso de renderizado ( Página Web ) : <nl> <nl> - * [ ipc ( renderer ) ] ( . . / . . / docs / api / ipc - renderer . md ) <nl> + * [ ipc ( renderizador ) ] ( . . / . . / docs / api / ipc - renderer . md ) <nl> * [ remote ] ( . . / . . / docs / api / remote . md ) <nl> * [ web - frame ] ( . . / . . / docs / api / web - frame . md ) <nl> <nl> - Módulos de ambos procesos : <nl> + # # # Módulos de Ambos Procesos : <nl> <nl> * [ clipboard ] ( . . / . . / docs / api / clipboard . md ) <nl> * [ crash - reporter ] ( . . / . . / docs / api / crash - reporter . md ) <nl> Módulos de ambos procesos : <nl> <nl> # # Desarrollo <nl> <nl> - * [ Guía de estilo ] ( . . / . . / docs / development / coding - style . md ) <nl> - * [ Estructura de directorio ] ( . . / . . / docs / development / source - code - directory - structure . md ) <nl> - * [ Diferencias técnicas con NW . js ( anteriormente conocido como node - webkit ) ] ( . . / . . / docs / development / atom - shell - vs - node - webkit . md ) <nl> - * [ Sistema de compilación ] ( . . / . . / docs / development / build - system - overview . md ) <nl> - * [ Instrucciones de compilación ( Mac ) ] ( . . / . . / docs / development / build - instructions - osx . md ) <nl> - * [ Instrucciones de compilación ( Windows ) ] ( . . / . . / docs / development / build - instructions - windows . md ) <nl> - * [ Instrucciones de compilación ( Linux ) ] ( . . / . . / docs / development / build - instructions - linux . md ) <nl> - * [ Configurando un servidor de símbolos en el depurador ] ( . . / . . / docs / development / setting - up - symbol - server . md ) <nl> + * [ Guía de Estilo ] ( development / coding - style . md ) <nl> + * [ Estructura de los directorios del Código Fuente ] ( . . / . . / development / source - code - directory - structure . md ) <nl> + * [ Diferencias Técnicas con NW . js ( anteriormente conocido como node - webkit ) ] ( . . / . . / development / atom - shell - vs - node - webkit . md ) <nl> + * [ Repaso del Sistema de Compilación ] ( . . / . . / development / build - system - overview . md ) <nl> + * [ Instrucciones de Compilación ( Mac ) ] ( . . / . . / development / build - instructions - osx . md ) <nl> + * [ Instrucciones de Compilación ( Windows ) ] ( . . / . . / development / build - instructions - windows . md ) <nl> + * [ Instrucciones de Compilación ( Linux ) ] ( . . / . . / development / build - instructions - linux . md ) <nl> + * [ Configurando un Servidor de Símbolos en el depurador ] ( . . / . . / development / setting - up - symbol - server . md ) <nl> new file mode 100644 <nl> index 000000000000 . . 2e8e7c6f4a9e <nl> mmm / dev / null <nl> ppp b / docs - translations / es / styleguide . md <nl> <nl> + # Gúia de estilo de Electron <nl> + <nl> + Encuentra el apartado correcto para cada tarea : [ leer la documentación de Electron ] ( # reading - electron - documentation ) <nl> + o [ escribir documentación para Electron ] ( # writing - electron - documentation ) . <nl> + <nl> + # # Escribir Documentación para Electron <nl> + <nl> + Estas son las maneras en las que construimos la documentación de Electron . <nl> + <nl> + - Máximo un título ` h1 ` por página . <nl> + - Utilizar ` bash ` en lugar de ` cmd ` en los bloques de código ( por el resaltado <nl> + de sintaxis ) . <nl> + - Los títulos ` h1 ` en el documento deben corresponder al nombre del objeto <nl> + ( ej . ` browser - window ` → ` BrowserWindow ` ) . <nl> + - Archivos separados por guiones , mas sin embargo , es correcto . <nl> + - No subtítulos seguidos por otros subtítulos , añadir por lo menos un enunciado <nl> + de descripción . <nl> + - Métodos de cabecera son delimitados con apóstrofes : ` codigo ` . <nl> + - Cabeceras de Eventos son delimitados con ' comillas ' simples . <nl> + - No generar listas de mas de dos niveles ( debido al renderizador de Markdown <nl> + desafortunadamente ) . <nl> + - Agregar títulos de sección : Eventos , Métodos de Clases y Métodos de Instancia . <nl> + - Utilizar ' deberá ' en lugar de ' debería ' al describir resultados . <nl> + - Eventos y Métodos son cabeceras ` h3 ` . <nl> + - Argumentos opcionales escritos como ` function ( required [ , optional ] ) ` . <nl> + - Argumentos opcionales son denotados cuando se llaman en listas . <nl> + - Delimitador de línea de 80 - columnas . <nl> + - Métodos específicos de Plataformas son denotados en italicas seguidas por la cabecera del método . <nl> + - ` ` ` # # # ` method ( foo , bar ) ` _OS X_ ` ` ` <nl> + - Preferir ' en el ___ proceso ' en lugar de ' sobre el ' <nl> + <nl> + # # # Traducciones de la Documentación <nl> + <nl> + Traducciones de documentos de Electron se encuentran dentro del folder <nl> + ` docs - translations ` . <nl> + <nl> + Para agregar otro set ( o un set parcial ) : <nl> + <nl> + - Crear un subdirectorio nombrado igual a la abreviación del lenguaje . <nl> + - Dentro de ese subdirectorio , duplicar el directorio de ` docs ` , manteniendo los <nl> + mismos nombres de directorios y archivos . <nl> + - Traducir los archivos . <nl> + - Actualizar el ` README . md ` dentro del subdirectorio del lenguaje apuntando a <nl> + los archivos que has traducido . <nl> + - Agregar un enlace al folder de tu traducción en la sección principal Electron <nl> + [ README ] ( https : / / github . com / atom / electron # documentation - translations ) . <nl> + <nl> + # # Leyendo la Documentación de Electron <nl> + <nl> + Estos son algunos consejos para entender la syntaxis de la documentación de <nl> + Electron . <nl> + <nl> + # # # Métodos <nl> + <nl> + Un ejemplo de la documentación del [ método ] ( https : / / developer . mozilla . org / en - US / docs / Glossary / Method ) : <nl> + <nl> + mmm <nl> + <nl> + ` methodName ( required [ , optional ] ) ) ` <nl> + <nl> + * ` require ` String , * * required * * <nl> + * ` optional ` Integer <nl> + <nl> + mmm <nl> + <nl> + El nombre del método es seguido por los argumentos que recibe . Argumentos <nl> + opcionales son denotados por corchetes rodeados por el argumento opcional y la <nl> + coma requerida si el argumento opcional fuera seguido por otro argumento . <nl> + <nl> + Debajo del método se encuentra mas información detallada de cada uno de los <nl> + argumentos . El tipo de argumento es denotado por los tipos comúnes : <nl> + [ ` String ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / String ) , <nl> + [ ` Number ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Number ) , <nl> + [ ` Object ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Object ) , <nl> + [ ` Array ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Array ) <nl> + o un tipo personalizado como el [ ` webContent ` ] ( api / web - content . md ) de Electron . <nl> + <nl> + # # # Eventos <nl> + <nl> + Un ejemplo de documentación del [ evento ] ( https : / / developer . mozilla . org / en - US / docs / Web / API / Event ) : <nl> + <nl> + mmm <nl> + <nl> + Event : ' wake - up ' <nl> + <nl> + Returns : <nl> + <nl> + * ` time ` String <nl> + <nl> + mmm <nl> + <nl> + El evento es una cadena que es utilizada luego de un método observador ` . on ` . Si <nl> + regresa un valor , el y su tipo son denotados abajo . Si se estaba a la escucha y <nl> + respondió a este evento se debería ver así : <nl> + <nl> + ` ` ` javascript <nl> + Alarm . on ( ' wake - up ' , function ( time ) { <nl> + console . log ( time ) <nl> + } ) <nl> + ` ` ` <nl> mmm a / docs - translations / es / tutorial / application - distribution . md <nl> ppp b / docs - translations / es / tutorial / application - distribution . md <nl> <nl> - # Distribución de aplicaciones <nl> + # Distribución de la Aplicación <nl> <nl> - Para distribuir tu aplicación con Electron , debes nombrar al directorio de tu aplicación <nl> - como ` app ` , y ponerlo bajo el directorio de recursos de Electron ( en OSX es ` Electron . app / Contents / Resources / ` , <nl> - en Linux y Windows es ` resources / ` ) : <nl> + Para distribuir tu aplicación con Electron , el directorio que contiene la <nl> + aplicación deberá llamarse ` app ` , y ser colocado debajo del directorio de <nl> + recursos de Electron ( en OSX es ` Electron . app / Contents / Resources / ` , en Linux y <nl> + Windows es ` resources / ` ) , de esta forma : <nl> <nl> - En OSX : <nl> + En OS X : <nl> <nl> ` ` ` text <nl> electron / Electron . app / Contents / Resources / app / <nl> electron / resources / app <nl> └ ─ ─ index . html <nl> ` ` ` <nl> <nl> - Posteriormente ejecutas ` Electron . app ` ( o ` electron ` en Linux , ` electron . exe ` en Windows ) , <nl> - y Electron iniciará la aplicación . El directorio ` electron ` será la distribución que recibirán los usuarios finales . <nl> + Luego ejecutar ` Electron . app ` ( o ` electron ` en Linux , ` electron . exe ` en Windows ) , <nl> + y Electron será iniciado como tu aplicación . El directorio ` electron ` será <nl> + entonces tu distribución que recibirán los usuarios finales . <nl> <nl> - # # Empaquetando tu aplicación como un archivo <nl> + # # Empaquetando tu aplicación en un archivo <nl> <nl> - Además de copiar todos tus archivos fuente para la distribución , también puedes <nl> - empaquetar tu aplicación como un archivo [ asar ] ( https : / / github . com / atom / asar ) <nl> - y de esta forma evitar la exposición del código fuente de tu aplicación a los usuarios . <nl> + Además de distribuir tu aplicación al copiar todos los archivos de código fuente , <nl> + también puedes empaquetar tu aplicación como un archivo [ asar ] ( https : / / github . com / atom / asar ) <nl> + y de esta forma evitar exponer del código fuente de tu aplicación a los usuarios . <nl> <nl> - Para usar un archivo ` asar ` en reemplazo de la carpeta ` app ` , debes renombrar <nl> - el archivo a ` app . asar ` , y ponerlo bajo el directorio de recursos de Electron ( como arriba ) , <nl> - Electron intentará leer el archivo y ejecutar la aplicación desde él . <nl> + Para utilizar un archivo ` asar ` en reemplazo del directorio ` app ` , debes de <nl> + renombrar el archivo a ` app . asar ` , y colocarlo por debajo el directorio de recursos <nl> + de Electron ( ver en seguida ) , Electron intentará leer el archivo y arrancar desde el . <nl> <nl> En OS X : <nl> <nl> electron / resources / <nl> └ ─ ─ app . asar <nl> ` ` ` <nl> <nl> - Más detalles en [ Empaquetamiento de aplicaciones ] ( application - packaging - es . md ) . <nl> + Más detalles en [ Empaquetado de Aplicaciones ] ( application - packaging . md ) . <nl> <nl> - # # Rebranding con binarios descargados <nl> + # # Redefinición con Binarios Descargados <nl> <nl> - Luego de empaquetar tu aplicación con Electron , podría ser útil agregar tu marca <nl> - antes de realizar la distribución . <nl> + Luego de empaquetar tu aplicación en Electron , querrás redefinir Electron antes <nl> + de distribuirlo a los usuarios . <nl> <nl> # # # Windows <nl> <nl> - Puedes renombrar ` electron . exe ` a cualquier nombre que desees , y editar su ícono y otras informaciones <nl> - con herramientas como [ rcedit ] ( https : / / github . com / atom / rcedit ) o [ ResEdit ] ( http : / / www . resedit . net ) . <nl> + Puedes renombrar ` electron . exe ` a cualquier nombre que desees , y editar su ícono <nl> + y otra información con herramientas como [ rcedit ] ( https : / / github . com / atom / rcedit ) <nl> + o [ ResEdit ] ( http : / / www . resedit . net ) . <nl> <nl> - # # # OS X <nl> + # # # OSX <nl> <nl> - Puedes renombrar ` Electron . app ` a cualquier nombre que desees . También debes modificar los campos <nl> - ` CFBundleDisplayName ` , ` CFBundleIdentifier ` y ` CFBundleName ` en los siguientes archivos : <nl> + Puedes renombrar ` Electron . app ` a cualquier nombre que desees , y tendrás que <nl> + renombrar los campos ` CFBundleDisplayName ` , ` CFBundleIdentifier ` y ` CFBundleName ` <nl> + en los siguientes archivos : <nl> <nl> * ` Electron . app / Contents / Info . plist ` <nl> * ` Electron . app / Contents / Frameworks / Electron Helper . app / Contents / Info . plist ` <nl> <nl> - También puedes renombrar el helper de la aplicación para evitar que aparezca como ` Electron Helper ` <nl> - en el Monitor de Actividades . <nl> + También puedes renombrar el helper de la aplicación para evitar que aparezca <nl> + como ` Electron Helper ` en el Monitor de Actividades . Pero asegurate de renombrar <nl> + el nombre de archivo del ejecutable . <nl> <nl> - La estructura de una aplicación renombrada sería así : <nl> + La estructura de una aplicación renombrada será : <nl> <nl> ` ` ` <nl> MyApp . app / Contents <nl> MyApp . app / Contents <nl> <nl> Puedes renombrar el ejectuable ` electron ` a cualquier nombre que desees . <nl> <nl> - # # Rebranding desde el código fuente de Electron <nl> + # # Redefinición mediante la recompilación de Electron desde el código fuente <nl> <nl> - También es posible agregar tu marca a Electron mediante un build personalizado . <nl> - Para realizar esto debes modificar el archivo ` atom . gyp ` . <nl> + También es posible redefinir Electron cambiando el nombre del producto y <nl> + compilandolo desde sus fuentes . Para realizar esto necesitas modificar el <nl> + archivo ` atom . gyp ` y realizar una compilación desde cero . <nl> <nl> # # # grunt - build - atom - shell <nl> <nl> - La modificación del código de Electron para agregar tu marca puede resultar complicada , una tarea Grunt <nl> - se ha creado para manejar esto de forma automatizada : <nl> - <nl> + La modificación a mano del código de Electron y su compilación puede resultar <nl> + complicada , por lo cual se ha generado una tarea Grunt para manejar esto de <nl> + forma automaticamente : <nl> [ grunt - build - atom - shell ] ( https : / / github . com / paulcbetts / grunt - build - atom - shell ) . <nl> <nl> - Esta tarea se encargará de modificar el archivo ` . gyp ` , compilar el código <nl> - y reconstruir los módulos nativos de la aplicación para que coincidan con el nuevo nombre . <nl> + Esta tarea se encargará de modificar el archivo ` . gyp ` , compilar el código desde <nl> + las fuentes , y luego reconstruir los módulos nativos de la aplicación para que <nl> + coincidan con el nuevo nombre del ejecutable . <nl> mmm a / docs / styleguide . md <nl> ppp b / docs / styleguide . md <nl> notated by brackets surrounding the optional argument as well as the comma <nl> required if this optional argument follows another argument . <nl> <nl> Below the method is more detailed information on each of the arguments . The type <nl> - of argument is notated by either the common types : [ ` String ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / String ) , [ ` Number ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Number ) , [ ` Object ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Object ) , [ ` Array ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Array ) <nl> + of argument is notated by either the common types : <nl> + [ ` String ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / String ) , <nl> + [ ` Number ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Number ) , <nl> + [ ` Object ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Object ) , <nl> + [ ` Array ` ] ( https : / / developer . mozilla . org / en - US / docs / Web / JavaScript / Reference / Global_Objects / Array ) <nl> or a custom type like Electron ' s [ ` webContent ` ] ( api / web - content . md ) . <nl> <nl> # # # Events <nl>
Merge pull request from mariozaizar / better - translations
electron/electron
8127bbc99203640bfc9fa2129b55a552a8ce6154
2015-10-10T01:13:53Z
mmm a / cocos / 3d / CCTerrain . cpp <nl> ppp b / cocos / 3d / CCTerrain . cpp <nl> static const char * vertex_shader = " \ <nl> " ; <nl> <nl> static const char * fragment_shader_RGB_4_DETAIL = " \ n # ifdef GL_ES \ n \ <nl> - precision lowp float ; \ <nl> - \ n # endif \ n \ <nl> - uniform vec3 u_color ; \ <nl> - varying vec2 v_texCoord ; \ <nl> - varying vec3 v_normal ; \ <nl> - uniform int u_has_alpha ; \ <nl> - uniform sampler2D u_alphaMap ; \ <nl> - uniform sampler2D u_texture0 ; \ <nl> - uniform sampler2D u_texture1 ; \ <nl> - uniform sampler2D u_texture2 ; \ <nl> - uniform sampler2D u_texture3 ; \ <nl> - uniform float u_detailSize [ 4 ] ; \ <nl> - void main ( ) \ <nl> - { \ <nl> - vec3 light_direction = vec3 ( - 1 , - 1 , 0 ) ; \ <nl> - float lightFactor = dot ( - light_direction , v_normal ) ; \ <nl> - if ( u_has_alpha < = 0 ) \ <nl> - { \ <nl> - gl_FragColor = texture2D ( u_texture0 , v_texCoord ) * lightFactor ; \ <nl> - } else \ <nl> - { \ <nl> - vec4 blendFactor = texture2D ( u_alphaMap , v_texCoord ) ; \ <nl> - vec4 color = vec4 ( 0 , 0 , 0 , 0 ) ; \ <nl> - color = texture2D ( u_texture0 , v_texCoord * u_detailSize [ 0 ] ) * blendFactor . r + \ <nl> - texture2D ( u_texture1 , v_texCoord * u_detailSize [ 1 ] ) * blendFactor . g + texture2D ( u_texture2 , v_texCoord * u_detailSize [ 2 ] ) * blendFactor . b ; \ n \ <nl> - float grayFactor = dot ( blendFactor . rgb , vec3 ( 1 , 1 , 1 ) ) ; \ <nl> - color + = texture2D ( u_texture3 , v_texCoord * u_detailSize [ 3 ] ) * ( 1 . 0 - grayFactor ) ; \ <nl> - gl_FragColor = color * lightFactor ; \ <nl> - } \ <nl> - } " ; <nl> + precision lowp float ; \ <nl> + \ n # endif \ n \ <nl> + uniform vec3 u_color ; \ <nl> + varying vec2 v_texCoord ; \ <nl> + varying vec3 v_normal ; \ <nl> + uniform int u_has_alpha ; \ <nl> + uniform sampler2D u_alphaMap ; \ <nl> + uniform sampler2D u_texture0 ; \ <nl> + uniform sampler2D u_texture1 ; \ <nl> + uniform sampler2D u_texture2 ; \ <nl> + uniform sampler2D u_texture3 ; \ <nl> + uniform float u_detailSize [ 4 ] ; \ <nl> + void main ( ) \ <nl> + { \ <nl> + vec3 light_direction = vec3 ( - 1 , - 1 , 0 ) ; \ <nl> + float lightFactor = dot ( - light_direction , v_normal ) ; \ <nl> + if ( u_has_alpha < = 0 ) \ <nl> + { \ <nl> + gl_FragColor = texture2D ( u_texture0 , v_texCoord ) * lightFactor ; \ <nl> + } else \ <nl> + { \ <nl> + vec4 blendFactor = texture2D ( u_alphaMap , v_texCoord ) ; \ <nl> + vec4 color = vec4 ( 0 , 0 , 0 , 0 ) ; \ <nl> + color = texture2D ( u_texture0 , v_texCoord * u_detailSize [ 0 ] ) * blendFactor . r + \ <nl> + texture2D ( u_texture1 , v_texCoord * u_detailSize [ 1 ] ) * blendFactor . g + texture2D ( u_texture2 , v_texCoord * u_detailSize [ 2 ] ) * blendFactor . b ; \ n \ <nl> + float grayFactor = dot ( blendFactor . rgb , vec3 ( 1 , 1 , 1 ) ) ; \ <nl> + color + = texture2D ( u_texture3 , v_texCoord * u_detailSize [ 3 ] ) * ( 1 . 0 - grayFactor ) ; \ <nl> + gl_FragColor = color * lightFactor ; \ <nl> + } \ <nl> + } " ; <nl> NS_CC_BEGIN <nl> Terrain * Terrain : : create ( TerrainData & parameter ) <nl> { <nl> void Terrain : : setIsEnableFrustumCull ( bool bool_value ) <nl> Terrain : : ~ Terrain ( ) <nl> { <nl> free ( _data ) ; <nl> + for ( int i = 0 ; i < MAX_CHUNKES ; i + + ) <nl> + { <nl> + for ( int j = 0 ; j < MAX_CHUNKES ; j + + ) <nl> + { <nl> + delete _chunkesArray [ i ] [ j ] ; <nl> + } <nl> + } <nl> + free ( _chunkesArray ) ; <nl> } <nl> <nl> void Terrain : : Chunk : : finish ( ) <nl> void Terrain : : Chunk : : updateVerticesForLOD ( ) <nl> <nl> } <nl> <nl> + Terrain : : Chunk : : ~ Chunk ( ) <nl> + { <nl> + glDeleteBuffers ( 2 , vbo ) ; <nl> + } <nl> + <nl> Terrain : : QuadTree : : QuadTree ( int x , int y , int width , int height , Terrain * terrain ) <nl> { <nl> _needDraw = true ; <nl> mmm a / cocos / 3d / CCTerrain . h <nl> ppp b / cocos / 3d / CCTerrain . h <nl> class CC_DLL Terrain : public Node { <nl> { <nl> / * Constructor * / <nl> Chunk ( ) ; <nl> + ~ Chunk ( ) ; <nl> / * vertices * / <nl> std : : vector < TerrainVertexData > vertices ; <nl> / * LOD indices * / <nl> class CC_DLL Terrain : public Node { <nl> GLuint vbo [ 2 ] ; <nl> QuadTree * quad ; <nl> int detailSize [ 4 ] ; <nl> - Chunk * _chunkesArray [ 256 ] [ 256 ] ; <nl> + Chunk * _chunkesArray [ MAX_CHUNKES ] [ MAX_CHUNKES ] ; <nl> std : : vector < TerrainVertexData > vertices ; <nl> std : : vector < GLushort > indices ; <nl> int imageWidth ; <nl>
fix memory leak
cocos2d/cocos2d-x
d6c3320d4927d94c31623e2b48bd75063b41bdda
2015-01-23T10:14:44Z
mmm a / CONTRIBUTING . md <nl> ppp b / CONTRIBUTING . md <nl> <nl> # # Questions about XBMC ? <nl> <nl> - To get your questions answered , please ask in the XBMC [ Forum ] or on IRC : # xbmc on freenode . net or [ webchat ] <nl> + To get your questions answered , please ask in the XBMC [ Forum ] or on IRC : # xbmc on freenode . net <nl> <nl> Do not open an issue . <nl> <nl> Please follow this process ; it ' s the best way to get your work included in the p <nl> <nl> - [ Open a Pull Request ] ( https : / / help . github . com / articles / using - pull - requests ) with a <nl> clear title and description . <nl> + <nl> + [ Forum ] : http : / / forum . xbmc . org / <nl>
CONTRIBUTING . md : minor cosmetics
xbmc/xbmc
826206fb3d4e140ed0a21fb8b1a340e8e8067d54
2014-01-17T17:44:09Z
mmm a / src / rpc / protocol . h <nl> ppp b / src / rpc / protocol . h <nl> enum HTTPStatusCode <nl> enum RPCErrorCode <nl> { <nl> / / ! Standard JSON - RPC 2 . 0 errors <nl> + / / RPC_INVALID_REQUEST is internally mapped to HTTP_BAD_REQUEST ( 400 ) . <nl> + / / It should not be used for application - layer errors . <nl> RPC_INVALID_REQUEST = - 32600 , <nl> + / / RPC_METHOD_NOT_FOUND is internally mapped to HTTP_NOT_FOUND ( 404 ) . <nl> + / / It should not be used for application - layer errors . <nl> RPC_METHOD_NOT_FOUND = - 32601 , <nl> RPC_INVALID_PARAMS = - 32602 , <nl> + / / RPC_INTERNAL_ERROR should only be used for genuine errors in bitcoind <nl> + / / ( for exampled datadir corruption ) . <nl> RPC_INTERNAL_ERROR = - 32603 , <nl> RPC_PARSE_ERROR = - 32700 , <nl> <nl>
Add commenting around JSON error codes
bitcoin/bitcoin
338bf065a454fee76d9dfa9c7a36161cac72309f
2017-03-08T19:22:55Z
mmm a / jstests / sharding / read_write_concern_defaults_propagation . js <nl> ppp b / jstests / sharding / read_write_concern_defaults_propagation . js <nl> ReadWriteConcernDefaultsPropagation . runTests ( st . s0 , mongosAndConfigNodes ) ; <nl> / / Verify the in - memory defaults are updated correctly . This verifies the cache is invalidated <nl> / / properly on secondaries when an update to the defaults document is replicated because the <nl> / / in - memory value will only be updated after an invalidation . <nl> - ReadWriteConcernDefaultsPropagation . runTests ( st . s0 , [ . . . mongosAndConfigNodes ] , true / * inMemory * / ) ; <nl> + ReadWriteConcernDefaultsPropagation . runTests ( st . s0 , mongosAndConfigNodes , true / * inMemory * / ) ; <nl> <nl> - / / TODO SERVER - 45282 : When the defaults document is deleted , later lookups with find a document with <nl> - / / no epoch , so the current defaults will not be overwritten on a mongos . After this is resolved , <nl> - / / this case should use " mongosAndConfigNodes " as the checkConns . <nl> - ReadWriteConcernDefaultsPropagation . runDropAndDeleteTests ( st . s0 , [ . . . st . configRS . nodes ] ) ; <nl> + ReadWriteConcernDefaultsPropagation . runDropAndDeleteTests ( st . s0 , mongosAndConfigNodes ) ; <nl> <nl> - / / TODO SERVER - 45282 : When the defaults document is deleted , later lookups with find a document with <nl> - / / no epoch , so the current defaults will not be overwritten on a mongos . After this is resolved , <nl> - / / this case should use " mongosAndConfigNodes " as the checkConns . <nl> ReadWriteConcernDefaultsPropagation . runDropAndDeleteTests ( st . configRS . getPrimary ( ) , <nl> - [ . . . st . configRS . nodes ] ) ; <nl> + mongosAndConfigNodes ) ; <nl> <nl> st . stop ( ) ; <nl> } ) ( ) ; <nl> mmm a / src / mongo / db / read_write_concern_defaults . cpp <nl> ppp b / src / mongo / db / read_write_concern_defaults . cpp <nl> class OnUpdateCommitHandler final : public RecoveryUnit : : Change { <nl> const boost : : optional < BSONObj > & newDefaultsDoc ) <nl> : _service ( service ) , _rwcDefaults ( rwcDefaults ) { <nl> / / Note this will throw if the document can ' t be parsed . In the case of a delete , there will <nl> - / / be no new defaults document and the RWConcern will be default constructed , which matches <nl> + / / be no new defaults document and the RWConcern will be default constructed , which matches <nl> / / the behavior when lookup discovers a non - existent defaults document . <nl> _rwc = newDefaultsDoc <nl> ? RWConcernDefault : : parse ( IDLParserErrorContext ( " RWDefaultsWriteObserver " ) , <nl> void ReadWriteConcernDefaults : : refreshIfNecessary ( OperationContext * opCtx ) { <nl> return ; <nl> } <nl> auto currentDefaultsHandle = _defaults . acquire ( opCtx , Type : : kReadWriteConcernEntry ) ; <nl> - if ( ! currentDefaultsHandle | | <nl> + if ( ! currentDefaultsHandle | | ! possibleNewDefaults - > getEpoch ( ) | | <nl> ( possibleNewDefaults - > getEpoch ( ) > ( * * currentDefaultsHandle ) - > getEpoch ( ) ) ) { <nl> - / / Use the new defaults if they have a higher epoch , or if there are currently no defaults . <nl> + / / Use the new defaults if they have a higher epoch , if there are no defaults in the cache , <nl> + / / or if the found defaults have no epoch , meaning there are no defaults in config . settings . <nl> log ( ) < < " refreshed RWC defaults to " < < possibleNewDefaults - > toBSON ( ) ; <nl> setDefault ( std : : move ( * possibleNewDefaults ) ) ; <nl> } <nl> mmm a / src / mongo / db / read_write_concern_defaults . h <nl> ppp b / src / mongo / db / read_write_concern_defaults . h <nl> class ReadWriteConcernDefaults { <nl> <nl> / * * <nl> * Manually looks up the latest defaults , and if their epoch is more recent than the cached <nl> - * defaults , then update the cache with the new defaults . <nl> + * defaults or indicates there are no defaults , then update the cache with the new defaults . <nl> * / <nl> void refreshIfNecessary ( OperationContext * opCtx ) ; <nl> <nl> mmm a / src / mongo / db / read_write_concern_defaults_test . cpp <nl> ppp b / src / mongo / db / read_write_concern_defaults_test . cpp <nl> TEST_F ( ReadWriteConcernDefaultsTestWithClusterTime , <nl> ASSERT_LT ( * oldDefaults . getLocalSetTime ( ) , * newDefaults . getLocalSetTime ( ) ) ; <nl> } <nl> <nl> + TEST_F ( ReadWriteConcernDefaultsTestWithClusterTime , TestRefreshDefaultsWithDeletedDefaults ) { <nl> + RWConcernDefault origDefaults ; <nl> + origDefaults . setEpoch ( Timestamp ( 10 , 20 ) ) ; <nl> + origDefaults . setSetTime ( Date_t : : fromMillisSinceEpoch ( 1234 ) ) ; <nl> + _lookupMock . setLookupCallReturnValue ( std : : move ( origDefaults ) ) ; <nl> + <nl> + auto origCachedDefaults = _rwcd . getDefault ( operationContext ( ) ) ; <nl> + ASSERT_EQ ( Timestamp ( 10 , 20 ) , * origCachedDefaults . getEpoch ( ) ) ; <nl> + ASSERT_EQ ( Date_t : : fromMillisSinceEpoch ( 1234 ) , * origCachedDefaults . getSetTime ( ) ) ; <nl> + <nl> + getClock ( ) - > reserveTicks ( 1 ) ; <nl> + getMockClockSource ( ) - > advance ( Milliseconds ( 1 ) ) ; <nl> + <nl> + _lookupMock . setLookupCallReturnValue ( RWConcernDefault ( ) ) ; <nl> + <nl> + _rwcd . refreshIfNecessary ( operationContext ( ) ) ; <nl> + <nl> + / / The cache should now contain default constructed defaults . <nl> + auto newCachedDefaults = _rwcd . getDefault ( operationContext ( ) ) ; <nl> + ASSERT ( ! newCachedDefaults . getEpoch ( ) ) ; <nl> + ASSERT ( ! newCachedDefaults . getSetTime ( ) ) ; <nl> + ASSERT_LT ( * origCachedDefaults . getLocalSetTime ( ) , * newCachedDefaults . getLocalSetTime ( ) ) ; <nl> + } <nl> + <nl> } / / namespace <nl> } / / namespace mongo <nl>
SERVER - 45282 Unify how mongos and mongod default RWC caches handle deleted defaults document
mongodb/mongo
e3dd9e80e38f3528bc50c3e1115c46a0687885fa
2020-01-08T15:35:46Z
mmm a / xbmc / pvr / windows / GUIViewStatePVR . cpp <nl> ppp b / xbmc / pvr / windows / GUIViewStatePVR . cpp <nl> CGUIViewStatePVR : : CGUIViewStatePVR ( const CFileItemList & items ) : <nl> AddSortMethod ( SORT_METHOD_SIZE , 553 , LABEL_MASKS ( " % L " , " % I " , " % L " , " % I " ) ) ; / / FileName , Size | Foldername , Size <nl> AddSortMethod ( SORT_METHOD_DATE , 552 , LABEL_MASKS ( " % L " , " % J " , " % L " , " % J " ) ) ; / / FileName , Date | Foldername , Date <nl> AddSortMethod ( SORT_METHOD_FILE , 561 , LABEL_MASKS ( " % L " , " % I " , " % L " , " " ) ) ; / / Filename , Size | FolderName , empty <nl> + <nl> + / / Sort recordings view by date as default <nl> + SetSortMethod ( SORT_METHOD_DATE ) ; <nl> } <nl> <nl> LoadViewState ( items . GetPath ( ) , ActiveView = = PVR_WINDOW_UNKNOWN ? WINDOW_PVR : WINDOW_PVR + 100 - ActiveView ) ; <nl>
Merge pull request from fetzerch / pvr - sorting
xbmc/xbmc
b469250e82082378b719484c5b3ff6508e7c66a1
2012-11-17T01:56:18Z
mmm a / src / serializer / log / lba / lba_list . cc <nl> ppp b / src / serializer / log / lba / lba_list . cc <nl> <nl> # include " cpu_context . hpp " <nl> # include " event_queue . hpp " <nl> <nl> + / / TODO : refactor this monstrosity of a file . Possible rewrite the <nl> + / / whole goddamn thing all together . ( Using a non O ( N ) algorithm on <nl> + / / startup would also help - we should be using a tree dagnabit ) . <nl> + <nl> / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> * Some serializer constants * <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> # define DELETE_BLOCK off64_t ( - 1 ) <nl> <nl> static const char lba_magic [ LBA_MAGIC_SIZE ] = { ' l ' , ' b ' , ' a ' , ' m ' , ' a ' , ' g ' , ' i ' , ' c ' } ; <nl> - static const char lba_super_magic [ LBA_MAGIC_SIZE ] = { ' l ' , ' b ' , ' a ' , ' s ' , ' u ' , ' p ' , ' e ' , ' r ' } ; <nl> + static const char lba_super_magic [ LBA_SUPER_MAGIC_SIZE ] = { ' l ' , ' b ' , ' a ' , ' s ' , ' u ' , ' p ' , ' e ' , ' r ' } ; <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * <nl> + * SERIALIZATION CODE * <nl> + * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + / * lba_buf_t represents a structure that keeps in memory information <nl> + * about the extent to be serialized on disk . It is a base class for <nl> + * lba_extent_buf_t ( that represents lba extents ) , and <nl> + * lba_superblock_buf_t ( that represents lba superblock ) . * / <nl> + struct lba_buf_t <nl> + { <nl> + public : <nl> + lba_buf_t ( lba_list_t * _owner ) <nl> + : owner ( _owner ) , amount_synced ( 0 ) , writes_out ( 0 ) , data ( NULL ) <nl> + { <nl> + / / Get us some memory <nl> + data = malloc_aligned ( owner - > extent_manager - > extent_size , DEVICE_BLOCK_SIZE ) ; <nl> + assert ( data ) ; <nl> + # ifndef NDEBUG <nl> + memset ( data , 0xBD , owner - > extent_manager - > extent_size ) ; / / Make Valgrind happy <nl> + # endif <nl> + } <nl> + <nl> + virtual ~ lba_buf_t ( ) { <nl> + assert ( writes_out = = 0 ) ; <nl> + free ( data ) ; <nl> + } <nl> + <nl> + virtual void on_write_complete ( ) = 0 ; <nl> + <nl> + public : <nl> + lba_list_t * owner ; / / The LBA list that this extent is a part of <nl> + size_t amount_synced ; / / How many bytes of the extent have been scheduled to be written <nl> + int writes_out ; / / How many lba_write_ts exist that point to this buf <nl> + void * data ; / / Pointer to a chunk of memory to be written to the file <nl> + } ; <nl> + <nl> + / * We allocate temporary storage for the LBA blocks we are writing in the form of lba_extent_buf_t . <nl> + Each lba_extent_buf_t represents an LBA extent on disk , and holds a buffer for the extent in <nl> + memory . The extent we are currently writing to lives in the lba_list_t ' s ' current_extent ' field . <nl> + When we fill up an lba_extent_buf_t , we remove it from ' current_extent ' , but the lba_extent_buf_t <nl> + is responsible for deallocating itself only after all of the writes in the IO queue that refer to it <nl> + have completed . * / <nl> + struct lba_extent_buf_t : public lba_buf_t , <nl> + public alloc_mixin_t < tls_small_obj_alloc_accessor < alloc_t > , lba_extent_buf_t > <nl> + { <nl> + public : <nl> + typedef lba_list_t : : lba_extent_t extent_t ; <nl> + <nl> + public : <nl> + lba_extent_buf_t ( lba_list_t * owner ) <nl> + : lba_buf_t ( owner ) , offset ( OFFSET_UNINITIALIZED ) , num_entries ( 0 ) <nl> + { <nl> + / / Generate ourselves an extent <nl> + offset = owner - > extent_manager - > gen_extent ( ) ; <nl> + <nl> + / / Make sure that the size of the header is a multiple of the size of one entry , so that the <nl> + / / header doesn ' t prevent the entries from aligning with DEVICE_BLOCK_SIZE . <nl> + assert ( offsetof ( extent_t , entries [ 0 ] ) % sizeof ( lba_list_t : : lba_entry_t ) = = 0 ) ; <nl> + memcpy ( reinterpret_cast < extent_t * > ( data ) - > magic , lba_magic , LBA_MAGIC_SIZE ) ; <nl> + } <nl> + <nl> + virtual ~ lba_extent_buf_t ( ) { } <nl> + <nl> + size_t amount_filled ( ) { <nl> + return offsetof ( extent_t , entries [ 0 ] ) + <nl> + sizeof ( lba_list_t : : lba_entry_t ) * num_entries ; <nl> + } <nl> + <nl> + void add_entry ( block_id_t id , off64_t offset ) { <nl> + <nl> + / / Make sure that entries will align with DEVICE_BLOCK_SIZE <nl> + assert ( DEVICE_BLOCK_SIZE % sizeof ( lba_list_t : : lba_entry_t ) = = 0 ) ; <nl> + <nl> + / / Make sure that there is room <nl> + assert ( amount_filled ( ) + sizeof ( lba_list_t : : lba_entry_t ) < = owner - > extent_manager - > extent_size ) ; <nl> + <nl> + reinterpret_cast < extent_t * > ( data ) - > entries [ num_entries ] . block_id = id ; <nl> + reinterpret_cast < extent_t * > ( data ) - > entries [ num_entries ] . offset = offset ; <nl> + num_entries + + ; <nl> + } <nl> + <nl> + / / Declared later due to circular dependency with lba_write_t <nl> + void sync ( ) ; <nl> + <nl> + virtual void on_write_complete ( ) { <nl> + assert ( writes_out > 0 ) ; <nl> + writes_out - - ; <nl> + <nl> + if ( writes_out = = 0 & & amount_synced = = owner - > extent_manager - > extent_size ) <nl> + delete this ; <nl> + } <nl> + <nl> + public : <nl> + off64_t offset ; / / The offset into the file of the start of the extent <nl> + int num_entries ; / / How many entries are currently in the extent in memory <nl> + } ; <nl> + <nl> + / * This is the in - memory structure that keeps track of the lba superblock . * / <nl> + struct lba_superblock_buf_t : public lba_buf_t , <nl> + public alloc_mixin_t < tls_small_obj_alloc_accessor < alloc_t > , lba_superblock_buf_t > <nl> + { <nl> + public : <nl> + typedef lba_list_t : : lba_superblock_t extent_t ; <nl> + typedef lba_list_t : : lba_superblock_entry_t entry_t ; <nl> + <nl> + public : <nl> + lba_superblock_buf_t ( lba_list_t * owner ) : lba_buf_t ( owner ) , f_initialized ( false ) <nl> + { <nl> + / / Make sure that the size of the header is a multiple of the size of one entry , so that the <nl> + / / header doesn ' t prevent the entries from aligning with DEVICE_BLOCK_SIZE . <nl> + assert ( offsetof ( extent_t , entries [ 0 ] ) % sizeof ( entry_t ) = = 0 ) ; <nl> + memcpy ( reinterpret_cast < extent_t * > ( data ) - > magic , lba_super_magic , LBA_SUPER_MAGIC_SIZE ) ; <nl> + } <nl> + <nl> + size_t amount_filled ( ) { <nl> + return offsetof ( extent_t , entries [ 0 ] ) + sizeof ( entry_t ) * owner - > lba_superblock_entry_count ; <nl> + } <nl> + <nl> + void add_entry ( off64_t offset , int nentries ) { <nl> + / / Make sure that entries will align with DEVICE_BLOCK_SIZE <nl> + assert ( DEVICE_BLOCK_SIZE % sizeof ( entry_t ) = = 0 ) ; <nl> + <nl> + / / Make sure that there is room <nl> + assert ( amount_filled ( ) + sizeof ( entry_t ) < = owner - > extent_manager - > extent_size ) ; <nl> + <nl> + int num_entries = owner - > lba_superblock_entry_count ; <nl> + reinterpret_cast < extent_t * > ( data ) - > entries [ num_entries ] . offset = offset ; <nl> + reinterpret_cast < extent_t * > ( data ) - > entries [ num_entries ] . lba_entries_count = nentries ; <nl> + owner - > lba_superblock_entry_count + + ; <nl> + } <nl> + <nl> + / / Declared later due to circular dependency with lba_write_t <nl> + void sync ( ) ; <nl> + <nl> + virtual void on_write_complete ( ) { <nl> + assert ( writes_out > 0 ) ; <nl> + writes_out - - ; <nl> + } <nl> + <nl> + private : <nl> + bool f_initialized ; <nl> + } ; <nl> + <nl> + / * When writing offsets to a file , we do not want to confirm to the user that the sync is complete <nl> + until not only the write that they initiated is complete , but all prior writes are complete . This is <nl> + handled by lba_write_t , which is in effect a linked list of writes . The lba_write_t ' s done ( ) method <nl> + will only run when the write and all prior writes are complete . * / <nl> + struct lba_write_t : <nl> + public iocallback_t , <nl> + public alloc_mixin_t < tls_small_obj_alloc_accessor < alloc_t > , lba_write_t > <nl> + { <nl> + <nl> + lba_write_t ( lba_list_t * owner , lba_buf_t * buf ) <nl> + : owner ( owner ) , buf ( buf ) , next_write ( NULL ) <nl> + { <nl> + / / The idea here is that every lba_write_t ' s next_write points <nl> + / / to the lba_write_t that ' s chronologically started after it . <nl> + waiting_for_this_write = true ; <nl> + if ( owner - > last_write ) { <nl> + assert ( ! owner - > last_write - > next_write ) ; <nl> + owner - > last_write - > next_write = this ; <nl> + waiting_for_last_write = true ; <nl> + } else { <nl> + waiting_for_last_write = false ; <nl> + } <nl> + owner - > last_write = this ; <nl> + } <nl> + <nl> + ~ lba_write_t ( ) { <nl> + assert ( ! waiting_for_this_write ) ; <nl> + assert ( ! waiting_for_last_write ) ; <nl> + } <nl> + <nl> + void on_io_complete ( event_t * e ) { <nl> + assert ( waiting_for_this_write ) ; <nl> + waiting_for_this_write = false ; <nl> + if ( buf ) buf - > on_write_complete ( ) ; <nl> + if ( ! waiting_for_last_write ) done ( ) ; <nl> + } <nl> + <nl> + void on_last_write_complete ( ) { <nl> + assert ( waiting_for_last_write ) ; <nl> + waiting_for_last_write = false ; <nl> + if ( ! waiting_for_this_write ) done ( ) ; <nl> + } <nl> + <nl> + void done ( ) { <nl> + while ( lba_list_t : : sync_callback_t * cb = callbacks . head ( ) ) { <nl> + callbacks . remove ( cb ) ; <nl> + cb - > on_lba_sync ( ) ; <nl> + } <nl> + if ( next_write ) next_write - > on_last_write_complete ( ) ; <nl> + if ( owner - > last_write = = this ) owner - > last_write = NULL ; <nl> + delete this ; <nl> + } <nl> + <nl> + bool waiting_for_last_write ; / / true unless the entire LBA up to this point is safely on disk <nl> + bool waiting_for_this_write ; / / true unless our chunk of the LBA is safely on disk <nl> + lba_list_t * owner ; <nl> + <nl> + / / We notify ' buf ' , ' callbacks ' , and / or ' next_write ' when we are done <nl> + lba_buf_t * buf ; <nl> + intrusive_list_t < lba_list_t : : sync_callback_t > callbacks ; <nl> + lba_write_t * next_write ; <nl> + } ; <nl> + <nl> + / / Declared here due to circular dependency with lba_write_t <nl> + void lba_extent_buf_t : : sync ( ) { <nl> + <nl> + if ( amount_synced < amount_filled ( ) ) { <nl> + / / The lba_write_t will register itself with the lba_list_t <nl> + lba_write_t * w = new lba_write_t ( owner , this ) ; <nl> + <nl> + event_queue_t * queue = get_cpu_context ( ) - > event_queue ; <nl> + queue - > iosys . schedule_aio_write ( <nl> + owner - > dbfd , <nl> + offset + amount_synced , / / Offset write begins at <nl> + amount_filled ( ) - amount_synced , / / Length of write <nl> + ( byte * ) data + amount_synced , <nl> + queue , <nl> + w ) ; <nl> + <nl> + amount_synced = amount_filled ( ) ; <nl> + writes_out + + ; <nl> + } <nl> + } <nl> + <nl> + void lba_superblock_buf_t : : sync ( ) { <nl> + assert ( owner - > lba_superblock_entry_count > = 0 ) ; <nl> + if ( owner - > lba_superblock_entry_count = = 0 ) <nl> + return ; <nl> + <nl> + lba_write_t * w = new lba_write_t ( owner , this ) ; <nl> + event_queue_t * queue = get_cpu_context ( ) - > event_queue ; <nl> + <nl> + size_t write_count = ceil_aligned ( amount_filled ( ) , DEVICE_BLOCK_SIZE ) ; <nl> + <nl> + if ( ! f_initialized | | write_count > owner - > extent_manager - > extent_size - amount_synced ) { <nl> + / / We need to generate a new extent <nl> + owner - > lba_superblock_offset = owner - > extent_manager - > gen_extent ( ) ; <nl> + amount_synced = 0 ; <nl> + } <nl> + <nl> + queue - > iosys . schedule_aio_write ( <nl> + owner - > dbfd , <nl> + owner - > lba_superblock_offset + amount_synced , / / Offset write begins at <nl> + write_count , / / Length of write <nl> + ( byte * ) data , <nl> + queue , <nl> + w ) ; <nl> + <nl> + amount_synced + = write_count ; <nl> + writes_out + + ; <nl> + f_initialized = true ; <nl> + } <nl> + <nl> + void lba_list_t : : make_entry_in_extent ( block_id_t block , off64_t offset ) { <nl> + <nl> + if ( ! current_extent ) { <nl> + current_extent = new lba_extent_buf_t ( this ) ; <nl> + } <nl> + <nl> + current_extent - > add_entry ( block , offset ) ; <nl> + <nl> + if ( current_extent - > amount_filled ( ) = = extent_manager - > extent_size ) { <nl> + / / Sync proactively so we don ' t have to keep track of which lba_extent_buf_ts are unsynced <nl> + current_extent - > sync ( ) ; <nl> + finalize_current_extent ( ) ; <nl> + } <nl> + } <nl> + <nl> + bool lba_list_t : : sync ( sync_callback_t * cb ) { <nl> + <nl> + assert ( state = = state_ready ) ; <nl> + <nl> + if ( current_extent ) { <nl> + / / This is the most common case . We have appended entries to an existing extent but not <nl> + / / filled it , or we filled one or more extents and then started a new one . If we filled more <nl> + / / than one extent and are now syncing the final one , that is okay , because the lba_write_t <nl> + / / will not call us back until the lba_write_ts from the previous extents are also done <nl> + / / writing . <nl> + <nl> + while ( current_extent - > amount_filled ( ) % DEVICE_BLOCK_SIZE ! = 0 ) { <nl> + current_extent - > add_entry ( PADDING_BLOCK_ID , PADDING_OFFSET ) ; <nl> + } <nl> + <nl> + current_extent - > sync ( ) ; <nl> + <nl> + / / If our padding filled the remaining empty space in the <nl> + / / extent , we ' re done with it , time to set current_extent to <nl> + / / NULL , so we create a new extent object when we need more <nl> + / / entries <nl> + if ( current_extent - > amount_filled ( ) = = extent_manager - > extent_size ) { <nl> + finalize_current_extent ( ) ; <nl> + } <nl> + } <nl> + <nl> + if ( last_write ) { <nl> + / / Attach our callback to the write that is in progress <nl> + if ( cb ) last_write - > callbacks . push_back ( cb ) ; <nl> + return false ; <nl> + } else { <nl> + return true ; <nl> + } <nl> + } <nl> + <nl> + void lba_list_t : : prepare_metablock ( metablock_mixin_t * metablock ) { <nl> + / / TODO : assert that all outstanding LBA disk write requests have <nl> + / / completed by this point . <nl> + metablock - > lba_superblock_offset = lba_superblock_offset ; <nl> + metablock - > lba_superblock_entries_count = lba_superblock_entry_count ; <nl> + if ( current_extent ) { <nl> + metablock - > last_lba_extent_offset = current_extent - > offset ; <nl> + metablock - > last_lba_extent_entries_count = current_extent - > num_entries ; <nl> + } else { <nl> + / / There is no current extent , which means the entry about the <nl> + / / last extent is stored in the lba superblock . <nl> + metablock - > last_lba_extent_offset = OFFSET_UNINITIALIZED ; <nl> + metablock - > last_lba_extent_entries_count = 0 ; <nl> + } <nl> + } <nl> <nl> / * * * * * * * * * * * * * * * * * * <nl> * INITIALIZATION * <nl> * * * * * * * * * * * * * * * * * * / <nl> lba_list_t : : lba_list_t ( extent_manager_t * em ) <nl> : extent_manager ( em ) , state ( state_unstarted ) , last_write ( NULL ) , next_free_id ( NULL_BLOCK_ID ) <nl> - { } <nl> + { <nl> + superblock_extent = new lba_superblock_buf_t ( this ) ; <nl> + } <nl> <nl> struct lba_start_fsm_t : <nl> public iocallback_t , <nl> struct lba_start_fsm_t : <nl> typedef lba_list_t : : block_info_t block_info_t ; <nl> <nl> lba_start_fsm_t ( lba_list_t * l ) <nl> - : owner ( l ) , state ( state_start ) , nextentsloaded ( 0 ) , nextentsrequested ( 0 ) { <nl> - / / TODO : Allocation <nl> - superblock_buffer = ( lba_superblock_t * ) malloc_aligned ( owner - > extent_manager - > extent_size , DEVICE_BLOCK_SIZE ) ; <nl> - assert ( superblock_buffer ) ; <nl> - } <nl> + : owner ( l ) , state ( state_start ) , nextentsloaded ( 0 ) , nextentsrequested ( 0 ) <nl> + { } <nl> <nl> ~ lba_start_fsm_t ( ) { <nl> assert ( state = = state_start | | state = = state_done ) ; <nl> - free ( superblock_buffer ) ; <nl> } <nl> <nl> bool run ( lba_list_t : : metablock_mixin_t * last_metablock , lba_list_t : : ready_callback_t * cb ) { <nl> struct lba_start_fsm_t : <nl> } <nl> <nl> bool load_lba_fsm ( ) { <nl> + lba_superblock_t * superblock_buffer = ( lba_superblock_t * ) owner - > superblock_extent - > data ; <nl> + <nl> if ( state = = state_load_superblock ) { <nl> / / Yay , we ' re loading the superblock that points to <nl> / / extents with all the LBA goodness <nl> struct lba_start_fsm_t : <nl> queue - > iosys . schedule_aio_read ( <nl> owner - > dbfd , <nl> owner - > lba_superblock_offset , <nl> - ( lba_list_t : : lba_superblock_t : : entry_count_to_file_size ( owner - > lba_superblock_entry_count ) <nl> - / DEVICE_BLOCK_SIZE * DEVICE_BLOCK_SIZE ) , / / ( this takes care of alignment ) <nl> + ceil_aligned ( lba_list_t : : lba_superblock_t : : entry_count_to_file_size ( owner - > lba_superblock_entry_count ) , <nl> + DEVICE_BLOCK_SIZE ) , <nl> superblock_buffer , <nl> queue , <nl> this ) ; <nl> struct lba_start_fsm_t : <nl> } <nl> <nl> if ( state = = state_load_extents ) { <nl> + / / First , verify that the superblock we loaded is a real <nl> + / / superblock <nl> + assert ( memcmp ( superblock_buffer - > magic , lba_super_magic , LBA_SUPER_MAGIC_SIZE ) = = 0 ) ; <nl> + <nl> event_queue_t * queue = get_cpu_context ( ) - > event_queue ; <nl> <nl> / / Load the LBA extents in the superblock , if any , as well <nl> / / as the last LBA extent from the metablock if it exists . <nl> lba_extent_blocks . reserve ( owner - > lba_superblock_entry_count + 1 ) ; <nl> for ( int i = 0 ; i < owner - > lba_superblock_entry_count ; i + + ) { <nl> - lba_extent_t * extent = ( lba_extent_t * ) malloc_aligned ( owner - > extent_manager - > extent_size , DEVICE_BLOCK_SIZE ) ; <nl> - lba_extent_blocks . push_back ( lba_extent_info_t ( extent , superblock_buffer - > entries [ i ] . lba_entries_count ) ) ; <nl> - queue - > iosys . schedule_aio_read ( <nl> - owner - > dbfd , <nl> - superblock_buffer - > entries [ i ] . offset , <nl> - owner - > extent_manager - > extent_size , <nl> - lba_extent_blocks [ i ] . first , <nl> - queue , <nl> - this ) ; <nl> - nextentsrequested + + ; <nl> + if ( superblock_buffer - > entries [ i ] . offset ! = PADDING_OFFSET ) { <nl> + lba_extent_t * extent = ( lba_extent_t * ) malloc_aligned ( owner - > extent_manager - > extent_size , DEVICE_BLOCK_SIZE ) ; <nl> + lba_extent_blocks . push_back ( lba_extent_info_t ( extent , superblock_buffer - > entries [ i ] . lba_entries_count ) ) ; <nl> + queue - > iosys . schedule_aio_read ( <nl> + owner - > dbfd , <nl> + superblock_buffer - > entries [ i ] . offset , <nl> + owner - > extent_manager - > extent_size , <nl> + lba_extent_blocks [ i ] . first , <nl> + queue , <nl> + this ) ; <nl> + nextentsrequested + + ; <nl> + } <nl> } <nl> <nl> / / If there is last extent in the metablock , load that too <nl> struct lba_start_fsm_t : <nl> int entries_in_lba_extent = extent_info . second ; <nl> <nl> / / Make sure it ' s a real LBA extent <nl> - assert ( memcmp ( buffer - > header . magic , lba_magic , LBA_MAGIC_SIZE ) = = 0 ) ; <nl> + assert ( memcmp ( buffer - > magic , lba_magic , LBA_MAGIC_SIZE ) = = 0 ) ; <nl> <nl> / / Record each entry , as long as we haven ' t already found a newer entry . We start from the <nl> / / end of the extent and work backwards so that we always read the newest entries first . <nl> struct lba_start_fsm_t : <nl> owner - > blocks . set_size ( entry - > block_id + 1 ) ; <nl> <nl> block_info_t * binfo = & owner - > blocks [ entry - > block_id ] ; <nl> - if ( ! binfo - > get_state ( ) = = lba_list_t : : block_not_found ) { <nl> + if ( binfo - > get_state ( ) = = lba_list_t : : block_not_found ) { <nl> if ( entry - > offset = = DELETE_BLOCK ) { <nl> binfo - > set_state ( lba_list_t : : block_unused ) ; <nl> } else { <nl> struct lba_start_fsm_t : <nl> / / Got an event on the superblock <nl> check ( " Error loading superblock " , e - > result < 0 ) ; <nl> state = state_load_extents ; <nl> + load_lba_fsm ( ) ; <nl> + return ; <nl> } else if ( state = = state_loading_extents ) { <nl> / / Got an event on an extent <nl> check ( " Error loading extent " , e - > result < 0 ) ; <nl> nextentsloaded + + ; <nl> if ( nextentsloaded = = nextentsrequested ) { <nl> state = state_process_extents ; <nl> + load_lba_fsm ( ) ; <nl> } <nl> + return ; <nl> } <nl> - <nl> - load_lba_fsm ( ) ; <nl> + fail ( " Invalid state . " ) ; <nl> } <nl> <nl> lba_list_t * owner ; <nl> struct lba_start_fsm_t : <nl> <nl> lba_list_t : : ready_callback_t * callback ; <nl> <nl> - lba_superblock_t * superblock_buffer ; <nl> typedef std : : pair < lba_extent_t * , int > lba_extent_info_t ; <nl> std : : vector < lba_extent_info_t , gnew_alloc < lba_extent_info_t > > lba_extent_blocks ; <nl> <nl> bool lba_list_t : : start ( fd_t fd , metablock_mixin_t * last_metablock , ready_callbac <nl> return starter - > run ( last_metablock , cb ) ; <nl> } <nl> <nl> + void lba_list_t : : finalize_current_extent ( ) { <nl> + / / Add current extent to the superblock <nl> + superblock_extent - > add_entry ( current_extent - > offset , current_extent - > num_entries ) ; <nl> + superblock_extent - > sync ( ) ; <nl> + <nl> + / / Clear it out <nl> + last_extent_offset = current_extent - > offset ; <nl> + last_extent_entry_count = current_extent - > num_entries ; <nl> + current_extent = NULL ; <nl> + } <nl> + <nl> / * * * * * * * * * * * * * * * * * * * * * * * * <nl> * LBA MANIPULATION OPS * <nl> * * * * * * * * * * * * * * * * * * * * * * * * / <nl> void lba_list_t : : delete_block ( block_id_t block ) { <nl> next_free_id = block ; <nl> } <nl> <nl> - <nl> - / * We allocate temporary storage for the LBA blocks we are writing in the form of lba_extent_buf_t . <nl> - Each lba_extent_buf_t represents an LBA extent on disk , and holds a buffer for the extent in <nl> - memory . The extent we are currently writing to lives in the lba_list_t ' s ' current_extent ' field . <nl> - When we fill up an lba_extent_buf_t , we remove it from ' current_extent ' , but the lba_extent_buf_t <nl> - is responsible for deallocating itself only after all of the writes in the IO queue that refer to it <nl> - have completed . * / <nl> - <nl> - struct lba_extent_buf_t : <nl> - public alloc_mixin_t < tls_small_obj_alloc_accessor < alloc_t > , lba_extent_buf_t > <nl> - { <nl> - <nl> - public : <nl> - lba_extent_buf_t ( lba_list_t * owner ) <nl> - : owner ( owner ) , num_entries ( 0 ) , amount_synced ( 0 ) , writes_out ( 0 ) { <nl> - <nl> - offset = owner - > extent_manager - > gen_extent ( ) ; <nl> - <nl> - data = ( lba_list_t : : lba_extent_t * ) malloc_aligned ( owner - > extent_manager - > extent_size , DEVICE_BLOCK_SIZE ) ; <nl> - assert ( data ) ; <nl> - <nl> - # ifndef NDEBUG <nl> - memset ( data , 0xBD , owner - > extent_manager - > extent_size ) ; / / Make Valgrind happy <nl> - # endif <nl> - <nl> - / / Make sure that the size of the header is a multiple of the size of one entry , so that the <nl> - / / header doesn ' t prevent the entries from aligning with DEVICE_BLOCK_SIZE . <nl> - assert ( offsetof ( lba_list_t : : lba_extent_t , entries [ 0 ] ) % sizeof ( lba_list_t : : lba_entry_t ) = = 0 ) ; <nl> - <nl> - memcpy ( data - > header . magic , lba_magic , LBA_MAGIC_SIZE ) ; <nl> - } <nl> - <nl> - ~ lba_extent_buf_t ( ) { <nl> - assert ( writes_out = = 0 ) ; <nl> - free ( data ) ; <nl> - } <nl> - <nl> - size_t amount_filled ( ) { <nl> - <nl> - return offsetof ( lba_list_t : : lba_extent_t , entries [ 0 ] ) + <nl> - sizeof ( lba_list_t : : lba_entry_t ) * num_entries ; <nl> - } <nl> - <nl> - void add_entry ( block_id_t id , off64_t offset ) { <nl> - <nl> - / / Make sure that entries will align with DEVICE_BLOCK_SIZE <nl> - assert ( DEVICE_BLOCK_SIZE % sizeof ( lba_list_t : : lba_entry_t ) = = 0 ) ; <nl> - <nl> - / / Make sure that there is room <nl> - assert ( amount_filled ( ) + sizeof ( lba_list_t : : lba_entry_t ) < = owner - > extent_manager - > extent_size ) ; <nl> - <nl> - data - > entries [ num_entries ] . block_id = id ; <nl> - data - > entries [ num_entries ] . offset = offset ; <nl> - num_entries + + ; <nl> - } <nl> - <nl> - / / Declared later due to circular dependency with lba_write_t <nl> - void sync ( ) ; <nl> - <nl> - void on_write_complete ( ) { <nl> - assert ( writes_out > 0 ) ; <nl> - writes_out - - ; <nl> - <nl> - if ( writes_out = = 0 & & amount_synced = = owner - > extent_manager - > extent_size ) <nl> - delete this ; <nl> - } <nl> - <nl> - lba_list_t : : lba_extent_t * data ; <nl> - <nl> - lba_list_t * owner ; / / The LBA list that this extent is a part of <nl> - off64_t offset ; / / The offset into the file of the start of the extent <nl> - int num_entries ; / / How many entries are currently in the extent in memory <nl> - size_t amount_synced ; / / How many bytes of the extent have been scheduled to be written <nl> - int writes_out ; / / How many lba_write_ts exist that point to this buf <nl> - } ; <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * <nl> - * SERIALIZATION CODE * <nl> - * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - / * When writing offsets to a file , we do not want to confirm to the user that the sync is complete <nl> - until not only the write that they initiated is complete , but all prior writes are complete . This is <nl> - handled by lba_write_t , which is in effect a linked list of writes . The lba_write_t ' s done ( ) method <nl> - will only run when the write and all prior writes are complete . * / <nl> - struct lba_write_t : <nl> - public iocallback_t , <nl> - public alloc_mixin_t < tls_small_obj_alloc_accessor < alloc_t > , lba_write_t > <nl> - { <nl> - <nl> - lba_write_t ( lba_list_t * owner , lba_extent_buf_t * buf ) <nl> - : owner ( owner ) , buf ( buf ) , next_write ( NULL ) <nl> - { <nl> - / / The idea here is that every lba_write_t ' s next_write points <nl> - / / to the lba_write_t that ' s chronologically started after it . <nl> - waiting_for_this_write = true ; <nl> - if ( owner - > last_write ) { <nl> - assert ( ! owner - > last_write - > next_write ) ; <nl> - owner - > last_write - > next_write = this ; <nl> - waiting_for_last_write = true ; <nl> - } else { <nl> - waiting_for_last_write = false ; <nl> - } <nl> - owner - > last_write = this ; <nl> - } <nl> - <nl> - ~ lba_write_t ( ) { <nl> - assert ( ! waiting_for_this_write ) ; <nl> - assert ( ! waiting_for_last_write ) ; <nl> - } <nl> - <nl> - void on_io_complete ( event_t * e ) { <nl> - assert ( waiting_for_this_write ) ; <nl> - waiting_for_this_write = false ; <nl> - if ( buf ) buf - > on_write_complete ( ) ; <nl> - if ( ! waiting_for_last_write ) done ( ) ; <nl> - } <nl> - <nl> - void on_last_write_complete ( ) { <nl> - assert ( waiting_for_last_write ) ; <nl> - waiting_for_last_write = false ; <nl> - if ( ! waiting_for_this_write ) done ( ) ; <nl> - } <nl> - <nl> - void done ( ) { <nl> - while ( lba_list_t : : sync_callback_t * cb = callbacks . head ( ) ) { <nl> - callbacks . remove ( cb ) ; <nl> - cb - > on_lba_sync ( ) ; <nl> - } <nl> - if ( next_write ) next_write - > on_last_write_complete ( ) ; <nl> - if ( owner - > last_write = = this ) owner - > last_write = NULL ; <nl> - delete this ; <nl> - } <nl> - <nl> - bool waiting_for_last_write ; / / true unless the entire LBA up to this point is safely on disk <nl> - bool waiting_for_this_write ; / / true unless our chunk of the LBA is safely on disk <nl> - lba_list_t * owner ; <nl> - <nl> - / / We notify ' buf ' , ' callbacks ' , and / or ' next_write ' when we are done <nl> - lba_extent_buf_t * buf ; <nl> - intrusive_list_t < lba_list_t : : sync_callback_t > callbacks ; <nl> - lba_write_t * next_write ; <nl> - } ; <nl> - <nl> - / / Declared here due to circular dependency with lba_write_t <nl> - void lba_extent_buf_t : : sync ( ) { <nl> - <nl> - if ( amount_synced < amount_filled ( ) ) { <nl> - <nl> - / / The lba_write_t will register itself with the lba_list_t <nl> - lba_write_t * w = new lba_write_t ( owner , this ) ; <nl> - <nl> - event_queue_t * queue = get_cpu_context ( ) - > event_queue ; <nl> - queue - > iosys . schedule_aio_write ( <nl> - owner - > dbfd , <nl> - offset + amount_synced , / / Offset write begins at <nl> - amount_filled ( ) - amount_synced , / / Length of write <nl> - ( byte * ) data + amount_synced , <nl> - queue , <nl> - w ) ; <nl> - <nl> - amount_synced = amount_filled ( ) ; <nl> - writes_out + + ; <nl> - } <nl> - } <nl> - <nl> - void lba_list_t : : make_entry_in_extent ( block_id_t block , off64_t offset ) { <nl> - <nl> - if ( ! current_extent ) { <nl> - current_extent = new lba_extent_buf_t ( this ) ; <nl> - } <nl> - <nl> - current_extent - > add_entry ( block , offset ) ; <nl> - <nl> - if ( current_extent - > amount_filled ( ) = = extent_manager - > extent_size ) { <nl> - / / Sync proactively so we doesn ' t have to keep track of which lba_extent_buf_ts are unsynced <nl> - current_extent - > sync ( ) ; <nl> - current_extent = NULL ; <nl> - } <nl> - } <nl> - <nl> - bool lba_list_t : : sync ( sync_callback_t * cb ) { <nl> - <nl> - assert ( state = = state_ready ) ; <nl> - <nl> - if ( current_extent ) { <nl> - / / This is the most common case . We have appended entries to an existing extent but not <nl> - / / filled it , or we filled one or more extents and then started a new one . If we filled more <nl> - / / than one extent and are now syncing the final one , that is okay , because the lba_write_t <nl> - / / will not call us back until the lba_write_ts from the previous extents are also done <nl> - / / writing . <nl> - <nl> - while ( current_extent - > amount_filled ( ) % DEVICE_BLOCK_SIZE ! = 0 ) { <nl> - current_extent - > add_entry ( PADDING_BLOCK_ID , PADDING_OFFSET ) ; <nl> - } <nl> - <nl> - current_extent - > sync ( ) ; <nl> - <nl> - / / If our padding filled the remaining empty space in the <nl> - / / extent , we ' re done with it , time to set current_extent to <nl> - / / NULL , so we create a new extent object when we need more <nl> - / / entries <nl> - if ( current_extent - > amount_filled ( ) = = extent_manager - > extent_size ) { <nl> - current_extent = NULL ; <nl> - } <nl> - } <nl> - <nl> - if ( last_write ) { <nl> - / / Attach our callback to the write that is in progress <nl> - if ( cb ) last_write - > callbacks . push_back ( cb ) ; <nl> - return false ; <nl> - } else { <nl> - return true ; <nl> - } <nl> - } <nl> - <nl> - void lba_list_t : : prepare_metablock ( metablock_mixin_t * metablock ) { <nl> - / / TODO : assert that all outstanding LBA disk write requests have <nl> - / / completed by this point . <nl> - metablock - > lba_superblock_offset = lba_superblock_offset ; <nl> - metablock - > lba_superblock_entries_count = lba_superblock_entry_count ; <nl> - if ( current_extent ) { <nl> - metablock - > last_lba_extent_offset = current_extent - > offset ; <nl> - metablock - > last_lba_extent_entries_count = current_extent - > num_entries ; <nl> - } else { <nl> - metablock - > last_lba_extent_offset = last_extent_offset ; <nl> - metablock - > last_lba_extent_entries_count = last_extent_entry_count ; <nl> - } <nl> - } <nl> - <nl> / * * * * * * * * * * * * * * * <nl> * DESTRUCTION * <nl> * * * * * * * * * * * * * * * / <nl> void lba_list_t : : shutdown ( ) { <nl> delete current_extent ; <nl> current_extent = NULL ; <nl> } <nl> + if ( superblock_extent ) { <nl> + delete superblock_extent ; <nl> + superblock_extent = NULL ; <nl> + } <nl> } <nl> <nl> lba_list_t : : ~ lba_list_t ( ) { <nl> mmm a / src / serializer / log / lba / lba_list . hpp <nl> ppp b / src / serializer / log / lba / lba_list . hpp <nl> <nl> <nl> / / Used internally by lba_list_t <nl> struct lba_extent_buf_t ; <nl> + struct lba_superblock_buf_t ; <nl> struct lba_write_t ; <nl> struct lba_start_fsm_t ; <nl> <nl> class lba_list_t <nl> } ; <nl> <nl> private : <nl> + friend class lba_buf_t ; <nl> friend class lba_extent_buf_t ; <nl> + friend class lba_superblock_buf_t ; <nl> friend class lba_write_t ; <nl> friend class lba_start_fsm_t ; <nl> <nl> class lba_list_t <nl> segmented_vector_t < block_info_t , MAX_BLOCK_ID > blocks ; <nl> <nl> lba_extent_buf_t * current_extent ; <nl> + lba_superblock_buf_t * superblock_extent ; <nl> <nl> off64_t lba_superblock_offset ; <nl> int lba_superblock_entry_count ; <nl> class lba_list_t <nl> block_id_t block_id ; <nl> off64_t offset ; / / Is either an offset into the file or DELETE_BLOCK <nl> } ; <nl> - struct lba_header_t { <nl> - char magic [ LBA_MAGIC_SIZE ] ; <nl> - } ; <nl> struct lba_extent_t { <nl> / / Header needs to be padded to a multiple of sizeof ( lba_entry_t ) <nl> - lba_header_t header ; <nl> - char padding [ sizeof ( lba_entry_t ) - sizeof ( lba_header_t ) % sizeof ( lba_entry_t ) ] ; <nl> + char magic [ LBA_MAGIC_SIZE ] ; <nl> + char padding [ sizeof ( lba_entry_t ) - sizeof ( magic ) % sizeof ( lba_entry_t ) ] ; <nl> lba_entry_t entries [ 0 ] ; <nl> } ; <nl> <nl> class lba_list_t <nl> } ; <nl> <nl> struct lba_superblock_t { <nl> + / / Header needs to be padded to a multiple of sizeof ( lba_superblock_entry_t ) <nl> char magic [ LBA_SUPER_MAGIC_SIZE ] ; <nl> + char padding [ sizeof ( lba_superblock_entry_t ) - sizeof ( magic ) % sizeof ( lba_superblock_entry_t ) ] ; <nl> <nl> / * The superblock contains references to all the extents <nl> * except the last . The reference to the last extent is <nl> class lba_list_t <nl> lba_superblock_entry_t entries [ 0 ] ; <nl> <nl> static int entry_count_to_file_size ( int nentries ) { <nl> - return sizeof ( lba_superblock_entry_t ) * nentries + sizeof ( magic ) ; <nl> + return sizeof ( lba_superblock_entry_t ) * nentries + offsetof ( lba_superblock_t , entries [ 0 ] ) ; <nl> } <nl> } ; <nl> <nl> private : <nl> void make_entry_in_extent ( block_id_t block , off64_t offset ) ; <nl> + void finalize_current_extent ( ) ; <nl> + <nl> private : <nl> / / class gc_array ; <nl> / / class gc_pq ; <nl> - typedef std : : bitset < ( EXTENT_SIZE - sizeof ( lba_header_t ) ) / sizeof ( lba_entry_t ) > gc_array ; <nl> - typedef priority_queue_t < gc_array , std : : less < gc_array > > gc_pq ; <nl> + / / typedef std : : bitset < ( EXTENT_SIZE - sizeof ( lba_header_t ) ) / sizeof ( lba_entry_t ) > gc_array ; <nl> + / / typedef priority_queue_t < gc_array , std : : less < gc_array > > gc_pq ; <nl> } ; <nl> <nl> # endif / * __SERIALIZER_LOG_LBA_LIST_HPP__ * / <nl> mmm a / src / utils . hpp <nl> ppp b / src / utils . hpp <nl> uint16_t htor ( uint16_t val ) { return htobe16 ( val ) ; } <nl> uint32_t htor ( uint32_t val ) { return htobe32 ( val ) ; } <nl> uint64_t htor ( uint64_t val ) { return htobe64 ( val ) ; } * / <nl> <nl> + template < typename T1 , typename T2 > <nl> + T1 ceil_aligned ( T1 value , T2 alignment ) { <nl> + if ( value % alignment ! = 0 ) { <nl> + return value + alignment - ( value % alignment ) ; <nl> + } else { <nl> + return value ; <nl> + } <nl> + } <nl> + <nl> # include " utils . tcc " <nl> # endif / / __UTILS_HPP__ <nl> mmm a / test / integration / parallel_insert . py <nl> ppp b / test / integration / parallel_insert . py <nl> <nl> from random import shuffle <nl> import os <nl> <nl> - NUM_INTS = 800000 <nl> + # NUM_INTS = 800000 <nl> + NUM_INTS = 21000 <nl> NUM_THREADS = 1 <nl> NUMSTR = " % d " <nl> <nl>
We can insert and get out elements when number of entries in the superblock is reasonably small ( 1 for now ) . Big progress
rethinkdb/rethinkdb
ce428fc91bd72e93524d08f90ad1e69d30161b7e
2010-08-30T23:41:07Z
mmm a / src / x87 / lithium - x87 . cc <nl> ppp b / src / x87 / lithium - x87 . cc <nl> LOperand * LPlatformChunk : : GetNextSpillSlot ( RegisterKind kind ) { <nl> <nl> void LStoreNamedField : : PrintDataTo ( StringStream * stream ) { <nl> object ( ) - > PrintTo ( stream ) ; <nl> - hydrogen ( ) - > access ( ) . PrintTo ( stream ) ; <nl> - stream - > Add ( " < - " ) ; <nl> + OStringStream os ; <nl> + os < < hydrogen ( ) - > access ( ) < < " < - " ; <nl> + stream - > Add ( os . c_str ( ) ) ; <nl> value ( ) - > PrintTo ( stream ) ; <nl> } <nl> <nl> mmm a / test / cctest / test - assembler - x87 . cc <nl> ppp b / test / cctest / test - assembler - x87 . cc <nl> TEST ( AssemblerIa320 ) { <nl> Handle < Code > code = isolate - > factory ( ) - > NewCode ( <nl> desc , Code : : ComputeFlags ( Code : : STUB ) , Handle < Code > ( ) ) ; <nl> # ifdef OBJECT_PRINT <nl> - code - > Print ( ) ; <nl> + OFStream os ( stdout ) ; <nl> + code - > Print ( os ) ; <nl> # endif <nl> F2 f = FUNCTION_CAST < F2 > ( code - > entry ( ) ) ; <nl> int res = f ( 3 , 4 ) ; <nl> TEST ( AssemblerIa321 ) { <nl> Handle < Code > code = isolate - > factory ( ) - > NewCode ( <nl> desc , Code : : ComputeFlags ( Code : : STUB ) , Handle < Code > ( ) ) ; <nl> # ifdef OBJECT_PRINT <nl> - code - > Print ( ) ; <nl> + OFStream os ( stdout ) ; <nl> + code - > Print ( os ) ; <nl> # endif <nl> F1 f = FUNCTION_CAST < F1 > ( code - > entry ( ) ) ; <nl> int res = f ( 100 ) ; <nl> TEST ( AssemblerIa322 ) { <nl> Handle < Code > code = isolate - > factory ( ) - > NewCode ( <nl> desc , Code : : ComputeFlags ( Code : : STUB ) , Handle < Code > ( ) ) ; <nl> # ifdef OBJECT_PRINT <nl> - code - > Print ( ) ; <nl> + OFStream os ( stdout ) ; <nl> + code - > Print ( os ) ; <nl> # endif <nl> F1 f = FUNCTION_CAST < F1 > ( code - > entry ( ) ) ; <nl> int res = f ( 10 ) ; <nl> TEST ( AssemblerIa329 ) { <nl> Handle < Code > code = isolate - > factory ( ) - > NewCode ( <nl> desc , Code : : ComputeFlags ( Code : : STUB ) , Handle < Code > ( ) ) ; <nl> # ifdef OBJECT_PRINT <nl> - code - > Print ( ) ; <nl> + OFStream os ( stdout ) ; <nl> + code - > Print ( os ) ; <nl> # endif <nl> <nl> F7 f = FUNCTION_CAST < F7 > ( code - > entry ( ) ) ; <nl> mmm a / test / cctest / test - disasm - x87 . cc <nl> ppp b / test / cctest / test - disasm - x87 . cc <nl> TEST ( DisasmIa320 ) { <nl> desc , Code : : ComputeFlags ( Code : : STUB ) , Handle < Code > ( ) ) ; <nl> USE ( code ) ; <nl> # ifdef OBJECT_PRINT <nl> - code - > Print ( ) ; <nl> + OFStream os ( stdout ) ; <nl> + code - > Print ( os ) ; <nl> byte * begin = code - > instruction_start ( ) ; <nl> byte * end = begin + code - > instruction_size ( ) ; <nl> disasm : : Disassembler : : Disassemble ( stdout , begin , end ) ; <nl>
X87 : More OStreamsUse OStreams more often
v8/v8
31134fafefdd7a358d1ddcee85dd848a1910dbef
2014-07-08T05:24:52Z
mmm a / examples / server . php <nl> ppp b / examples / server . php <nl> function my_onClose ( $ serv , $ fd , $ from_id ) <nl> function my_onConnect ( $ serv , $ fd , $ from_id ) <nl> { <nl> / / throw new Exception ( " hello world " ) ; <nl> + var_dump ( $ serv - > connection_info ( $ fd ) ) ; <nl> echo " Worker # { $ serv - > worker_pid } Client [ $ fd @ $ from_id ] : Connect . \ n " ; <nl> } <nl> <nl> function my_onWorkerStart ( $ serv , $ worker_id ) <nl> / / processRename ( $ serv , $ worker_id ) ; <nl> / / forkChildInWorker ( ) ; <nl> / / setTimerInWorker ( $ serv , $ worker_id ) ; <nl> - if ( $ worker_id = = 0 ) <nl> - { <nl> - sleep ( 20 ) ; <nl> - echo " sleep finish \ n " ; <nl> - } <nl> } <nl> <nl> function my_onWorkerStop ( $ serv , $ worker_id ) <nl> mmm a / swoole_http . c <nl> ppp b / swoole_http . c <nl> static int http_request_message_complete ( php_http_parser * parser ) <nl> <nl> static void http_onClose ( swServer * serv , int fd , int from_id ) <nl> { <nl> + swConnection * conn = swServer_connection_get ( serv , fd ) ; <nl> + http_client * client = conn - > object ; <nl> + if ( client - > end = = 0 ) <nl> + { <nl> + client - > end = 1 ; <nl> + } <nl> swHashMap_del_int ( php_sw_http_clients , fd ) ; <nl> - <nl> if ( php_sw_callback [ SW_SERVER_CB_onClose ] ! = NULL ) <nl> { <nl> php_swoole_onClose ( serv , fd , from_id ) ; <nl> static void sha1 ( const char * str , unsigned char * digest ) <nl> <nl> static int websocket_handshake ( http_client * client ) <nl> { <nl> - <nl> / / HTTP / 1 . 1 101 Switching Protocols \ r \ nUpgrade : websocket \ r \ nConnection : Upgrade \ r \ nSec - WebSocket - Accept : % s \ r \ nSec - WebSocket - Version : % s \ r \ nKeepAlive : off \ r \ nContent - Length : 0 \ r \ nServer : ZWebSocket \ r \ n <nl> TSRMLS_FETCH_FROM_CTX ( sw_thread_ctx ? sw_thread_ctx : NULL ) ; <nl> zval * header = zend_read_property ( swoole_http_request_class_entry_ptr , client - > zrequest , ZEND_STRL ( " header " ) , 1 TSRMLS_CC ) ; <nl> static int http_onReceive ( swFactory * factory , swEventData * req ) <nl> * / <nl> http_request_new ( client TSRMLS_CC ) ; <nl> <nl> + conn - > object = client ; <nl> parser - > data = client ; <nl> + <nl> php_http_parser_init ( parser , PHP_HTTP_REQUEST ) ; <nl> <nl> zval * zdata = php_swoole_get_data ( req TSRMLS_CC ) ; <nl>
fixed set end when http connection closed .
swoole/swoole-src
aa6922714bcd81c1f8c6cd1dab3dfde838cdd46f
2015-01-28T11:09:29Z
mmm a / lib / Sema / CSSimplify . cpp <nl> ppp b / lib / Sema / CSSimplify . cpp <nl> performMemberLookup ( Type baseTy , const Constraint & constraint ) { <nl> <nl> / / If our base is an existential type , we can ' t make use of any <nl> / / constructor whose signature involves associated types . <nl> - / / FIXME : Mark this as ' unavailable ' . <nl> if ( isExistential & & <nl> isUnavailableInExistential ( getTypeChecker ( ) , constructor ) ) { <nl> result . addUnviable ( constructor , <nl> ConstraintSystem : : simplifyMemberConstraint ( const Constraint & constraint ) { <nl> break ; <nl> } <nl> <nl> - <nl> - / / If the lookup found no results at all , diagnose it as such . <nl> - if ( result . UnviableCandidates . empty ( ) & & <nl> - result . ViableCandidates . empty ( ) ) { <nl> - <nl> - / / Various kinds of lookups have recovery attempts . <nl> - if ( constraint . getKind ( ) = = ConstraintKind : : TypeMember ) { <nl> - / / If the base type was an optional , try to look through it . <nl> - if ( shouldAttemptFixes ( ) & & baseObjTy - > getOptionalObjectType ( ) ) { <nl> - / / Note the fix . <nl> - increaseScore ( SK_Fix ) ; <nl> - if ( worseThanBestSolution ( ) ) <nl> - return SolutionKind : : Error ; <nl> - <nl> - Fixes . push_back ( { FixKind : : ForceOptional , constraint . getLocator ( ) } ) ; <nl> - <nl> - / / Look through one level of optional . <nl> - addConstraint ( Constraint : : create ( * this , ConstraintKind : : TypeMember , <nl> - baseObjTy - > getOptionalObjectType ( ) , <nl> - constraint . getSecondType ( ) , <nl> - constraint . getMember ( ) , <nl> - constraint . getLocator ( ) ) ) ; <nl> - return SolutionKind : : Solved ; <nl> - } <nl> - <nl> - <nl> - / / FIXME : Customize diagnostic to mention types . <nl> - recordFailure ( constraint . getLocator ( ) , Failure : : DoesNotHaveMember , <nl> - baseObjTy , name ) ; <nl> - <nl> - return SolutionKind : : Error ; <nl> - } <nl> - <nl> - <nl> - auto instanceTy = baseObjTy ; <nl> - if ( auto MTT = instanceTy - > getAs < MetatypeType > ( ) ) <nl> - instanceTy = MTT - > getInstanceType ( ) ; <nl> - <nl> - / / Value member lookup has some hacks too . <nl> - Type rawValueType ; <nl> - if ( shouldAttemptFixes ( ) & & name = = TC . Context . Id_fromRaw & & <nl> - ( rawValueType = getRawRepresentableValueType ( TC , DC , instanceTy ) ) ) { <nl> - / / Replace a reference to " . fromRaw " with a reference to init ( rawValue : ) . <nl> - / / FIXME : This is temporary . <nl> - <nl> - / / Record this fix . <nl> - increaseScore ( SK_Fix ) ; <nl> - if ( worseThanBestSolution ( ) ) <nl> - return SolutionKind : : Error ; <nl> - <nl> - auto locator = constraint . getLocator ( ) ; <nl> - Fixes . push_back ( { FixKind : : FromRawToInit , getConstraintLocator ( locator ) } ) ; <nl> - <nl> - / / Form the type that " fromRaw " would have had and bind the <nl> - / / member type to it . <nl> - Type fromRawType = FunctionType : : get ( ParenType : : get ( TC . Context , <nl> - rawValueType ) , <nl> - OptionalType : : get ( instanceTy ) ) ; <nl> - addConstraint ( ConstraintKind : : Bind , memberTy , fromRawType , locator ) ; <nl> - <nl> - return SolutionKind : : Solved ; <nl> - } <nl> - <nl> - if ( shouldAttemptFixes ( ) & & name = = TC . Context . Id_toRaw & & <nl> - ( rawValueType = getRawRepresentableValueType ( TC , DC , instanceTy ) ) ) { <nl> - / / Replace a call to " toRaw " with a reference to rawValue . <nl> - / / FIXME : This is temporary . <nl> - <nl> - / / Record this fix . <nl> - increaseScore ( SK_Fix ) ; <nl> - if ( worseThanBestSolution ( ) ) <nl> - return SolutionKind : : Error ; <nl> - <nl> - auto locator = constraint . getLocator ( ) ; <nl> - Fixes . push_back ( { FixKind : : ToRawToRawValue , getConstraintLocator ( locator ) } ) ; <nl> - <nl> - / / Form the type that " toRaw " would have had and bind the member <nl> - / / type to it . <nl> - Type toRawType = FunctionType : : get ( TupleType : : getEmpty ( TC . Context ) , <nl> - rawValueType ) ; <nl> - addConstraint ( ConstraintKind : : Bind , memberTy , toRawType , locator ) ; <nl> - <nl> - return SolutionKind : : Solved ; <nl> - } <nl> - <nl> - if ( shouldAttemptFixes ( ) & & name . isSimpleName ( " allZeros " ) & & <nl> - ( rawValueType = getRawRepresentableValueType ( TC , DC , instanceTy ) ) ) { <nl> - / / Replace a reference to " X . allZeros " with a reference to X ( ) . <nl> - / / FIXME : This is temporary . <nl> - <nl> - / / Record this fix . <nl> - increaseScore ( SK_Fix ) ; <nl> - if ( worseThanBestSolution ( ) ) <nl> - return SolutionKind : : Error ; <nl> - <nl> - auto locator = constraint . getLocator ( ) ; <nl> - Fixes . push_back ( { FixKind : : AllZerosToInit , getConstraintLocator ( locator ) } ) ; <nl> - <nl> - / / Form the type that " allZeros " would have had and bind the <nl> - / / member type to it . <nl> - addConstraint ( ConstraintKind : : Bind , memberTy , rawValueType , locator ) ; <nl> - return SolutionKind : : Solved ; <nl> - } <nl> + / / If we found viable candidates , then we ' re done ! <nl> + if ( ! result . ViableCandidates . empty ( ) ) { <nl> + addOverloadSet ( memberTy , result . ViableCandidates , constraint . getLocator ( ) , <nl> + result . getFavoredChoice ( ) ) ; <nl> <nl> + return SolutionKind : : Solved ; <nl> + } <nl> + <nl> + <nl> + / / If we found some unviable results , then fail , but without recovery . <nl> + if ( ! result . UnviableCandidates . empty ( ) ) { <nl> + recordFailure ( constraint . getLocator ( ) , Failure : : DoesNotHaveMember , <nl> + baseObjTy , name ) ; <nl> + return SolutionKind : : Error ; <nl> + } <nl> + <nl> + <nl> + / / If the lookup found no hits at all ( either viable or unviable ) , diagnose it <nl> + / / as such and try to recover in various ways . <nl> + <nl> + if ( constraint . getKind ( ) = = ConstraintKind : : TypeMember ) { <nl> + / / If the base type was an optional , try to look through it . <nl> if ( shouldAttemptFixes ( ) & & baseObjTy - > getOptionalObjectType ( ) ) { <nl> - / / If the base type was an optional , look through it . <nl> - <nl> / / Note the fix . <nl> increaseScore ( SK_Fix ) ; <nl> if ( worseThanBestSolution ( ) ) <nl> ConstraintSystem : : simplifyMemberConstraint ( const Constraint & constraint ) { <nl> Fixes . push_back ( { FixKind : : ForceOptional , constraint . getLocator ( ) } ) ; <nl> <nl> / / Look through one level of optional . <nl> - addValueMemberConstraint ( baseObjTy - > getOptionalObjectType ( ) , <nl> - constraint . getMember ( ) , <nl> - constraint . getSecondType ( ) , <nl> - constraint . getLocator ( ) ) ; <nl> + addConstraint ( Constraint : : create ( * this , ConstraintKind : : TypeMember , <nl> + baseObjTy - > getOptionalObjectType ( ) , <nl> + constraint . getSecondType ( ) , <nl> + constraint . getMember ( ) , <nl> + constraint . getLocator ( ) ) ) ; <nl> return SolutionKind : : Solved ; <nl> } <nl> <nl> + / / FIXME : Customize diagnostic to mention types . <nl> recordFailure ( constraint . getLocator ( ) , Failure : : DoesNotHaveMember , <nl> baseObjTy , name ) ; <nl> + <nl> return SolutionKind : : Error ; <nl> } <nl> <nl> <nl> - / / If we found some unviable results , then fail , but without recovery . <nl> - / / If the lookup found no results at all , diagnose it as such . <nl> - if ( result . ViableCandidates . empty ( ) ) { <nl> - recordFailure ( constraint . getLocator ( ) , Failure : : DoesNotHaveMember , <nl> - baseObjTy , name ) ; <nl> - return SolutionKind : : Error ; <nl> + auto instanceTy = baseObjTy ; <nl> + if ( auto MTT = instanceTy - > getAs < MetatypeType > ( ) ) <nl> + instanceTy = MTT - > getInstanceType ( ) ; <nl> + <nl> + / / Value member lookup has some hacks too . <nl> + Type rawValueType ; <nl> + if ( shouldAttemptFixes ( ) & & name = = TC . Context . Id_fromRaw & & <nl> + ( rawValueType = getRawRepresentableValueType ( TC , DC , instanceTy ) ) ) { <nl> + / / Replace a reference to " . fromRaw " with a reference to init ( rawValue : ) . <nl> + / / FIXME : This is temporary . <nl> + <nl> + / / Record this fix . <nl> + increaseScore ( SK_Fix ) ; <nl> + if ( worseThanBestSolution ( ) ) <nl> + return SolutionKind : : Error ; <nl> + <nl> + auto locator = constraint . getLocator ( ) ; <nl> + Fixes . push_back ( { FixKind : : FromRawToInit , getConstraintLocator ( locator ) } ) ; <nl> + <nl> + / / Form the type that " fromRaw " would have had and bind the <nl> + / / member type to it . <nl> + Type fromRawType = FunctionType : : get ( ParenType : : get ( TC . Context , <nl> + rawValueType ) , <nl> + OptionalType : : get ( instanceTy ) ) ; <nl> + addConstraint ( ConstraintKind : : Bind , memberTy , fromRawType , locator ) ; <nl> + <nl> + return SolutionKind : : Solved ; <nl> } <nl> <nl> - / / If the base type is a tuple type , look for the named or indexed member <nl> - / / of the tuple . <nl> - / / FIXME : This special case can probably be removed now . <nl> - if ( baseObjTy - > is < TupleType > ( ) ) { <nl> - / / Tuple member lookup can only have a single result . <nl> - assert ( result . ViableCandidates . size ( ) = = 1 & & " Unknown tuple member " ) ; <nl> + if ( shouldAttemptFixes ( ) & & name = = TC . Context . Id_toRaw & & <nl> + ( rawValueType = getRawRepresentableValueType ( TC , DC , instanceTy ) ) ) { <nl> + / / Replace a call to " toRaw " with a reference to rawValue . <nl> + / / FIXME : This is temporary . <nl> + <nl> + / / Record this fix . <nl> + increaseScore ( SK_Fix ) ; <nl> + if ( worseThanBestSolution ( ) ) <nl> + return SolutionKind : : Error ; <nl> + <nl> + auto locator = constraint . getLocator ( ) ; <nl> + Fixes . push_back ( { FixKind : : ToRawToRawValue , getConstraintLocator ( locator ) } ) ; <nl> + <nl> + / / Form the type that " toRaw " would have had and bind the member <nl> + / / type to it . <nl> + Type toRawType = FunctionType : : get ( TupleType : : getEmpty ( TC . Context ) , <nl> + rawValueType ) ; <nl> + addConstraint ( ConstraintKind : : Bind , memberTy , toRawType , locator ) ; <nl> <nl> - addBindOverloadConstraint ( memberTy , result . ViableCandidates [ 0 ] , <nl> - constraint . getLocator ( ) ) ; <nl> return SolutionKind : : Solved ; <nl> } <nl> <nl> - / / We had a viable candidate , add it ! <nl> - addOverloadSet ( memberTy , result . ViableCandidates , constraint . getLocator ( ) , <nl> - result . getFavoredChoice ( ) ) ; <nl> + if ( shouldAttemptFixes ( ) & & name . isSimpleName ( " allZeros " ) & & <nl> + ( rawValueType = getRawRepresentableValueType ( TC , DC , instanceTy ) ) ) { <nl> + / / Replace a reference to " X . allZeros " with a reference to X ( ) . <nl> + / / FIXME : This is temporary . <nl> <nl> - return SolutionKind : : Solved ; <nl> + / / Record this fix . <nl> + increaseScore ( SK_Fix ) ; <nl> + if ( worseThanBestSolution ( ) ) <nl> + return SolutionKind : : Error ; <nl> + <nl> + auto locator = constraint . getLocator ( ) ; <nl> + Fixes . push_back ( { FixKind : : AllZerosToInit , getConstraintLocator ( locator ) } ) ; <nl> + <nl> + / / Form the type that " allZeros " would have had and bind the <nl> + / / member type to it . <nl> + addConstraint ( ConstraintKind : : Bind , memberTy , rawValueType , locator ) ; <nl> + return SolutionKind : : Solved ; <nl> + } <nl> + <nl> + if ( shouldAttemptFixes ( ) & & baseObjTy - > getOptionalObjectType ( ) ) { <nl> + / / If the base type was an optional , look through it . <nl> + <nl> + / / Note the fix . <nl> + increaseScore ( SK_Fix ) ; <nl> + if ( worseThanBestSolution ( ) ) <nl> + return SolutionKind : : Error ; <nl> + <nl> + Fixes . push_back ( { FixKind : : ForceOptional , constraint . getLocator ( ) } ) ; <nl> + <nl> + / / Look through one level of optional . <nl> + addValueMemberConstraint ( baseObjTy - > getOptionalObjectType ( ) , <nl> + constraint . getMember ( ) , <nl> + constraint . getSecondType ( ) , <nl> + constraint . getLocator ( ) ) ; <nl> + return SolutionKind : : Solved ; <nl> + } <nl> + <nl> + recordFailure ( constraint . getLocator ( ) , Failure : : DoesNotHaveMember , <nl> + baseObjTy , name ) ; <nl> + return SolutionKind : : Error ; <nl> } <nl> <nl> ConstraintSystem : : SolutionKind <nl>
Simplify logic in simplifyMemberConstraint , NFC .
apple/swift
9df95e8377c5f09dcdcd328a43e928c3a8acb57f
2015-07-30T04:09:08Z
mmm a / mk / install . mk <nl> ppp b / mk / install . mk <nl> init_dir : = $ ( etc_dir ) / init . d <nl> conf_dir : = $ ( etc_dir ) / rethinkdb <nl> conf_instance_dir : = $ ( conf_dir ) / instances . d <nl> lib_dir : = $ ( prefix ) / lib / rethinkdb <nl> - web_res_dir : = $ ( share_dir ) / web <nl> pidfile_dir : = $ ( var_dir ) / run / rethinkdb <nl> data_dir : = $ ( var_dir ) / lib / rethinkdb <nl> language_drivers_dir : = $ ( share_dir ) / drivers <nl> install - data : <nl> $ P INSTALL $ ( DESTDIR ) $ ( data_dir ) / instances . d <nl> umask 022 & & install - m755 - d $ ( DESTDIR ) $ ( data_dir ) / instances . d <nl> <nl> - . PHONY : install - web <nl> - install - web : web - assets <nl> - $ P INSTALL $ ( DESTDIR ) $ ( web_res_dir ) <nl> - umask 022 & & install - m755 - d $ ( DESTDIR ) $ ( web_res_dir ) <nl> - cd $ ( WEB_ASSETS_BUILD_DIR ) ; find . - type d - exec install - m755 - d $ ( abspath $ ( DESTDIR ) ) $ ( web_res_dir ) / { } \ ; <nl> - cd $ ( WEB_ASSETS_BUILD_DIR ) ; find . - type f - exec install - m644 { } $ ( abspath $ ( DESTDIR ) ) $ ( web_res_dir ) / { } \ ; <nl> - <nl> . PHONY : install - docs <nl> install - docs : <nl> $ P INSTALL $ ( ASSETS_DIR ) / docs / LICENSE $ ( DESTDIR ) $ ( doc_dir ) / copyright <nl> install - docs : <nl> install - m644 $ ( ASSETS_DIR ) / docs / LICENSE $ ( DESTDIR ) $ ( doc_dir ) / copyright <nl> <nl> . PHONY : install <nl> - install : install - binaries install - manpages install - docs install - tools install - web install - data install - config <nl> + install : install - binaries install - manpages install - docs install - tools install - data install - config <nl> mmm a / mk / paths . mk <nl> ppp b / mk / paths . mk <nl> PROTO_DIR : = $ ( BUILD_DIR ) / proto <nl> DEP_DIR : = $ ( BUILD_DIR ) / dep <nl> OBJ_DIR : = $ ( BUILD_DIR ) / obj <nl> <nl> - WEB_ASSETS_DIR_NAME : = rethinkdb_web_assets <nl> - WEB_ASSETS_BUILD_DIR : = $ ( BUILD_DIR ) / $ ( WEB_ASSETS_DIR_NAME ) <nl> + WEB_ASSETS_DIR_NAME : = web_assets <nl> + WEB_ASSETS_BUILD_DIR : = $ ( BUILD_ROOT_DIR ) / $ ( WEB_ASSETS_DIR_NAME ) <nl> <nl> PRECOMPILED_DIR : = $ ( TOP ) / precompiled <nl> <nl> mmm a / scripts / compile - web - assets . py <nl> ppp b / scripts / compile - web - assets . py <nl> def main ( ) : <nl> # List all the files in assets_root <nl> <nl> assets = [ <nl> - Asset ( os . path . relpath ( os . path . join ( root , path ) , assets_root ) ) <nl> + os . path . relpath ( os . path . join ( root , path ) , assets_root ) <nl> for root , __ , paths in os . walk ( assets_root ) <nl> for path in paths <nl> ] <nl> def main ( ) : <nl> <nl> write_assets ( assets_root , assets ) <nl> <nl> - write_index ( assets ) <nl> - <nl> - # An Asset describes a file and it ' s index inthe web_assets array <nl> - class Asset ( object ) : <nl> - def __init__ ( self , path ) : <nl> - self . path = path <nl> - self . index = None <nl> - <nl> prelude = " " " <nl> / / Generated by scripts / compile - web - assets . py <nl> <nl> - # include < string . h > <nl> + # include < map > <nl> + # include < utility > <nl> + # include < string > <nl> " " " <nl> <nl> - # The generated get_web_assets function returns the content of an <nl> - # asset given its path <nl> - def write_index ( assets ) : <nl> - print ( ' const char * get_web_asset ( const char * path ) { ' ) <nl> - print ( ' size_t length = strlen ( path ) ; ' ) <nl> - write_choice ( assets , indent = 1 , min_length = 0 ) <nl> - print ( ' return NULL ; ' ) <nl> - print ( ' } ; ' ) <nl> - <nl> - # Generate a balanced static search tree for the given assets <nl> - # assuming length is at least min_length <nl> - def write_choice ( assets , indent , min_length ) : <nl> - assert len ( assets ) ! = 0 : <nl> - if len ( assets ) = = 1 : <nl> - asset = assets [ 0 ] <nl> - write ( indent , ' if ( ! strcmp ( path , ' + encode ( asset . path ) + ' ) ) { ' ) <nl> - write ( indent , ' return web_assets [ ' + str ( asset . index ) + ' ] ; ' ) <nl> - write ( indent , ' } ' ) <nl> - else : <nl> - split = best_split ( assets , min_length ) <nl> - write ( indent , ' if ( ' + split . condition ( ) + ' ) { ' ) <nl> - write_choice ( split . left , indent + 1 , min_length ) <nl> - write ( indent , ' } else { ' ) <nl> - write_choice ( split . right , indent + 1 , split . right_min_length or min_length ) <nl> - write ( indent , ' } ' ) <nl> - <nl> - # Find a split point that most closely divides the assets into two halves <nl> - def best_split ( assets , min_length ) : <nl> - current_split = gen_split_length ( assets ) <nl> - for i in range ( 0 , min_length ) : <nl> - split = gen_split_char ( assets , i ) <nl> - if split . rank ( ) < current_split . rank ( ) : <nl> - current_split = split <nl> - return current_split <nl> - <nl> - # Find a length that best divides the assets <nl> - def gen_split_length ( assets ) : <nl> - split = gen_split ( assets , lambda asset : len ( asset . path ) , ' length ' ) <nl> - split . right_min_length = split . split_val <nl> - return split <nl> - <nl> - # Find the value of a given character index that best divides the assets <nl> - def gen_split_char ( assets , i ) : <nl> - return gen_split ( assets , lambda asset : asset . path [ i ] , ' path [ ' + str ( i ) + ' ] ' ) <nl> - <nl> - # Find the value of an arbitrary function that best divides the assets <nl> - def gen_split ( assets , key , field ) : <nl> - sorted_assets = sorted ( assets , key = key ) <nl> - left = [ ] <nl> - current_rank = 1 <nl> - split_val = None <nl> - for val , group in itertools . groupby ( sorted_assets , key = key ) : <nl> - group = list ( group ) <nl> - new_rank = rank ( len ( left ) + len ( group ) , len ( assets ) - len ( left ) - len ( group ) ) <nl> - if new_rank < current_rank : <nl> - left + = group <nl> - current_rank = new_rank <nl> - else : <nl> - split_val = val <nl> - break <nl> - if split_val = = None : <nl> - return Split ( field , key ( sorted_assets [ 0 ] ) , [ ] , assets ) <nl> - else : <nl> - right = sorted_assets [ len ( left ) : ] <nl> - return Split ( field , split_val , left , right ) <nl> - <nl> - # Calculate the rank of a given split . Ranges from 0 to 0 . 5 . Lower is better <nl> - def rank ( left_count , right_count ) : <nl> - return abs ( 0 . 5 - left_count / ( left_count + right_count ) ) <nl> - <nl> - # A Split contains a split point and all the assets to the left and right of it <nl> - # - field is a string describing the C + + value being compared <nl> - # - split_val is the value of that field for this split <nl> - # - left contains all the assets where the field is lesser than split_val <nl> - # - right contains all the assets where the field is greater than or equal to split_val <nl> - # - right_min_length is the minimum string size of the asset ' s path <nl> - class Split ( object ) : <nl> - def __init__ ( self , field , split_val , left , right , right_min_length = None ) : <nl> - self . field = field <nl> - self . split_val = split_val <nl> - self . left = left <nl> - self . right = right <nl> - self . right_min_length = right_min_length <nl> - <nl> - def condition ( self ) : <nl> - if isinstance ( self . split_val , str ) : <nl> - split_val = " ' " + self . split_val + " ' " <nl> - else : <nl> - split_val = str ( self . split_val ) <nl> - return self . field + " < " + split_val <nl> - <nl> - def rank ( self ) : <nl> - return rank ( len ( self . left ) , len ( self . right ) ) <nl> - <nl> - def __str__ ( self ) : <nl> - return ( <nl> - " Split ( field = " + str ( self . field ) + <nl> - " , split_val = " + str ( self . split_val ) + <nl> - " , left = " + str ( map ( lambda a : a . path , self . left ) ) + <nl> - " , right = " + str ( map ( lambda a : a . path , self . right ) ) + <nl> - " , right_min_length = " + str ( self . right_min_length ) + <nl> - " ) " <nl> - ) <nl> - <nl> - def write ( indent , line ) : <nl> - print ( indent * ' ' + line ) <nl> - <nl> def write_assets ( asset_root , assets ) : <nl> - print ( ' const char * web_assets [ ] = { ' ) <nl> + <nl> + print ( ' std : : map < std : : string , const std : : pair < const char * , size_t > > static_web_assets = { ' ) <nl> for i , asset in enumerate ( assets ) : <nl> - asset . index = i <nl> - print ( ' / / ' + asset . path , end = ' ' ) <nl> - data = open ( os . path . join ( asset_root , asset . path ) ) . read ( ) <nl> - position = 0 <nl> - trigraph = 0 <nl> - prev_e = None <nl> + <nl> + print ( ' { ' + encode ( ' / ' + asset ) + ' , { ' , end = ' ' ) <nl> + <nl> + data = open ( os . path . join ( asset_root , asset ) ) . read ( ) <nl> + position = 0 # track the position to keep lines short <nl> + trigraph = 0 # track consecutive question marks to avoid writing trigraphs <nl> + prev_e = None # track the previous character to avoid tacking on hex digits <nl> + <nl> for c in data : <nl> + <nl> if position = = 0 : <nl> - print ( ) <nl> - print ( ' " ' , end = ' ' ) <nl> - position = 5 <nl> + # start a new line <nl> + print ( ' \ n " ' , end = ' ' ) <nl> + position = 7 <nl> trigraph = 0 <nl> prev_e = None <nl> + <nl> if trigraph > = 2 and c in " = / ' ( ) ! < > - " : <nl> + # split a trigraph <nl> print ( ' " " ' , end = ' ' ) <nl> prev_e = None <nl> position + = 3 <nl> trigraph = 0 <nl> elif c = = ' ? ' : <nl> + # count the amount of question marks <nl> trigraph + = 1 <nl> else : <nl> trigraph = 0 <nl> + <nl> e = encode_char ( c , prev_e ) <nl> prev_e = e <nl> print ( e , end = ' ' ) <nl> position + = len ( e ) <nl> + <nl> if position > 82 or c = = ' \ n ' : <nl> + # end a line if it gets too long and on newlines <nl> print ( ' " ' , end = ' ' ) <nl> position = 0 <nl> + <nl> if position ! = 0 : <nl> - print ( ' " , ' ) <nl> - else : <nl> - print ( ' , ' ) <nl> - print ( ' NULL ' ) <nl> + print ( ' " ' , end = ' ' ) <nl> + print ( ' , ' ) <nl> + print ( ' ' + str ( len ( data ) ) + ' } } , ' ) <nl> + <nl> print ( ' } ; ' ) <nl> <nl> def encode ( string ) : <nl> mmm a / src / build . mk <nl> ppp b / src / build . mk <nl> RT_CXXFLAGS + = - pthread <nl> RT_CXXFLAGS + = " - DPRODUCT_NAME = \ " $ ( PRODUCT_NAME ) \ " " <nl> RT_CXXFLAGS + = " - D__STDC_LIMIT_MACROS " <nl> RT_CXXFLAGS + = " - D__STDC_FORMAT_MACROS " <nl> - RT_CXXFLAGS + = - DWEB_ASSETS_DIR_NAME = ' " $ ( WEB_ASSETS_DIR_NAME ) " ' <nl> RT_CXXFLAGS + = - Wall - Wextra <nl> <nl> # Force 64 - bit off_t size on Linux - - also , sizeof ( off_t ) will be <nl> ifeq ( $ ( AGRESSIVE_BUF_UNLOADING ) , 1 ) <nl> RT_CXXFLAGS + = - DAGRESSIVE_BUF_UNLOADING = 1 <nl> endif <nl> <nl> - RT_CXXFLAGS + = - DWEBRESDIR = ' " $ ( web_res_dir ) " ' <nl> - <nl> # TODO : > ( ) only works on bash > = 4 <nl> LD_OUTPUT_FILTER ? = <nl> ifeq ( $ ( COMPILER ) , INTEL ) <nl> NAMES : = $ ( patsubst $ ( SOURCE_DIR ) / % . cc , % , $ ( SOURCES ) ) <nl> DEPS : = $ ( patsubst % , $ ( DEP_DIR ) / % $ ( DEPS_POSTFIX ) . d , $ ( NAMES ) ) <nl> OBJS : = $ ( QL2_PROTO_OBJS ) $ ( patsubst % , $ ( OBJ_DIR ) / % . o , $ ( NAMES ) ) <nl> <nl> - SERVER_EXEC_OBJS : = $ ( QL2_PROTO_OBJS ) $ ( patsubst $ ( SOURCE_DIR ) / % . cc , $ ( OBJ_DIR ) / % . o , $ ( SERVER_EXEC_SOURCES ) ) <nl> + SERVER_EXEC_OBJS : = $ ( OBJ_DIR ) / web_assets / web_assets . o $ ( QL2_PROTO_OBJS ) $ ( patsubst $ ( SOURCE_DIR ) / % . cc , $ ( OBJ_DIR ) / % . o , $ ( SERVER_EXEC_SOURCES ) ) <nl> <nl> SERVER_NOMAIN_OBJS : = $ ( QL2_PROTO_OBJS ) $ ( patsubst $ ( SOURCE_DIR ) / % . cc , $ ( OBJ_DIR ) / % . o , $ ( filter - out % / main . cc , $ ( SOURCES ) ) ) <nl> <nl> $ ( BUILD_DIR ) / $ ( GDB_FUNCTIONS_NAME ) : | $ ( BUILD_DIR ) / . <nl> $ P CP $ @ <nl> cp $ ( SCRIPTS_DIR ) / $ ( GDB_FUNCTIONS_NAME ) $ @ <nl> <nl> + . PRECIOUS : $ ( BUILD_DIR ) / web_assets / web_assets . cc <nl> + $ ( BUILD_DIR ) / web_assets / web_assets . cc : $ ( TOP ) / scripts / compile - web - assets . py | $ ( WEB_ASSETS_BUILD_DIR ) $ ( BUILD_DIR ) / web_assets / . <nl> + $ P GENERATE <nl> + $ ( TOP ) / scripts / compile - web - assets . py $ ( WEB_ASSETS_BUILD_DIR ) > $ @ <nl> + <nl> + $ ( OBJ_DIR ) / web_assets / web_assets . o : $ ( BUILD_DIR ) / web_assets / web_assets . cc $ ( MAKEFILE_DEPENDENCY ) <nl> + mkdir - p $ ( dir $ @ ) <nl> + $ P CC <nl> + $ ( RT_CXX ) $ ( RT_CXXFLAGS ) - c - o $ @ $ < <nl> + <nl> $ ( OBJ_DIR ) / % . pb . o : $ ( PROTO_DIR ) / % . pb . cc $ ( MAKEFILE_DEPENDENCY ) $ ( QL2_PROTO_HEADERS ) <nl> mkdir - p $ ( dir $ @ ) <nl> $ P CC <nl> mmm a / src / clustering / administration / http / server . cc <nl> ppp b / src / clustering / administration / http / server . cc <nl> administrative_http_server_manager_t : : administrative_http_server_manager_t ( <nl> uuid_u _us , <nl> std : : string path ) <nl> { <nl> - std : : set < std : : string > white_list ; <nl> - white_list . insert ( " / cluster . css " ) ; <nl> - white_list . insert ( " / index . html " ) ; <nl> - white_list . insert ( " / js / backbone - min . js " ) ; <nl> - white_list . insert ( " / js / bootstrap " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - typeahead . js . fork . backup " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - alert . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - button . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - carousel . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - collapse . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - dropdown . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - modal . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - popover . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - scrollspy . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - tab . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - tooltip . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - transition . js " ) ; <nl> - white_list . insert ( " / js / bootstrap / bootstrap - typeahead . js " ) ; <nl> - white_list . insert ( " / js / chosen " ) ; <nl> - white_list . insert ( " / js / chosen / chosen - sprite . png " ) ; <nl> - white_list . insert ( " / js / chosen / chosen . css " ) ; <nl> - white_list . insert ( " / js / chosen / chosen . jquery . min . js " ) ; <nl> - white_list . insert ( " / js / ZeroClipboard . min . js " ) ; <nl> - white_list . insert ( " / js / ZeroClipboard . swf " ) ; <nl> - white_list . insert ( " / js / codemirror " ) ; <nl> - white_list . insert ( " / js / codemirror / ambiance . css " ) ; <nl> - white_list . insert ( " / js / codemirror / codemirror . css " ) ; <nl> - white_list . insert ( " / js / codemirror / codemirror . js " ) ; <nl> - white_list . insert ( " / js / codemirror / javascript . js " ) ; <nl> - white_list . insert ( " / js / codemirror / matchbrackets . js " ) ; <nl> - white_list . insert ( " / js / nanoscroller / jquery . nanoscroller . min . js " ) ; <nl> - white_list . insert ( " / js / nanoscroller / nanoscroller . css " ) ; <nl> - white_list . insert ( " / js / jquery . color . js " ) ; <nl> - white_list . insert ( " / js / backbone . js " ) ; <nl> - white_list . insert ( " / js / cubism . v1 . js " ) ; <nl> - white_list . insert ( " / js / d3 . v2 . min . js " ) ; <nl> - white_list . insert ( " / js / date - en - US . js " ) ; <nl> - white_list . insert ( " / js / jquery - 1 . 7 . 2 . min . js " ) ; <nl> - white_list . insert ( " / js / jquery . cookie . js " ) ; <nl> - white_list . insert ( " / js / jquery . dataTables . min . js " ) ; <nl> - white_list . insert ( " / js / jquery . form . js " ) ; <nl> - white_list . insert ( " / js / jquery . hotkeys . js " ) ; <nl> - white_list . insert ( " / js / jquery . lightbox_me . js " ) ; <nl> - white_list . insert ( " / js / jquery . timeago . js " ) ; <nl> - white_list . insert ( " / js / jquery . validate . min . js " ) ; <nl> - white_list . insert ( " / js / less - 1 . 1 . 4 . min . js " ) ; <nl> - white_list . insert ( " / js / rdb_cubism . v1 . js " ) ; <nl> - white_list . insert ( " / js / reql_docs . json " ) ; <nl> - white_list . insert ( " / js / underscore - min . js " ) ; <nl> - white_list . insert ( " / js / xdate . js " ) ; <nl> - white_list . insert ( " / js / handlebars . runtime - 1 . 0 . 0 . js " ) ; <nl> - white_list . insert ( " / js / template . js " ) ; <nl> - white_list . insert ( " / js / rethinkdb . js " ) ; <nl> - white_list . insert ( " / fonts / copse - regular - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / copse - regular - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / copse - regular - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / copse - regular - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / copse_OFL . txt " ) ; <nl> - white_list . insert ( " / fonts / generator_config . txt " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - bold - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - bold - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - bold - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - bold - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - regular - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - regular - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - regular - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / inconsolata - regular - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / inconsolata_OFL . txt " ) ; <nl> - white_list . insert ( " / fonts / open - sans_LICENSE . txt " ) ; <nl> - white_list . insert ( " / fonts / opensans - bold - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - bold - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - bold - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - bold - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - bolditalic - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - bolditalic - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - bolditalic - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - bolditalic - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabold - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabold - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabold - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabold - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabolditalic - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabolditalic - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabolditalic - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - extrabolditalic - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - italic - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - italic - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - italic - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - italic - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - light - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - light - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - light - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - light - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - lightitalic - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - lightitalic - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - lightitalic - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - lightitalic - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - regular - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - regular - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - regular - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - regular - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibold - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibold - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibold - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibold - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibolditalic - webfont . eot " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibolditalic - webfont . svg " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibolditalic - webfont . ttf " ) ; <nl> - white_list . insert ( " / fonts / opensans - semibolditalic - webfont . woff " ) ; <nl> - white_list . insert ( " / fonts / stylesheet . css " ) ; <nl> - white_list . insert ( " / images / warning - icon . png " ) ; <nl> - white_list . insert ( " / images / fullscreen_16x16 . png " ) ; <nl> - white_list . insert ( " / images / cog_16x16 . png " ) ; <nl> - white_list . insert ( " / images / db . png " ) ; <nl> - white_list . insert ( " / images / cog_white_16x16 . png " ) ; <nl> - white_list . insert ( " / images / trash_stroke_16x16 . png " ) ; <nl> - white_list . insert ( " / images / book_alt_16x16 . png " ) ; <nl> - white_list . insert ( " / images / book_alt2_16x14 . png " ) ; <nl> - white_list . insert ( " / images / fullscreen_exit_16x16 . png " ) ; <nl> - white_list . insert ( " / images / ajax - loader . gif " ) ; <nl> - white_list . insert ( " / images / arrow_down . png " ) ; <nl> - white_list . insert ( " / images / arrow_right . png " ) ; <nl> - white_list . insert ( " / images / bar - line - graph - icon . png " ) ; <nl> - white_list . insert ( " / images / bars - icon . png " ) ; <nl> - white_list . insert ( " / images / bars - icon_server - assignments . png " ) ; <nl> - white_list . insert ( " / images / bars - icon_white . png " ) ; <nl> - white_list . insert ( " / images / body_bg_tile . png " ) ; <nl> - white_list . insert ( " / images / clock - icon . png " ) ; <nl> - white_list . insert ( " / images / clock - icon_alt . png " ) ; <nl> - white_list . insert ( " / images / cog - icon . png " ) ; <nl> - white_list . insert ( " / images / copy_to_clipboard_16x16 . png " ) ; <nl> - white_list . insert ( " / images / disk - icon . png " ) ; <nl> - white_list . insert ( " / images / disk - slot - icon . png " ) ; <nl> - white_list . insert ( " / images / document - icon . png " ) ; <nl> - white_list . insert ( " / images / eye - icon_white . png " ) ; <nl> - white_list . insert ( " / images / globe - icon_white . png " ) ; <nl> - white_list . insert ( " / images / graph - icon . png " ) ; <nl> - white_list . insert ( " / images / green - light . png " ) ; <nl> - white_list . insert ( " / images / green - light_glow . png " ) ; <nl> - white_list . insert ( " / images / green - light_glow_small . png " ) ; <nl> - white_list . insert ( " / images / grid - icon . png " ) ; <nl> - white_list . insert ( " / images / icon - magnifying_glass . png " ) ; <nl> - white_list . insert ( " / images / layers - icon . png " ) ; <nl> - white_list . insert ( " / images / list - horiz - dash . png " ) ; <nl> - white_list . insert ( " / images / list - square - bullet . png " ) ; <nl> - white_list . insert ( " / images / list - vert - dash . png " ) ; <nl> - white_list . insert ( " / images / live - icon . png " ) ; <nl> - white_list . insert ( " / images / navbar - active . png " ) ; <nl> - white_list . insert ( " / images / pencil - icon . png " ) ; <nl> - white_list . insert ( " / images / pencil - icon_big . png " ) ; <nl> - white_list . insert ( " / images / push - arrow - left - icon . png " ) ; <nl> - white_list . insert ( " / images / query_round_trip - icon . png " ) ; <nl> - white_list . insert ( " / images / query_server_time - icon . png " ) ; <nl> - white_list . insert ( " / images / query_shard_access - icon . png " ) ; <nl> - white_list . insert ( " / images / red - light . png " ) ; <nl> - white_list . insert ( " / images / red - light_glow . png " ) ; <nl> - white_list . insert ( " / images / red - light_glow_small . png " ) ; <nl> - white_list . insert ( " / images / resolve_issue - clock_icon . png " ) ; <nl> - white_list . insert ( " / images / resolve_issue - danger_icon . png " ) ; <nl> - white_list . insert ( " / images / resolve_issue - details_icon . png " ) ; <nl> - white_list . insert ( " / images / resolve_issue - message_icon . png " ) ; <nl> - white_list . insert ( " / images / resolve_issue - resolved_icon . png " ) ; <nl> - white_list . insert ( " / images / server - icon . png " ) ; <nl> - white_list . insert ( " / images / server - icon_server - assignments . png " ) ; <nl> - white_list . insert ( " / images / status - panel_bg_tile . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_1 - error . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_1 . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_2 - error . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_2 . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_3 - error . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_3 . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_4 - error . png " ) ; <nl> - white_list . insert ( " / images / status_panel - icon_4 . png " ) ; <nl> - white_list . insert ( " / images / yellow - light_glow . png " ) ; <nl> - white_list . insert ( " / favicon . ico " ) ; <nl> - white_list . insert ( " / cluster - min . js " ) ; <nl> - <nl> - file_app . init ( new file_http_app_t ( white_list , path ) ) ; <nl> + file_app . init ( new file_http_app_t ( path ) ) ; <nl> <nl> cluster_semilattice_app . init ( new cluster_semilattice_http_app_t ( _metadata_change_handler , _directory_metadata , _us ) ) ; <nl> auth_semilattice_app . init ( new auth_semilattice_http_app_t ( _auth_change_handler , _directory_metadata , _us ) ) ; <nl> mmm a / src / clustering / administration / main / command_line . cc <nl> ppp b / src / clustering / administration / main / command_line . cc <nl> void initialize_logfile ( const std : : map < std : : string , options : : values_t > & opts , <nl> install_fallback_log_writer ( filename ) ; <nl> } <nl> <nl> - std : : string get_web_path ( boost : : optional < std : : string > web_static_directory , char * * argv ) { <nl> - / / We check first for a run - time option , then check the home of the binary , <nl> - / / and then we check in the install location if such a location was provided <nl> - / / at compile time . <nl> + std : : string get_web_path ( boost : : optional < std : : string > web_static_directory ) { <nl> path_t result ; <nl> + <nl> if ( web_static_directory ) { <nl> result = parse_as_path ( * web_static_directory ) ; <nl> } else { <nl> - result = parse_as_path ( argv [ 0 ] ) ; <nl> - result . nodes . pop_back ( ) ; <nl> - result . nodes . push_back ( WEB_ASSETS_DIR_NAME ) ; <nl> - # ifdef WEBRESDIR <nl> - std : : string chkdir ( WEBRESDIR ) ; <nl> - if ( ( access ( render_as_path ( result ) . c_str ( ) , F_OK ) ) & & ( ! access ( chkdir . c_str ( ) , F_OK ) ) ) { <nl> - result = parse_as_path ( chkdir ) ; <nl> - } <nl> - # endif / / WEBRESDIR <nl> + return std : : string ( ) ; <nl> } <nl> <nl> / / Make sure we return an absolute path <nl> std : : string get_web_path ( boost : : optional < std : : string > web_static_directory , char <nl> return abs_path . path ( ) ; <nl> } <nl> <nl> - std : : string get_web_path ( const std : : map < std : : string , options : : values_t > & opts , char * * argv ) { <nl> + std : : string get_web_path ( const std : : map < std : : string , options : : values_t > & opts ) { <nl> if ( ! exists_option ( opts , " - - no - http - admin " ) ) { <nl> boost : : optional < std : : string > web_static_directory = get_optional_option ( opts , " - - web - static - directory " ) ; <nl> - return get_web_path ( web_static_directory , argv ) ; <nl> + return get_web_path ( web_static_directory ) ; <nl> } <nl> return std : : string ( ) ; <nl> } <nl> int main_rethinkdb_serve ( int argc , char * argv [ ] ) { <nl> <nl> service_address_ports_t address_ports = get_service_address_ports ( opts ) ; <nl> <nl> - std : : string web_path = get_web_path ( opts , argv ) ; <nl> + std : : string web_path = get_web_path ( opts ) ; <nl> <nl> int num_workers ; <nl> if ( ! parse_cores_option ( opts , & num_workers ) ) { <nl> int main_rethinkdb_proxy ( int argc , char * argv [ ] ) { <nl> base_path_t base_path ( " . " ) ; <nl> initialize_logfile ( opts , base_path ) ; <nl> <nl> - std : : string web_path = get_web_path ( opts , argv ) ; <nl> + std : : string web_path = get_web_path ( opts ) ; <nl> const int num_workers = get_cpu_count ( ) ; <nl> <nl> if ( check_pid_file ( opts ) ! = EXIT_SUCCESS ) { <nl> int main_rethinkdb_porcelain ( int argc , char * argv [ ] ) { <nl> <nl> const service_address_ports_t address_ports = get_service_address_ports ( opts ) ; <nl> <nl> - std : : string web_path = get_web_path ( opts , argv ) ; <nl> + std : : string web_path = get_web_path ( opts ) ; <nl> <nl> int num_workers ; <nl> if ( ! parse_cores_option ( opts , & num_workers ) ) { <nl> mmm a / src / http / file_app . cc <nl> ppp b / src / http / file_app . cc <nl> <nl> <nl> # include < time . h > <nl> <nl> - # include < set > <nl> + # include < map > <nl> # include < string > <nl> <nl> # include " errors . hpp " <nl> <nl> # include " stl_utils . hpp " <nl> # include " time . hpp " <nl> <nl> - file_http_app_t : : file_http_app_t ( std : : set < std : : string > _whitelist , std : : string _asset_dir ) <nl> - : whitelist ( _whitelist ) , asset_dir ( _asset_dir ) <nl> + extern std : : map < std : : string , const std : : pair < const char * , size_t > > static_web_assets ; <nl> + <nl> + file_http_app_t : : file_http_app_t ( std : : string _asset_dir ) <nl> + : asset_dir ( _asset_dir ) <nl> { } <nl> <nl> + bool ends_with ( const std : : string & str , const std : : string & end ) { <nl> + return str . rfind ( end ) = = str . length ( ) - end . length ( ) ; <nl> + } <nl> + <nl> void file_http_app_t : : handle ( const http_req_t & req , http_res_t * result , signal_t * ) { <nl> if ( req . method ! = GET ) { <nl> * result = http_res_t ( HTTP_METHOD_NOT_ALLOWED ) ; <nl> void file_http_app_t : : handle ( const http_req_t & req , http_res_t * result , signal_t <nl> } <nl> <nl> std : : string resource ( req . resource . as_string ( ) ) ; <nl> - if ( resource ! = " / " & & resource ! = " " & & ! std_contains ( whitelist , resource ) ) { <nl> - printf_buffer_t resource_buffer ; <nl> - debug_print_quoted_string ( & resource_buffer , <nl> - reinterpret_cast < const uint8_t * > ( resource . data ( ) ) , <nl> - resource . length ( ) ) ; <nl> - logNTC ( " Someone asked for the nonwhitelisted file % s . If this should be " <nl> - " accessible , add it to the whitelist . " , resource_buffer . c_str ( ) ) ; <nl> - * result = http_res_t ( HTTP_FORBIDDEN ) ; <nl> - return ; <nl> - } <nl> <nl> std : : string filename ; <nl> <nl> void file_http_app_t : : handle ( const http_req_t & req , http_res_t * result , signal_t <nl> filename = resource ; <nl> } <nl> <nl> + std : : pair < const char * , size_t > resource_data ; <nl> + try { <nl> + resource_data = static_web_assets . at ( filename ) ; <nl> + } catch ( std : : out_of_range ) { <nl> + printf_buffer_t resource_buffer ; <nl> + debug_print_quoted_string ( & resource_buffer , <nl> + reinterpret_cast < const uint8_t * > ( resource . data ( ) ) , <nl> + resource . length ( ) ) ; <nl> + logNTC ( " Someone asked for the nonwhitelisted file % s . If this should be " <nl> + " accessible , add it to the static web assets . " , resource_buffer . c_str ( ) ) ; <nl> + * result = http_res_t ( HTTP_FORBIDDEN ) ; <nl> + return ; <nl> + } <nl> + <nl> time_t expires ; <nl> # ifndef NDEBUG <nl> / / In debug mode , do not cache static web assets <nl> void file_http_app_t : : handle ( const http_req_t & req , http_res_t * result , signal_t <nl> # endif <nl> result - > add_header_line ( " Expires " , http_format_date ( expires ) ) ; <nl> <nl> - thread_pool_t : : run_in_blocker_pool ( boost : : bind ( & file_http_app_t : : handle_blocking , this , filename , result ) ) ; <nl> - <nl> - if ( result - > code = = 404 ) { <nl> - logNTC ( " File % s was requested and is on the whitelist but we didn ' t find it in the directory . " , ( asset_dir + filename ) . c_str ( ) ) ; <nl> - } <nl> - } <nl> - <nl> - bool ends_with ( const std : : string & str , const std : : string & end ) { <nl> - return str . rfind ( end ) = = str . length ( ) - end . length ( ) ; <nl> - } <nl> - <nl> - void file_http_app_t : : handle_blocking ( std : : string filename , http_res_t * res_out ) { <nl> - <nl> / / TODO more robust mimetype detection ? <nl> std : : string mimetype = " text / plain " ; <nl> if ( ends_with ( filename , " . js " ) ) { <nl> void file_http_app_t : : handle_blocking ( std : : string filename , http_res_t * res_out ) <nl> } else if ( ends_with ( filename , " . gif " ) ) { <nl> mimetype = " image / gif " ; <nl> } <nl> + result - > add_header_line ( " Content - Type " , mimetype ) ; <nl> + <nl> + if ( asset_dir . empty ( ) ) { <nl> + result - > body . assign ( resource_data . first , resource_data . second ) ; <nl> + result - > code = 200 ; <nl> + } else { <nl> + thread_pool_t : : run_in_blocker_pool ( boost : : bind ( & file_http_app_t : : handle_blocking , this , filename , result ) ) ; <nl> + <nl> + if ( result - > code = = 404 ) { <nl> + logNTC ( " File % s was requested and is on the whitelist but we didn ' t find it in the directory . " , ( asset_dir + filename ) . c_str ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void file_http_app_t : : handle_blocking ( std : : string filename , http_res_t * res_out ) { <nl> <nl> / / FIXME : make sure that we won ' t walk out of our sandbox ! Check symbolic links , etc . <nl> blocking_read_file_stream_t stream ; <nl> bool initialized = stream . init ( ( asset_dir + filename ) . c_str ( ) ) ; <nl> <nl> - res_out - > add_header_line ( " Content - Type " , mimetype ) ; <nl> - <nl> if ( ! initialized ) { <nl> res_out - > code = 404 ; <nl> return ; <nl> mmm a / src / http / file_app . hpp <nl> ppp b / src / http / file_app . hpp <nl> <nl> # define HTTP_FILE_APP_HPP_ <nl> <nl> # include < string > <nl> - # include < set > <nl> <nl> # include " http / http . hpp " <nl> <nl> class file_http_app_t : public http_app_t { <nl> public : <nl> - file_http_app_t ( std : : set < std : : string > _whitelist , std : : string _asset_dir ) ; <nl> + file_http_app_t ( std : : string _asset_dir ) ; <nl> <nl> void handle ( const http_req_t & , http_res_t * result , signal_t * interruptor ) ; <nl> private : <nl> void handle_blocking ( std : : string filename , http_res_t * res_out ) ; <nl> <nl> - std : : set < std : : string > whitelist ; <nl> std : : string asset_dir ; <nl> } ; <nl> <nl>
Got static web assets to work
rethinkdb/rethinkdb
9065250f0d118a61a82bab56f751edc0c53945aa
2014-10-17T00:39:41Z
mmm a / aten / src / ATen / native / cuda / Shape . cu <nl> ppp b / aten / src / ATen / native / cuda / Shape . cu <nl> void hip_parallel_cat ( Tensor & out , const TensorList & inputs , int64_t dimension , <nl> batchCounter < CAT_ARRAY_BATCH_SIZE & & <nl> ( i + batchCounter ) < inputs . size ( ) ; <nl> + + batchCounter ) { <nl> - int64_t dimSize = at : : native : : size ( inputs [ i + batchCounter ] , dimension ) ; <nl> + int64_t dimSize = 0 ; <nl> + / / There is a legacy case where a 1 - D empty tensor can be concat with <nl> + / / high - dimensional tensor <nl> + if ( inputs [ i + batchCounter ] . numel ( ) > 0 ) { <nl> + dimSize = at : : native : : size ( inputs [ i + batchCounter ] , dimension ) ; <nl> + } <nl> <nl> stackInputs [ batchCounter ] . input = <nl> inputs [ i + batchCounter ] . data_ptr < scalar_t > ( ) ; <nl> void parallel_cat ( Tensor & out , const TensorList & inputs , int64_t dimension , <nl> batchCounter < CAT_ARRAY_BATCH_SIZE & & <nl> ( i + batchCounter ) < inputs . size ( ) ; <nl> + + batchCounter ) { <nl> - int64_t dimSize = at : : native : : size ( inputs [ i + batchCounter ] , dimension ) ; <nl> + int64_t dimSize = 0 ; <nl> + / / There is a legacy case where a 1 - D empty tensor can be concat with <nl> + / / high - dimensional tensor <nl> + if ( inputs [ i + batchCounter ] . numel ( ) > 0 ) { <nl> + dimSize = at : : native : : size ( inputs [ i + batchCounter ] , dimension ) ; <nl> + } <nl> catMetaData . input [ batchCounter ] = inputs [ i + batchCounter ] . data_ptr < scalar_t > ( ) ; <nl> catMetaData . offset [ batchCounter ] = offset ; <nl> catMetaData . dimSize [ batchCounter ] = dimSize ; <nl> Tensor & cat_out_cuda ( Tensor & out , TensorList inputs , int64_t dimension ) { <nl> auto should_skip = [ ] ( const Tensor & t ) { <nl> return t . dim ( ) = = 1 & & at : : native : : size ( t , 0 ) = = 0 ; <nl> } ; <nl> - bool hasSkippedInput = false ; <nl> <nl> const Tensor * notSkippedTensor = NULL ; / / non - owning reference <nl> int nDims = 0 ; <nl> Tensor & cat_out_cuda ( Tensor & out , TensorList inputs , int64_t dimension ) { <nl> } <nl> at : : assert_no_internal_overlap ( out ) ; <nl> <nl> - for ( int i = 0 ; i < inputs . size ( ) ; i + + ) <nl> - { <nl> + for ( int i = 0 ; i < inputs . size ( ) ; i + + ) { <nl> if ( should_skip ( inputs [ i ] ) ) { <nl> - hasSkippedInput = true ; <nl> continue ; <nl> } <nl> nDims = inputs [ i ] . dim ( ) ; <nl> Tensor & cat_out_cuda ( Tensor & out , TensorList inputs , int64_t dimension ) { <nl> / / We parallelize the copy if all 6 conditions pass : <nl> / / <nl> / / 1 . There is more than one input tensor <nl> - / / 2 . No empty inputs <nl> - / / 3 . The out tensor is 32 - bit indexable <nl> - / / 4 . The number of dimensions is < = 4 <nl> - / / 5 . All input tensors are contiguous ( output tensor may be non - contig ) <nl> - / / 6 . All input tensors can use 32 - bit indexing <nl> + / / 2 . The out tensor is 32 - bit indexable <nl> + / / 3 . The number of dimensions is < = 4 <nl> + / / 4 . All input tensors are contiguous ( output tensor may be non - contig ) <nl> + / / 5 . All input tensors can use 32 - bit indexing <nl> <nl> const bool all32BitIndexable = std : : all_of ( inputs . begin ( ) , inputs . end ( ) , <nl> [ ] ( const Tensor & t ) { <nl> Tensor & cat_out_cuda ( Tensor & out , TensorList inputs , int64_t dimension ) { <nl> } ) ; <nl> allSameType = allSameType & & ( out . scalar_type ( ) = = firstType ) ; <nl> if ( inputs . size ( ) > 1 & & <nl> - ! hasSkippedInput & & <nl> out . dim ( ) < = CAT_ARRAY_MAX_INPUT_DIMS & & <nl> at : : cuda : : detail : : canUse32BitIndexMath ( out ) & & <nl> allContiguous & & <nl>
[ pytorch / ops ] Concat fast path w / zero tensor ( )
pytorch/pytorch
e3b55a8a652f82f0f3de9ab22fbddba76766114b
2020-10-30T01:14:40Z
mmm a / src / app / ui / select_accelerator . cpp <nl> ppp b / src / app / ui / select_accelerator . cpp <nl> <nl> # include " base / bind . h " <nl> # include " base / signal . h " <nl> <nl> + # include < cctype > <nl> + <nl> namespace app { <nl> <nl> using namespace ui ; <nl> class SelectAccelerator : : KeyField : public ui : : Entry { <nl> case kKeyDownMessage : <nl> if ( hasFocus ( ) & & ! isReadOnly ( ) ) { <nl> KeyMessage * keymsg = static_cast < KeyMessage * > ( msg ) ; <nl> + KeyModifiers modifiers = keymsg - > keyModifiers ( ) ; <nl> + <nl> + if ( keymsg - > scancode ( ) = = kKeySpace ) <nl> + modifiers = ( KeyModifiers ) ( modifiers & ~ kKeySpaceModifier ) ; <nl> <nl> m_accel = Accelerator ( <nl> - keymsg - > keyModifiers ( ) , <nl> + modifiers , <nl> keymsg - > scancode ( ) , <nl> - keymsg - > unicodeChar ( ) > = 32 ? keymsg - > unicodeChar ( ) : 0 ) ; <nl> + keymsg - > unicodeChar ( ) > 32 ? <nl> + std : : tolower ( keymsg - > unicodeChar ( ) ) : 0 ) ; <nl> updateText ( ) ; <nl> <nl> AccelChange ( & m_accel ) ; <nl> SelectAccelerator : : SelectAccelerator ( const ui : : Accelerator & accel ) <nl> void SelectAccelerator : : onModifierChange ( KeyModifiers modifier , CheckBox * checkbox ) <nl> { <nl> bool state = ( checkbox - > isSelected ( ) ) ; <nl> + KeyModifiers modifiers = m_accel . modifiers ( ) ; <nl> + KeyScancode scancode = m_accel . scancode ( ) ; <nl> + int unicodeChar = m_accel . unicodeChar ( ) ; <nl> + <nl> + modifiers = ( KeyModifiers ) ( ( modifiers & ~ modifier ) | ( state ? modifier : 0 ) ) ; <nl> + if ( modifiers = = kKeySpaceModifier & & scancode = = kKeySpace ) <nl> + modifiers = kKeyNoneModifier ; <nl> <nl> - m_accel = Accelerator ( <nl> - ( KeyModifiers ) ( ( m_accel . modifiers ( ) & ~ modifier ) | ( state ? modifier : 0 ) ) , <nl> - m_accel . scancode ( ) , <nl> - m_accel . unicodeChar ( ) ) ; <nl> + m_accel = Accelerator ( modifiers , scancode , unicodeChar ) ; <nl> <nl> m_keyField - > setAccel ( m_accel ) ; <nl> updateAssignedTo ( ) ; <nl> mmm a / src / ui / accelerator . cpp <nl> ppp b / src / ui / accelerator . cpp <nl> <nl> # include " base / string . h " <nl> <nl> # include < allegro / keyboard . h > <nl> - # include < ctype . h > <nl> + # include < cctype > <nl> # include < string > <nl> # include < vector > <nl> <nl> Accelerator : : Accelerator ( const std : : string & str ) <nl> } <nl> <nl> if ( ( tok [ 0 ] > = ' a ' ) & & ( tok [ 0 ] < = ' z ' ) ) <nl> - m_scancode = ( KeyScancode ) ( ( int ) kKeyA + tolower ( tok [ 0 ] ) - ' a ' ) ; <nl> + m_scancode = ( KeyScancode ) ( ( int ) kKeyA + std : : tolower ( tok [ 0 ] ) - ' a ' ) ; <nl> else if ( ( tok [ 0 ] > = ' 0 ' ) & & ( tok [ 0 ] < = ' 9 ' ) ) <nl> m_scancode = ( KeyScancode ) ( ( int ) kKey0 + tok [ 0 ] - ' 0 ' ) ; <nl> else { <nl> Accelerator : : Accelerator ( const std : : string & str ) <nl> } <nl> } <nl> <nl> + bool Accelerator : : operator = = ( const Accelerator & other ) const <nl> + { <nl> + if ( m_modifiers ! = other . m_modifiers ) <nl> + return false ; <nl> + <nl> + if ( m_scancode = = other . m_scancode ) { <nl> + if ( m_scancode ! = kKeyNil ) <nl> + return true ; <nl> + else if ( m_unicodeChar ! = 0 ) <nl> + return ( std : : tolower ( m_unicodeChar ) = = std : : tolower ( other . m_unicodeChar ) ) ; <nl> + } <nl> + <nl> + return false ; <nl> + } <nl> + <nl> bool Accelerator : : isEmpty ( ) const <nl> { <nl> return <nl> bool Accelerator : : check ( KeyModifiers modifiers , KeyScancode scancode , int unicod <nl> } <nl> / / For any other legal Unicode code <nl> else if ( unicodeChar > = ' ' ) { <nl> - unicodeChar = tolower ( unicodeChar ) ; <nl> + unicodeChar = std : : tolower ( unicodeChar ) ; <nl> <nl> / * without shift ( because characters like ' * ' can be trigger with <nl> " Shift + 8 " , so we don ' t want " Shift + * " ) * / <nl> mmm a / src / ui / accelerator . h <nl> ppp b / src / ui / accelerator . h <nl> namespace ui { <nl> bool check ( KeyModifiers modifiers , KeyScancode scancode , int unicodeChar ) const ; <nl> bool checkFromAllegroKeyArray ( ) const ; <nl> <nl> - bool operator = = ( const Accelerator & other ) const { <nl> - return <nl> - ( m_modifiers = = other . m_modifiers & & <nl> - m_scancode = = other . m_scancode & & <nl> - m_unicodeChar = = other . m_unicodeChar ) ; <nl> - } <nl> - <nl> + bool operator = = ( const Accelerator & other ) const ; <nl> bool operator ! = ( const Accelerator & other ) const { <nl> return ! operator = = ( other ) ; <nl> } <nl>
Fix comparison between ui : : Accelerators
aseprite/aseprite
8bec9be4b267b5c7a2a979fd8fa596eb933023bb
2014-10-30T02:50:48Z
mmm a / gypfiles / standalone . gypi <nl> ppp b / gypfiles / standalone . gypi <nl> <nl> # are using a custom toolchain and need to control - B in ldflags . <nl> # Do not use 32 - bit gold on 32 - bit hosts as it runs out address space <nl> # for component = static_library builds . <nl> - [ ' ( OS = = " linux " or OS = = " android " ) and ( target_arch = = " x64 " or target_arch = = " arm " or ( target_arch = = " ia32 " and host_arch = = " x64 " ) ) ' , { <nl> + [ ' ( ( OS = = " linux " or OS = = " android " ) and ( target_arch = = " x64 " or target_arch = = " arm " or ( target_arch = = " ia32 " and host_arch = = " x64 " ) ) ) or ( OS = = " linux " and target_arch = = " mipsel " ) ' , { <nl> ' linux_use_bundled_gold % ' : 1 , <nl> } , { <nl> ' linux_use_bundled_gold % ' : 0 , <nl> mmm a / gypfiles / toolchain . gypi <nl> ppp b / gypfiles / toolchain . gypi <nl> <nl> # are using a custom toolchain and need to control - B in ldflags . <nl> # Do not use 32 - bit gold on 32 - bit hosts as it runs out address space <nl> # for component = static_library builds . <nl> - [ ' OS = = " linux " and ( target_arch = = " x64 " or target_arch = = " arm " ) ' , { <nl> + [ ' ( ( OS = = " linux " or OS = = " android " ) and ( target_arch = = " x64 " or target_arch = = " arm " or ( target_arch = = " ia32 " and host_arch = = " x64 " ) ) ) or ( OS = = " linux " and target_arch = = " mipsel " ) ' , { <nl> ' linux_use_bundled_gold % ' : 1 , <nl> } , { <nl> ' linux_use_bundled_gold % ' : 0 , <nl>
Broaden the condition under which gold is used as linker .
v8/v8
8465244e79b587aecf7d7c7ab7f89148530b9a7c
2016-07-05T10:28:17Z
mmm a / dbms / include / DB / AggregateFunctions / AggregateFunctionQuantileExactWeighted . h <nl> ppp b / dbms / include / DB / AggregateFunctions / AggregateFunctionQuantileExactWeighted . h <nl> class AggregateFunctionQuantilesExactWeighted final <nl> const Pair * end = array + size ; <nl> <nl> size_t level_index = 0 ; <nl> - UInt64 threshold = sum_weight * levels . levels [ level_index ] ; <nl> + UInt64 threshold = sum_weight * levels . levels [ levels . permutation [ level_index ] ] ; <nl> <nl> while ( it < end ) <nl> { <nl> class AggregateFunctionQuantilesExactWeighted final <nl> <nl> while ( accumulated > = threshold ) <nl> { <nl> - data_to [ old_size + level_index ] = it - > first ; <nl> + data_to [ old_size + levels . permutation [ level_index ] ] = it - > first ; <nl> + + level_index ; <nl> <nl> if ( level_index = = num_levels ) <nl> return ; <nl> <nl> - threshold = sum_weight * levels . levels [ level_index ] ; <nl> + threshold = sum_weight * levels . levels [ levels . permutation [ level_index ] ] ; <nl> } <nl> <nl> + + it ; <nl> class AggregateFunctionQuantilesExactWeighted final <nl> <nl> while ( level_index < num_levels ) <nl> { <nl> - data_to [ old_size + level_index ] = array [ size - 1 ] . first ; <nl> + data_to [ old_size + levels . permutation [ level_index ] ] = array [ size - 1 ] . first ; <nl> + + level_index ; <nl> } <nl> } <nl>
Fixed error [ # METR - 20381 ] .
ClickHouse/ClickHouse
1203a0a9c4c6e156a6d8999734fee6516820cb0e
2016-03-13T18:15:41Z
mmm a / tensorflow / contrib / cmake / CMakeLists . txt <nl> ppp b / tensorflow / contrib / cmake / CMakeLists . txt <nl> option ( tensorflow_ENABLE_SNAPPY_SUPPORT " Enable SNAPPY compression support " ON ) <nl> <nl> # GPU , CUDA and cuDNN options <nl> option ( tensorflow_ENABLE_GPU " Enable GPU support " OFF ) <nl> - option ( tensorflow_CUDA_VERSION " CUDA version to build against " 9 . 0 ) <nl> - option ( tensorflow_CUDNN_VERSION " cuDNN version to build against " 7 ) <nl> + set ( tensorflow_CUDA_VERSION " 9 . 0 " CACHE STRING " CUDA version to build against " ) <nl> + set ( tensorflow_CUDNN_VERSION " 7 " CACHE STRING " cuDNN version to build against " ) <nl> <nl> if ( HAIKU ) <nl> option ( tensorflow_ENABLE_POSITION_INDEPENDENT_CODE " Enable PIE support " OFF ) <nl>
Instead of " option " use " set " to define non - bool cmake build args . ( )
tensorflow/tensorflow
798fa36d11119e6fdc13b90a14abfe1805e7de90
2017-12-15T06:02:41Z
mmm a / hphp / runtime / ext / vsdebug / command . h <nl> ppp b / hphp / runtime / ext / vsdebug / command . h <nl> struct VariablesCommand : public VSCommand { <nl> folly : : dynamic * vars <nl> ) ; <nl> <nl> - static const std : : string getVariableValue ( <nl> + struct VariableValue { <nl> + explicit VariableValue ( const std : : string & value , bool hasSummaryOverride = false ) <nl> + : m_value { value } , <nl> + m_hasSummaryOverride ( hasSummaryOverride ) <nl> + { } <nl> + const std : : string m_value ; <nl> + bool m_hasSummaryOverride ; <nl> + } ; <nl> + <nl> + static const VariableValue getVariableValue ( <nl> DebuggerSession * session , <nl> Debugger * debugger , <nl> request_id_t requestId , <nl> const Variant & variable <nl> ) ; <nl> <nl> - static const std : : string getObjectSummary ( <nl> + static const VariableValue getObjectSummary ( <nl> DebuggerSession * session , <nl> Debugger * debugger , <nl> request_id_t requestId , <nl> mmm a / hphp / runtime / ext / vsdebug / variables_command . cpp <nl> ppp b / hphp / runtime / ext / vsdebug / variables_command . cpp <nl> folly : : dynamic VariablesCommand : : serializeVariable ( <nl> folly : : dynamic var = folly : : dynamic : : object ; <nl> const std : : string variableName = doNotModifyName ? name : getPHPVarName ( name ) ; <nl> <nl> + auto value = getVariableValue ( session , debugger , requestId , variable ) ; <nl> + <nl> var [ " name " ] = variableName ; <nl> - var [ " value " ] = getVariableValue ( session , debugger , requestId , variable ) ; <nl> + var [ " value " ] = value . m_value ; <nl> var [ " type " ] = getTypeName ( variable ) ; <nl> <nl> - / / If the variable is an array or object , register it as a server object and <nl> - / / indicate how many children it has . <nl> - if ( variable . isArray ( ) | | variable . isObject ( ) ) { <nl> + / / If there is a summary value returned from the object , then we don ' t want <nl> + / / to show children . Otherwise , if the variable is an array or object , <nl> + / / register it as a server object and indicate how many children it has . <nl> + if ( ! value . m_hasSummaryOverride & & ( variable . isArray ( ) | | variable . isObject ( ) ) ) { <nl> bool hasChildren = false ; <nl> unsigned int id = session - > generateVariableId ( <nl> requestId , <nl> const char * VariablesCommand : : getTypeName ( const Variant & variable ) { <nl> } <nl> } <nl> <nl> - const std : : string VariablesCommand : : getVariableValue ( <nl> + const VariablesCommand : : VariableValue VariablesCommand : : getVariableValue ( <nl> DebuggerSession * session , <nl> Debugger * debugger , <nl> request_id_t requestId , <nl> const std : : string VariablesCommand : : getVariableValue ( <nl> / / the variable ' s value . <nl> case KindOfUninit : <nl> case KindOfNull : <nl> - return " null " ; <nl> + return VariableValue { " null " } ; <nl> <nl> case KindOfBoolean : <nl> - return variable . toBooleanVal ( ) ? " true " : " false " ; <nl> + return VariableValue { variable . toBooleanVal ( ) ? " true " : " false " } ; <nl> <nl> case KindOfInt64 : <nl> - return std : : to_string ( variable . toInt64Val ( ) ) ; <nl> + return VariableValue { std : : to_string ( variable . toInt64Val ( ) ) } ; <nl> <nl> case KindOfDouble : { <nl> / / Convert double to string , but remove any trailing 0s after the <nl> const std : : string VariablesCommand : : getVariableValue ( <nl> if ( dblString [ dblString . size ( ) - 1 ] = = ' . ' ) { <nl> dblString + = " 0 " ; <nl> } <nl> - return dblString ; <nl> + return VariableValue { dblString } ; <nl> } <nl> <nl> case KindOfPersistentString : <nl> case KindOfString : <nl> - return variable . toCStrRef ( ) . toCppString ( ) ; <nl> + return VariableValue { variable . toCStrRef ( ) . toCppString ( ) } ; <nl> <nl> case KindOfResource : { <nl> auto res = variable . toResource ( ) ; <nl> const std : : string VariablesCommand : : getVariableValue ( <nl> resourceDesc + = " ' type = ' " ; <nl> resourceDesc + = res - > o_getResourceName ( ) . data ( ) ; <nl> resourceDesc + = " ' " ; <nl> - return resourceDesc ; <nl> + return VariableValue { resourceDesc } ; <nl> } <nl> <nl> case KindOfPersistentVec : <nl> case KindOfVec : <nl> - return format ( " vec [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) ; <nl> + return VariableValue { format ( " vec [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) } ; <nl> case KindOfPersistentArray : <nl> case KindOfArray : { <nl> - return format ( " array [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) ; <nl> + return VariableValue { format ( " array [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) } ; <nl> } <nl> <nl> case KindOfPersistentDict : <nl> case KindOfDict : { <nl> - return format ( " dict [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) ; <nl> + return VariableValue { format ( " dict [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) } ; <nl> } <nl> <nl> case KindOfPersistentKeyset : <nl> case KindOfKeyset : { <nl> - return format ( " keyset [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) ; <nl> + return VariableValue { format ( " keyset [ { } ] " , variable . toArray ( ) . size ( ) ) . str ( ) } ; <nl> } <nl> <nl> case KindOfRef : <nl> / / Note : PHP references are not supported in Hack . <nl> - return " reference " ; <nl> + return VariableValue { " reference " } ; <nl> <nl> case KindOfObject : <nl> return getObjectSummary ( session , debugger , requestId , variable . toCObjRef ( ) ) ; <nl> <nl> default : <nl> - return " Unexpected variable type " ; <nl> + return VariableValue { " Unexpected variable type " } ; <nl> } <nl> } <nl> <nl> - const std : : string VariablesCommand : : getObjectSummary ( <nl> + const VariablesCommand : : VariableValue VariablesCommand : : getObjectSummary ( <nl> DebuggerSession * session , <nl> Debugger * debugger , <nl> request_id_t threadId , <nl> const std : : string VariablesCommand : : getObjectSummary ( <nl> executor . execute ( ) ; <nl> <nl> if ( executor . m_debugDisplay . isString ( ) ) { <nl> - return executor . m_debugDisplay . toCStrRef ( ) . toCppString ( ) ; <nl> + return VariableValue { <nl> + executor . m_debugDisplay . toCStrRef ( ) . toCppString ( ) , <nl> + true <nl> + } ; <nl> } <nl> <nl> - return obj - > getClassName ( ) . c_str ( ) ; <nl> + return VariableValue { obj - > getClassName ( ) . c_str ( ) } ; <nl> } <nl> <nl> int VariablesCommand : : addComplexChildren ( <nl> mmm a / hphp / test / slow / ext_vsdebug / context . php <nl> ppp b / hphp / test / slow / ext_vsdebug / context . php <nl> <nl> array ( <nl> " path " = > $ path , <nl> " breakpoints " = > [ <nl> - array ( " line " = > 24 , " calibratedLine " = > 24 , " condition " = > " " ) , <nl> - array ( " line " = > 25 , " calibratedLine " = > 25 , " condition " = > " " ) , <nl> - array ( " line " = > 27 , " calibratedLine " = > 28 , " condition " = > " " ) , <nl> - array ( " line " = > 32 , " calibratedLine " = > 32 , " condition " = > " " ) , <nl> + array ( " line " = > 20 , " calibratedLine " = > 20 , " condition " = > " " ) , <nl> + array ( " line " = > 21 , " calibratedLine " = > 21 , " condition " = > " " ) , <nl> + array ( " line " = > 23 , " calibratedLine " = > 24 , " condition " = > " " ) , <nl> + array ( " line " = > 28 , " calibratedLine " = > 28 , " condition " = > " " ) , <nl> ] ) <nl> ] ; <nl> <nl> <nl> array ( <nl> " source " = > array ( " path " = > $ path , " name " = > $ path ) , <nl> " id " = > 1 , <nl> - " line " = > 24 , <nl> + " line " = > 20 , <nl> " name " = > " innerFunc " <nl> ) , <nl> array ( <nl> " source " = > array ( " path " = > $ path , " name " = > $ path ) , <nl> " id " = > 2 , <nl> - " line " = > 35 , <nl> + " line " = > 31 , <nl> " name " = > " { main } " <nl> ) <nl> ] <nl> <nl> array ( <nl> " type " = > " B " , <nl> " name " = > " \ $ bObj " , <nl> - " value " = > " class B " , <nl> + " value " = > " B " , <nl> ) , <nl> array ( <nl> " type " = > " array " , <nl> <nl> array ( <nl> " type " = > " B " , <nl> " name " = > " 0 " , <nl> - " value " = > " class B " , <nl> + " value " = > " B " , <nl> " variablesReference " = > 14 <nl> ) , <nl> array ( <nl> " type " = > " B " , <nl> " name " = > " 1 " , <nl> - " value " = > " class B " , <nl> + " value " = > " B " , <nl> " variablesReference " = > 14 <nl> ) <nl> ] <nl> mmm a / hphp / test / slow / ext_vsdebug / context . php . test <nl> ppp b / hphp / test / slow / ext_vsdebug / context . php . test <nl> class B extends A { <nl> protected int $ b = 2 ; <nl> public int $ c = 3 ; <nl> const HELLOB = " hello1 " ; <nl> - <nl> - public function __toDebugDisplay ( ) : string { <nl> - return " class B " ; <nl> - } <nl> } <nl> <nl> function innerFunc ( ) { <nl> new file mode 100644 <nl> index 00000000000 . . 154a5e1c021 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / ext_vsdebug / todebugdisplay . php <nl> <nl> + < ? hh <nl> + require ( __DIR__ . ' / common . inc ' ) ; <nl> + <nl> + $ path = __FILE__ . " . test " ; <nl> + $ breakpoints = [ <nl> + array ( <nl> + " path " = > $ path , <nl> + " breakpoints " = > [ <nl> + array ( " line " = > 14 , " calibratedLine " = > 14 , " condition " = > " " ) , <nl> + ] ) <nl> + ] ; <nl> + <nl> + $ testProcess = vsDebugLaunch ( __FILE__ . " . test " , true , $ breakpoints ) ; <nl> + <nl> + / / Verify we hit breakpoint 1 . <nl> + verifyBpHit ( $ breakpoints [ 0 ] { ' path ' } , $ breakpoints [ 0 ] { ' breakpoints ' } [ 0 ] ) ; <nl> + <nl> + / / Check thread stacks . <nl> + $ seq = sendVsCommand ( array ( <nl> + " command " = > " stackTrace " , <nl> + " type " = > " request " , <nl> + " arguments " = > array ( <nl> + " threadId " = > 1 <nl> + ) <nl> + ) ) ; <nl> + <nl> + $ msg = json_decode ( getNextVsDebugMessage ( ) , true ) ; <nl> + checkObjEqualRecursively ( $ msg , array ( <nl> + " type " = > " response " , <nl> + " command " = > " stackTrace " , <nl> + " request_seq " = > $ seq , <nl> + " success " = > true , <nl> + " body " = > array ( <nl> + " totalFrames " = > 2 , <nl> + " stackFrames " = > [ <nl> + array ( <nl> + " source " = > array ( " path " = > $ path , " name " = > $ path ) , <nl> + " id " = > 1 , <nl> + " line " = > 14 , <nl> + " name " = > " innerFunc " <nl> + ) , <nl> + array ( <nl> + " source " = > array ( " path " = > $ path , " name " = > $ path ) , <nl> + " id " = > 2 , <nl> + " line " = > 17 , <nl> + " name " = > " { main } " <nl> + ) <nl> + ] <nl> + ) <nl> + ) <nl> + ) ; <nl> + <nl> + / / Check threads . <nl> + $ seq = sendVsCommand ( array ( <nl> + " command " = > " threads " , <nl> + " type " = > " request " ) ) ; <nl> + $ msg = json_decode ( getNextVsDebugMessage ( ) , true ) ; <nl> + checkObjEqualRecursively ( $ msg , array ( <nl> + " type " = > " response " , <nl> + " command " = > " threads " , <nl> + " request_seq " = > $ seq , <nl> + " success " = > true , <nl> + " body " = > [ <nl> + " threads " = > [ array ( " name " = > " Request 1 " , " id " = > 1 ) ] <nl> + ] <nl> + ) ) ; <nl> + <nl> + / / Get scopes . <nl> + $ seq = sendVsCommand ( array ( <nl> + " command " = > " scopes " , <nl> + " type " = > " request " , <nl> + " arguments " = > array ( " frameId " = > 1 ) ) ) ; <nl> + $ msg = json_decode ( getNextVsDebugMessage ( ) , true ) ; <nl> + <nl> + checkObjEqualRecursively ( $ msg , array ( <nl> + " type " = > " response " , <nl> + " command " = > " scopes " , <nl> + " request_seq " = > $ seq , <nl> + " success " = > true , <nl> + " body " = > [ <nl> + " scopes " = > [ <nl> + array ( <nl> + " namedVariables " = > 1 , <nl> + " name " = > " Locals " , <nl> + ) , <nl> + array ( <nl> + " namedVariables " = > 9 , <nl> + " name " = > " Superglobals " , <nl> + ) , <nl> + array ( <nl> + " namedVariables " = > 2 , <nl> + " name " = > " Constants " , <nl> + ) <nl> + ] ] <nl> + ) ) ; <nl> + <nl> + / / Get locals , only $ a should be visible right here . <nl> + $ seq = sendVsCommand ( array ( <nl> + " command " = > " variables " , <nl> + " type " = > " request " , <nl> + " arguments " = > array ( " variablesReference " = > 3 ) ) ) ; <nl> + $ msg = json_decode ( getNextVsDebugMessage ( ) , true ) ; <nl> + <nl> + if ( isset ( $ msg [ ' body ' ] [ ' variables ' ] [ 0 ] [ ' variablesReference ' ] ) ) { <nl> + throw new ErrorException ( ' A class with a __toDebugDisplay method should not return variablesReference ' ) ; <nl> + } <nl> + <nl> + checkObjEqualRecursively ( $ msg , array ( <nl> + " type " = > " response " , <nl> + " command " = > " variables " , <nl> + " request_seq " = > $ seq , <nl> + " success " = > true , <nl> + " body " = > [ <nl> + " variables " = > [ <nl> + array ( <nl> + " type " = > " A " , <nl> + " name " = > " \ $ a " , <nl> + " value " = > " A ( 42 ) " , <nl> + ) , <nl> + ] ] <nl> + ) ) ; <nl> + <nl> + resumeTarget ( ) ; <nl> + <nl> + checkForOutput ( $ testProcess , " lol \ n " , " stdout " ) ; <nl> + checkForOutput ( $ testProcess , " hello world 2 \ n " , " stdout " ) ; <nl> + vsDebugCleanup ( $ testProcess ) ; <nl> + <nl> + echo " OK ! \ n " ; <nl> new file mode 100644 <nl> index 00000000000 . . d64066171aa <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / ext_vsdebug / todebugdisplay . php . expect <nl> @ @ - 0 , 0 + 1 @ @ <nl> + OK ! <nl> new file mode 100644 <nl> index 00000000000 . . 6320bc07a68 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / ext_vsdebug / todebugdisplay . php . test <nl> <nl> + < ? hh <nl> + <nl> + class A { <nl> + public int $ a = 42 ; <nl> + <nl> + public function __toDebugDisplay ( ) : string { <nl> + return " A ( { $ this - > a } ) " ; <nl> + } <nl> + } <nl> + <nl> + function innerFunc ( ) { <nl> + $ a = new A ( ) ; <nl> + <nl> + echo " lol \ n " ; <nl> + } <nl> + <nl> + innerFunc ( ) ; <nl> + echo " hello world 2 \ n " ; <nl>
elide children if there is a __toDebugDisplay value
facebook/hhvm
9cf58a488c14f7c8fa44295dfee521fbf718c1bc
2018-12-08T16:06:05Z
mmm a / src / feedback - vector . cc <nl> ppp b / src / feedback - vector . cc <nl> Map FeedbackNexus : : GetFirstMap ( ) const { <nl> return Map ( ) ; <nl> } <nl> <nl> - InlineCacheState FeedbackNexus : : StateFromFeedback ( ) const { <nl> + InlineCacheState FeedbackNexus : : ic_state ( ) const { <nl> Isolate * isolate = GetIsolate ( ) ; <nl> MaybeObject feedback = GetFeedback ( ) ; <nl> <nl> mmm a / src / feedback - vector . h <nl> ppp b / src / feedback - vector . h <nl> class FeedbackNexus final { <nl> return vector ( ) - > GetLanguageMode ( slot ( ) ) ; <nl> } <nl> <nl> - InlineCacheState ic_state ( ) const { return StateFromFeedback ( ) ; } <nl> - bool IsUninitialized ( ) const { return StateFromFeedback ( ) = = UNINITIALIZED ; } <nl> - bool IsMegamorphic ( ) const { return StateFromFeedback ( ) = = MEGAMORPHIC ; } <nl> - bool IsGeneric ( ) const { return StateFromFeedback ( ) = = GENERIC ; } <nl> + InlineCacheState ic_state ( ) const ; <nl> + bool IsUninitialized ( ) const { return ic_state ( ) = = UNINITIALIZED ; } <nl> + bool IsMegamorphic ( ) const { return ic_state ( ) = = MEGAMORPHIC ; } <nl> + bool IsGeneric ( ) const { return ic_state ( ) = = GENERIC ; } <nl> <nl> void Print ( std : : ostream & os ) ; / / NOLINT <nl> <nl> / / For map - based ICs ( load , keyed - load , store , keyed - store ) . <nl> Map GetFirstMap ( ) const ; <nl> <nl> - InlineCacheState StateFromFeedback ( ) const ; <nl> int ExtractMaps ( MapHandles * maps ) const ; <nl> MaybeObjectHandle FindHandlerForMap ( Handle < Map > map ) const ; <nl> bool FindHandlers ( MaybeObjectHandles * code_list , int length = - 1 ) const ; <nl> <nl> bool IsCleared ( ) const { <nl> - InlineCacheState state = StateFromFeedback ( ) ; <nl> + InlineCacheState state = ic_state ( ) ; <nl> return ! FLAG_use_ic | | state = = UNINITIALIZED | | state = = PREMONOMORPHIC ; <nl> } <nl> <nl> mmm a / src / ic / ic . cc <nl> ppp b / src / ic / ic . cc <nl> const char * GetModifier ( KeyedAccessStoreMode mode ) { <nl> void IC : : TraceIC ( const char * type , Handle < Object > name ) { <nl> if ( FLAG_ic_stats ) { <nl> if ( AddressIsDeoptimizedCode ( ) ) return ; <nl> - State new_state = nexus ( ) - > StateFromFeedback ( ) ; <nl> + State new_state = nexus ( ) - > ic_state ( ) ; <nl> TraceIC ( type , name , state ( ) , new_state ) ; <nl> } <nl> } <nl> IC : : IC ( Isolate * isolate , Handle < FeedbackVector > vector , FeedbackSlot slot , <nl> } <nl> pc_address_ = StackFrame : : ResolveReturnAddressLocation ( pc_address ) ; <nl> DCHECK_IMPLIES ( ! vector . is_null ( ) , kind_ = = nexus_ . kind ( ) ) ; <nl> - state_ = ( vector . is_null ( ) ) ? NO_FEEDBACK : nexus_ . StateFromFeedback ( ) ; <nl> + state_ = ( vector . is_null ( ) ) ? NO_FEEDBACK : nexus_ . ic_state ( ) ; <nl> old_state_ = state_ ; <nl> } <nl> <nl> mmm a / src / objects - printer . cc <nl> ppp b / src / objects - printer . cc <nl> void FeedbackNexus : : Print ( std : : ostream & os ) { / / NOLINT <nl> case FeedbackSlotKind : : kStoreKeyedStrict : <nl> case FeedbackSlotKind : : kStoreInArrayLiteral : <nl> case FeedbackSlotKind : : kCloneObject : { <nl> - os < < InlineCacheState2String ( StateFromFeedback ( ) ) ; <nl> + os < < InlineCacheState2String ( ic_state ( ) ) ; <nl> break ; <nl> } <nl> case FeedbackSlotKind : : kBinaryOp : { <nl> mmm a / test / cctest / heap / test - heap . cc <nl> ppp b / test / cctest / heap / test - heap . cc <nl> static void CheckVectorIC ( Handle < JSFunction > f , int slot_index , <nl> FeedbackVectorHelper helper ( vector ) ; <nl> FeedbackSlot slot = helper . slot ( slot_index ) ; <nl> FeedbackNexus nexus ( vector , slot ) ; <nl> - CHECK ( nexus . StateFromFeedback ( ) = = desired_state ) ; <nl> + CHECK ( nexus . ic_state ( ) = = desired_state ) ; <nl> } <nl> <nl> TEST ( IncrementalMarkingPreservesMonomorphicConstructor ) { <nl> void CheckIC ( Handle < JSFunction > function , int slot_index , <nl> FeedbackVector vector = function - > feedback_vector ( ) ; <nl> FeedbackSlot slot ( slot_index ) ; <nl> FeedbackNexus nexus ( vector , slot ) ; <nl> - CHECK_EQ ( nexus . StateFromFeedback ( ) , state ) ; <nl> + CHECK_EQ ( nexus . ic_state ( ) , state ) ; <nl> } <nl> <nl> TEST ( MonomorphicStaysMonomorphicAfterGC ) { <nl> mmm a / test / cctest / test - api . cc <nl> ppp b / test / cctest / test - api . cc <nl> THREADED_TEST ( ShadowObjectAndDataProperty ) { <nl> i : : FeedbackSlot slot = i : : FeedbackVector : : ToSlot ( 0 ) ; <nl> i : : FeedbackNexus nexus ( foo - > feedback_vector ( ) , slot ) ; <nl> CHECK_EQ ( i : : FeedbackSlotKind : : kStoreGlobalSloppy , nexus . kind ( ) ) ; <nl> - CHECK_EQ ( i : : PREMONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( i : : PREMONOMORPHIC , nexus . ic_state ( ) ) ; <nl> CompileRun ( " foo ( 1 ) " ) ; <nl> - CHECK_EQ ( i : : MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( i : : MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> / / We go a bit further , checking that the form of monomorphism is <nl> / / a PropertyCell in the vector . This is because we want to make sure <nl> / / we didn ' t settle for a " poor man ' s monomorphism , " such as a <nl> THREADED_TEST ( ShadowObjectAndDataPropertyTurbo ) { <nl> i : : FeedbackSlot slot = i : : FeedbackVector : : ToSlot ( 0 ) ; <nl> i : : FeedbackNexus nexus ( foo - > feedback_vector ( ) , slot ) ; <nl> CHECK_EQ ( i : : FeedbackSlotKind : : kStoreGlobalSloppy , nexus . kind ( ) ) ; <nl> - CHECK_EQ ( i : : PREMONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( i : : PREMONOMORPHIC , nexus . ic_state ( ) ) ; <nl> CompileRun ( " % OptimizeFunctionOnNextCall ( foo ) ; foo ( 1 ) " ) ; <nl> - CHECK_EQ ( i : : MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( i : : MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> i : : HeapObject heap_object ; <nl> CHECK ( nexus . GetFeedback ( ) . GetHeapObject ( & heap_object ) ) ; <nl> CHECK ( heap_object - > IsPropertyCell ( ) ) ; <nl> mmm a / test / cctest / test - feedback - vector . cc <nl> ppp b / test / cctest / test - feedback - vector . cc <nl> TEST ( VectorCallICStates ) { <nl> Handle < FeedbackVector > ( f - > feedback_vector ( ) , isolate ) ; <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CompileRun ( " f ( function ( ) { return 16 ; } ) " ) ; <nl> - CHECK_EQ ( GENERIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( GENERIC , nexus . ic_state ( ) ) ; <nl> <nl> / / After a collection , state should remain GENERIC . <nl> CcTest : : CollectAllGarbage ( ) ; <nl> - CHECK_EQ ( GENERIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( GENERIC , nexus . ic_state ( ) ) ; <nl> } <nl> <nl> TEST ( VectorCallFeedback ) { <nl> TEST ( VectorCallFeedback ) { <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> HeapObject heap_object ; <nl> CHECK ( nexus . GetFeedback ( ) - > GetHeapObjectIfWeak ( & heap_object ) ) ; <nl> CHECK_EQ ( * foo , heap_object ) ; <nl> <nl> CcTest : : CollectAllGarbage ( ) ; <nl> / / It should stay monomorphic even after a GC . <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> } <nl> <nl> TEST ( VectorCallFeedbackForArray ) { <nl> TEST ( VectorCallFeedbackForArray ) { <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> HeapObject heap_object ; <nl> CHECK ( nexus . GetFeedback ( ) - > GetHeapObjectIfWeak ( & heap_object ) ) ; <nl> CHECK_EQ ( * isolate - > array_function ( ) , heap_object ) ; <nl> <nl> CcTest : : CollectAllGarbage ( ) ; <nl> / / It should stay monomorphic even after a GC . <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> } <nl> <nl> size_t GetFeedbackVectorLength ( Isolate * isolate , const char * src , <nl> TEST ( VectorCallCounts ) { <nl> Handle < FeedbackVector > ( f - > feedback_vector ( ) , isolate ) ; <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CompileRun ( " f ( foo ) ; f ( foo ) ; " ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> CHECK_EQ ( 3 , nexus . GetCallCount ( ) ) ; <nl> <nl> / / Send the IC megamorphic , but we should still have incrementing counts . <nl> CompileRun ( " f ( function ( ) { return 12 ; } ) ; " ) ; <nl> - CHECK_EQ ( GENERIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( GENERIC , nexus . ic_state ( ) ) ; <nl> CHECK_EQ ( 4 , nexus . GetCallCount ( ) ) ; <nl> } <nl> <nl> TEST ( VectorConstructCounts ) { <nl> <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CHECK ( feedback_vector - > Get ( slot ) - > IsWeak ( ) ) ; <nl> <nl> CompileRun ( " f ( Foo ) ; f ( Foo ) ; " ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> CHECK_EQ ( 3 , nexus . GetCallCount ( ) ) ; <nl> <nl> / / Send the IC megamorphic , but we should still have incrementing counts . <nl> CompileRun ( " f ( function ( ) { } ) ; " ) ; <nl> - CHECK_EQ ( GENERIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( GENERIC , nexus . ic_state ( ) ) ; <nl> CHECK_EQ ( 4 , nexus . GetCallCount ( ) ) ; <nl> } <nl> <nl> TEST ( VectorLoadICStates ) { <nl> Handle < FeedbackVector > ( f - > feedback_vector ( ) , isolate ) ; <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> - CHECK_EQ ( PREMONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( PREMONOMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CompileRun ( " f ( o ) " ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> / / Verify that the monomorphic map is the one we expect . <nl> v8 : : MaybeLocal < v8 : : Value > v8_o = <nl> CcTest : : global ( ) - > Get ( context . local ( ) , v8_str ( " o " ) ) ; <nl> TEST ( VectorLoadICStates ) { <nl> <nl> / / Now go polymorphic . <nl> CompileRun ( " f ( { blarg : 3 , foo : 2 } ) " ) ; <nl> - CHECK_EQ ( POLYMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( POLYMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CompileRun ( <nl> " delete o . foo ; " <nl> " f ( o ) " ) ; <nl> - CHECK_EQ ( POLYMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( POLYMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CompileRun ( " f ( { blarg : 3 , torino : 10 , foo : 2 } ) " ) ; <nl> - CHECK_EQ ( POLYMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( POLYMORPHIC , nexus . ic_state ( ) ) ; <nl> MapHandles maps ; <nl> nexus . ExtractMaps ( & maps ) ; <nl> CHECK_EQ ( 4 , maps . size ( ) ) ; <nl> <nl> / / Finally driven megamorphic . <nl> CompileRun ( " f ( { blarg : 3 , gran : 3 , torino : 10 , foo : 2 } ) " ) ; <nl> - CHECK_EQ ( MEGAMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MEGAMORPHIC , nexus . ic_state ( ) ) ; <nl> CHECK ( nexus . GetFirstMap ( ) . is_null ( ) ) ; <nl> <nl> / / After a collection , state should not be reset to PREMONOMORPHIC . <nl> CcTest : : CollectAllGarbage ( ) ; <nl> - CHECK_EQ ( MEGAMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MEGAMORPHIC , nexus . ic_state ( ) ) ; <nl> } <nl> <nl> TEST ( VectorLoadGlobalICSlotSharing ) { <nl> TEST ( VectorLoadGlobalICSlotSharing ) { <nl> CHECK_SLOT_KIND ( helper , 1 , FeedbackSlotKind : : kLoadGlobalInsideTypeof ) ; <nl> FeedbackSlot slot1 = helper . slot ( 0 ) ; <nl> FeedbackSlot slot2 = helper . slot ( 1 ) ; <nl> - CHECK_EQ ( MONOMORPHIC , <nl> - FeedbackNexus ( feedback_vector , slot1 ) . StateFromFeedback ( ) ) ; <nl> - CHECK_EQ ( MONOMORPHIC , <nl> - FeedbackNexus ( feedback_vector , slot2 ) . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , FeedbackNexus ( feedback_vector , slot1 ) . ic_state ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , FeedbackNexus ( feedback_vector , slot2 ) . ic_state ( ) ) ; <nl> } <nl> <nl> <nl> TEST ( VectorLoadICOnSmi ) { <nl> Handle < FeedbackVector > ( f - > feedback_vector ( ) , isolate ) ; <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> - CHECK_EQ ( PREMONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( PREMONOMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> CompileRun ( " f ( 34 ) " ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> / / Verify that the monomorphic map is the one we expect . <nl> Map number_map = ReadOnlyRoots ( heap ) . heap_number_map ( ) ; <nl> CHECK_EQ ( number_map , nexus . GetFirstMap ( ) ) ; <nl> <nl> / / Now go polymorphic on o . <nl> CompileRun ( " f ( o ) " ) ; <nl> - CHECK_EQ ( POLYMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( POLYMORPHIC , nexus . ic_state ( ) ) ; <nl> <nl> MapHandles maps ; <nl> nexus . ExtractMaps ( & maps ) ; <nl> TEST ( VectorLoadICOnSmi ) { <nl> <nl> / / The degree of polymorphism doesn ' t change . <nl> CompileRun ( " f ( 100 ) " ) ; <nl> - CHECK_EQ ( POLYMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( POLYMORPHIC , nexus . ic_state ( ) ) ; <nl> MapHandles maps2 ; <nl> nexus . ExtractMaps ( & maps2 ) ; <nl> CHECK_EQ ( 2 , maps2 . size ( ) ) ; <nl> TEST ( VectorStoreICBasic ) { <nl> CHECK_EQ ( 1 , helper . slot_count ( ) ) ; <nl> FeedbackSlot slot ( 0 ) ; <nl> FeedbackNexus nexus ( feedback_vector , slot ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> } <nl> <nl> TEST ( StoreOwnIC ) { <nl> TEST ( StoreOwnIC ) { <nl> CHECK_SLOT_KIND ( helper , 0 , FeedbackSlotKind : : kLiteral ) ; <nl> CHECK_SLOT_KIND ( helper , 1 , FeedbackSlotKind : : kStoreOwnNamed ) ; <nl> FeedbackNexus nexus ( feedback_vector , helper . slot ( 1 ) ) ; <nl> - CHECK_EQ ( MONOMORPHIC , nexus . StateFromFeedback ( ) ) ; <nl> + CHECK_EQ ( MONOMORPHIC , nexus . ic_state ( ) ) ; <nl> } <nl> <nl> } / / namespace <nl>
[ ic ] Remove FeedbackNexus : : StateFromFeedback ( ) in favor of ic_state ( )
v8/v8
cbee0b9cf1bcd1feaa1fc4f75ca3f6338a6c36c2
2019-02-13T14:52:48Z
mmm a / . travis . yml <nl> ppp b / . travis . yml <nl> script : <nl> - mkdir build & & cd build <nl> - . . / configure $ BITCOIN_CONFIG_ALL $ BITCOIN_CONFIG | | ( cat config . log & & false ) <nl> - make $ MAKEJOBS $ GOAL | | ( echo " Build failure . Verbose build follows . " & & make $ GOAL V = 1 ; false ) <nl> + - make distdir <nl> - export LD_LIBRARY_PATH = $ TRAVIS_BUILD_DIR / depends / $ HOST / lib <nl> - if [ " $ RUN_TESTS " = " true " ] ; then make $ MAKEJOBS check VERBOSE = 1 ; fi <nl> - if [ " $ RUN_TESTS " = " true " ] ; then qa / pull - tester / rpc - tests . py - - coverage ; fi <nl>
travis : make distdir
bitcoin/bitcoin
fad632ed7a266bcd7a4f65bf253af9e4b5c70d2f
2016-12-20T21:54:13Z
mmm a / lib / SIL / Verifier / CMakeLists . txt <nl> ppp b / lib / SIL / Verifier / CMakeLists . txt <nl> <nl> target_sources ( swiftSIL PRIVATE <nl> - LoadBorrowInvalidationChecker . cpp <nl> + LoadBorrowImmutabilityChecker . cpp <nl> LinearLifetimeChecker . cpp <nl> MemoryLifetime . cpp <nl> SILOwnershipVerifier . cpp <nl> similarity index 90 % <nl> rename from lib / SIL / Verifier / LoadBorrowInvalidationChecker . cpp <nl> rename to lib / SIL / Verifier / LoadBorrowImmutabilityChecker . cpp <nl> mmm a / lib / SIL / Verifier / LoadBorrowInvalidationChecker . cpp <nl> ppp b / lib / SIL / Verifier / LoadBorrowImmutabilityChecker . cpp <nl> <nl> - / / = = = mmm LoadBorrowInvalidationChecker . cpp mmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - = = = / / <nl> + / / = = = mmm LoadBorrowImmutabilityChecker . cpp mmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - = = = / / <nl> / / <nl> / / This source file is part of the Swift . org open source project <nl> / / <nl> <nl> / / / \ file <nl> / / / <nl> / / / This file defines a verifier that exhaustively validates that there aren ' t <nl> - / / / any load_borrows in a SIL module that are invalidated by a write to their <nl> + / / / any load_borrows in a SIL module that have in - scope writes to their <nl> / / / underlying storage . <nl> / / / <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - # define DEBUG_TYPE " sil - load - borrow - invalidation - checker " <nl> + # define DEBUG_TYPE " sil - load - borrow - immutability - checker " <nl> # include " VerifierPrivate . h " <nl> # include " swift / Basic / Debug . h " <nl> # include " swift / Basic / LLVM . h " <nl> using namespace swift : : silverifier ; <nl> / / Write Gatherer <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - static bool constructValuesForBuiltinKey ( <nl> - Operand * op , BuiltinInst * bi , <nl> - SmallVectorImpl < Operand * > & wellBehavedWriteAccumulator ) { <nl> + / / Helper for gatherAddressWrites . <nl> + static bool gatherBuiltinWrites ( Operand * op , BuiltinInst * bi , <nl> + SmallVectorImpl < Operand * > & writeAccumulator ) { <nl> / / If we definitely do not write to memory , just return true early . <nl> if ( ! bi - > mayWriteToMemory ( ) ) { <nl> return true ; <nl> static bool constructValuesForBuiltinKey ( <nl> <nl> / / TODO : Should we make this an exhaustive list so that when new builtins are <nl> / / added , they need to actually update this code ? <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> return true ; <nl> } <nl> <nl> / / / Returns true if we were able to ascertain that either the initialValue has <nl> / / / no write uses or all of the write uses were writes that we could understand . <nl> static bool <nl> - constructValuesForKey ( SILValue initialValue , <nl> - SmallVectorImpl < Operand * > & wellBehavedWriteAccumulator ) { <nl> - SmallVector < Operand * , 8 > worklist ( initialValue - > getUses ( ) ) ; <nl> + gatherAddressWrites ( SILValue address , <nl> + SmallVectorImpl < Operand * > & writeAccumulator ) { <nl> + SmallVector < Operand * , 8 > worklist ( address - > getUses ( ) ) ; <nl> <nl> while ( ! worklist . empty ( ) ) { <nl> auto * op = worklist . pop_back_val ( ) ; <nl> constructValuesForKey ( SILValue initialValue , <nl> if ( auto * oeai = dyn_cast < OpenExistentialAddrInst > ( user ) ) { <nl> / / Mutable access ! <nl> if ( oeai - > getAccessKind ( ) ! = OpenedExistentialAccess : : Immutable ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> } <nl> <nl> / / Otherwise , look through it and continue . <nl> constructValuesForKey ( SILValue initialValue , <nl> } <nl> <nl> / / Add any destroy_addrs to the resultAccumulator . <nl> - if ( isa < DestroyAddrInst > ( user ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + if ( isa < DestroyAddrInst > ( user ) | | isa < DestroyValueInst > ( user ) ) { <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> <nl> if ( auto * mdi = dyn_cast < MarkDependenceInst > ( user ) ) { <nl> if ( mdi - > getValue ( ) = = op - > get ( ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> } <nl> continue ; <nl> } <nl> <nl> if ( isa < InjectEnumAddrInst > ( user ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> if ( auto * ccbi = dyn_cast < CheckedCastAddrBranchInst > ( user ) ) { <nl> if ( ccbi - > getConsumptionKind ( ) = = CastConsumptionKind : : TakeAlways | | <nl> ccbi - > getConsumptionKind ( ) = = CastConsumptionKind : : TakeOnSuccess ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> } <nl> constructValuesForKey ( SILValue initialValue , <nl> if ( auto * bai = dyn_cast < BeginAccessInst > ( user ) ) { <nl> / / If we do not have a read , mark this as a write . <nl> if ( bai - > getAccessKind ( ) ! = SILAccessKind : : Read ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> } <nl> <nl> / / Otherwise , add the users to the worklist and continue . <nl> constructValuesForKey ( SILValue initialValue , <nl> / / If we have a load , we just need to mark the load [ take ] as a write . <nl> if ( auto * li = dyn_cast < LoadInst > ( user ) ) { <nl> if ( li - > getOwnershipQualifier ( ) = = LoadOwnershipQualifier : : Take ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> } <nl> continue ; <nl> } <nl> constructValuesForKey ( SILValue initialValue , <nl> # define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE ( Name , name , NAME ) \ <nl> if ( auto * li = dyn_cast < Load # # Name # # Inst > ( user ) ) { \ <nl> if ( li - > isTake ( ) = = IsTake ) { \ <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; \ <nl> + writeAccumulator . push_back ( op ) ; \ <nl> } \ <nl> continue ; \ <nl> } \ <nl> if ( isa < Store # # Name # # Inst > ( user ) ) { \ <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; \ <nl> + writeAccumulator . push_back ( op ) ; \ <nl> continue ; \ <nl> } <nl> # include " swift / AST / ReferenceStorage . def " <nl> constructValuesForKey ( SILValue initialValue , <nl> / / interprocedural analysis that we do not perform here . <nl> if ( auto fas = FullApplySite : : isa ( user ) ) { <nl> if ( fas . isIndirectResultOperand ( * op ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> } <nl> <nl> if ( argConv . isInoutConvention ( ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> if ( argConv . isOwnedConvention ( ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> } <nl> <nl> if ( auto as = ApplySite : : isa ( user ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> if ( auto * cai = dyn_cast < CopyAddrInst > ( user ) ) { <nl> / / If our value is the destination , this is a write . <nl> if ( cai - > getDest ( ) = = op - > get ( ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> / / Ok , so we are Src by process of elimination . Make sure we are not being <nl> / / taken . <nl> if ( cai - > isTakeOfSrc ( ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> } <nl> <nl> if ( isa < StoreInst > ( user ) | | isa < AssignInst > ( user ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> constructValuesForKey ( SILValue initialValue , <nl> } <nl> <nl> if ( info . isIndirectMutating ( ) | | info . isConsumed ( ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> } <nl> constructValuesForKey ( SILValue initialValue , <nl> <nl> / / unconditional_checked_cast_addr does a take on its input memory . <nl> if ( isa < UnconditionalCheckedCastAddrInst > ( user ) ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> continue ; <nl> } <nl> <nl> if ( auto * ccabi = dyn_cast < CheckedCastAddrBranchInst > ( user ) ) { <nl> if ( ccabi - > getConsumptionKind ( ) ! = CastConsumptionKind : : CopyOnSuccess ) { <nl> - wellBehavedWriteAccumulator . push_back ( op ) ; <nl> + writeAccumulator . push_back ( op ) ; <nl> } <nl> continue ; <nl> } <nl> <nl> if ( auto * bi = dyn_cast < BuiltinInst > ( user ) ) { <nl> - if ( constructValuesForBuiltinKey ( op , bi , wellBehavedWriteAccumulator ) ) { <nl> + if ( gatherBuiltinWrites ( op , bi , writeAccumulator ) ) { <nl> continue ; <nl> } <nl> } <nl> constructValuesForKey ( SILValue initialValue , <nl> } <nl> <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> - / / Load Borrow Never Invalidated Analysis <nl> + / / Load Borrow Immutability Analysis <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - LoadBorrowNeverInvalidatedAnalysis : : LoadBorrowNeverInvalidatedAnalysis ( <nl> + LoadBorrowImmutabilityAnalysis : : LoadBorrowImmutabilityAnalysis ( <nl> DeadEndBlocks & deadEndBlocks ) <nl> - : cache ( constructValuesForKey ) , deadEndBlocks ( deadEndBlocks ) { } <nl> + : cache ( gatherAddressWrites ) , deadEndBlocks ( deadEndBlocks ) { } <nl> <nl> - bool LoadBorrowNeverInvalidatedAnalysis : : <nl> + / / \ p address may be an address , pointer , or box type . <nl> + bool LoadBorrowImmutabilityAnalysis : : <nl> doesAddressHaveWriteThatInvalidatesLoadBorrow ( <nl> LoadBorrowInst * lbi , ArrayRef < Operand * > endBorrowUses , <nl> SILValue address ) { <nl> bool LoadBorrowNeverInvalidatedAnalysis : : <nl> / / Top Level Entrypoint <nl> / / = = = mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - = = = / / <nl> <nl> - bool LoadBorrowNeverInvalidatedAnalysis : : <nl> + bool LoadBorrowImmutabilityAnalysis : : <nl> doesBoxHaveWritesThatInvalidateLoadBorrow ( LoadBorrowInst * lbi , <nl> ArrayRef < Operand * > endBorrowUses , <nl> SILValue originalBox ) { <nl> bool LoadBorrowNeverInvalidatedAnalysis : : <nl> <nl> return false ; <nl> } <nl> - bool LoadBorrowNeverInvalidatedAnalysis : : isInvalidated ( <nl> + bool LoadBorrowImmutabilityAnalysis : : isInvalidated ( <nl> LoadBorrowInst * lbi ) { <nl> <nl> / / FIXME : To be reenabled separately in a follow - on commit . <nl> mmm a / lib / SIL / Verifier / SILVerifier . cpp <nl> ppp b / lib / SIL / Verifier / SILVerifier . cpp <nl> class SILVerifier : public SILVerifierBase < SILVerifier > { <nl> llvm : : DenseMap < const SILInstruction * , unsigned > InstNumbers ; <nl> <nl> DeadEndBlocks DEBlocks ; <nl> - LoadBorrowNeverInvalidatedAnalysis loadBorrowNeverInvalidatedAnalysis ; <nl> + LoadBorrowImmutabilityAnalysis loadBorrowNeverInvalidatedAnalysis ; <nl> bool SingleFunction = true ; <nl> <nl> SILVerifier ( const SILVerifier & ) = delete ; <nl> mmm a / lib / SIL / Verifier / VerifierPrivate . h <nl> ppp b / lib / SIL / Verifier / VerifierPrivate . h <nl> class Operand ; <nl> <nl> namespace silverifier { <nl> <nl> - class LoadBorrowNeverInvalidatedAnalysis { <nl> + class LoadBorrowImmutabilityAnalysis { <nl> SmallMultiMapCache < SILValue , Operand * > cache ; <nl> DeadEndBlocks & deadEndBlocks ; <nl> <nl> public : <nl> - LoadBorrowNeverInvalidatedAnalysis ( DeadEndBlocks & deadEndBlocks ) ; <nl> + LoadBorrowImmutabilityAnalysis ( DeadEndBlocks & deadEndBlocks ) ; <nl> <nl> / / / Returns true if exhaustively lbi is guaranteed to never be invalidated by <nl> / / / local writes . <nl>
LoadBorrowImmutabilityChecker renaming .
apple/swift
4f05d8a857f08b42c0def949fe37c99d4131be49
2020-10-21T20:09:40Z
mmm a / script / release / notes / notes . js <nl> ppp b / script / release / notes / notes . js <nl> <nl> # ! / usr / bin / env node <nl> <nl> + ' use strict ' ; <nl> + <nl> const childProcess = require ( ' child_process ' ) ; <nl> const fs = require ( ' fs ' ) ; <nl> const os = require ( ' os ' ) ; <nl> const CACHE_DIR = path . resolve ( __dirname , ' . cache ' ) ; <nl> const NO_NOTES = ' No notes ' ; <nl> const FOLLOW_REPOS = [ ' electron / electron ' , ' electron / node ' ] ; <nl> <nl> - const breakTypes = new Set ( [ ' breaking - change ' ] ) ; <nl> const docTypes = new Set ( [ ' doc ' , ' docs ' ] ) ; <nl> const featTypes = new Set ( [ ' feat ' , ' feature ' ] ) ; <nl> const fixTypes = new Set ( [ ' fix ' ] ) ; <nl> const otherTypes = new Set ( [ ' spec ' , ' build ' , ' test ' , ' chore ' , ' deps ' , ' refactor ' , ' tools ' , ' vendor ' , ' perf ' , ' style ' , ' ci ' ] ) ; <nl> - const knownTypes = new Set ( [ . . . breakTypes . keys ( ) , . . . docTypes . keys ( ) , . . . featTypes . keys ( ) , . . . fixTypes . keys ( ) , . . . otherTypes . keys ( ) ] ) ; <nl> + const knownTypes = new Set ( [ . . . docTypes . keys ( ) , . . . featTypes . keys ( ) , . . . fixTypes . keys ( ) , . . . otherTypes . keys ( ) ] ) ; <nl> + <nl> + / * * <nl> + * * * <nl> + * * / <nl> + <nl> + / / link to a GitHub item , e . g . an issue or pull request <nl> + class GHKey { <nl> + constructor ( owner , repo , number ) { <nl> + this . owner = owner ; <nl> + this . repo = repo ; <nl> + this . number = number ; <nl> + } <nl> + } <nl> + <nl> + class Commit { <nl> + constructor ( hash , owner , repo ) { <nl> + this . hash = hash ; / / string <nl> + this . owner = owner ; / / string <nl> + this . repo = repo ; / / string <nl> + <nl> + this . body = null ; / / string <nl> + this . isBreakingChange = false ; <nl> + this . issueNumber = null ; / / number <nl> + this . note = null ; / / string <nl> + this . prKeys = new Set ( ) ; / / GHKey <nl> + this . revertHash = null ; / / string <nl> + this . semanticType = null ; / / string <nl> + this . subject = null ; / / string <nl> + } <nl> + } <nl> + <nl> + class Pool { <nl> + constructor ( ) { <nl> + this . commits = [ ] ; / / Array < Commit > <nl> + this . processedHashes = new Set ( ) ; <nl> + this . pulls = { } ; / / GHKey . number = > octokit pull object <nl> + } <nl> + } <nl> + <nl> + / * * <nl> + * * * <nl> + * * / <nl> <nl> const runGit = async ( dir , args ) = > { <nl> const response = await GitProcess . exec ( args , dir ) ; <nl> const getCommonAncestor = async ( dir , point1 , point2 ) = > { <nl> return runGit ( dir , [ ' merge - base ' , point1 , point2 ] ) ; <nl> } ; <nl> <nl> - const setPullRequest = ( commit , owner , repo , number ) = > { <nl> - if ( ! owner | | ! repo | | ! number ) { <nl> - throw new Error ( JSON . stringify ( { owner , repo , number } , null , 2 ) ) ; <nl> - } <nl> - <nl> - if ( ! commit . originalPr ) { <nl> - commit . originalPr = commit . pr ; <nl> - } <nl> - <nl> - commit . pr = { owner , repo , number } ; <nl> - <nl> - if ( ! commit . originalPr ) { <nl> - commit . originalPr = commit . pr ; <nl> - } <nl> - } ; <nl> - <nl> - const getNoteFromClerk = async ( number , owner , repo ) = > { <nl> - const comments = await getComments ( number , owner , repo ) ; <nl> + const getNoteFromClerk = async ( ghKey ) = > { <nl> + const comments = await getComments ( ghKey ) ; <nl> if ( ! comments | | ! comments . data ) return ; <nl> <nl> const CLERK_LOGIN = ' release - clerk [ bot ] ' ; <nl> const getNoteFromBody = body = > { <nl> / * * <nl> * Looks for our project ' s conventions in the commit message : <nl> * <nl> - * ' semantic : some description ' - - sets type , subject <nl> + * ' semantic : some description ' - - sets semanticType , subject <nl> * ' some description ( # 99999 ) ' - - sets subject , pr <nl> * ' Fixes # 3333 ' - - sets issueNumber <nl> * ' Merge pull request # 99999 from $ { branchname } ' - - sets pr <nl> * ' This reverts commit $ { sha } ' - - sets revertHash <nl> - * line starting with ' BREAKING CHANGE ' in body - - sets breakingChange <nl> + * line starting with ' BREAKING CHANGE ' in body - - sets isBreakingChange <nl> * ' Backport of # 99999 ' - - sets pr <nl> * / <nl> - const parseCommitMessage = ( commitMessage , owner , repo , commit = { } ) = > { <nl> + const parseCommitMessage = ( commitMessage , commit ) = > { <nl> + const { owner , repo } = commit ; <nl> + <nl> / / split commitMessage into subject & body <nl> let subject = commitMessage ; <nl> let body = ' ' ; <nl> const parseCommitMessage = ( commitMessage , owner , repo , commit = { } ) = > { <nl> subject = subject . slice ( 0 , pos ) . trim ( ) ; <nl> } <nl> <nl> - if ( ! commit . originalSubject ) { <nl> - commit . originalSubject = subject ; <nl> - } <nl> - <nl> if ( body ) { <nl> commit . body = body ; <nl> <nl> const parseCommitMessage = ( commitMessage , owner , repo , commit = { } ) = > { <nl> / / if the subject ends in ' ( # dddd ) ' , treat it as a pull request id <nl> let match ; <nl> if ( ( match = subject . match ( / ^ ( . * ) \ s \ ( # ( \ d + ) \ ) $ / ) ) ) { <nl> - setPullRequest ( commit , owner , repo , parseInt ( match [ 2 ] ) ) ; <nl> + commit . prKeys . add ( new GHKey ( owner , repo , parseInt ( match [ 2 ] ) ) ) ; <nl> subject = match [ 1 ] ; <nl> } <nl> <nl> / / if the subject begins with ' word : ' , treat it as a semantic commit <nl> if ( ( match = subject . match ( / ^ ( \ w + ) : \ s ( . * ) $ / ) ) ) { <nl> - const type = match [ 1 ] . toLocaleLowerCase ( ) ; <nl> - if ( knownTypes . has ( type ) ) { <nl> - commit . type = type ; <nl> + const semanticType = match [ 1 ] . toLocaleLowerCase ( ) ; <nl> + if ( knownTypes . has ( semanticType ) ) { <nl> + commit . semanticType = semanticType ; <nl> subject = match [ 2 ] ; <nl> } <nl> } <nl> <nl> / / Check for GitHub commit message that indicates a PR <nl> if ( ( match = subject . match ( / ^ Merge pull request # ( \ d + ) from ( . * ) $ / ) ) ) { <nl> - setPullRequest ( commit , owner , repo , parseInt ( match [ 1 ] ) ) ; <nl> - commit . pr . branch = match [ 2 ] . trim ( ) ; <nl> + commit . prKeys . add ( new GHKey ( owner , repo , parseInt ( match [ 1 ] ) ) ) ; <nl> } <nl> <nl> - / / Check for a trop comment that indicates a PR <nl> - if ( ( match = commitMessage . match ( / \ bBackport of # ( \ d + ) \ b / ) ) ) { <nl> - setPullRequest ( commit , owner , repo , parseInt ( match [ 1 ] ) ) ; <nl> + / / Check for a comment that indicates a PR <nl> + const backportPattern = / ( ? : ^ | \ n ) ( ? : manual | manually ) ? backport . * ( ? : # ( \ d + ) | \ / pull \ / ( \ d + ) ) / im ; <nl> + if ( ( match = commitMessage . match ( backportPattern ) ) ) { <nl> + / / This might be the first or second capture group depending on if it ' s a link or not . <nl> + const backportNumber = match [ 1 ] ? parseInt ( match [ 1 ] , 10 ) : parseInt ( match [ 2 ] , 10 ) ; <nl> + commit . prKeys . add ( new GHKey ( owner , repo , backportNumber ) ) ; <nl> } <nl> <nl> / / https : / / help . github . com / articles / closing - issues - using - keywords / <nl> - if ( ( match = subject . match ( / \ b ( ? : close | closes | closed | fix | fixes | fixed | resolve | resolves | resolved | for ) \ s # ( \ d + ) \ b / ) ) ) { <nl> + if ( ( match = body . match ( / \ b ( ? : close | closes | closed | fix | fixes | fixed | resolve | resolves | resolved | for ) \ s # ( \ d + ) \ b / i ) ) ) { <nl> commit . issueNumber = parseInt ( match [ 1 ] ) ; <nl> - if ( ! commit . type ) { <nl> - commit . type = ' fix ' ; <nl> - } <nl> - } <nl> - <nl> - / / look for ' fixes ' in markdown ; e . g . ' Fixes [ # 8952 ] ( https : / / github . com / electron / electron / issues / 8952 ) ' <nl> - if ( ! commit . issueNumber & & ( ( match = commitMessage . match ( / Fixes \ [ # ( \ d + ) \ ] \ ( https : \ / \ / github . com \ / ( \ w + ) \ / ( \ w + ) \ / issues \ / ( \ d + ) \ ) / ) ) ) ) { <nl> - commit . issueNumber = parseInt ( match [ 1 ] ) ; <nl> - if ( commit . pr & & commit . pr . number = = = commit . issueNumber ) { <nl> - commit . pr = null ; <nl> - } <nl> - if ( commit . originalPr & & commit . originalPr . number = = = commit . issueNumber ) { <nl> - commit . originalPr = null ; <nl> - } <nl> - if ( ! commit . type ) { <nl> - commit . type = ' fix ' ; <nl> - } <nl> + commit . semanticType = commit . semanticType | | ' fix ' ; <nl> } <nl> <nl> / / https : / / www . conventionalcommits . org / en <nl> const parseCommitMessage = ( commitMessage , owner , repo , commit = { } ) = > { <nl> . split ( / \ r ? \ n / ) / / split into lines <nl> . map ( line = > line . trim ( ) ) <nl> . some ( line = > line . startsWith ( ' BREAKING CHANGE ' ) ) ) { <nl> - commit . type = ' breaking - change ' ; <nl> + commit . isBreakingChange = true ; <nl> } <nl> <nl> / / Check for a reversion commit <nl> const parseCommitMessage = ( commitMessage , owner , repo , commit = { } ) = > { <nl> commit . revertHash = match [ 1 ] ; <nl> } <nl> <nl> - / / Edge case : manual backport where commit has ` owner / repo # pull ` notation <nl> - if ( commitMessage . toLowerCase ( ) . includes ( ' backport ' ) & & <nl> - ( ( match = commitMessage . match ( / \ b ( \ w + ) \ / ( \ w + ) # ( \ d + ) \ b / ) ) ) ) { <nl> - const [ , owner , repo , number ] = match ; <nl> - if ( FOLLOW_REPOS . includes ( ` $ { owner } / $ { repo } ` ) ) { <nl> - setPullRequest ( commit , owner , repo , number ) ; <nl> - } <nl> - } <nl> - <nl> - / / Edge case : manual backport where commit has a link to the backport PR <nl> - if ( commitMessage . includes ( ' ackport ' ) & & <nl> - ( ( match = commitMessage . match ( / https : \ / \ / github \ . com \ / ( \ w + ) \ / ( \ w + ) \ / pull \ / ( \ d + ) / ) ) ) ) { <nl> - const [ , owner , repo , number ] = match ; <nl> - if ( FOLLOW_REPOS . includes ( ` $ { owner } / $ { repo } ` ) ) { <nl> - setPullRequest ( commit , owner , repo , number ) ; <nl> - } <nl> - } <nl> - <nl> - / / Legacy commits : pre - semantic commits <nl> - if ( ! commit . type | | commit . type = = = ' chore ' ) { <nl> - const commitMessageLC = commitMessage . toLocaleLowerCase ( ) ; <nl> - if ( ( match = commitMessageLC . match ( / \ bchore \ ( ( \ w + ) \ ) : / ) ) ) { <nl> - / / example : ' Chore ( docs ) : description ' <nl> - commit . type = knownTypes . has ( match [ 1 ] ) ? match [ 1 ] : ' chore ' ; <nl> - } else if ( commitMessageLC . match ( / \ b ( ? : fix | fixes | fixed ) / ) ) { <nl> - / / example : ' fix a bug ' <nl> - commit . type = ' fix ' ; <nl> - } else if ( commitMessageLC . match ( / \ [ ( ? : docs | doc ) \ ] / ) ) { <nl> - / / example : ' [ docs ] <nl> - commit . type = ' doc ' ; <nl> - } <nl> - } <nl> - <nl> commit . subject = subject . trim ( ) ; <nl> return commit ; <nl> } ; <nl> <nl> + const parsePullText = ( pull , commit ) = > parseCommitMessage ( ` $ { pull . data . title } \ n \ n $ { pull . data . body } ` , commit ) ; <nl> + <nl> const getLocalCommitHashes = async ( dir , ref ) = > { <nl> const args = [ ' log ' , ' - z ' , ' - - format = % H ' , ref ] ; <nl> return ( await runGit ( dir , args ) ) . split ( ' \ 0 ' ) . map ( hash = > hash . trim ( ) ) ; <nl> } ; <nl> <nl> - / * <nl> - * possible properties : <nl> - * breakingChange , email , hash , issueNumber , originalSubject , parentHashes , <nl> - * pr { owner , repo , number , branch } , revertHash , subject , type <nl> - * / <nl> - const getLocalCommitDetails = async ( module , point1 , point2 ) = > { <nl> + / / return an array of Commits <nl> + const getLocalCommits = async ( module , point1 , point2 ) = > { <nl> const { owner , repo , dir } = module ; <nl> <nl> const fieldSep = ' | | ' ; <nl> - const format = [ ' % H ' , ' % P ' , ' % aE ' , ' % B ' ] . join ( fieldSep ) ; <nl> + const format = [ ' % H ' , ' % B ' ] . join ( fieldSep ) ; <nl> const args = [ ' log ' , ' - z ' , ' - - cherry - pick ' , ' - - right - only ' , ' - - first - parent ' , ` - - format = $ { format } ` , ` $ { point1 } . . $ { point2 } ` ] ; <nl> - const commits = ( await runGit ( dir , args ) ) . split ( ' \ 0 ' ) . map ( field = > field . trim ( ) ) ; <nl> - const details = [ ] ; <nl> - for ( const commit of commits ) { <nl> - if ( ! commit ) { <nl> + const logs = ( await runGit ( dir , args ) ) . split ( ' \ 0 ' ) . map ( field = > field . trim ( ) ) ; <nl> + <nl> + const commits = [ ] ; <nl> + for ( const log of logs ) { <nl> + if ( ! log ) { <nl> continue ; <nl> } <nl> - const [ hash , parentHashes , email , commitMessage ] = commit . split ( fieldSep , 4 ) . map ( field = > field . trim ( ) ) ; <nl> - details . push ( parseCommitMessage ( commitMessage , owner , repo , { <nl> - email , <nl> - hash , <nl> - owner , <nl> - repo , <nl> - parentHashes : parentHashes . split ( ) <nl> - } ) ) ; <nl> - } <nl> - return details ; <nl> + const [ hash , message ] = log . split ( fieldSep , 2 ) . map ( field = > field . trim ( ) ) ; <nl> + commits . push ( parseCommitMessage ( message , new Commit ( hash , owner , repo ) ) ) ; <nl> + } <nl> + return commits ; <nl> } ; <nl> <nl> const checkCache = async ( name , operation ) = > { <nl> const checkCache = async ( name , operation ) = > { <nl> if ( fs . existsSync ( filename ) ) { <nl> return JSON . parse ( fs . readFileSync ( filename , ' utf8 ' ) ) ; <nl> } <nl> + process . stdout . write ( ' . ' ) ; <nl> const response = await operation ( ) ; <nl> if ( response ) { <nl> fs . writeFileSync ( filename , JSON . stringify ( response ) ) ; <nl> async function runRetryable ( fn , maxRetries ) { <nl> if ( lastError . status ! = = 404 ) throw lastError ; <nl> } <nl> <nl> - const getPullRequest = async ( number , owner , repo ) = > { <nl> + const getPullRequest = async ( ghKey ) = > { <nl> + const { number , owner , repo } = ghKey ; <nl> const name = ` $ { owner } - $ { repo } - pull - $ { number } ` ; <nl> const retryableFunc = ( ) = > octokit . pulls . get ( { pull_number : number , owner , repo } ) ; <nl> return checkCache ( name , ( ) = > runRetryable ( retryableFunc , MAX_FAIL_COUNT ) ) ; <nl> } ; <nl> <nl> - const getComments = async ( number , owner , repo ) = > { <nl> + const getComments = async ( ghKey ) = > { <nl> + const { number , owner , repo } = ghKey ; <nl> const name = ` $ { owner } - $ { repo } - issue - $ { number } - comments ` ; <nl> const retryableFunc = ( ) = > octokit . issues . listComments ( { issue_number : number , owner , repo , per_page : 100 } ) ; <nl> return checkCache ( name , ( ) = > runRetryable ( retryableFunc , MAX_FAIL_COUNT ) ) ; <nl> const getComments = async ( number , owner , repo ) = > { <nl> <nl> const addRepoToPool = async ( pool , repo , from , to ) = > { <nl> const commonAncestor = await getCommonAncestor ( repo . dir , from , to ) ; <nl> + <nl> + / / add the commits <nl> const oldHashes = await getLocalCommitHashes ( repo . dir , from ) ; <nl> oldHashes . forEach ( hash = > { pool . processedHashes . add ( hash ) ; } ) ; <nl> - const commits = await getLocalCommitDetails ( repo , commonAncestor , to ) ; <nl> + const commits = await getLocalCommits ( repo , commonAncestor , to ) ; <nl> pool . commits . push ( . . . commits ) ; <nl> + <nl> + / / add the pulls <nl> + for ( const commit of commits ) { <nl> + let prKey ; <nl> + for ( prKey of commit . prKeys . values ( ) ) { <nl> + const pull = await getPullRequest ( prKey ) ; <nl> + if ( ! pull | | ! pull . data ) break ; / / couldn ' t get it <nl> + if ( pool . pulls [ prKey . number ] ) break ; / / already have it <nl> + pool . pulls [ prKey . number ] = pull ; <nl> + parsePullText ( pull , commit ) ; <nl> + } <nl> + } <nl> } ; <nl> <nl> / * * * <nl> const shouldIncludeMultibranchChanges = ( version ) = > { <nl> return show ; <nl> } ; <nl> <nl> + function getOldestMajorBranchOfPull ( pull ) { <nl> + return pull . data . labels <nl> + . map ( label = > label . name . match ( / merged \ / ( \ d + ) - ( \ d + ) - x / ) | | label . name . match ( / merged \ / ( \ d + ) - x - y / ) ) <nl> + . filter ( label = > ! ! label ) <nl> + . map ( label = > parseInt ( label [ 1 ] ) ) <nl> + . filter ( major = > ! ! major ) <nl> + . sort ( ) <nl> + . shift ( ) ; <nl> + } <nl> + <nl> + function getOldestMajorBranchOfCommit ( commit , pool ) { <nl> + return [ . . . commit . prKeys . values ( ) ] <nl> + . map ( prKey = > pool . pulls [ prKey . number ] ) <nl> + . filter ( pull = > ! ! pull ) <nl> + . map ( pull = > getOldestMajorBranchOfPull ( pull ) ) <nl> + . filter ( major = > ! ! major ) <nl> + . sort ( ) <nl> + . shift ( ) ; <nl> + } <nl> + <nl> / * * * <nl> * * * * Main <nl> * * * / <nl> const getNotes = async ( fromRef , toRef , newVersion ) = > { <nl> fs . mkdirSync ( CACHE_DIR ) ; <nl> } <nl> <nl> - const pool = { <nl> - processedHashes : new Set ( ) , <nl> - commits : [ ] <nl> - } ; <nl> + const pool = new Pool ( ) ; <nl> <nl> / / get the electron / electron commits <nl> const electron = { owner : ' electron ' , repo : ' electron ' , dir : ELECTRON_VERSION } ; <nl> const getNotes = async ( fromRef , toRef , newVersion ) = > { <nl> pool . processedHashes . add ( revertHash ) ; <nl> } <nl> <nl> - / / scrape PRs for release note ' Notes : ' comments <nl> + / / ensure the commit has a note <nl> for ( const commit of pool . commits ) { <nl> - let pr = commit . pr ; <nl> - <nl> - let prSubject ; <nl> - while ( pr & & ! commit . note ) { <nl> - const note = await getNoteFromClerk ( pr . number , pr . owner , pr . repo ) ; <nl> - if ( note ) { <nl> - commit . note = note ; <nl> - } <nl> - <nl> - / / if we already have all the data we need , stop scraping the PRs <nl> - if ( commit . note & & commit . type & & prSubject ) { <nl> + for ( const prKey of commit . prKeys . values ( ) ) { <nl> + commit . note = commit . note | | await getNoteFromClerk ( prKey ) ; <nl> + if ( commit . note ) { <nl> break ; <nl> } <nl> - <nl> - const prData = await getPullRequest ( pr . number , pr . owner , pr . repo ) ; <nl> - if ( ! prData | | ! prData . data ) { <nl> - break ; <nl> - } <nl> - <nl> - / / try to pull a release note from the pull comment <nl> - const prParsed = parseCommitMessage ( ` $ { prData . data . title } \ n \ n $ { prData . data . body } ` , pr . owner , pr . repo ) ; <nl> - if ( ! commit . note ) { <nl> - commit . note = prParsed . note ; <nl> - } <nl> - if ( ! commit . type | | prParsed . type = = = ' breaking - change ' ) { <nl> - commit . type = prParsed . type ; <nl> - } <nl> - prSubject = prSubject | | prParsed . subject ; <nl> - <nl> - pr = prParsed . pr & & ( prParsed . pr . number ! = = pr . number ) ? prParsed . pr : null ; <nl> } <nl> - <nl> - / / if we still don ' t have a note , it ' s because someone missed a ' Notes : <nl> - / / comment in a PR somewhere . . . use the PR subject as a fallback . <nl> - commit . note = commit . note | | prSubject ; <nl> + / / use a fallback note in case someone missed a ' Notes ' comment <nl> + commit . note = commit . note | | commit . subject ; <nl> } <nl> <nl> / / remove non - user - facing commits <nl> const getNotes = async ( fromRef , toRef , newVersion ) = > { <nl> . filter ( commit = > ! ( ( commit . note | | commit . subject ) . match ( / ^ [ Bb ] ump v \ d + \ . \ d + \ . \ d + / ) ) ) ; <nl> <nl> if ( ! shouldIncludeMultibranchChanges ( newVersion ) ) { <nl> - / / load all the prDatas <nl> - await Promise . all ( <nl> - pool . commits . map ( commit = > ( async ( ) = > { <nl> - const { pr } = commit ; <nl> - if ( typeof pr = = = ' object ' ) { <nl> - const prData = await getPullRequest ( pr . number , pr . owner , pr . repo ) ; <nl> - if ( prData ) { <nl> - commit . prData = prData ; <nl> - } <nl> - } <nl> - } ) ( ) ) <nl> - ) ; <nl> - <nl> - / / remove items that already landed in a previous major / minor series <nl> + const currentMajor = semver . parse ( newVersion ) . major ; <nl> pool . commits = pool . commits <nl> - . filter ( commit = > { <nl> - if ( ! commit . prData ) { <nl> - return true ; <nl> - } <nl> - const reducer = ( accumulator , current ) = > { <nl> - if ( ! semver . valid ( accumulator ) ) { return current ; } <nl> - if ( ! semver . valid ( current ) ) { return accumulator ; } <nl> - return semver . lt ( accumulator , current ) ? accumulator : current ; <nl> - } ; <nl> - const earliestRelease = commit . prData . data . labels <nl> - . map ( label = > label . name . match ( / merged \ / ( \ d + ) - ( \ d + ) - x / ) ) <nl> - . filter ( label = > ! ! label ) <nl> - . map ( label = > ` $ { label [ 1 ] } . $ { label [ 2 ] } . 0 ` ) <nl> - . reduce ( reducer , null ) ; <nl> - if ( ! semver . valid ( earliestRelease ) ) { <nl> - return true ; <nl> - } <nl> - return semver . diff ( earliestRelease , newVersion ) . includes ( ' patch ' ) ; <nl> - } ) ; <nl> + . filter ( commit = > getOldestMajorBranchOfCommit ( commit , pool ) > = currentMajor ) ; <nl> } <nl> <nl> pool . commits = removeSupercededChromiumUpdates ( pool . commits ) ; <nl> const getNotes = async ( fromRef , toRef , newVersion ) = > { <nl> } ; <nl> <nl> pool . commits . forEach ( commit = > { <nl> - const str = commit . type ; <nl> - if ( ! str ) { <nl> - notes . unknown . push ( commit ) ; <nl> - } else if ( breakTypes . has ( str ) ) { <nl> + const str = commit . semanticType ; <nl> + if ( commit . isBreakingChange ) { <nl> notes . breaking . push ( commit ) ; <nl> + } else if ( ! str ) { <nl> + notes . unknown . push ( commit ) ; <nl> } else if ( docTypes . has ( str ) ) { <nl> notes . docs . push ( commit ) ; <nl> } else if ( featTypes . has ( str ) ) { <nl> const removeSupercededChromiumUpdates = ( commits ) = > { <nl> <nl> / / keep the newest update . <nl> if ( updates . length ) { <nl> - updates . sort ( ( a , b ) = > a . originalPr . number - b . originalPr . number ) ; <nl> - keepers . push ( updates . pop ( ) ) ; <nl> + const compare = ( a , b ) = > ( a . note | | a . subject ) . localeCompare ( b . note | | b . subject ) ; <nl> + keepers . push ( updates . sort ( compare ) . pop ( ) ) ; <nl> } <nl> <nl> return keepers ; <nl> const removeSupercededChromiumUpdates = ( commits ) = > { <nl> <nl> const renderLink = ( commit , explicitLinks ) = > { <nl> let link ; <nl> - const pr = commit . originalPr ; <nl> - if ( pr ) { <nl> - const { owner , repo , number } = pr ; <nl> - const url = ` https : / / github . com / $ { owner } / $ { repo } / pull / $ { number } ` ; <nl> - const text = owner = = = ' electron ' & & repo = = = ' electron ' <nl> - ? ` # $ { number } ` <nl> - : ` $ { owner } / $ { repo } # $ { number } ` ; <nl> - link = explicitLinks ? ` [ $ { text } ] ( $ { url } ) ` : text ; <nl> - } else { <nl> - const { owner , repo , hash } = commit ; <nl> + const { owner , repo } = commit ; <nl> + const keyIt = commit . prKeys . values ( ) . next ( ) ; <nl> + if ( keyIt . done ) / * no PRs * / { <nl> + const { hash } = commit ; <nl> const url = ` https : / / github . com / $ { owner } / $ { repo } / commit / $ { hash } ` ; <nl> const text = owner = = = ' electron ' & & repo = = = ' electron ' <nl> ? ` $ { hash . slice ( 0 , 8 ) } ` <nl> : ` $ { owner } / $ { repo } @ $ { hash . slice ( 0 , 8 ) } ` ; <nl> link = explicitLinks ? ` [ $ { text } ] ( $ { url } ) ` : text ; <nl> + } else { <nl> + const { number } = keyIt . value ; <nl> + const url = ` https : / / github . com / $ { owner } / $ { repo } / pull / $ { number } ` ; <nl> + const text = owner = = = ' electron ' & & repo = = = ' electron ' <nl> + ? ` # $ { number } ` <nl> + : ` $ { owner } / $ { repo } # $ { number } ` ; <nl> + link = explicitLinks ? ` [ $ { text } ] ( $ { url } ) ` : text ; <nl> } <nl> return link ; <nl> } ; <nl>
Remove redundant release note items ( )
electron/electron
8bc6b81edc09e356ee940c5de1bcdda63310d038
2020-05-01T00:00:59Z
mmm a / . gitignore <nl> ppp b / . gitignore <nl> cmake / cmake - build - debug / <nl> <nl> # Visual Studio 2017 <nl> . vs <nl> + <nl> + # IntelliJ <nl> + . idea <nl> + * . iml <nl> mmm a / Makefile . am <nl> ppp b / Makefile . am <nl> php_EXTRA_DIST = \ <nl> php / tests / proto / test_reserved_message_upper . proto \ <nl> php / tests / proto / test_service . proto \ <nl> php / tests / proto / test_service_namespace . proto \ <nl> + php / tests / proto / test_wrapper_type_setters . proto \ <nl> php / tests / test . sh \ <nl> php / tests / test_base . php \ <nl> php / tests / test_util . php \ <nl> php / tests / undefined_test . php \ <nl> - php / tests / well_known_test . php <nl> + php / tests / well_known_test . php \ <nl> + php / tests / wrapper_type_setters_test . php <nl> <nl> python_EXTRA_DIST = \ <nl> python / MANIFEST . in \ <nl> mmm a / php / composer . json <nl> ppp b / php / composer . json <nl> <nl> } <nl> } , <nl> " scripts " : { <nl> - " test " : " ( cd tests & & rm - rf generated & & mkdir - p generated & & . . / . . / src / protoc - - php_out = generated proto / empty / echo . proto proto / test . proto proto / test_include . proto proto / test_no_namespace . proto proto / test_prefix . proto proto / test_php_namespace . proto proto / test_empty_php_namespace . proto proto / test_reserved_enum_lower . proto proto / test_reserved_enum_upper . proto proto / test_reserved_enum_value_lower . proto proto / test_reserved_enum_value_upper . proto proto / test_reserved_message_lower . proto proto / test_reserved_message_upper . proto proto / test_service . proto proto / test_service_namespace . proto proto / test_descriptors . proto ) & & ( cd . . / src & & . / protoc - - php_out = . . / php / tests / generated - I . . / php / tests - I . . . / php / tests / proto / test_import_descriptor_proto . proto ) & & vendor / bin / phpunit " <nl> + " test " : " ( cd tests & & rm - rf generated & & mkdir - p generated & & . . / . . / src / protoc - - php_out = generated - I . . / . . / src - I . proto / empty / echo . proto proto / test . proto proto / test_include . proto proto / test_no_namespace . proto proto / test_prefix . proto proto / test_php_namespace . proto proto / test_empty_php_namespace . proto proto / test_reserved_enum_lower . proto proto / test_reserved_enum_upper . proto proto / test_reserved_enum_value_lower . proto proto / test_reserved_enum_value_upper . proto proto / test_reserved_message_lower . proto proto / test_reserved_message_upper . proto proto / test_service . proto proto / test_service_namespace . proto proto / test_wrapper_type_setters . proto proto / test_descriptors . proto ) & & ( cd . . / src & & . / protoc - - php_out = . . / php / tests / generated - I . . / php / tests - I . . . / php / tests / proto / test_import_descriptor_proto . proto ) & & vendor / bin / phpunit " <nl> } <nl> } <nl> mmm a / php / ext / google / protobuf / message . c <nl> ppp b / php / ext / google / protobuf / message . c <nl> void custom_data_init ( const zend_class_entry * ce , <nl> & intern - > std PHP_PROTO_TSRMLS_CC ) ; <nl> } <nl> <nl> + # define INIT_MESSAGE_WITH_ARRAY \ <nl> + { \ <nl> + zval * array_wrapper = NULL ; \ <nl> + if ( zend_parse_parameters ( ZEND_NUM_ARGS ( ) TSRMLS_CC , \ <nl> + " | a ! " , & array_wrapper ) = = FAILURE ) { \ <nl> + return ; \ <nl> + } \ <nl> + Message_construct ( getThis ( ) , array_wrapper ) ; \ <nl> + } <nl> + <nl> void build_class_from_descriptor ( <nl> PHP_PROTO_HASHTABLE_VALUE php_descriptor TSRMLS_DC ) { <nl> Descriptor * desc = UNBOX_HASHTABLE_VALUE ( Descriptor , php_descriptor ) ; <nl> void Message_construct ( zval * msg , zval * array_wrapper ) { <nl> zval * submsg = CACHED_PTR_TO_ZVAL_PTR ( cached ) ; <nl> ZVAL_OBJ ( submsg , desc - > klass - > create_object ( desc - > klass TSRMLS_CC ) ) ; <nl> Message_construct ( submsg , NULL ) ; <nl> - MessageHeader * from = UNBOX ( MessageHeader , <nl> - CACHED_PTR_TO_ZVAL_PTR ( ( CACHED_VALUE * ) value ) ) ; <nl> MessageHeader * to = UNBOX ( MessageHeader , submsg ) ; <nl> - if ( from - > descriptor ! = to - > descriptor ) { <nl> - zend_error ( E_USER_ERROR , " Cannot merge messages with different class . " ) ; <nl> - return ; <nl> + const upb_filedef * file = upb_def_file ( upb_msgdef_upcast ( submsgdef ) ) ; <nl> + if ( ! strcmp ( upb_filedef_name ( file ) , " google / protobuf / wrappers . proto " ) & & <nl> + Z_TYPE_P ( CACHED_PTR_TO_ZVAL_PTR ( ( CACHED_VALUE * ) value ) ) ! = IS_OBJECT ) { <nl> + const upb_fielddef * value_field = upb_msgdef_itof ( submsgdef , 1 ) ; <nl> + layout_set ( to - > descriptor - > layout , to , <nl> + value_field , CACHED_PTR_TO_ZVAL_PTR ( ( CACHED_VALUE * ) value ) <nl> + TSRMLS_CC ) ; <nl> + } else { <nl> + MessageHeader * from = <nl> + UNBOX ( MessageHeader , <nl> + CACHED_PTR_TO_ZVAL_PTR ( ( CACHED_VALUE * ) value ) ) ; <nl> + if ( from - > descriptor ! = to - > descriptor ) { <nl> + zend_error ( E_USER_ERROR , <nl> + " Cannot merge messages with different class . " ) ; <nl> + return ; <nl> + } <nl> + <nl> + layout_merge ( from - > descriptor - > layout , from , to TSRMLS_CC ) ; <nl> } <nl> - <nl> - layout_merge ( from - > descriptor - > layout , from , to TSRMLS_CC ) ; <nl> } else { <nl> message_set_property_internal ( msg , & key , <nl> CACHED_PTR_TO_ZVAL_PTR ( ( CACHED_VALUE * ) value ) TSRMLS_CC ) ; <nl> void Message_construct ( zval * msg , zval * array_wrapper ) { <nl> / / modified . As a result , the first created instance will be a normal zend <nl> / / object . Here , we manually modify it to our message in such a case . <nl> PHP_METHOD ( Message , __construct ) { <nl> - / / Init message with array <nl> - zval * array_wrapper = NULL ; <nl> - if ( zend_parse_parameters ( ZEND_NUM_ARGS ( ) TSRMLS_CC , <nl> - " | a ! " , & array_wrapper ) = = FAILURE ) { <nl> - return ; <nl> - } <nl> - <nl> - Message_construct ( getThis ( ) , array_wrapper ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_METHOD ( Message , clear ) { <nl> static void hex_to_binary ( const char * hex , char * * binary , int * binary_len ) { <nl> PHP_METHOD ( Any , __construct ) { <nl> init_file_any ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( any_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Any , any , TypeUrl , " type_url " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Duration , __construct ) { <nl> init_file_duration ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( duration_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Duration , duration , Seconds , " seconds " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Timestamp , __construct ) { <nl> init_file_timestamp ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( timestamp_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Timestamp , timestamp , Seconds , " seconds " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Api , __construct ) { <nl> init_file_api ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( api_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Api , api , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( BoolValue , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( bool_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( BoolValue , bool_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( BytesValue , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( bytes_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( BytesValue , bytes_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( DoubleValue , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( double_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( DoubleValue , double_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Enum , __construct ) { <nl> init_file_type ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( enum_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Enum , enum , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( EnumValue , __construct ) { <nl> init_file_type ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( enum_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( EnumValue , enum_value , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( FieldMask , __construct ) { <nl> init_file_field_mask ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( field_mask_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( FieldMask , field_mask , Paths , " paths " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Field , __construct ) { <nl> init_file_type ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( field_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Field , field , Kind , " kind " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( FloatValue , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( float_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( FloatValue , float_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( GPBEmpty , __construct ) { <nl> init_file_empty ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( empty_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Int32Value , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( int32_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Int32Value , int32_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Int64Value , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( int64_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Int64Value , int64_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( ListValue , __construct ) { <nl> init_file_struct ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( list_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( ListValue , list_value , Values , " values " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Method , __construct ) { <nl> init_file_api ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( method_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Method , method , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Mixin , __construct ) { <nl> init_file_api ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( mixin_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Mixin , mixin , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Option , __construct ) { <nl> init_file_type ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( option_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Option , option , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( SourceContext , __construct ) { <nl> init_file_source_context ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( source_context_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( SourceContext , source_context , FileName , " file_name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( StringValue , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( string_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( StringValue , string_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Struct , __construct ) { <nl> init_file_struct ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( struct_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Struct , struct , Fields , " fields " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Type , __construct ) { <nl> init_file_type ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( type_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( Type , type , Name , " name " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( UInt32Value , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( u_int32_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( UInt32Value , u_int32_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( UInt64Value , __construct ) { <nl> init_file_wrappers ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( u_int64_value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_FIELD_ACCESSORS ( UInt64Value , u_int64_value , Value , " value " ) <nl> PHP_PROTO_INIT_SUBMSGCLASS_END <nl> PHP_METHOD ( Value , __construct ) { <nl> init_file_struct ( TSRMLS_C ) ; <nl> MessageHeader * intern = UNBOX ( MessageHeader , getThis ( ) ) ; <nl> - custom_data_init ( value_type , intern PHP_PROTO_TSRMLS_CC ) ; <nl> + INIT_MESSAGE_WITH_ARRAY ; <nl> } <nl> <nl> PHP_PROTO_ONEOF_FIELD_ACCESSORS ( Value , value , NullValue , " null_value " ) <nl> mmm a / php / ext / google / protobuf / type_check . c <nl> ppp b / php / ext / google / protobuf / type_check . c <nl> static zend_uchar convert_numeric_string ( <nl> type # # _t * type # # _value ) { \ <nl> int64_t lval ; \ <nl> double dval ; \ <nl> - \ <nl> + TSRMLS_FETCH ( ) ; \ <nl> switch ( convert_numeric_string ( val , len , & lval , & dval ) ) { \ <nl> case IS_DOUBLE : { \ <nl> return convert_double_to_ # # type ( dval , type # # _value ) ; \ <nl> static zend_uchar convert_numeric_string ( <nl> return convert_int64_to_ # # type ( lval , type # # _value ) ; \ <nl> } \ <nl> default : \ <nl> - zend_error ( E_USER_ERROR , \ <nl> - " Given string value cannot be converted to integer . " ) ; \ <nl> + zend_throw_exception ( NULL , \ <nl> + " Given string value cannot be converted to integer . " , \ <nl> + 0 TSRMLS_CC ) ; \ <nl> return false ; \ <nl> } \ <nl> } \ <nl> \ <nl> bool protobuf_convert_to_ # # type ( zval * from , type # # _t * to ) { \ <nl> + TSRMLS_FETCH ( ) ; \ <nl> switch ( Z_TYPE_P ( from ) ) { \ <nl> case IS_LONG : { \ <nl> return convert_int64_to_ # # type ( Z_LVAL_P ( from ) , to ) ; \ <nl> static zend_uchar convert_numeric_string ( <nl> to ) ; \ <nl> } \ <nl> default : { \ <nl> - zend_error ( E_USER_ERROR , \ <nl> - " Given value cannot be converted to integer . " ) ; \ <nl> + zend_throw_exception ( NULL , \ <nl> + " Given value cannot be converted to integer . " , \ <nl> + 0 TSRMLS_CC ) ; \ <nl> return false ; \ <nl> } \ <nl> } \ <nl> CONVERT_TO_INTEGER ( uint64 ) ; <nl> int64_t lval ; \ <nl> double dval ; \ <nl> \ <nl> + TSRMLS_FETCH ( ) ; \ <nl> switch ( convert_numeric_string ( val , len , & lval , & dval ) ) { \ <nl> case IS_DOUBLE : { \ <nl> * type # # _value = ( type ) dval ; \ <nl> CONVERT_TO_INTEGER ( uint64 ) ; <nl> return true ; \ <nl> } \ <nl> default : \ <nl> - zend_error ( E_USER_ERROR , \ <nl> - " Given string value cannot be converted to integer . " ) ; \ <nl> + zend_throw_exception ( NULL , \ <nl> + " Given string value cannot be converted to integer . " , \ <nl> + 0 TSRMLS_CC ) ; \ <nl> return false ; \ <nl> } \ <nl> } \ <nl> \ <nl> bool protobuf_convert_to_ # # type ( zval * from , type * to ) { \ <nl> + TSRMLS_FETCH ( ) ; \ <nl> switch ( Z_TYPE_P ( from ) ) { \ <nl> case IS_LONG : { \ <nl> return convert_int64_to_ # # type ( Z_LVAL_P ( from ) , to ) ; \ <nl> CONVERT_TO_INTEGER ( uint64 ) ; <nl> to ) ; \ <nl> } \ <nl> default : { \ <nl> - zend_error ( E_USER_ERROR , \ <nl> - " Given value cannot be converted to integer . " ) ; \ <nl> + zend_throw_exception ( NULL , \ <nl> + " Given value cannot be converted to integer . " , \ <nl> + 0 TSRMLS_CC ) ; \ <nl> return false ; \ <nl> } \ <nl> } \ <nl> CONVERT_TO_FLOAT ( double ) ; <nl> # undef CONVERT_TO_FLOAT <nl> <nl> bool protobuf_convert_to_bool ( zval * from , int8_t * to ) { <nl> + TSRMLS_FETCH ( ) ; <nl> switch ( Z_TYPE_P ( from ) ) { <nl> # if PHP_MAJOR_VERSION < 7 <nl> case IS_BOOL : <nl> bool protobuf_convert_to_bool ( zval * from , int8_t * to ) { <nl> } <nl> } break ; <nl> default : { <nl> - zend_error ( E_USER_ERROR , " Given value cannot be converted to bool . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Given value cannot be converted to bool . " , <nl> + 0 TSRMLS_CC ) ; <nl> return false ; <nl> } <nl> } <nl> bool protobuf_convert_to_bool ( zval * from , int8_t * to ) { <nl> } <nl> <nl> bool protobuf_convert_to_string ( zval * from ) { <nl> + TSRMLS_FETCH ( ) ; <nl> switch ( Z_TYPE_P ( from ) ) { <nl> case IS_STRING : { <nl> return true ; <nl> bool protobuf_convert_to_string ( zval * from ) { <nl> return true ; <nl> } <nl> default : <nl> - zend_error ( E_USER_ERROR , " Given value cannot be converted to string . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Given value cannot be converted to string . " , <nl> + 0 TSRMLS_CC ) ; <nl> return false ; <nl> } <nl> } <nl> PHP_METHOD ( Util , checkMessage ) { <nl> RETURN_NULL ( ) ; <nl> } <nl> if ( ! instanceof_function ( Z_OBJCE_P ( val ) , klass TSRMLS_CC ) ) { <nl> - zend_error ( E_USER_ERROR , " Given value is not an instance of % s . " , <nl> - klass - > name ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Given value is not an instance of % s . " , klass - > name , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> RETURN_ZVAL ( val , 1 , 0 ) ; <nl> void check_repeated_field ( const zend_class_entry * klass , PHP_PROTO_LONG type , <nl> <nl> } else if ( Z_TYPE_P ( val ) = = IS_OBJECT ) { <nl> if ( ! instanceof_function ( Z_OBJCE_P ( val ) , repeated_field_type TSRMLS_CC ) ) { <nl> - zend_error ( E_USER_ERROR , " Given value is not an instance of % s . " , <nl> - repeated_field_type - > name ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Given value is not an instance of % s . " , <nl> + repeated_field_type - > name , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> RepeatedField * intern = UNBOX ( RepeatedField , val ) ; <nl> if ( to_fieldtype ( type ) ! = intern - > type ) { <nl> - zend_error ( E_USER_ERROR , " Incorrect repeated field type . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Incorrect repeated field type . " , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> if ( klass ! = NULL & & intern - > msg_ce ! = klass ) { <nl> - zend_error ( E_USER_ERROR , <nl> - " Expect a repeated field of % s , but % s is given . " , klass - > name , <nl> - intern - > msg_ce - > name ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Expect a repeated field of % s , but % s is given . " , <nl> + klass - > name , <nl> + intern - > msg_ce - > name , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> RETURN_ZVAL ( val , 1 , 0 ) ; <nl> } else { <nl> - zend_error ( E_USER_ERROR , " Incorrect repeated field type . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Incorrect repeated field type . " , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> } <nl> void check_map_field ( const zend_class_entry * klass , PHP_PROTO_LONG key_type , <nl> RETURN_ZVAL ( CACHED_TO_ZVAL_PTR ( map_field ) , 1 , 1 ) ; <nl> } else if ( Z_TYPE_P ( val ) = = IS_OBJECT ) { <nl> if ( ! instanceof_function ( Z_OBJCE_P ( val ) , map_field_type TSRMLS_CC ) ) { <nl> - zend_error ( E_USER_ERROR , " Given value is not an instance of % s . " , <nl> - map_field_type - > name ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Given value is not an instance of % s . " , <nl> + map_field_type - > name , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> Map * intern = UNBOX ( Map , val ) ; <nl> if ( to_fieldtype ( key_type ) ! = intern - > key_type ) { <nl> - zend_error ( E_USER_ERROR , " Incorrect map field key type . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Incorrect map field key type . " , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> if ( to_fieldtype ( value_type ) ! = intern - > value_type ) { <nl> - zend_error ( E_USER_ERROR , " Incorrect map field value type . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Incorrect map field value type . " , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> if ( klass ! = NULL & & intern - > msg_ce ! = klass ) { <nl> - zend_error ( E_USER_ERROR , " Expect a map field of % s , but % s is given . " , <nl> - klass - > name , intern - > msg_ce - > name ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Expect a map field of % s , but % s is given . " , <nl> + klass - > name , intern - > msg_ce - > name , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> RETURN_ZVAL ( val , 1 , 0 ) ; <nl> } else { <nl> - zend_error ( E_USER_ERROR , " Incorrect map field type . " ) ; <nl> + zend_throw_exception ( <nl> + NULL , " Incorrect map field type . " , <nl> + 0 TSRMLS_CC ) ; <nl> return ; <nl> } <nl> } <nl> mmm a / php / phpunit . xml <nl> ppp b / php / phpunit . xml <nl> <nl> < file > tests / well_known_test . php < / file > <nl> < file > tests / descriptors_test . php < / file > <nl> < file > tests / generated_service_test . php < / file > <nl> + < file > tests / wrapper_type_setters_test . php < / file > <nl> < / testsuite > <nl> < / testsuites > <nl> < / phpunit > <nl> mmm a / php / src / Google / Protobuf / Internal / FieldDescriptor . php <nl> ppp b / php / src / Google / Protobuf / Internal / FieldDescriptor . php <nl> public function isTimestamp ( ) <nl> $ this - > getMessageType ( ) - > getClass ( ) = = = " Google \ Protobuf \ Timestamp " ; <nl> } <nl> <nl> + public function isWrapperType ( ) <nl> + { <nl> + if ( $ this - > getType ( ) = = GPBType : : MESSAGE ) { <nl> + $ class = $ this - > getMessageType ( ) - > getClass ( ) ; <nl> + return in_array ( $ class , [ <nl> + " Google \ Protobuf \ DoubleValue " , <nl> + " Google \ Protobuf \ FloatValue " , <nl> + " Google \ Protobuf \ Int64Value " , <nl> + " Google \ Protobuf \ UInt64Value " , <nl> + " Google \ Protobuf \ Int32Value " , <nl> + " Google \ Protobuf \ UInt32Value " , <nl> + " Google \ Protobuf \ BoolValue " , <nl> + " Google \ Protobuf \ StringValue " , <nl> + " Google \ Protobuf \ BytesValue " , <nl> + ] ) ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> private static function isTypePackable ( $ field_type ) <nl> { <nl> return ( $ field_type ! = = GPBType : : STRING & & <nl> mmm a / php / src / Google / Protobuf / Internal / Message . php <nl> ppp b / php / src / Google / Protobuf / Internal / Message . php <nl> private function convertJsonValueToProtoValue ( <nl> * <nl> * @ param array $ array An array containing message properties and values . <nl> * @ return null . <nl> - * @ throws Exception Invalid data . <nl> + * @ throws \ Exception Invalid data . <nl> * / <nl> protected function mergeFromArray ( array $ array ) <nl> { <nl> protected function mergeFromArray ( array $ array ) <nl> ' Invalid message property : ' . $ key ) ; <nl> } <nl> $ setter = $ field - > getSetter ( ) ; <nl> + if ( $ field - > isWrapperType ( ) ) { <nl> + self : : normalizeToMessageType ( $ value , $ field - > getMessageType ( ) - > getClass ( ) ) ; <nl> + } <nl> $ this - > $ setter ( $ value ) ; <nl> } <nl> } <nl> <nl> + / * * <nl> + * Tries to normalize $ value into a provided protobuf wrapper type $ class . <nl> + * If $ value is any type other than an object , we attempt to construct an <nl> + * instance of $ class and assign $ value to it using the setValue method <nl> + * shared by all wrapper types . <nl> + * <nl> + * @ param mixed $ value The value to normalize . <nl> + * @ param string $ class The expected wrapper class name <nl> + * @ throws \ Exception If $ value cannot be converted to a wrapper type <nl> + * / <nl> + private static function normalizeToMessageType ( & $ value , $ class ) <nl> + { <nl> + if ( is_null ( $ value ) | | is_object ( $ value ) ) { <nl> + / / This handles the case that $ value is an instance of $ class . We <nl> + / / choose not to do any more strict checking here , relying on the <nl> + / / existing type checking done by GPBUtil . <nl> + return ; <nl> + } else { <nl> + / / Try to instantiate $ class and set the value <nl> + try { <nl> + $ msg = new $ class ; <nl> + $ msg - > setValue ( $ value ) ; <nl> + $ value = $ msg ; <nl> + return ; <nl> + } catch ( \ Exception $ exception ) { <nl> + throw new \ Exception ( <nl> + " Error normalizing value to type ' $ class ' : " . $ exception - > getMessage ( ) , <nl> + $ exception - > getCode ( ) , <nl> + $ exception <nl> + ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> protected function mergeFromJsonArray ( $ array ) <nl> { <nl> if ( is_a ( $ this , " Google \ Protobuf \ Any " ) ) { <nl> new file mode 100644 <nl> index 0000000000 . . e1e3309c54 <nl> mmm / dev / null <nl> ppp b / php / tests / proto / test_wrapper_type_setters . proto <nl> <nl> + syntax = " proto3 " ; <nl> + <nl> + import " google / protobuf / wrappers . proto " ; <nl> + <nl> + package foo ; <nl> + <nl> + message TestWrapperSetters { <nl> + google . protobuf . DoubleValue double_value = 1 ; <nl> + google . protobuf . FloatValue float_value = 2 ; <nl> + google . protobuf . Int64Value int64_value = 3 ; <nl> + google . protobuf . UInt64Value uint64_value = 4 ; <nl> + google . protobuf . Int32Value int32_value = 5 ; <nl> + google . protobuf . UInt32Value uint32_value = 6 ; <nl> + google . protobuf . BoolValue bool_value = 7 ; <nl> + google . protobuf . StringValue string_value = 8 ; <nl> + google . protobuf . BytesValue bytes_value = 9 ; <nl> + <nl> + oneof wrapped_oneofs { <nl> + google . protobuf . DoubleValue double_value_oneof = 10 ; <nl> + google . protobuf . StringValue string_value_oneof = 11 ; <nl> + } <nl> + } <nl> mmm a / php / tests / test . sh <nl> ppp b / php / tests / test . sh <nl> set - e <nl> phpize & & . / configure CFLAGS = ' - g - O0 ' & & make <nl> popd <nl> <nl> - tests = ( array_test . php encode_decode_test . php generated_class_test . php map_field_test . php well_known_test . php descriptors_test . php ) <nl> + tests = ( array_test . php encode_decode_test . php generated_class_test . php map_field_test . php well_known_test . php descriptors_test . php wrapper_type_setters_test . php ) <nl> <nl> for t in " $ { tests [ @ ] } " <nl> do <nl> new file mode 100644 <nl> index 0000000000 . . 3d09c9a8c2 <nl> mmm / dev / null <nl> ppp b / php / tests / wrapper_type_setters_test . php <nl> <nl> + < ? php <nl> + <nl> + require_once ( ' test_base . php ' ) ; <nl> + require_once ( ' test_util . php ' ) ; <nl> + <nl> + use Foo \ TestWrapperSetters ; <nl> + use Google \ Protobuf \ BoolValue ; <nl> + use Google \ Protobuf \ BytesValue ; <nl> + use Google \ Protobuf \ DoubleValue ; <nl> + use Google \ Protobuf \ FloatValue ; <nl> + use Google \ Protobuf \ Int32Value ; <nl> + use Google \ Protobuf \ Int64Value ; <nl> + use Google \ Protobuf \ StringValue ; <nl> + use Google \ Protobuf \ UInt32Value ; <nl> + use Google \ Protobuf \ UInt64Value ; <nl> + <nl> + class WrapperTypeSettersTest extends TestBase <nl> + { <nl> + / * * <nl> + * @ dataProvider gettersAndSettersDataProvider <nl> + * / <nl> + public function testGettersAndSetters ( <nl> + $ class , <nl> + $ wrapperClass , <nl> + $ setter , <nl> + $ valueSetter , <nl> + $ getter , <nl> + $ valueGetter , <nl> + $ sequence <nl> + ) { <nl> + $ oldSetterMsg = new $ class ( ) ; <nl> + $ newSetterMsg = new $ class ( ) ; <nl> + foreach ( $ sequence as list ( $ value , $ expectedValue ) ) { <nl> + / / Manually wrap the value to pass to the old setter <nl> + $ wrappedValue = is_null ( $ value ) ? $ value : new $ wrapperClass ( [ ' value ' = > $ value ] ) ; <nl> + <nl> + / / Set values using new and old setters <nl> + $ oldSetterMsg - > $ setter ( $ wrappedValue ) ; <nl> + $ newSetterMsg - > $ valueSetter ( $ value ) ; <nl> + <nl> + / / Get expected values old getter <nl> + $ expectedValue = $ oldSetterMsg - > $ getter ( ) ; <nl> + <nl> + / / Check that old getter returns the same value after using the <nl> + / / new setter <nl> + $ actualValue = $ newSetterMsg - > $ getter ( ) ; <nl> + $ this - > assertEquals ( $ expectedValue , $ actualValue ) ; <nl> + <nl> + / / Check that new getter returns the unwrapped value from <nl> + / / $ expectedValue <nl> + $ actualValueNewGetter = $ newSetterMsg - > $ valueGetter ( ) ; <nl> + if ( is_null ( $ expectedValue ) ) { <nl> + $ this - > assertNull ( $ actualValueNewGetter ) ; <nl> + } else { <nl> + $ this - > assertEquals ( $ expectedValue - > getValue ( ) , $ actualValueNewGetter ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + public function gettersAndSettersDataProvider ( ) <nl> + { <nl> + return [ <nl> + [ TestWrapperSetters : : class , DoubleValue : : class , " setDoubleValue " , " setDoubleValueValue " , " getDoubleValue " , " getDoubleValueValue " , [ <nl> + [ 1 . 1 , new DoubleValue ( [ " value " = > 1 . 1 ] ) ] , <nl> + [ 2 . 2 , new DoubleValue ( [ " value " = > 2 . 2 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new DoubleValue ( ) ] , <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , FloatValue : : class , " setFloatValue " , " setFloatValueValue " , " getFloatValue " , " getFloatValueValue " , [ <nl> + [ 1 . 1 , new FloatValue ( [ " value " = > 1 . 1 ] ) ] , <nl> + [ 2 . 2 , new FloatValue ( [ " value " = > 2 . 2 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new FloatValue ( ) ] , <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , Int64Value : : class , " setInt64Value " , " setInt64ValueValue " , " getInt64Value " , " getInt64ValueValue " , [ <nl> + [ 123 , new Int64Value ( [ " value " = > 123 ] ) ] , <nl> + [ - 789 , new Int64Value ( [ " value " = > - 789 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new Int64Value ( ) ] , <nl> + [ 5 . 5 , new Int64Value ( [ " value " = > 5 ] ) ] , / / Test conversion from float to int <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , UInt64Value : : class , " setUInt64Value " , " setUInt64ValueValue " , " getUInt64Value " , " getUInt64ValueValue " , [ <nl> + [ 123 , new UInt64Value ( [ " value " = > 123 ] ) ] , <nl> + [ 789 , new UInt64Value ( [ " value " = > 789 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new UInt64Value ( ) ] , <nl> + [ 5 . 5 , new UInt64Value ( [ " value " = > 5 ] ) ] , / / Test conversion from float to int <nl> + [ - 7 , new UInt64Value ( [ " value " = > - 7 ] ) ] , / / Test conversion from - ve to + ve <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , Int32Value : : class , " setInt32Value " , " setInt32ValueValue " , " getInt32Value " , " getInt32ValueValue " , [ <nl> + [ 123 , new Int32Value ( [ " value " = > 123 ] ) ] , <nl> + [ - 789 , new Int32Value ( [ " value " = > - 789 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new Int32Value ( ) ] , <nl> + [ 5 . 5 , new Int32Value ( [ " value " = > 5 ] ) ] , / / Test conversion from float to int <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , UInt32Value : : class , " setUInt32Value " , " setUInt32ValueValue " , " getUInt32Value " , " getUInt32ValueValue " , [ <nl> + [ 123 , new UInt32Value ( [ " value " = > 123 ] ) ] , <nl> + [ 789 , new UInt32Value ( [ " value " = > 789 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new UInt32Value ( ) ] , <nl> + [ 5 . 5 , new UInt32Value ( [ " value " = > 5 ] ) ] , / / Test conversion from float to int <nl> + [ - 7 , new UInt32Value ( [ " value " = > - 7 ] ) ] , / / Test conversion from - ve to + ve <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , BoolValue : : class , " setBoolValue " , " setBoolValueValue " , " getBoolValue " , " getBoolValueValue " , [ <nl> + [ true , new BoolValue ( [ " value " = > true ] ) ] , <nl> + [ false , new BoolValue ( [ " value " = > false ] ) ] , <nl> + [ null , null ] , <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , StringValue : : class , " setStringValue " , " setStringValueValue " , " getStringValue " , " getStringValueValue " , [ <nl> + [ " asdf " , new StringValue ( [ " value " = > " asdf " ] ) ] , <nl> + [ " " , new StringValue ( [ " value " = > " " ] ) ] , <nl> + [ null , null ] , <nl> + [ " " , new StringValue ( ) ] , <nl> + [ 5 , new StringValue ( [ " value " = > " 5 " ] ) ] , / / Test conversion from number to string <nl> + [ 5 . 5 , new StringValue ( [ " value " = > " 5 . 5 " ] ) ] , / / Test conversion from number to string <nl> + [ - 7 , new StringValue ( [ " value " = > " - 7 " ] ) ] , / / Test conversion from number to string <nl> + [ - 7 . 5 , new StringValue ( [ " value " = > " - 7 . 5 " ] ) ] , / / Test conversion from number to string <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , BytesValue : : class , " setBytesValue " , " setBytesValueValue " , " getBytesValue " , " getBytesValueValue " , [ <nl> + [ " asdf " , new BytesValue ( [ " value " = > " asdf " ] ) ] , <nl> + [ " " , new BytesValue ( [ " value " = > " " ] ) ] , <nl> + [ null , null ] , <nl> + [ " " , new BytesValue ( ) ] , <nl> + [ 5 , new BytesValue ( [ " value " = > " 5 " ] ) ] , / / Test conversion from number to bytes <nl> + [ 5 . 5 , new BytesValue ( [ " value " = > " 5 . 5 " ] ) ] , / / Test conversion from number to bytes <nl> + [ - 7 , new BytesValue ( [ " value " = > " - 7 " ] ) ] , / / Test conversion from number to bytes <nl> + [ - 7 . 5 , new BytesValue ( [ " value " = > " - 7 . 5 " ] ) ] , / / Test conversion from number to bytes <nl> + ] ] , <nl> + [ TestWrapperSetters : : class , DoubleValue : : class , " setDoubleValueOneof " , " setDoubleValueOneofValue " , " getDoubleValueOneof " , " getDoubleValueOneofValue " , [ <nl> + [ 1 . 1 , new DoubleValue ( [ " value " = > 1 . 1 ] ) ] , <nl> + [ 2 . 2 , new DoubleValue ( [ " value " = > 2 . 2 ] ) ] , <nl> + [ null , null ] , <nl> + [ 0 , new DoubleValue ( ) ] , <nl> + ] ] , [ TestWrapperSetters : : class , StringValue : : class , " setStringValueOneof " , " setStringValueOneofValue " , " getStringValueOneof " , " getStringValueOneofValue " , [ <nl> + [ " asdf " , new StringValue ( [ " value " = > " asdf " ] ) ] , <nl> + [ " " , new StringValue ( [ " value " = > " " ] ) ] , <nl> + [ null , null ] , <nl> + [ " " , new StringValue ( ) ] , <nl> + [ 5 , new StringValue ( [ " value " = > " 5 " ] ) ] , / / Test conversion from number to string <nl> + [ 5 . 5 , new StringValue ( [ " value " = > " 5 . 5 " ] ) ] , / / Test conversion from number to string <nl> + [ - 7 , new StringValue ( [ " value " = > " - 7 " ] ) ] , / / Test conversion from number to string <nl> + [ - 7 . 5 , new StringValue ( [ " value " = > " - 7 . 5 " ] ) ] , / / Test conversion from number to string <nl> + ] ] , <nl> + ] ; <nl> + } <nl> + <nl> + / * * <nl> + * @ dataProvider invalidSettersDataProvider <nl> + * @ expectedException \ Exception <nl> + * / <nl> + public function testInvalidSetters ( $ class , $ setter , $ value ) <nl> + { <nl> + ( new $ class ( ) ) - > $ setter ( $ value ) ; <nl> + } <nl> + <nl> + public function invalidSettersDataProvider ( ) <nl> + { <nl> + return [ <nl> + [ TestWrapperSetters : : class , " setDoubleValueValue " , " abc " ] , <nl> + [ TestWrapperSetters : : class , " setDoubleValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setDoubleValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setDoubleValueValue " , new DoubleValue ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setFloatValueValue " , " abc " ] , <nl> + [ TestWrapperSetters : : class , " setFloatValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setFloatValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setFloatValueValue " , new FloatValue ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setInt64ValueValue " , " abc " ] , <nl> + [ TestWrapperSetters : : class , " setInt64ValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setInt64ValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setInt64ValueValue " , new Int64Value ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setUInt64ValueValue " , " abc " ] , <nl> + [ TestWrapperSetters : : class , " setUInt64ValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setUInt64ValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setUInt64ValueValue " , new UInt64Value ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setInt32ValueValue " , " abc " ] , <nl> + [ TestWrapperSetters : : class , " setInt32ValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setInt32ValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setInt32ValueValue " , new Int32Value ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setUInt32ValueValue " , " abc " ] , <nl> + [ TestWrapperSetters : : class , " setUInt32ValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setUInt32ValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setUInt32ValueValue " , new UInt32Value ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setBoolValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setBoolValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setBoolValueValue " , new BoolValue ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setStringValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setStringValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setStringValueValue " , new StringValue ( ) ] , <nl> + <nl> + [ TestWrapperSetters : : class , " setBytesValueValue " , [ ] ] , <nl> + [ TestWrapperSetters : : class , " setBytesValueValue " , new stdClass ( ) ] , <nl> + [ TestWrapperSetters : : class , " setBytesValueValue " , new BytesValue ( ) ] , <nl> + ] ; <nl> + } <nl> + <nl> + / * * <nl> + * @ dataProvider constructorWithWrapperTypeDataProvider <nl> + * / <nl> + public function testConstructorWithWrapperType ( $ class , $ wrapperClass , $ wrapperField , $ getter , $ value ) <nl> + { <nl> + $ actualInstance = new $ class ( [ $ wrapperField = > $ value ] ) ; <nl> + $ expectedInstance = new $ class ( [ $ wrapperField = > new $ wrapperClass ( [ ' value ' = > $ value ] ) ] ) ; <nl> + $ this - > assertEquals ( $ expectedInstance - > $ getter ( ) - > getValue ( ) , $ actualInstance - > $ getter ( ) - > getValue ( ) ) ; <nl> + } <nl> + <nl> + public function constructorWithWrapperTypeDataProvider ( ) <nl> + { <nl> + return [ <nl> + [ TestWrapperSetters : : class , DoubleValue : : class , ' double_value ' , ' getDoubleValue ' , 1 . 1 ] , <nl> + [ TestWrapperSetters : : class , FloatValue : : class , ' float_value ' , ' getFloatValue ' , 2 . 2 ] , <nl> + [ TestWrapperSetters : : class , Int64Value : : class , ' int64_value ' , ' getInt64Value ' , 3 ] , <nl> + [ TestWrapperSetters : : class , UInt64Value : : class , ' uint64_value ' , ' getUInt64Value ' , 4 ] , <nl> + [ TestWrapperSetters : : class , Int32Value : : class , ' int32_value ' , ' getInt32Value ' , 5 ] , <nl> + [ TestWrapperSetters : : class , UInt32Value : : class , ' uint32_value ' , ' getUInt32Value ' , 6 ] , <nl> + [ TestWrapperSetters : : class , BoolValue : : class , ' bool_value ' , ' getBoolValue ' , true ] , <nl> + [ TestWrapperSetters : : class , StringValue : : class , ' string_value ' , ' getStringValue ' , " eight " ] , <nl> + [ TestWrapperSetters : : class , BytesValue : : class , ' bytes_value ' , ' getBytesValue ' , " nine " ] , <nl> + ] ; <nl> + } <nl> + } <nl> mmm a / src / google / protobuf / compiler / php / php_generator . cc <nl> ppp b / src / google / protobuf / compiler / php / php_generator . cc <nl> void GenerateMessageConstructorDocComment ( io : : Printer * printer , <nl> int is_descriptor ) ; <nl> void GenerateFieldDocComment ( io : : Printer * printer , const FieldDescriptor * field , <nl> int is_descriptor , int function_type ) ; <nl> + void GenerateWrapperFieldGetterDocComment ( io : : Printer * printer , <nl> + const FieldDescriptor * field ) ; <nl> + void GenerateWrapperFieldSetterDocComment ( io : : Printer * printer , <nl> + const FieldDescriptor * field ) ; <nl> void GenerateEnumDocComment ( io : : Printer * printer , const EnumDescriptor * enum_ , <nl> int is_descriptor ) ; <nl> void GenerateEnumValueDocComment ( io : : Printer * printer , <nl> void GenerateFieldAccessor ( const FieldDescriptor * field , bool is_descriptor , <nl> field - > name ( ) ) ; <nl> } <nl> <nl> + / / For wrapper types , generate an additional getXXXValue getter <nl> + if ( ! field - > is_map ( ) & & <nl> + ! field - > is_repeated ( ) & & <nl> + field - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_MESSAGE & & <nl> + IsWrapperType ( field ) ) { <nl> + GenerateWrapperFieldGetterDocComment ( printer , field ) ; <nl> + printer - > Print ( <nl> + " public function get ^ camel_name ^ Value ( ) \ n " <nl> + " { \ n " <nl> + " $ wrapper = $ this - > get ^ camel_name ^ ( ) ; \ n " <nl> + " return is_null ( $ wrapper ) ? null : $ wrapper - > getValue ( ) ; \ n " <nl> + " } \ n \ n " , <nl> + " camel_name " , UnderscoresToCamelCase ( field - > name ( ) , true ) ) ; <nl> + } <nl> + <nl> / / Generate setter . <nl> GenerateFieldDocComment ( printer , field , is_descriptor , kFieldSetter ) ; <nl> printer - > Print ( <nl> void GenerateFieldAccessor ( const FieldDescriptor * field , bool is_descriptor , <nl> printer - > Print ( <nl> " } \ n \ n " ) ; <nl> <nl> + / / For wrapper types , generate an additional setXXXValue getter <nl> + if ( ! field - > is_map ( ) & & <nl> + ! field - > is_repeated ( ) & & <nl> + field - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_MESSAGE & & <nl> + IsWrapperType ( field ) ) { <nl> + GenerateWrapperFieldSetterDocComment ( printer , field ) ; <nl> + printer - > Print ( <nl> + " public function set ^ camel_name ^ Value ( $ var ) \ n " <nl> + " { \ n " <nl> + " $ wrappedVar = is_null ( $ var ) ? null : new \ \ ^ wrapper_type ^ ( [ ' value ' = > $ var ] ) ; \ n " <nl> + " return $ this - > set ^ camel_name ^ ( $ wrappedVar ) ; \ n " <nl> + " } \ n \ n " , <nl> + " camel_name " , UnderscoresToCamelCase ( field - > name ( ) , true ) , <nl> + " wrapper_type " , LegacyFullClassName ( field - > message_type ( ) , is_descriptor ) ) ; <nl> + } <nl> + <nl> / / Generate has method for proto2 only . <nl> if ( is_descriptor ) { <nl> printer - > Print ( <nl> void GenerateUseDeclaration ( bool is_descriptor , io : : Printer * printer ) { <nl> printer - > Print ( <nl> " use Google \ \ Protobuf \ \ Internal \ \ GPBType ; \ n " <nl> " use Google \ \ Protobuf \ \ Internal \ \ RepeatedField ; \ n " <nl> - " use Google \ \ Protobuf \ \ Internal \ \ GPBUtil ; \ n \ n " ) ; <nl> + " use Google \ \ Protobuf \ \ Internal \ \ GPBUtil ; \ n " <nl> + " use Google \ \ Protobuf \ \ Internal \ \ GPBWrapperUtils ; \ n \ n " ) ; <nl> } else { <nl> printer - > Print ( <nl> " use Google \ \ Protobuf \ \ Internal \ \ GPBType ; \ n " <nl> " use Google \ \ Protobuf \ \ Internal \ \ GPBWire ; \ n " <nl> " use Google \ \ Protobuf \ \ Internal \ \ RepeatedField ; \ n " <nl> " use Google \ \ Protobuf \ \ Internal \ \ InputStream ; \ n " <nl> - " use Google \ \ Protobuf \ \ Internal \ \ GPBUtil ; \ n \ n " ) ; <nl> + " use Google \ \ Protobuf \ \ Internal \ \ GPBUtil ; \ n " <nl> + " use Google \ \ Protobuf \ \ Internal \ \ GPBWrapperUtils ; \ n \ n " ) ; <nl> } <nl> } <nl> <nl> void GenerateFieldDocComment ( io : : Printer * printer , const FieldDescriptor * field , <nl> printer - > Print ( " * / \ n " ) ; <nl> } <nl> <nl> + void GenerateWrapperFieldGetterDocComment ( io : : Printer * printer , const FieldDescriptor * field ) { <nl> + / / Generate a doc comment for the special getXXXValue methods that are <nl> + / / generated for wrapper types . <nl> + const FieldDescriptor * primitiveField = field - > message_type ( ) - > FindFieldByName ( " value " ) ; <nl> + printer - > Print ( " / * * \ n " ) ; <nl> + printer - > Print ( <nl> + " * Returns the unboxed value from < code > get ^ camel_name ^ ( ) < / code > \ n \ n " , <nl> + " camel_name " , UnderscoresToCamelCase ( field - > name ( ) , true ) ) ; <nl> + GenerateDocCommentBody ( printer , field ) ; <nl> + printer - > Print ( <nl> + " * Generated from protobuf field < code > ^ def ^ < / code > \ n " , <nl> + " def " , EscapePhpdoc ( FirstLineOf ( field - > DebugString ( ) ) ) ) ; <nl> + printer - > Print ( " * @ return ^ php_type ^ | null \ n " , <nl> + " php_type " , PhpGetterTypeName ( primitiveField , false ) ) ; <nl> + printer - > Print ( " * / \ n " ) ; <nl> + } <nl> + <nl> + void GenerateWrapperFieldSetterDocComment ( io : : Printer * printer , const FieldDescriptor * field ) { <nl> + / / Generate a doc comment for the special setXXXValue methods that are <nl> + / / generated for wrapper types . <nl> + const FieldDescriptor * primitiveField = field - > message_type ( ) - > FindFieldByName ( " value " ) ; <nl> + printer - > Print ( " / * * \ n " ) ; <nl> + printer - > Print ( <nl> + " * Sets the field by wrapping a primitive type in a ^ message_name ^ object . \ n \ n " , <nl> + " message_name " , LegacyFullClassName ( field - > message_type ( ) , false ) ) ; <nl> + GenerateDocCommentBody ( printer , field ) ; <nl> + printer - > Print ( <nl> + " * Generated from protobuf field < code > ^ def ^ < / code > \ n " , <nl> + " def " , EscapePhpdoc ( FirstLineOf ( field - > DebugString ( ) ) ) ) ; <nl> + printer - > Print ( " * @ param ^ php_type ^ | null $ var \ n " , <nl> + " php_type " , PhpSetterTypeName ( primitiveField , false ) ) ; <nl> + printer - > Print ( " * @ return $ this \ n " ) ; <nl> + printer - > Print ( " * / \ n " ) ; <nl> + } <nl> + <nl> void GenerateEnumDocComment ( io : : Printer * printer , const EnumDescriptor * enum_ , <nl> int is_descriptor ) { <nl> printer - > Print ( " / * * \ n " ) ; <nl> mmm a / src / google / protobuf / compiler / php / php_generator . h <nl> ppp b / src / google / protobuf / compiler / php / php_generator . h <nl> PROTOC_EXPORT std : : string GeneratedClassName ( <nl> PROTOC_EXPORT std : : string GeneratedClassName ( <nl> const google : : protobuf : : ServiceDescriptor * desc ) ; <nl> <nl> + inline bool IsWrapperType ( const FieldDescriptor * descriptor ) { <nl> + return descriptor - > cpp_type ( ) = = FieldDescriptor : : CPPTYPE_MESSAGE & & <nl> + descriptor - > message_type ( ) - > file ( ) - > name ( ) = = " google / protobuf / wrappers . proto " ; <nl> + } <nl> + <nl> } / / namespace php <nl> } / / namespace compiler <nl> } / / namespace protobuf <nl> mmm a / tests . sh <nl> ppp b / tests . sh <nl> generate_php_test_proto ( ) { <nl> rm - rf generated <nl> mkdir generated <nl> . . / . . / src / protoc - - php_out = generated \ <nl> + - I . . / . . / src - I . \ <nl> proto / empty / echo . proto \ <nl> proto / test . proto \ <nl> proto / test_include . proto \ <nl> generate_php_test_proto ( ) { <nl> proto / test_reserved_message_upper . proto \ <nl> proto / test_service . proto \ <nl> proto / test_service_namespace . proto \ <nl> + proto / test_wrapper_type_setters . proto \ <nl> proto / test_descriptors . proto <nl> pushd . . / . . / src <nl> . / protoc - - php_out = . . / php / tests / generated - I . . / php / tests - I . \ <nl>
PHP : Add support for primitive types in setters ( )
protocolbuffers/protobuf
6a51c03823448a9229c50795ae0d984ac0fe4fbd
2018-10-07T23:56:41Z
mmm a / docs / source / community / contribution_guide . rst <nl> ppp b / docs / source / community / contribution_guide . rst <nl> the best entrance point are great places to start . <nl> Adding Tutorials <nl> ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ <nl> <nl> - A great deal of the tutorials on ` pytorch . org < http : / / pytorch . org / > ` __ <nl> + A great deal of the tutorials on ` pytorch . org < https : / / pytorch . org / > ` __ <nl> come from the community itself and we welcome additional contributions . <nl> To learn more about how to contribute a new tutorial you can learn more <nl> here : ` PyTorch . org Tutorial Contribution Guide on <nl> Python Docs <nl> ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ <nl> <nl> PyTorch documentation is generated from python source using <nl> - ` Sphinx < http : / / www . sphinx - doc . org / en / master / > ` __ . Generated HTML is <nl> + ` Sphinx < https : / / www . sphinx - doc . org / en / master / > ` __ . Generated HTML is <nl> copied to the docs folder in the master branch of <nl> ` pytorch . github . io < https : / / github . com / pytorch / pytorch . github . io / tree / master / docs > ` __ , <nl> and is served via GitHub pages . <nl> <nl> - - Site : http : / / pytorch . org / docs <nl> + - Site : https : / / pytorch . org / docs <nl> - GitHub : https : / / github . com / pytorch / pytorch / tree / master / docs <nl> - Served from : <nl> ` https : / / github . com / pytorch / pytorch . github . io / tree / master / doc < https : / / github . com / pytorch / pytorch . github . io / tree / master / docs > ` __ <nl> are built on a special server and the resulting files are copied to the <nl> https : / / github . com / pytorch / cppdocs repo , and are served from GitHub <nl> pages . <nl> <nl> - - Site : http : / / pytorch . org / cppdocs <nl> + - Site : https : / / pytorch . org / cppdocs <nl> - GitHub : https : / / github . com / pytorch / pytorch / tree / master / docs / cpp <nl> - Served from : https : / / github . com / pytorch / cppdocs <nl> <nl> Tutorials are built using <nl> from executable python sources files , or from restructured - text ( rst ) <nl> files . <nl> <nl> - - Site : http : / / pytorch . org / tutorials <nl> - - GitHub : http : / / github . com / pytorch / tutorials <nl> + - Site : https : / / pytorch . org / tutorials <nl> + - GitHub : https : / / github . com / pytorch / tutorials <nl> <nl> Tutorials Build Overview <nl> ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ <nl> mmm a / docs / source / notes / cuda . rst <nl> ppp b / docs / source / notes / cuda . rst <nl> necessary synchronization when data is moved around , as explained above . <nl> However , when using non - default streams , it is the user ' s responsibility to <nl> ensure proper synchronization . <nl> <nl> - . . _CUDA stream : http : / / docs . nvidia . com / cuda / cuda - c - programming - guide / index . html # streams <nl> + . . _CUDA stream : https : / / docs . nvidia . com / cuda / cuda - c - programming - guide / index . html # streams <nl> <nl> . . _cuda - memory - management : <nl> <nl> mmm a / torch / _lowrank . py <nl> ppp b / torch / _lowrank . py <nl> def svd_lowrank ( A , q = 6 , niter = 2 , M = None ) : <nl> structure with randomness : probabilistic algorithms for <nl> constructing approximate matrix decompositions , <nl> arXiv : 0909 . 4061 [ math . NA ; math . PR ] , 2009 ( available at <nl> - ` arXiv < http : / / arxiv . org / abs / 0909 . 4061 > ` _ ) . <nl> + ` arXiv < https : / / arxiv . org / abs / 0909 . 4061 > ` _ ) . <nl> <nl> " " " <nl> if not torch . jit . is_scripting ( ) : <nl> mmm a / torch / cuda / streams . py <nl> ppp b / torch / cuda / streams . py <nl> def wait_event ( self , event ) : <nl> operations are affected . <nl> <nl> . . _CUDA Stream documentation : <nl> - http : / / docs . nvidia . com / cuda / cuda - runtime - api / group__CUDART__STREAM . html <nl> + https : / / docs . nvidia . com / cuda / cuda - runtime - api / group__CUDART__STREAM . html <nl> " " " <nl> event . wait ( self ) <nl> <nl> mmm a / torch / nn / modules / dropout . py <nl> ppp b / torch / nn / modules / dropout . py <nl> class Dropout2d ( _DropoutNd ) : <nl> > > > output = m ( input ) <nl> <nl> . . _Efficient Object Localization Using Convolutional Networks : <nl> - http : / / arxiv . org / abs / 1411 . 4280 <nl> + https : / / arxiv . org / abs / 1411 . 4280 <nl> " " " <nl> <nl> def forward ( self , input : Tensor ) - > Tensor : <nl> class Dropout3d ( _DropoutNd ) : <nl> > > > output = m ( input ) <nl> <nl> . . _Efficient Object Localization Using Convolutional Networks : <nl> - http : / / arxiv . org / abs / 1411 . 4280 <nl> + https : / / arxiv . org / abs / 1411 . 4280 <nl> " " " <nl> <nl> def forward ( self , input : Tensor ) - > Tensor : <nl> class FeatureAlphaDropout ( _DropoutNd ) : <nl> <nl> . . _Self - Normalizing Neural Networks : https : / / arxiv . org / abs / 1706 . 02515 <nl> . . _Efficient Object Localization Using Convolutional Networks : <nl> - http : / / arxiv . org / abs / 1411 . 4280 <nl> + https : / / arxiv . org / abs / 1411 . 4280 <nl> " " " <nl> <nl> def forward ( self , input : Tensor ) - > Tensor : <nl> mmm a / torch / nn / modules / pooling . py <nl> ppp b / torch / nn / modules / pooling . py <nl> class FractionalMaxPool2d ( Module ) : <nl> > > > output = m ( input ) <nl> <nl> . . _Fractional MaxPooling : <nl> - http : / / arxiv . org / abs / 1412 . 6071 <nl> + https : / / arxiv . org / abs / 1412 . 6071 <nl> " " " <nl> __constants__ = [ ' kernel_size ' , ' return_indices ' , ' output_size ' , <nl> ' output_ratio ' ] <nl> class FractionalMaxPool3d ( Module ) : <nl> > > > output = m ( input ) <nl> <nl> . . _Fractional MaxPooling : <nl> - http : / / arxiv . org / abs / 1412 . 6071 <nl> + https : / / arxiv . org / abs / 1412 . 6071 <nl> " " " <nl> __constants__ = [ ' kernel_size ' , ' return_indices ' , ' output_size ' , <nl> ' output_ratio ' ] <nl> mmm a / torch / optim / asgd . py <nl> ppp b / torch / optim / asgd . py <nl> class ASGD ( Optimizer ) : <nl> weight_decay ( float , optional ) : weight decay ( L2 penalty ) ( default : 0 ) <nl> <nl> . . _Acceleration of stochastic approximation by averaging : <nl> - http : / / dl . acm . org / citation . cfm ? id = 131098 <nl> + https : / / dl . acm . org / citation . cfm ? id = 131098 <nl> " " " <nl> <nl> def __init__ ( self , params , lr = 1e - 2 , lambd = 1e - 4 , alpha = 0 . 75 , t0 = 1e6 , weight_decay = 0 ) : <nl> mmm a / torch / optim / rmsprop . py <nl> ppp b / torch / optim / rmsprop . py <nl> class RMSprop ( Optimizer ) : <nl> r " " " Implements RMSprop algorithm . <nl> <nl> Proposed by G . Hinton in his <nl> - ` course < http : / / www . cs . toronto . edu / ~ tijmen / csc321 / slides / lecture_slides_lec6 . pdf > ` _ . <nl> + ` course < https : / / www . cs . toronto . edu / ~ tijmen / csc321 / slides / lecture_slides_lec6 . pdf > ` _ . <nl> <nl> The centered version first appears in ` Generating Sequences <nl> With Recurrent Neural Networks < https : / / arxiv . org / pdf / 1308 . 0850v5 . pdf > ` _ . <nl> mmm a / torch / quasirandom . py <nl> ppp b / torch / quasirandom . py <nl> class SobolEngine ( object ) : <nl> This implementation of an engine for Sobol sequences is capable of <nl> sampling sequences up to a maximum dimension of 1111 . It uses direction <nl> numbers to generate these sequences , and these numbers have been adapted <nl> - from ` here < http : / / web . maths . unsw . edu . au / ~ fkuo / sobol / joe - kuo - old . 1111 > ` _ . <nl> + from ` here < https : / / web . maths . unsw . edu . au / ~ fkuo / sobol / joe - kuo - old . 1111 > ` _ . <nl> <nl> References : <nl> - Art B . Owen . Scrambling Sobol and Niederreiter - Xing points . <nl>
Fix HTTP links in documentation to HTTPS ( )
pytorch/pytorch
6b50874cb70f27020b88d16ce8e7fc6a186549ee
2020-07-07T03:05:21Z
mmm a / . cicd / generate - serial - tests . sh <nl> ppp b / . cicd / generate - serial - tests . sh <nl> cat < < EOF <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 20 } <nl> skip : \ $ { SKIP_ $ { PLATFORM_NAME_UPCASE } _ $ { VERSION_MAJOR } } \ $ { SKIP_SERIAL_TESTS } <nl> EOF <nl> done <nl> mmm a / . cicd / pipeline . yml <nl> ppp b / . cicd / pipeline . yml <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_AMAZON_LINUX_2 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : centos : CentOS 7 . 6 - Long - Running Tests " <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_CENTOS_7 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : ubuntu : Ubuntu 16 . 04 - Long - Running Tests " <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_UBUNTU_16 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : ubuntu : Ubuntu 18 . 04 - Long - Running Tests " <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_UBUNTU_18 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : darwin : macOS 10 . 14 - Long - Running Tests " <nl> steps : <nl> wait - network : true <nl> agents : <nl> - " queue = mac - anka - large - node - fleet " <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_MOJAVE } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - wait : <nl> mmm a / . cicd / unpinned . yml <nl> ppp b / . cicd / unpinned . yml <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_AMAZON_LINUX_2 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : centos : CentOS 7 . 6 - Long - Running Tests " <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_CENTOS_7 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : ubuntu : Ubuntu 16 . 04 - Long - Running Tests " <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_UBUNTU_16 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : ubuntu : Ubuntu 18 . 04 - Long - Running Tests " <nl> steps : <nl> BUILDKITE_AGENT_ACCESS_TOKEN : <nl> agents : <nl> queue : " automation - eos - builder - fleet " <nl> - timeout : $ { TIMEOUT : - 10 } <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_UBUNTU_18 } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - label : " : darwin : macOS 10 . 14 - Long - Running Tests " <nl> steps : <nl> wait - network : true <nl> agents : <nl> - " queue = mac - anka - large - node - fleet " <nl> + timeout : $ { TIMEOUT : - 90 } <nl> skip : $ { SKIP_MOJAVE } $ { SKIP_LONG_RUNNING_TESTS : - true } <nl> <nl> - wait : <nl>
Increase timeouts on non - parallelizable tests
EOSIO/eos
1b37a1d6ed11c81514c8f31cc6b3470ed8669f5d
2019-08-30T14:56:55Z
mmm a / classify / Makefile . am <nl> ppp b / classify / Makefile . am <nl> AM_CPPFLAGS = \ <nl> include_HEADERS = \ <nl> adaptive . h baseline . h blobclass . h chartoname . h \ <nl> classify . h cluster . h clusttool . h cutoffs . h \ <nl> - extern . h extract . h \ <nl> + errorcounter . h extern . h extract . h \ <nl> featdefs . h flexfx . h float2int . h fpoint . h fxdefs . h \ <nl> + intfeaturedist . h intfeaturemap . h intfeaturespace . h \ <nl> intfx . h intmatcher . h intproto . h kdtree . h \ <nl> - mf . h mfdefs . h mfoutline . h mfx . h \ <nl> + mastertrainer . h mf . h mfdefs . h mfoutline . h mfx . h \ <nl> normfeat . h normmatch . h \ <nl> ocrfeatures . h outfeat . h picofeat . h protos . h \ <nl> - speckle . h xform2d . h <nl> + sampleiterator . h shapeclassifier . h shapetable . h \ <nl> + speckle . h tessclassifier . h trainingsample . h trainingsampleset . h xform2d . h <nl> <nl> if ! USING_MULTIPLELIBS <nl> noinst_LTLIBRARIES = libtesseract_classify . la <nl> endif <nl> libtesseract_classify_la_SOURCES = \ <nl> adaptive . cpp adaptmatch . cpp blobclass . cpp \ <nl> chartoname . cpp classify . cpp cluster . cpp clusttool . cpp cutoffs . cpp \ <nl> - extract . cpp \ <nl> + errorcounter . cpp extract . cpp \ <nl> featdefs . cpp flexfx . cpp float2int . cpp fpoint . cpp fxdefs . cpp \ <nl> + intfeaturedist . cpp intfeaturemap . cpp intfeaturespace . cpp \ <nl> intfx . cpp intmatcher . cpp intproto . cpp kdtree . cpp \ <nl> - mf . cpp mfdefs . cpp mfoutline . cpp mfx . cpp \ <nl> + mastertrainer . cpp mf . cpp mfdefs . cpp mfoutline . cpp mfx . cpp \ <nl> normfeat . cpp normmatch . cpp \ <nl> ocrfeatures . cpp outfeat . cpp picofeat . cpp protos . cpp \ <nl> - speckle . cpp xform2d . cpp <nl> + sampleiterator . cpp shapetable . cpp speckle . cpp \ <nl> + tessclassifier . cpp trainingsample . cpp trainingsampleset . cpp xform2d . cpp <nl> <nl> <nl> mmm a / classify / adaptmatch . cpp <nl> ppp b / classify / adaptmatch . cpp <nl> <nl> # include " pageres . h " <nl> # include " params . h " <nl> # include " classify . h " <nl> + # include " shapetable . h " <nl> + # include " tessclassifier . h " <nl> + # include " trainingsample . h " <nl> # include " unicharset . h " <nl> # include " dict . h " <nl> # include " featdefs . h " <nl> + # include " genericvector . h " <nl> <nl> # include < stdio . h > <nl> # include < string . h > <nl> - # include < ctype . h > <nl> # include < stdlib . h > <nl> # include < math . h > <nl> # ifdef __UNIX__ <nl> <nl> # define WORST_POSSIBLE_RATING ( 1 . 0 ) <nl> <nl> struct ScoredClass { <nl> - CLASS_ID id ; <nl> + CLASS_ID unichar_id ; <nl> + int shape_id ; <nl> FLOAT32 rating ; <nl> + bool adapted ; <nl> inT16 config ; <nl> - inT16 config2 ; <nl> inT16 fontinfo_id ; <nl> inT16 fontinfo_id2 ; <nl> } ; <nl> struct ADAPT_RESULTS { <nl> BlobLength = MAX_INT32 ; <nl> NumMatches = 0 ; <nl> HasNonfragment = false ; <nl> - best_match . id = NO_CLASS ; <nl> + best_match . unichar_id = NO_CLASS ; <nl> + best_match . shape_id = - 1 ; <nl> best_match . rating = WORST_POSSIBLE_RATING ; <nl> + best_match . adapted = false ; <nl> best_match . config = 0 ; <nl> - best_match . config2 = 0 ; <nl> best_match . fontinfo_id = kBlankFontinfoId ; <nl> best_match . fontinfo_id2 = kBlankFontinfoId ; <nl> } <nl> namespace tesseract { <nl> * <nl> * / <nl> void Classify : : AdaptiveClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> BLOB_CHOICE_LIST * Choices , <nl> CLASS_PRUNER_RESULTS CPResults ) { <nl> assert ( Choices ! = NULL ) ; <nl> void Classify : : AdaptiveClassifier ( TBLOB * Blob , <nl> <nl> Results - > Initialize ( ) ; <nl> <nl> - DoAdaptiveMatch ( Blob , Results ) ; <nl> + DoAdaptiveMatch ( Blob , denorm , Results ) ; <nl> if ( CPResults ! = NULL ) <nl> memcpy ( CPResults , Results - > CPResults , <nl> sizeof ( CPResults [ 0 ] ) * Results - > NumMatches ) ; <nl> void Classify : : AdaptiveClassifier ( TBLOB * Blob , <nl> qsort ( ( void * ) Results - > match , Results - > NumMatches , <nl> sizeof ( ScoredClass ) , CompareByRating ) ; <nl> RemoveExtraPuncs ( Results ) ; <nl> - ConvertMatchesToChoices ( Results , Choices ) ; <nl> + ConvertMatchesToChoices ( denorm , Blob - > bounding_box ( ) , Results , Choices ) ; <nl> <nl> if ( matcher_debug_level > = 1 ) { <nl> cprintf ( " AD Matches = " ) ; <nl> void Classify : : AdaptiveClassifier ( TBLOB * Blob , <nl> <nl> # ifndef GRAPHICS_DISABLED <nl> if ( classify_enable_adaptive_debugger ) <nl> - DebugAdaptiveClassifier ( Blob , Results ) ; <nl> + DebugAdaptiveClassifier ( Blob , denorm , Results ) ; <nl> # endif <nl> <nl> NumClassesOutput + = Choices - > length ( ) ; <nl> void Classify : : AdaptiveClassifier ( TBLOB * Blob , <nl> Choices = new BLOB_CHOICE_LIST ( ) ; <nl> BLOB_CHOICE_IT temp_it ; <nl> temp_it . set_to_list ( Choices ) ; <nl> - temp_it . add_to_end ( new BLOB_CHOICE ( 0 , 50 . 0f , - 20 . 0f , - 1 , - 1 , NULL ) ) ; <nl> + temp_it . add_to_end ( <nl> + new BLOB_CHOICE ( 0 , 50 . 0f , - 20 . 0f , - 1 , - 1 , NULL , 0 , 0 , false ) ) ; <nl> } <nl> <nl> delete Results ; <nl> void Classify : : LearnWord ( const char * filename , const char * rejmap , <nl> float * thresholds = NULL ; <nl> if ( filename = = NULL ) { <nl> / / Adaption mode . <nl> - if ( ! EnableLearning | | word - > best_choice = = NULL ) <nl> + if ( ! EnableLearning | | word - > best_choice = = NULL | | <nl> + / / If word - > best_choice is not recorded at the top of accumulator ' s <nl> + / / best choices ( which could happen for choices that are <nl> + / / altered with ReplaceAmbig ( ) ) we skip the adaption . <nl> + ! getDict ( ) . CurrentBestChoiceIs ( * ( word - > best_choice ) ) ) <nl> return ; / / Can ' t or won ' t adapt . <nl> <nl> NumWordsAdaptedTo + + ; <nl> if ( classify_learning_debug_level > = 1 ) <nl> tprintf ( " \ n \ nAdapting to word = % s \ n " , <nl> - word - > best_choice - > debug_string ( unicharset ) . string ( ) ) ; <nl> + word - > best_choice - > debug_string ( ) . string ( ) ) ; <nl> thresholds = new float [ word_len ] ; <nl> - GetAdaptThresholds ( word - > rebuild_word , * word - > best_choice , <nl> + GetAdaptThresholds ( word - > rebuild_word , word - > denorm , * word - > best_choice , <nl> * word - > raw_choice , thresholds ) ; <nl> } <nl> int start_blob = 0 ; <nl> void Classify : : LearnWord ( const char * filename , const char * rejmap , <nl> if ( word - > correct_text [ ch ] . length ( ) > 0 & & rej_map_char = = ' 1 ' ) { <nl> float threshold = thresholds ! = NULL ? thresholds [ ch ] : 0 . 0f ; <nl> <nl> + LearnPieces ( filename , start_blob , word - > best_state [ ch ] , <nl> + threshold , CST_WHOLE , word - > correct_text [ ch ] . string ( ) , word ) ; <nl> + <nl> if ( word - > best_state [ ch ] > 1 & & ! disable_character_fragments ) { <nl> / / Check that the character breaks into meaningful fragments <nl> / / that each match a whole character with at least <nl> void Classify : : LearnWord ( const char * filename , const char * rejmap , <nl> int frag ; <nl> for ( frag = 0 ; frag < word - > best_state [ ch ] ; + + frag ) { <nl> if ( classify_character_fragments_garbage_certainty_threshold < 0 ) { <nl> - garbage | = LooksLikeGarbage ( frag_blob ) ; <nl> + garbage | = LooksLikeGarbage ( word - > denorm , frag_blob ) ; <nl> } <nl> frag_blob = frag_blob - > next ; <nl> } <nl> / / Learn the fragments . <nl> if ( ! garbage ) { <nl> - for ( frag = 0 ; frag < word - > best_state [ ch ] ; + + frag ) { <nl> - STRING frag_str = CHAR_FRAGMENT : : to_string ( <nl> - word - > correct_text [ ch ] . string ( ) , frag , word - > best_state [ ch ] ) ; <nl> - LearnPieces ( filename , start_blob + frag , 1 , <nl> - threshold , CST_FRAGMENT , frag_str . string ( ) , word ) ; <nl> + bool pieces_all_natural = word - > PiecesAllNatural ( start_blob , <nl> + word - > best_state [ ch ] ) ; <nl> + if ( pieces_all_natural | | ! prioritize_division ) { <nl> + for ( frag = 0 ; frag < word - > best_state [ ch ] ; + + frag ) { <nl> + GenericVector < STRING > tokens ; <nl> + word - > correct_text [ ch ] . split ( ' ' , & tokens ) ; <nl> + <nl> + tokens [ 0 ] = CHAR_FRAGMENT : : to_string ( <nl> + tokens [ 0 ] . string ( ) , frag , word - > best_state [ ch ] , <nl> + pieces_all_natural ) ; <nl> + <nl> + STRING full_string ; <nl> + for ( int i = 0 ; i < tokens . size ( ) ; i + + ) { <nl> + full_string + = tokens [ i ] ; <nl> + if ( i ! = tokens . size ( ) - 1 ) <nl> + full_string + = ' ' ; <nl> + } <nl> + LearnPieces ( filename , start_blob + frag , 1 , <nl> + threshold , CST_FRAGMENT , full_string . string ( ) , word ) ; <nl> + } <nl> } <nl> } <nl> } <nl> <nl> - LearnPieces ( filename , start_blob , word - > best_state [ ch ] , <nl> - threshold , CST_WHOLE , word - > correct_text [ ch ] . string ( ) , word ) ; <nl> - <nl> / / TODO ( rays ) : re - enable this part of the code when we switch to the <nl> / / new classifier that needs to see examples of garbage . <nl> / * <nl> void Classify : : LearnPieces ( const char * filename , int start , int length , <nl> TBLOB * blob = word - > chopped_word - > blobs ; <nl> for ( int i = 0 ; i < start ; + + i ) <nl> blob = blob - > next ; <nl> + / / Rotate the blob if needed for classification . <nl> + const DENORM * denorm = & word - > denorm ; <nl> + TBLOB * rotated_blob = blob - > ClassifyNormalizeIfNeeded ( & denorm ) ; <nl> + if ( rotated_blob = = NULL ) <nl> + rotated_blob = blob ; <nl> <nl> / / Draw debug windows showing the blob that is being learned if needed . <nl> if ( strcmp ( classify_learn_debug_str . string ( ) , correct_text ) = = 0 ) { <nl> RefreshDebugWindow ( & learn_debug_win_ , " LearnPieces " , 600 , <nl> word - > chopped_word - > bounding_box ( ) ) ; <nl> - blob - > plot ( learn_debug_win_ , ScrollView : : GREEN , ScrollView : : BROWN ) ; <nl> + rotated_blob - > plot ( learn_debug_win_ , ScrollView : : GREEN , ScrollView : : BROWN ) ; <nl> learn_debug_win_ - > Update ( ) ; <nl> window_wait ( learn_debug_win_ ) ; <nl> } <nl> void Classify : : LearnPieces ( const char * filename , int start , int length , <nl> classify_norm_method . set_value ( character ) ; / / force char norm spc 30 / 11 / 93 <nl> tess_bn_matching . set_value ( false ) ; / / turn it off <nl> tess_cn_matching . set_value ( false ) ; <nl> - LearnBlob ( feature_defs_ , filename , blob , word - > denorm , correct_text ) ; <nl> - } else { <nl> - if ( ! unicharset . contains_unichar ( correct_text ) ) { <nl> - unicharset . unichar_insert ( correct_text ) ; <nl> - / / TODO ( rays ) We may need to worry about exceeding MAX_NUM_CLASSES . <nl> - / / if ( unicharset_boxes - > size ( ) > MAX_NUM_CLASSES ) . . . <nl> - } <nl> + LearnBlob ( feature_defs_ , filename , rotated_blob , * denorm , <nl> + correct_text ) ; <nl> + } else if ( unicharset . contains_unichar ( correct_text ) ) { <nl> UNICHAR_ID class_id = unicharset . unichar_to_id ( correct_text ) ; <nl> + int font_id = word - > fontinfo ! = NULL <nl> + ? fontinfo_table_ . get_id ( * word - > fontinfo ) <nl> + : 0 ; <nl> if ( classify_learning_debug_level > = 1 ) <nl> tprintf ( " Adapting to char = % s , thr = % g font_id = % d \ n " , <nl> - unicharset . id_to_unichar ( class_id ) , threshold , word - > fontinfo_id ) ; <nl> + unicharset . id_to_unichar ( class_id ) , threshold , font_id ) ; <nl> / / If filename is not NULL we are doing recognition <nl> / / ( as opposed to training ) , so we must have already set word fonts . <nl> - AdaptToChar ( blob , class_id , word - > fontinfo_id , threshold ) ; <nl> + AdaptToChar ( rotated_blob , * denorm , class_id , font_id , threshold ) ; <nl> + } else if ( classify_debug_level > = 1 ) { <nl> + tprintf ( " Can ' t adapt to % s not in unicharset \ n " , correct_text ) ; <nl> + } <nl> + if ( rotated_blob ! = blob ) { <nl> + delete rotated_blob ; <nl> + delete denorm ; <nl> } <nl> <nl> break_pieces ( blob , word - > seam_array , start , start + length - 1 ) ; <nl> void Classify : : EndAdaptiveClassifier ( ) { <nl> AllConfigsOff = NULL ; <nl> TempProtoMask = NULL ; <nl> } <nl> + delete shape_table_ ; <nl> + shape_table_ = NULL ; <nl> } / * EndAdaptiveClassifier * / <nl> <nl> <nl> void Classify : : InitAdaptiveClassifier ( bool load_pre_trained_templates ) { <nl> ReadIntTemplates ( tessdata_manager . GetDataFilePtr ( ) ) ; <nl> if ( tessdata_manager . DebugLevel ( ) > 0 ) tprintf ( " Loaded inttemp \ n " ) ; <nl> <nl> + if ( tessdata_manager . SeekToStart ( TESSDATA_SHAPE_TABLE ) ) { <nl> + shape_table_ = new ShapeTable ( unicharset ) ; <nl> + if ( ! shape_table_ - > DeSerialize ( tessdata_manager . swap ( ) , <nl> + tessdata_manager . GetDataFilePtr ( ) ) ) { <nl> + tprintf ( " Error loading shape table ! \ n " ) ; <nl> + delete shape_table_ ; <nl> + shape_table_ = NULL ; <nl> + } else if ( tessdata_manager . DebugLevel ( ) > 0 ) { <nl> + tprintf ( " Successfully loaded shape table ! \ n " ) ; <nl> + } <nl> + } <nl> + <nl> ASSERT_HOST ( tessdata_manager . SeekToStart ( TESSDATA_PFFMTABLE ) ) ; <nl> ReadNewCutoffs ( tessdata_manager . GetDataFilePtr ( ) , <nl> + tessdata_manager . swap ( ) , <nl> tessdata_manager . GetEndOffset ( TESSDATA_PFFMTABLE ) , <nl> CharNormCutoffs ) ; <nl> if ( tessdata_manager . DebugLevel ( ) > 0 ) tprintf ( " Loaded pffmtable \ n " ) ; <nl> void Classify : : InitAdaptiveClassifier ( bool load_pre_trained_templates ) { <nl> } <nl> } / * InitAdaptiveClassifier * / <nl> <nl> - void Classify : : ResetAdaptiveClassifier ( ) { <nl> + void Classify : : ResetAdaptiveClassifierInternal ( ) { <nl> if ( classify_learning_debug_level > 0 ) { <nl> tprintf ( " Resetting adaptive classifier ( NumAdaptationsFailed = % d ) \ n " , <nl> NumAdaptationsFailed ) ; <nl> void Classify : : PrintAdaptiveStatistics ( FILE * File ) { <nl> * enabled then it will remain enabled on the first pass . If it is <nl> * disabled , then it will remain disabled . This is only put here to <nl> * make it very clear that learning is controlled directly by the global <nl> - * setting of EnableLearning . <nl> + * setting of EnableLearning . <nl> * <nl> * Globals : <nl> * - # EnableLearning <nl> void Classify : : SettupPass2 ( ) { <nl> * @ note History : Thu Mar 14 12 : 49 : 39 1991 , DSJ , Created . <nl> * / <nl> void Classify : : InitAdaptedClass ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> int FontinfoId , <nl> ADAPT_CLASS Class , <nl> void Classify : : InitAdaptedClass ( TBLOB * Blob , <nl> cprintf ( " Added new class ' % s ' with class id % d and % d protos . \ n " , <nl> unicharset . id_to_unichar ( ClassId ) , ClassId , NumFeatures ) ; <nl> if ( classify_learning_debug_level > 1 ) <nl> - DisplayAdaptedChar ( Blob , IClass ) ; <nl> + DisplayAdaptedChar ( Blob , denorm , IClass ) ; <nl> } <nl> <nl> if ( IsEmptyAdaptedClass ( Class ) ) <nl> int Classify : : AdaptableWord ( TWERD * Word , <nl> int BestChoiceLength = BestChoiceWord . length ( ) ; <nl> float adaptable_score = <nl> getDict ( ) . segment_penalty_dict_case_ok + ADAPTABLE_WERD_ADJUSTMENT ; <nl> - return ( / / rules that apply in general - simplest to compute first <nl> - BestChoiceLength > 0 & & <nl> - BestChoiceLength = = Word - > NumBlobs ( ) & & <nl> - BestChoiceLength < = MAX_ADAPTABLE_WERD_SIZE & & ( <nl> - ( classify_enable_new_adapt_rules & & <nl> - getDict ( ) . CurrentBestChoiceAdjustFactor ( ) < = adaptable_score & & <nl> - getDict ( ) . AlternativeChoicesWorseThan ( adaptable_score ) & & <nl> - getDict ( ) . CurrentBestChoiceIs ( BestChoiceWord ) ) | | <nl> - ( ! classify_enable_new_adapt_rules & & / / old rules <nl> - BestChoiceLength = = RawChoiceWord . length ( ) & & <nl> - ( ( getDict ( ) . valid_word_or_number ( BestChoiceWord ) & & <nl> - getDict ( ) . case_ok ( BestChoiceWord , getDict ( ) . getUnicharset ( ) ) ) ) ) ) ) ; <nl> + return / / rules that apply in general - simplest to compute first <nl> + BestChoiceLength > 0 & & <nl> + BestChoiceLength = = Word - > NumBlobs ( ) & & <nl> + BestChoiceLength < = MAX_ADAPTABLE_WERD_SIZE & & <nl> + getDict ( ) . CurrentBestChoiceAdjustFactor ( ) < = adaptable_score & & <nl> + getDict ( ) . AlternativeChoicesWorseThan ( adaptable_score ) & & <nl> + getDict ( ) . CurrentBestChoiceIs ( BestChoiceWord ) ; <nl> } <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> int Classify : : AdaptableWord ( TWERD * Word , <nl> * @ note History : Thu Mar 14 09 : 36 : 03 1991 , DSJ , Created . <nl> * / <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> int FontinfoId , <nl> FLOAT32 Threshold ) { <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> Class = AdaptedTemplates - > Class [ ClassId ] ; <nl> assert ( Class ! = NULL ) ; <nl> if ( IsEmptyAdaptedClass ( Class ) ) { <nl> - InitAdaptedClass ( Blob , ClassId , FontinfoId , Class , AdaptedTemplates ) ; <nl> + InitAdaptedClass ( Blob , denorm , ClassId , FontinfoId , Class , <nl> + AdaptedTemplates ) ; <nl> } <nl> else { <nl> IClass = ClassForClassId ( AdaptedTemplates - > Templates , ClassId ) ; <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> } <nl> } <nl> im_ . Match ( IClass , AllProtosOn , MatchingFontConfigs , <nl> - NumFeatures , NumFeatures , IntFeatures , 0 , <nl> + NumFeatures , IntFeatures , <nl> & IntResult , classify_adapt_feature_threshold , <nl> NO_DEBUG , matcher_debug_separate_windows ) ; <nl> FreeBitVector ( MatchingFontConfigs ) ; <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> IntResult . Config , TempConfig - > NumTimesSeen ) ; <nl> <nl> if ( TempConfigReliable ( ClassId , TempConfig ) ) { <nl> - MakePermanent ( AdaptedTemplates , ClassId , IntResult . Config , Blob ) ; <nl> - UpdateAmbigsGroup ( ClassId , Blob ) ; <nl> + MakePermanent ( AdaptedTemplates , ClassId , IntResult . Config , denorm , <nl> + Blob ) ; <nl> + UpdateAmbigsGroup ( ClassId , denorm , Blob ) ; <nl> } <nl> } <nl> else { <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> cprintf ( " Found poor match to temp config % d = % 4 . 1f % % . \ n " , <nl> IntResult . Config , ( 1 . 0 - IntResult . Rating ) * 100 . 0 ) ; <nl> if ( classify_learning_debug_level > 2 ) <nl> - DisplayAdaptedChar ( Blob , IClass ) ; <nl> + DisplayAdaptedChar ( Blob , denorm , IClass ) ; <nl> } <nl> NewTempConfigId = MakeNewTemporaryConfig ( AdaptedTemplates , <nl> ClassId , <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> FloatFeatures ) ; <nl> if ( NewTempConfigId > = 0 & & <nl> TempConfigReliable ( ClassId , TempConfigFor ( Class , NewTempConfigId ) ) ) { <nl> - MakePermanent ( AdaptedTemplates , ClassId , NewTempConfigId , Blob ) ; <nl> - UpdateAmbigsGroup ( ClassId , Blob ) ; <nl> + MakePermanent ( AdaptedTemplates , ClassId , NewTempConfigId , denorm , Blob ) ; <nl> + UpdateAmbigsGroup ( ClassId , denorm , Blob ) ; <nl> } <nl> <nl> # ifndef GRAPHICS_DISABLED <nl> if ( classify_learning_debug_level > 1 ) { <nl> - DisplayAdaptedChar ( Blob , IClass ) ; <nl> + DisplayAdaptedChar ( Blob , denorm , IClass ) ; <nl> } <nl> # endif <nl> } <nl> void Classify : : AdaptToChar ( TBLOB * Blob , <nl> } <nl> } / * AdaptToChar * / <nl> <nl> - void Classify : : DisplayAdaptedChar ( TBLOB * blob , INT_CLASS_STRUCT * int_class ) { <nl> + void Classify : : DisplayAdaptedChar ( TBLOB * blob , const DENORM & denorm , <nl> + INT_CLASS_STRUCT * int_class ) { <nl> # ifndef GRAPHICS_DISABLED <nl> int bloblength = 0 ; <nl> INT_FEATURE_ARRAY features ; <nl> - CLASS_NORMALIZATION_ARRAY norm_array ; <nl> - int num_features = GetBaselineFeatures ( blob , PreTrainedTemplates , features , <nl> + uinT8 * norm_array = new uinT8 [ unicharset . size ( ) ] ; <nl> + int num_features = GetBaselineFeatures ( blob , denorm , PreTrainedTemplates , <nl> + features , <nl> norm_array , & bloblength ) ; <nl> + delete [ ] norm_array ; <nl> INT_RESULT_STRUCT IntResult ; <nl> <nl> im_ . Match ( int_class , AllProtosOn , AllConfigsOn , <nl> - num_features , num_features , features , 0 , <nl> + num_features , features , <nl> & IntResult , classify_adapt_feature_threshold , <nl> NO_DEBUG , matcher_debug_separate_windows ) ; <nl> cprintf ( " Best match to temp config % d = % 4 . 1f % % . \ n " , <nl> void Classify : : DisplayAdaptedChar ( TBLOB * blob , INT_CLASS_STRUCT * int_class ) { <nl> ConfigMask = 1 < < IntResult . Config ; <nl> ShowMatchDisplay ( ) ; <nl> im_ . Match ( int_class , AllProtosOn , ( BIT_VECTOR ) & ConfigMask , <nl> - num_features , num_features , features , 0 , <nl> + num_features , features , <nl> & IntResult , classify_adapt_feature_threshold , <nl> 6 | 0x19 , matcher_debug_separate_windows ) ; <nl> UpdateMatchDisplay ( ) ; <nl> - bool adaptive_on = true ; <nl> - bool pretrained_on = false ; <nl> - GetClassToDebug ( " Adapting " , & adaptive_on , & pretrained_on ) ; <nl> } <nl> # endif <nl> } <nl> void Classify : : DisplayAdaptedChar ( TBLOB * blob , INT_CLASS_STRUCT * int_class ) { <nl> * @ note History : Thu Mar 14 09 : 36 : 03 1991 , DSJ , Created . <nl> * / <nl> void Classify : : AdaptToPunc ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> int FontinfoId , <nl> FLOAT32 Threshold ) { <nl> void Classify : : AdaptToPunc ( TBLOB * Blob , <nl> int i ; <nl> <nl> Results - > Initialize ( ) ; <nl> - CharNormClassifier ( Blob , PreTrainedTemplates , Results ) ; <nl> + CharNormClassifier ( Blob , denorm , PreTrainedTemplates , Results ) ; <nl> RemoveBadMatches ( Results ) ; <nl> <nl> if ( Results - > NumMatches ! = 1 ) { <nl> void Classify : : AdaptToPunc ( TBLOB * Blob , <nl> unicharset . id_to_unichar ( ClassId ) ) ; <nl> <nl> for ( i = 0 ; i < Results - > NumMatches ; i + + ) <nl> - cprintf ( " % s " , unicharset . id_to_unichar ( Results - > match [ i ] . id ) ) ; <nl> - cprintf ( " ) \ n " ) ; <nl> + tprintf ( " % s " , unicharset . id_to_unichar ( Results - > match [ i ] . unichar_id ) ) ; <nl> + tprintf ( " ) \ n " ) ; <nl> } <nl> } else { <nl> # ifndef SECURE_NAMES <nl> void Classify : : AdaptToPunc ( TBLOB * Blob , <nl> cprintf ( " Adapting to punc = % s , thr = % g \ n " , <nl> unicharset . id_to_unichar ( ClassId ) , Threshold ) ; <nl> # endif <nl> - AdaptToChar ( Blob , ClassId , FontinfoId , Threshold ) ; <nl> + AdaptToChar ( Blob , denorm , ClassId , FontinfoId , Threshold ) ; <nl> } <nl> delete Results ; <nl> } / * AdaptToPunc * / <nl> void Classify : : AdaptToPunc ( TBLOB * Blob , <nl> * / <nl> void Classify : : AddNewResult ( ADAPT_RESULTS * results , <nl> CLASS_ID class_id , <nl> + int shape_id , <nl> FLOAT32 rating , <nl> + bool adapted , <nl> int config , <nl> - int config2 , <nl> int fontinfo_id , <nl> int fontinfo_id2 ) { <nl> ScoredClass * old_match = FindScoredUnichar ( results , class_id ) ; <nl> ScoredClass match = <nl> - { class_id , rating , config , config2 , fontinfo_id , fontinfo_id2 } ; <nl> + { class_id , <nl> + shape_id , <nl> + rating , <nl> + adapted , <nl> + static_cast < inT16 > ( config ) , <nl> + static_cast < inT16 > ( fontinfo_id ) , <nl> + static_cast < inT16 > ( fontinfo_id2 ) } ; <nl> <nl> if ( rating > results - > best_match . rating + matcher_bad_match_pad | | <nl> ( old_match & & rating > = old_match - > rating ) ) <nl> void Classify : : AddNewResult ( ADAPT_RESULTS * results , <nl> if ( ! unicharset . get_fragment ( class_id ) ) <nl> results - > HasNonfragment = true ; <nl> <nl> - if ( class_id = = NO_CLASS | | <nl> - ! ClassForClassId ( PreTrainedTemplates , class_id ) ) <nl> - match . config = ~ 0 ; <nl> - <nl> if ( old_match ) <nl> old_match - > rating = rating ; <nl> else <nl> void Classify : : AddNewResult ( ADAPT_RESULTS * results , <nl> * @ note History : Tue Mar 12 19 : 40 : 36 1991 , DSJ , Created . <nl> * / <nl> void Classify : : AmbigClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> INT_TEMPLATES Templates , <nl> ADAPT_CLASS * Classes , <nl> UNICHAR_ID * Ambiguities , <nl> ADAPT_RESULTS * Results ) { <nl> int NumFeatures ; <nl> INT_FEATURE_ARRAY IntFeatures ; <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ; <nl> + uinT8 * CharNormArray = new uinT8 [ unicharset . size ( ) ] ; <nl> INT_RESULT_STRUCT IntResult ; <nl> CLASS_ID ClassId ; <nl> <nl> AmbigClassifierCalls + + ; <nl> <nl> - NumFeatures = GetCharNormFeatures ( Blob , Templates , IntFeatures , CharNormArray , <nl> + NumFeatures = GetCharNormFeatures ( Blob , denorm , Templates , IntFeatures , <nl> + NULL , CharNormArray , <nl> & ( Results - > BlobLength ) , NULL ) ; <nl> - if ( NumFeatures < = 0 ) <nl> + if ( NumFeatures < = 0 ) { <nl> + delete [ ] CharNormArray ; <nl> return ; <nl> + } <nl> <nl> - if ( matcher_debug_level > = 2 ) <nl> - cprintf ( " AM Matches = " ) ; <nl> + bool debug = matcher_debug_level > = 2 | | classify_debug_level > 1 ; <nl> + if ( debug ) <nl> + tprintf ( " AM Matches = " ) ; <nl> <nl> + int top = Blob - > bounding_box ( ) . top ( ) ; <nl> + int bottom = Blob - > bounding_box ( ) . bottom ( ) ; <nl> while ( * Ambiguities > = 0 ) { <nl> ClassId = * Ambiguities ; <nl> <nl> im_ . SetCharNormMatch ( classify_integer_matcher_multiplier ) ; <nl> im_ . Match ( ClassForClassId ( Templates , ClassId ) , <nl> AllProtosOn , AllConfigsOn , <nl> - Results - > BlobLength , NumFeatures , IntFeatures , <nl> - CharNormArray [ ClassId ] , & IntResult , <nl> + NumFeatures , IntFeatures , <nl> + & IntResult , <nl> classify_adapt_feature_threshold , NO_DEBUG , <nl> matcher_debug_separate_windows ) ; <nl> <nl> - if ( matcher_debug_level > = 2 ) <nl> - cprintf ( " % s - % - 2d % 2 . 0f " , unicharset . id_to_unichar ( ClassId ) , <nl> - IntResult . Config , <nl> - IntResult . Rating * 100 . 0 ) ; <nl> - <nl> - assert ( Classes ! = NULL ) ; <nl> - AddNewResult ( Results , ClassId , IntResult . Rating , <nl> - IntResult . Config , IntResult . Config2 , <nl> - GetFontinfoId ( Classes [ ClassId ] , IntResult . Config ) , <nl> - GetFontinfoId ( Classes [ ClassId ] , IntResult . Config2 ) ) ; <nl> + ExpandShapesAndApplyCorrections ( NULL , debug , ClassId , bottom , top , 0 , <nl> + Results - > BlobLength , CharNormArray , <nl> + IntResult , Results ) ; <nl> Ambiguities + + ; <nl> <nl> NumAmbigClassesTried + + ; <nl> } <nl> - if ( matcher_debug_level > = 2 ) <nl> - cprintf ( " \ n " ) ; <nl> - <nl> + delete [ ] CharNormArray ; <nl> } / * AmbigClassifier * / <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> void Classify : : AmbigClassifier ( TBLOB * Blob , <nl> / / / Returns integer matcher results inside CLASS_PRUNER_RESULTS structure . <nl> void Classify : : MasterMatcher ( INT_TEMPLATES templates , <nl> inT16 num_features , <nl> - INT_FEATURE_ARRAY features , <nl> - CLASS_NORMALIZATION_ARRAY norm_factors , <nl> + const INT_FEATURE_STRUCT * features , <nl> + const uinT8 * norm_factors , <nl> ADAPT_CLASS * classes , <nl> int debug , <nl> int num_classes , <nl> void Classify : : MasterMatcher ( INT_TEMPLATES templates , <nl> : AllConfigsOn ; <nl> <nl> im_ . Match ( ClassForClassId ( templates , class_id ) , <nl> - protos , configs , final_results - > BlobLength , <nl> - num_features , features , norm_factors [ class_id ] , <nl> + protos , configs , <nl> + num_features , features , <nl> & int_result , classify_adapt_feature_threshold , debug , <nl> matcher_debug_separate_windows ) ; <nl> - / / Compute class feature corrections . <nl> - double miss_penalty = tessedit_class_miss_scale * <nl> - int_result . FeatureMisses ; <nl> - if ( matcher_debug_level > = 2 | | classify_debug_level > 1 ) { <nl> - cprintf ( " % s - % - 2d % 2 . 1f ( CP % 2 . 1f , IM % 2 . 1f + MP % 2 . 1f ) " , <nl> - unicharset . id_to_unichar ( class_id ) , int_result . Config , <nl> - ( int_result . Rating + miss_penalty ) * 100 . 0 , <nl> - results [ c ] . Rating * 100 . 0 , <nl> - int_result . Rating * 100 . 0 , miss_penalty * 100 . 0 ) ; <nl> - if ( c % 4 = = 3 ) <nl> - cprintf ( " \ n " ) ; <nl> + bool debug = matcher_debug_level > = 2 | | classify_debug_level > 1 ; <nl> + ExpandShapesAndApplyCorrections ( classes , debug , class_id , bottom , top , <nl> + results [ c ] . Rating , <nl> + final_results - > BlobLength , norm_factors , <nl> + int_result , final_results ) ; <nl> + } <nl> + } <nl> + <nl> + / / Converts configs to fonts , and if the result is not adapted , and a <nl> + / / shape_table_ is present , the shape is expanded to include all <nl> + / / unichar_ids represented , before applying a set of corrections to the <nl> + / / distance rating in int_result , ( see ComputeCorrectedRating . ) <nl> + / / The results are added to the final_results output . <nl> + void Classify : : ExpandShapesAndApplyCorrections ( <nl> + ADAPT_CLASS * classes , bool debug , int class_id , int bottom , int top , <nl> + float cp_rating , int blob_length , const uinT8 * cn_factors , <nl> + INT_RESULT_STRUCT & int_result , ADAPT_RESULTS * final_results ) { <nl> + / / Compute the fontinfo_ids . <nl> + int fontinfo_id = kBlankFontinfoId ; <nl> + int fontinfo_id2 = kBlankFontinfoId ; <nl> + if ( classes ! = NULL ) { <nl> + / / Adapted result . <nl> + fontinfo_id = GetFontinfoId ( classes [ class_id ] , int_result . Config ) ; <nl> + if ( int_result . Config2 > = 0 ) <nl> + fontinfo_id2 = GetFontinfoId ( classes [ class_id ] , int_result . Config2 ) ; <nl> + } else { <nl> + / / Pre - trained result . <nl> + fontinfo_id = ClassAndConfigIDToFontOrShapeID ( class_id , int_result . Config ) ; <nl> + if ( int_result . Config2 > = 0 ) { <nl> + fontinfo_id2 = ClassAndConfigIDToFontOrShapeID ( class_id , <nl> + int_result . Config2 ) ; <nl> } <nl> - / / Penalize non - alnums for being vertical misfits . <nl> - if ( ! unicharset . get_isalpha ( class_id ) & & <nl> - ! unicharset . get_isdigit ( class_id ) & & <nl> - norm_factors [ class_id ] ! = 0 & & classify_misfit_junk_penalty > 0 . 0 ) { <nl> - int min_bottom , max_bottom , min_top , max_top ; <nl> - unicharset . get_top_bottom ( class_id , & min_bottom , & max_bottom , <nl> - & min_top , & max_top ) ; <nl> - if ( classify_debug_level > 1 ) { <nl> - tprintf ( " top = % d , vs [ % d , % d ] , bottom = % d , vs [ % d , % d ] \ n " , <nl> - top , min_top , max_top , bottom , min_bottom , max_bottom ) ; <nl> - } <nl> - if ( top < min_top | | top > max_top | | <nl> - bottom < min_bottom | | bottom > max_bottom ) { <nl> - miss_penalty + = classify_misfit_junk_penalty ; <nl> + if ( shape_table_ ! = NULL ) { <nl> + / / Actually fontinfo_id is an index into the shape_table_ and it <nl> + / / contains a list of unchar_id / font_id pairs . <nl> + int shape_id = fontinfo_id ; <nl> + const Shape & shape = shape_table_ - > GetShape ( fontinfo_id ) ; <nl> + double min_rating = 0 . 0 ; <nl> + for ( int c = 0 ; c < shape . size ( ) ; + + c ) { <nl> + int unichar_id = shape [ c ] . unichar_id ; <nl> + fontinfo_id = shape [ c ] . font_ids [ 0 ] ; <nl> + if ( shape [ c ] . font_ids . size ( ) > 1 ) <nl> + fontinfo_id2 = shape [ c ] . font_ids [ 1 ] ; <nl> + else if ( fontinfo_id2 ! = kBlankFontinfoId ) <nl> + fontinfo_id2 = shape_table_ - > GetShape ( fontinfo_id2 ) [ 0 ] . font_ids [ 0 ] ; <nl> + double rating = ComputeCorrectedRating ( debug , unichar_id , cp_rating , <nl> + int_result . Rating , <nl> + int_result . FeatureMisses , <nl> + bottom , top , blob_length , <nl> + cn_factors ) ; <nl> + if ( c = = 0 | | rating < min_rating ) <nl> + min_rating = rating ; <nl> + if ( unicharset . get_enabled ( unichar_id ) ) { <nl> + AddNewResult ( final_results , unichar_id , shape_id , rating , <nl> + classes ! = NULL , int_result . Config , <nl> + fontinfo_id , fontinfo_id2 ) ; <nl> + } <nl> } <nl> + int_result . Rating = min_rating ; <nl> + return ; <nl> } <nl> - int_result . Rating + = miss_penalty ; <nl> - if ( int_result . Rating > WORST_POSSIBLE_RATING ) <nl> - int_result . Rating = WORST_POSSIBLE_RATING ; <nl> - if ( classes ! = NULL ) { <nl> - AddNewResult ( final_results , class_id , int_result . Rating , <nl> - int_result . Config , int_result . Config2 , <nl> - GetFontinfoId ( classes [ class_id ] , int_result . Config ) , <nl> - GetFontinfoId ( classes [ class_id ] , int_result . Config2 ) ) ; <nl> - } else { <nl> - AddNewResult ( final_results , class_id , int_result . Rating , <nl> - int_result . Config , int_result . Config2 , <nl> - kBlankFontinfoId , kBlankFontinfoId ) ; <nl> + } <nl> + double rating = ComputeCorrectedRating ( debug , class_id , cp_rating , <nl> + int_result . Rating , <nl> + int_result . FeatureMisses , <nl> + bottom , top , blob_length , <nl> + cn_factors ) ; <nl> + if ( unicharset . get_enabled ( class_id ) ) { <nl> + AddNewResult ( final_results , class_id , - 1 , rating , <nl> + classes ! = NULL , int_result . Config , <nl> + fontinfo_id , fontinfo_id2 ) ; <nl> + } <nl> + int_result . Rating = rating ; <nl> + } <nl> <nl> + / / Applies a set of corrections to the distance im_rating , <nl> + / / including the cn_correction , miss penalty and additional penalty <nl> + / / for non - alnums being vertical misfits . Returns the corrected distance . <nl> + double Classify : : ComputeCorrectedRating ( bool debug , int unichar_id , <nl> + double cp_rating , double im_rating , <nl> + int feature_misses , <nl> + int bottom , int top , <nl> + int blob_length , <nl> + const uinT8 * cn_factors ) { <nl> + / / Compute class feature corrections . <nl> + double cn_corrected = im_ . ApplyCNCorrection ( im_rating , blob_length , <nl> + cn_factors [ unichar_id ] ) ; <nl> + double miss_penalty = tessedit_class_miss_scale * feature_misses ; <nl> + double vertical_penalty = 0 . 0 ; <nl> + / / Penalize non - alnums for being vertical misfits . <nl> + if ( ! unicharset . get_isalpha ( unichar_id ) & & <nl> + ! unicharset . get_isdigit ( unichar_id ) & & <nl> + cn_factors [ unichar_id ] ! = 0 & & classify_misfit_junk_penalty > 0 . 0 ) { <nl> + int min_bottom , max_bottom , min_top , max_top ; <nl> + unicharset . get_top_bottom ( unichar_id , & min_bottom , & max_bottom , <nl> + & min_top , & max_top ) ; <nl> + if ( debug ) { <nl> + tprintf ( " top = % d , vs [ % d , % d ] , bottom = % d , vs [ % d , % d ] \ n " , <nl> + top , min_top , max_top , bottom , min_bottom , max_bottom ) ; <nl> } <nl> - <nl> - / / Add unichars ambiguous with class_id with the same rating as class_id . <nl> - if ( use_definite_ambigs_for_classifier ) { <nl> - const UnicharIdVector * definite_ambigs = <nl> - getDict ( ) . getUnicharAmbigs ( ) . OneToOneDefiniteAmbigs ( class_id ) ; <nl> - int ambigs_size = ( definite_ambigs = = NULL ) ? 0 : definite_ambigs - > size ( ) ; <nl> - for ( int ambig = 0 ; ambig < ambigs_size ; + + ambig ) { <nl> - UNICHAR_ID ambig_class_id = ( * definite_ambigs ) [ ambig ] ; <nl> - / / Do not include ambig_class_id if it has permanent adapted templates . <nl> - if ( classes [ class_id ] - > NumPermConfigs > 0 ) continue ; <nl> - ScoredClass * ambig_match = <nl> - FindScoredUnichar ( final_results , ambig_class_id ) ; <nl> - if ( matcher_debug_level > = 3 ) { <nl> - tprintf ( " class : % d definite ambig : % d rating : old % . 4f new % . 4f \ n " , <nl> - class_id , ambig_class_id , <nl> - ambig_match ? ambig_match - > rating : WORST_POSSIBLE_RATING , <nl> - int_result . Rating ) ; <nl> - } <nl> - if ( ambig_match ) { <nl> - / / ambig_class_id was already added to final_results , <nl> - / / so just need to modify the rating . <nl> - if ( int_result . Rating < ambig_match - > rating ) { <nl> - ambig_match - > rating = int_result . Rating ; <nl> - } <nl> - } else { <nl> - if ( classes ! = NULL ) { <nl> - AddNewResult ( <nl> - final_results , ambig_class_id , int_result . Rating , <nl> - int_result . Config , int_result . Config2 , <nl> - GetFontinfoId ( classes [ class_id ] , int_result . Config ) , <nl> - GetFontinfoId ( classes [ class_id ] , int_result . Config2 ) ) ; <nl> - } else { <nl> - AddNewResult ( final_results , ambig_class_id , int_result . Rating , <nl> - int_result . Config , int_result . Config2 , <nl> - kBlankFontinfoId , kBlankFontinfoId ) ; <nl> - } <nl> - } <nl> - } <nl> + if ( top < min_top | | top > max_top | | <nl> + bottom < min_bottom | | bottom > max_bottom ) { <nl> + vertical_penalty = classify_misfit_junk_penalty ; <nl> } <nl> } <nl> - if ( matcher_debug_level > = 2 | | classify_debug_level > 1 ) <nl> - cprintf ( " \ n " ) ; <nl> + double result = cn_corrected + miss_penalty + vertical_penalty ; <nl> + if ( result > WORST_POSSIBLE_RATING ) <nl> + result = WORST_POSSIBLE_RATING ; <nl> + if ( debug ) { <nl> + tprintf ( " % s : % 2 . 1f ( CP % 2 . 1f , IM % 2 . 1f + CN % . 2f ( % d ) + MP % 2 . 1f + VP % 2 . 1f ) \ n " , <nl> + unicharset . id_to_unichar ( unichar_id ) , <nl> + result * 100 . 0 , <nl> + cp_rating * 100 . 0 , <nl> + im_rating * 100 . 0 , <nl> + ( cn_corrected - im_rating ) * 100 . 0 , <nl> + cn_factors [ unichar_id ] , <nl> + miss_penalty * 100 . 0 , <nl> + vertical_penalty * 100 . 0 ) ; <nl> + } <nl> + return result ; <nl> } <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> void Classify : : MasterMatcher ( INT_TEMPLATES templates , <nl> * @ note History : Tue Mar 12 19 : 38 : 03 1991 , DSJ , Created . <nl> * / <nl> UNICHAR_ID * Classify : : BaselineClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> ADAPT_TEMPLATES Templates , <nl> ADAPT_RESULTS * Results ) { <nl> int NumFeatures ; <nl> int NumClasses ; <nl> INT_FEATURE_ARRAY IntFeatures ; <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ; <nl> + uinT8 * CharNormArray = new uinT8 [ unicharset . size ( ) ] ; <nl> CLASS_ID ClassId ; <nl> <nl> BaselineClassifierCalls + + ; <nl> <nl> NumFeatures = GetBaselineFeatures ( <nl> - Blob , Templates - > Templates , IntFeatures , CharNormArray , <nl> + Blob , denorm , Templates - > Templates , IntFeatures , CharNormArray , <nl> & ( Results - > BlobLength ) ) ; <nl> - if ( NumFeatures < = 0 ) <nl> + if ( NumFeatures < = 0 ) { <nl> + delete [ ] CharNormArray ; <nl> return NULL ; <nl> + } <nl> <nl> - NumClasses = ClassPruner ( Templates - > Templates , NumFeatures , IntFeatures , <nl> - CharNormArray , BaselineCutoffs , Results - > CPResults ) ; <nl> + NumClasses = PruneClasses ( Templates - > Templates , NumFeatures , IntFeatures , <nl> + CharNormArray , BaselineCutoffs , Results - > CPResults ) ; <nl> <nl> NumBaselineClassesTried + = NumClasses ; <nl> <nl> UNICHAR_ID * Classify : : BaselineClassifier ( TBLOB * Blob , <nl> Templates - > Class , matcher_debug_flags , NumClasses , <nl> Blob - > bounding_box ( ) , Results - > CPResults , Results ) ; <nl> <nl> - ClassId = Results - > best_match . id ; <nl> + delete [ ] CharNormArray ; <nl> + ClassId = Results - > best_match . unichar_id ; <nl> if ( ClassId = = NO_CLASS ) <nl> return ( NULL ) ; <nl> / * this is a bug - maybe should return " " * / <nl> UNICHAR_ID * Classify : : BaselineClassifier ( TBLOB * Blob , <nl> * @ note History : Tue Mar 12 16 : 02 : 52 1991 , DSJ , Created . <nl> * / <nl> int Classify : : CharNormClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> INT_TEMPLATES Templates , <nl> ADAPT_RESULTS * Results ) { <nl> int NumFeatures ; <nl> int NumClasses ; <nl> INT_FEATURE_ARRAY IntFeatures ; <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ; <nl> <nl> CharNormClassifierCalls + + ; <nl> <nl> - NumFeatures = GetCharNormFeatures ( Blob , Templates , IntFeatures , CharNormArray , <nl> + uinT8 * CharNormArray = new uinT8 [ unicharset . size ( ) ] ; <nl> + int num_pruner_classes = MAX ( unicharset . size ( ) , <nl> + PreTrainedTemplates - > NumClasses ) ; <nl> + uinT8 * PrunerNormArray = new uinT8 [ num_pruner_classes ] ; <nl> + NumFeatures = GetCharNormFeatures ( Blob , denorm , Templates , IntFeatures , <nl> + PrunerNormArray , CharNormArray , <nl> & ( Results - > BlobLength ) , NULL ) ; <nl> - if ( NumFeatures < = 0 ) <nl> + if ( NumFeatures < = 0 ) { <nl> + delete [ ] CharNormArray ; <nl> + delete [ ] PrunerNormArray ; <nl> return 0 ; <nl> + } <nl> <nl> - NumClasses = ClassPruner ( Templates , NumFeatures , IntFeatures , CharNormArray , <nl> - CharNormCutoffs , Results - > CPResults ) ; <nl> + NumClasses = PruneClasses ( Templates , NumFeatures , IntFeatures , <nl> + PrunerNormArray , <nl> + shape_table_ ! = NULL ? & shapetable_cutoffs_ [ 0 ] <nl> + : CharNormCutoffs , <nl> + Results - > CPResults ) ; <nl> <nl> if ( tessedit_single_match & & NumClasses > 1 ) <nl> NumClasses = 1 ; <nl> int Classify : : CharNormClassifier ( TBLOB * Blob , <nl> MasterMatcher ( Templates , NumFeatures , IntFeatures , CharNormArray , <nl> NULL , matcher_debug_flags , NumClasses , <nl> Blob - > bounding_box ( ) , Results - > CPResults , Results ) ; <nl> + delete [ ] CharNormArray ; <nl> + delete [ ] PrunerNormArray ; <nl> return NumFeatures ; <nl> } / * CharNormClassifier * / <nl> <nl> + / / As CharNormClassifier , but operates on a TrainingSample and outputs to <nl> + / / a GenericVector of ShapeRating without conversion to classes . <nl> + int Classify : : CharNormTrainingSample ( bool pruner_only , <nl> + const TrainingSample & sample , <nl> + GenericVector < ShapeRating > * results ) { <nl> + results - > clear ( ) ; <nl> + ADAPT_RESULTS * adapt_results = new ADAPT_RESULTS ( ) ; <nl> + adapt_results - > Initialize ( ) ; <nl> + / / Compute the bounding box of the features . <nl> + int num_features = sample . num_features ( ) ; <nl> + TBOX blob_box ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) { <nl> + const INT_FEATURE_STRUCT feature = sample . features ( ) [ f ] ; <nl> + TBOX fbox ( feature . X , feature . Y , feature . X , feature . Y ) ; <nl> + blob_box + = fbox ; <nl> + } <nl> + / / Compute the char_norm_array from the saved cn_feature . <nl> + FEATURE norm_feature = NewFeature ( & CharNormDesc ) ; <nl> + norm_feature - > Params [ CharNormY ] = sample . cn_feature ( CharNormY ) ; <nl> + norm_feature - > Params [ CharNormLength ] = sample . cn_feature ( CharNormLength ) ; <nl> + norm_feature - > Params [ CharNormRx ] = sample . cn_feature ( CharNormRx ) ; <nl> + norm_feature - > Params [ CharNormRy ] = sample . cn_feature ( CharNormRy ) ; <nl> + uinT8 * char_norm_array = new uinT8 [ unicharset . size ( ) ] ; <nl> + int num_pruner_classes = MAX ( unicharset . size ( ) , <nl> + PreTrainedTemplates - > NumClasses ) ; <nl> + uinT8 * pruner_norm_array = new uinT8 [ num_pruner_classes ] ; <nl> + adapt_results - > BlobLength = <nl> + static_cast < int > ( ActualOutlineLength ( norm_feature ) * 20 + 0 . 5 ) ; <nl> + ComputeCharNormArrays ( norm_feature , PreTrainedTemplates , char_norm_array , <nl> + pruner_norm_array ) ; <nl> + <nl> + int num_classes = PruneClasses ( PreTrainedTemplates , num_features , <nl> + sample . features ( ) , <nl> + pruner_norm_array , <nl> + shape_table_ ! = NULL ? & shapetable_cutoffs_ [ 0 ] <nl> + : CharNormCutoffs , <nl> + adapt_results - > CPResults ) ; <nl> + delete [ ] pruner_norm_array ; <nl> + if ( pruner_only ) { <nl> + / / Convert pruner results to output format . <nl> + for ( int i = 0 ; i < num_classes ; + + i ) { <nl> + int class_id = adapt_results - > CPResults [ i ] . Class ; <nl> + int shape_id = class_id ; <nl> + if ( shape_table_ ! = NULL ) { <nl> + / / All shapes in a class have the same combination of unichars , so <nl> + / / it doesn ' t really matter which config we give it , as we aren ' t <nl> + / / trying to get the font here . <nl> + shape_id = ClassAndConfigIDToFontOrShapeID ( class_id , 0 ) ; <nl> + } <nl> + results - > push_back ( <nl> + ShapeRating ( shape_id , 1 . 0f - adapt_results - > CPResults [ i ] . Rating ) ) ; <nl> + } <nl> + } else { <nl> + im_ . SetCharNormMatch ( classify_integer_matcher_multiplier ) ; <nl> + MasterMatcher ( PreTrainedTemplates , num_features , sample . features ( ) , <nl> + char_norm_array , <nl> + NULL , matcher_debug_flags , num_classes , <nl> + blob_box , adapt_results - > CPResults , adapt_results ) ; <nl> + / / Convert master matcher results to output format . <nl> + for ( int i = 0 ; i < adapt_results - > NumMatches ; i + + ) { <nl> + ScoredClass next = adapt_results - > match [ i ] ; <nl> + results - > push_back ( ShapeRating ( next . shape_id , 1 . 0f - next . rating ) ) ; <nl> + } <nl> + results - > sort ( & ShapeRating : : SortDescendingRating ) ; <nl> + } <nl> + delete [ ] char_norm_array ; <nl> + delete adapt_results ; <nl> + return num_features ; <nl> + } / * CharNormTrainingSample * / <nl> + <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> / * * <nl> void Classify : : ClassifyAsNoise ( ADAPT_RESULTS * Results ) { <nl> Rating * = Rating ; <nl> Rating / = 1 . 0 + Rating ; <nl> <nl> - AddNewResult ( Results , NO_CLASS , Rating , - 1 , - 1 , <nl> + AddNewResult ( Results , NO_CLASS , - 1 , Rating , false , - 1 , <nl> kBlankFontinfoId , kBlankFontinfoId ) ; <nl> } / * ClassifyAsNoise * / <nl> } / / namespace tesseract <nl> void Classify : : ClassifyAsNoise ( ADAPT_RESULTS * Results ) { <nl> / / Return a pointer to the scored unichar in results , or NULL if not present . <nl> ScoredClass * FindScoredUnichar ( ADAPT_RESULTS * results , UNICHAR_ID id ) { <nl> for ( int i = 0 ; i < results - > NumMatches ; i + + ) { <nl> - if ( results - > match [ i ] . id = = id ) <nl> + if ( results - > match [ i ] . unichar_id = = id ) <nl> return & results - > match [ i ] ; <nl> } <nl> return NULL ; <nl> ScoredClass * FindScoredUnichar ( ADAPT_RESULTS * results , UNICHAR_ID id ) { <nl> / / to WORST_POSSIBLE_RATING . <nl> ScoredClass ScoredUnichar ( ADAPT_RESULTS * results , UNICHAR_ID id ) { <nl> ScoredClass poor_result = <nl> - { id , WORST_POSSIBLE_RATING , - 1 , - 1 , kBlankFontinfoId , kBlankFontinfoId } ; <nl> + { id , - 1 , WORST_POSSIBLE_RATING , false , - 1 , <nl> + kBlankFontinfoId , kBlankFontinfoId } ; <nl> ScoredClass * entry = FindScoredUnichar ( results , id ) ; <nl> return ( entry = = NULL ) ? poor_result : * entry ; <nl> } <nl> int CompareByRating ( const void * arg1 , / / ScoredClass * class1 <nl> else if ( class1 - > rating > class2 - > rating ) <nl> return 1 ; <nl> <nl> - if ( class1 - > id < class2 - > id ) <nl> + if ( class1 - > unichar_id < class2 - > unichar_id ) <nl> return - 1 ; <nl> - else if ( class1 - > id > class2 - > id ) <nl> + else if ( class1 - > unichar_id > class2 - > unichar_id ) <nl> return 1 ; <nl> return 0 ; <nl> } <nl> namespace tesseract { <nl> / / / sure that there is at least one non - fragmented classification included . <nl> / / / For each classification result check the unicharset for " definite " <nl> / / / ambiguities and modify the resulting Choices accordingly . <nl> - void Classify : : ConvertMatchesToChoices ( ADAPT_RESULTS * Results , <nl> + void Classify : : ConvertMatchesToChoices ( const DENORM & denorm , const TBOX & box , <nl> + ADAPT_RESULTS * Results , <nl> BLOB_CHOICE_LIST * Choices ) { <nl> assert ( Choices ! = NULL ) ; <nl> FLOAT32 Rating ; <nl> void Classify : : ConvertMatchesToChoices ( ADAPT_RESULTS * Results , <nl> bool contains_nonfrag = false ; <nl> temp_it . set_to_list ( Choices ) ; <nl> int choices_length = 0 ; <nl> + / / With no shape_table_ maintain the previous MAX_MATCHES as the maximum <nl> + / / number of returned results , but with a shape_table_ we want to have room <nl> + / / for at least the biggest shape ( which might contain hundreds of Indic <nl> + / / grapheme fragments ) and more , so use double the size of the biggest shape <nl> + / / if that is more than the default . <nl> + int max_matches = MAX_MATCHES ; <nl> + if ( shape_table_ ! = NULL ) { <nl> + max_matches = shape_table_ - > MaxNumUnichars ( ) * 2 ; <nl> + if ( max_matches < MAX_MATCHES ) <nl> + max_matches = MAX_MATCHES ; <nl> + } <nl> <nl> for ( int i = 0 ; i < Results - > NumMatches ; i + + ) { <nl> ScoredClass next = Results - > match [ i ] ; <nl> int fontinfo_id = next . fontinfo_id ; <nl> int fontinfo_id2 = next . fontinfo_id2 ; <nl> - if ( fontinfo_id = = kBlankFontinfoId ) { <nl> - / / ScoredClass next must have come from pre - trained templates , <nl> - / / so we infer its font information from fontset_table . <nl> - int font_set_id = PreTrainedTemplates - > Class [ next . id ] - > font_set_id ; <nl> - if ( font_set_id > = 0 ) { <nl> - const FontSet & fs = fontset_table_ . get ( font_set_id ) ; <nl> - if ( next . config > = 0 & & next . config < fs . size ) { <nl> - fontinfo_id = fs . configs [ next . config ] ; <nl> - } <nl> - if ( next . config2 > = 0 & & next . config2 < fs . size ) { <nl> - fontinfo_id2 = fs . configs [ next . config2 ] ; <nl> - } <nl> - } <nl> - } <nl> - bool current_is_frag = ( unicharset . get_fragment ( next . id ) ! = NULL ) ; <nl> - if ( temp_it . length ( ) + 1 = = MAX_MATCHES & & <nl> + bool adapted = next . adapted ; <nl> + bool current_is_frag = ( unicharset . get_fragment ( next . unichar_id ) ! = NULL ) ; <nl> + if ( temp_it . length ( ) + 1 = = max_matches & & <nl> ! contains_nonfrag & & current_is_frag ) { <nl> continue ; / / look for a non - fragmented character to fill the <nl> / / last spot in Choices if only fragments are present <nl> void Classify : : ConvertMatchesToChoices ( ADAPT_RESULTS * Results , <nl> Rating * = rating_scale * Results - > BlobLength ; <nl> Certainty * = - ( getDict ( ) . certainty_scale ) ; <nl> } <nl> - temp_it . add_to_end ( new BLOB_CHOICE ( next . id , Rating , Certainty , <nl> + inT16 min_xheight , max_xheight ; <nl> + denorm . XHeightRange ( next . unichar_id , unicharset , box , <nl> + & min_xheight , & max_xheight ) ; <nl> + temp_it . add_to_end ( new BLOB_CHOICE ( next . unichar_id , Rating , Certainty , <nl> fontinfo_id , fontinfo_id2 , <nl> - unicharset . get_script ( next . id ) ) ) ; <nl> + unicharset . get_script ( next . unichar_id ) , <nl> + min_xheight , max_xheight , adapted ) ) ; <nl> contains_nonfrag | = ! current_is_frag ; / / update contains_nonfrag <nl> choices_length + + ; <nl> - if ( choices_length > = MAX_MATCHES ) break ; <nl> + if ( choices_length > = max_matches ) break ; <nl> } <nl> Results - > NumMatches = choices_length ; <nl> } / / ConvertMatchesToChoices <nl> void Classify : : ConvertMatchesToChoices ( ADAPT_RESULTS * Results , <nl> * @ note History : Wed Mar 13 16 : 44 : 41 1991 , DSJ , Created . <nl> * / <nl> void Classify : : DebugAdaptiveClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> ADAPT_RESULTS * Results ) { <nl> + for ( int i = 0 ; i < Results - > NumMatches ; i + + ) { <nl> + if ( Results - > match [ i ] . rating < Results - > best_match . rating ) <nl> + Results - > best_match = Results - > match [ i ] ; <nl> + } <nl> const char * Prompt = <nl> " Left - click in IntegerMatch Window to continue or right click to debug . . . " ; <nl> - const char * DebugMode = " All Templates " ; <nl> - CLASS_ID LastClass = Results - > best_match . id ; <nl> - CLASS_ID ClassId ; <nl> + CLASS_ID unichar_id = Results - > best_match . unichar_id ; <nl> + int shape_id = Results - > best_match . shape_id ; <nl> bool adaptive_on = true ; <nl> bool pretrained_on = true ; <nl> <nl> - ShowMatchDisplay ( ) ; <nl> - cprintf ( " \ nDebugging class = % s ( % s ) . . . \ n " , <nl> - unicharset . id_to_unichar ( LastClass ) , DebugMode ) ; <nl> - ShowBestMatchFor ( Blob , LastClass , adaptive_on , pretrained_on ) ; <nl> - UpdateMatchDisplay ( ) ; <nl> - <nl> - while ( ( ClassId = GetClassToDebug ( Prompt , & adaptive_on , <nl> - & pretrained_on ) ) ! = 0 ) { <nl> + const char * debug_mode ; <nl> + do { <nl> if ( ! pretrained_on ) <nl> - DebugMode = " Adaptive Templates Only " ; <nl> + debug_mode = " Adaptive Templates Only " ; <nl> else if ( ! adaptive_on ) <nl> - DebugMode = " PreTrained Templates Only " ; <nl> + debug_mode = " PreTrained Templates Only " ; <nl> else <nl> - DebugMode = " All Templates " ; <nl> - LastClass = ClassId ; <nl> - <nl> + debug_mode = " All Templates " ; <nl> ShowMatchDisplay ( ) ; <nl> - cprintf ( " \ nDebugging class = % d = % s ( % s ) . . . \ n " , <nl> - LastClass , unicharset . id_to_unichar ( LastClass ) , DebugMode ) ; <nl> - ShowBestMatchFor ( Blob , LastClass , adaptive_on , pretrained_on ) ; <nl> + tprintf ( " Debugging class % d = % s in mode % s . . . " , <nl> + unichar_id , unicharset . id_to_unichar ( unichar_id ) , debug_mode ) ; <nl> + if ( shape_id > = 0 & & shape_table_ ! = NULL ) { <nl> + tprintf ( " from shape % s \ n " , shape_table_ - > DebugStr ( shape_id ) . string ( ) ) ; <nl> + } <nl> + ShowBestMatchFor ( Blob , denorm , unichar_id , shape_id , adaptive_on , <nl> + pretrained_on , Results ) ; <nl> UpdateMatchDisplay ( ) ; <nl> - } <nl> + } while ( ( unichar_id = GetClassToDebug ( Prompt , & adaptive_on , <nl> + & pretrained_on , & shape_id ) ) ! = 0 ) ; <nl> } / * DebugAdaptiveClassifier * / <nl> # endif <nl> <nl> void Classify : : DebugAdaptiveClassifier ( TBLOB * Blob , <nl> * @ note History : Tue Mar 12 08 : 50 : 11 1991 , DSJ , Created . <nl> * / <nl> void Classify : : DoAdaptiveMatch ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> ADAPT_RESULTS * Results ) { <nl> UNICHAR_ID * Ambiguities ; <nl> <nl> void Classify : : DoAdaptiveMatch ( TBLOB * Blob , <nl> <nl> if ( AdaptedTemplates - > NumPermClasses < matcher_permanent_classes_min | | <nl> tess_cn_matching ) { <nl> - CharNormClassifier ( Blob , PreTrainedTemplates , Results ) ; <nl> - } <nl> - else { <nl> - Ambiguities = BaselineClassifier ( Blob , AdaptedTemplates , Results ) ; <nl> + CharNormClassifier ( Blob , denorm , PreTrainedTemplates , Results ) ; <nl> + } else { <nl> + Ambiguities = BaselineClassifier ( Blob , denorm , AdaptedTemplates , Results ) ; <nl> if ( ( Results - > NumMatches > 0 & & <nl> MarginalMatch ( Results - > best_match . rating ) & & <nl> ! tess_bn_matching ) | | <nl> Results - > NumMatches = = 0 ) { <nl> - CharNormClassifier ( Blob , PreTrainedTemplates , Results ) ; <nl> + CharNormClassifier ( Blob , denorm , PreTrainedTemplates , Results ) ; <nl> } else if ( Ambiguities & & * Ambiguities > = 0 & & ! tess_bn_matching ) { <nl> - AmbigClassifier ( Blob , <nl> + AmbigClassifier ( Blob , denorm , <nl> PreTrainedTemplates , <nl> AdaptedTemplates - > Class , <nl> Ambiguities , <nl> void Classify : : DoAdaptiveMatch ( TBLOB * Blob , <nl> / / if the results contain only fragments . <nl> / / TODO ( daria ) : verify that this is better than <nl> / / just adding a NULL classification . <nl> - if ( ! Results - > HasNonfragment ) { <nl> - Results - > NumMatches = 0 ; <nl> - } <nl> - if ( Results - > NumMatches = = 0 ) <nl> + if ( ! Results - > HasNonfragment | | Results - > NumMatches = = 0 ) <nl> ClassifyAsNoise ( Results ) ; <nl> } / * DoAdaptiveMatch * / <nl> <nl> void Classify : : DoAdaptiveMatch ( TBLOB * Blob , <nl> * @ param [ out ] Thresholds array of thresholds to be filled in <nl> * <nl> * Globals : <nl> - * - classify_enable_new_adapt_rules <nl> * - matcher_good_threshold <nl> * - matcher_perfect_threshold <nl> * - matcher_rating_margin <nl> void Classify : : DoAdaptiveMatch ( TBLOB * Blob , <nl> * @ note History : Fri May 31 09 : 22 : 08 1991 , DSJ , Created . <nl> * / <nl> void Classify : : GetAdaptThresholds ( TWERD * Word , <nl> + const DENORM & denorm , <nl> const WERD_CHOICE & BestChoice , <nl> const WERD_CHOICE & BestRawChoice , <nl> FLOAT32 Thresholds [ ] ) { <nl> - TBLOB * Blob ; <nl> - const char * BestChoice_string = BestChoice . unichar_string ( ) . string ( ) ; <nl> - const char * BestChoice_lengths = BestChoice . unichar_lengths ( ) . string ( ) ; <nl> - const char * BestRawChoice_string = BestRawChoice . unichar_string ( ) . string ( ) ; <nl> - const char * BestRawChoice_lengths = BestRawChoice . unichar_lengths ( ) . string ( ) ; <nl> - <nl> - if ( classify_enable_new_adapt_rules & & / * new rules * / <nl> - getDict ( ) . CurrentBestChoiceIs ( BestChoice ) ) { <nl> - getDict ( ) . FindClassifierErrors ( matcher_perfect_threshold , <nl> - matcher_good_threshold , <nl> - matcher_rating_margin , <nl> - Thresholds ) ; <nl> - } else { / * old rules * / <nl> - for ( Blob = Word - > blobs ; <nl> - Blob ! = NULL ; <nl> - Blob = Blob - > next , BestChoice_string + = * ( BestChoice_lengths + + ) , <nl> - BestRawChoice_string + = * ( BestRawChoice_lengths + + ) , Thresholds + + ) <nl> - if ( * ( BestChoice_lengths ) = = * ( BestRawChoice_lengths ) & & <nl> - strncmp ( BestChoice_string , BestRawChoice_string , <nl> - * ( BestChoice_lengths ) ) = = 0 ) <nl> - * Thresholds = matcher_good_threshold ; <nl> - else { <nl> - / * the blob was incorrectly classified - find the rating threshold <nl> - needed to create a template which will correct the error with <nl> - some margin . However , don ' t waste time trying to make <nl> - templates which are too tight . * / <nl> - * Thresholds = GetBestRatingFor ( <nl> - Blob , unicharset . unichar_to_id ( BestChoice_string , <nl> - * BestChoice_lengths ) ) ; <nl> - * Thresholds * = ( 1 . 0 - matcher_rating_margin ) ; <nl> - * Thresholds = ClipToRange < double > ( <nl> - * Thresholds , matcher_perfect_threshold , matcher_good_threshold ) ; <nl> - } <nl> - } <nl> + getDict ( ) . FindClassifierErrors ( matcher_perfect_threshold , <nl> + matcher_good_threshold , <nl> + matcher_rating_margin , <nl> + Thresholds ) ; <nl> } / * GetAdaptThresholds * / <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> void Classify : : GetAdaptThresholds ( TWERD * Word , <nl> * @ note History : Fri Mar 15 08 : 08 : 22 1991 , DSJ , Created . <nl> * / <nl> UNICHAR_ID * Classify : : GetAmbiguities ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID CorrectClass ) { <nl> ADAPT_RESULTS * Results = new ADAPT_RESULTS ( ) ; <nl> UNICHAR_ID * Ambiguities ; <nl> UNICHAR_ID * Classify : : GetAmbiguities ( TBLOB * Blob , <nl> <nl> Results - > Initialize ( ) ; <nl> <nl> - CharNormClassifier ( Blob , PreTrainedTemplates , Results ) ; <nl> + CharNormClassifier ( Blob , denorm , PreTrainedTemplates , Results ) ; <nl> RemoveBadMatches ( Results ) ; <nl> qsort ( ( void * ) Results - > match , Results - > NumMatches , <nl> sizeof ( ScoredClass ) , CompareByRating ) ; <nl> UNICHAR_ID * Classify : : GetAmbiguities ( TBLOB * Blob , <nl> Ambiguities = ( UNICHAR_ID * ) Emalloc ( sizeof ( UNICHAR_ID ) * <nl> ( Results - > NumMatches + 1 ) ) ; <nl> if ( Results - > NumMatches > 1 | | <nl> - ( Results - > NumMatches = = 1 & & Results - > match [ 0 ] . id ! = CorrectClass ) ) { <nl> + ( Results - > NumMatches = = 1 & & <nl> + Results - > match [ 0 ] . unichar_id ! = CorrectClass ) ) { <nl> for ( i = 0 ; i < Results - > NumMatches ; i + + ) <nl> - Ambiguities [ i ] = Results - > match [ i ] . id ; <nl> + Ambiguities [ i ] = Results - > match [ i ] . unichar_id ; <nl> Ambiguities [ i ] = - 1 ; <nl> } else { <nl> Ambiguities [ 0 ] = - 1 ; <nl> UNICHAR_ID * Classify : : GetAmbiguities ( TBLOB * Blob , <nl> return Ambiguities ; <nl> } / * GetAmbiguities * / <nl> <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - / * * <nl> - * This routine sets up the feature extractor to extract <nl> - * baseline normalized pico - features . <nl> - * <nl> - * The extracted pico - features are converted <nl> - * to integer form and placed in IntFeatures . CharNormArray <nl> - * is filled with 0 ' s to indicate to the matcher that no <nl> - * character normalization adjustment needs to be done . <nl> - * <nl> - * The total length of all blob outlines <nl> - * in baseline normalized units is also returned . <nl> - * <nl> - * @ param Blob blob to extract features from <nl> - * @ param Templates used to compute char norm adjustments <nl> - * @ param IntFeatures array to fill with integer features <nl> - * @ param CharNormArray array to fill with dummy char norm adjustments <nl> - * @ param BlobLength length of blob in baseline - normalized units <nl> - * <nl> - * Globals : none <nl> - * <nl> - * @ return Number of pico - features returned ( 0 if an error occurred ) <nl> - * @ note Exceptions : none <nl> - * @ note History : Tue Mar 12 17 : 55 : 18 1991 , DSJ , Created . <nl> - * / <nl> - int Classify : : GetBaselineFeatures ( TBLOB * Blob , <nl> - INT_TEMPLATES Templates , <nl> - INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> - inT32 * BlobLength ) { <nl> - FEATURE_SET Features ; <nl> - int NumFeatures ; <nl> - <nl> - if ( classify_enable_int_fx ) { <nl> - return GetIntBaselineFeatures ( Blob , Templates , <nl> - IntFeatures , CharNormArray , BlobLength ) ; <nl> - } <nl> - <nl> - classify_norm_method . set_value ( baseline ) ; <nl> - Features = ExtractPicoFeatures ( Blob ) ; <nl> - <nl> - NumFeatures = Features - > NumFeatures ; <nl> - * BlobLength = NumFeatures ; <nl> - if ( NumFeatures > UNLIKELY_NUM_FEAT ) { <nl> - FreeFeatureSet ( Features ) ; <nl> - return ( 0 ) ; <nl> - } <nl> - <nl> - ComputeIntFeatures ( Features , IntFeatures ) ; <nl> - ClearCharNormArray ( Templates , CharNormArray ) ; <nl> - <nl> - FreeFeatureSet ( Features ) ; <nl> - return NumFeatures ; <nl> - } / * GetBaselineFeatures * / <nl> - <nl> - / * * <nl> - * This routine classifies Blob against both sets of <nl> - * templates for the specified class and returns the best <nl> - * rating found . <nl> - * <nl> - * @ param Blob blob to get best rating for <nl> - * @ param ClassId class blob is to be compared to <nl> - * <nl> - * Globals : <nl> - * - PreTrainedTemplates built - in templates <nl> - * - AdaptedTemplates current set of adapted templates <nl> - * - AllProtosOn dummy mask to enable all protos <nl> - * - AllConfigsOn dummy mask to enable all configs <nl> - * <nl> - * @ return Best rating for match of Blob to ClassId . <nl> - * @ note Exceptions : none <nl> - * @ note History : Tue Apr 9 09 : 01 : 24 1991 , DSJ , Created . <nl> - * / <nl> - FLOAT32 Classify : : GetBestRatingFor ( TBLOB * Blob , <nl> - CLASS_ID ClassId ) { <nl> - int NumCNFeatures , NumBLFeatures ; <nl> - INT_FEATURE_ARRAY CNFeatures , BLFeatures ; <nl> - INT_RESULT_STRUCT CNResult , BLResult ; <nl> - inT32 BlobLength ; <nl> - <nl> - CNResult . Rating = BLResult . Rating = 1 . 0 ; <nl> - <nl> - if ( ! LegalClassId ( ClassId ) ) <nl> - return 1 . 0 ; <nl> - <nl> - uinT8 * CNAdjust = new uinT8 [ MAX_NUM_CLASSES ] ; <nl> - uinT8 * BLAdjust = new uinT8 [ MAX_NUM_CLASSES ] ; <nl> - <nl> - if ( ! UnusedClassIdIn ( PreTrainedTemplates , ClassId ) ) { <nl> - NumCNFeatures = GetCharNormFeatures ( Blob , PreTrainedTemplates , <nl> - CNFeatures , CNAdjust , & BlobLength , <nl> - NULL ) ; <nl> - if ( NumCNFeatures > 0 ) { <nl> - im_ . SetCharNormMatch ( classify_integer_matcher_multiplier ) ; <nl> - im_ . Match ( ClassForClassId ( PreTrainedTemplates , ClassId ) , <nl> - AllProtosOn , AllConfigsOn , <nl> - BlobLength , NumCNFeatures , CNFeatures , <nl> - CNAdjust [ ClassId ] , & CNResult , <nl> - classify_adapt_feature_threshold , NO_DEBUG , <nl> - matcher_debug_separate_windows ) ; <nl> - } <nl> - } <nl> - <nl> - if ( ! UnusedClassIdIn ( AdaptedTemplates - > Templates , ClassId ) ) { <nl> - NumBLFeatures = GetBaselineFeatures ( Blob , <nl> - AdaptedTemplates - > Templates , <nl> - BLFeatures , BLAdjust , & BlobLength ) ; <nl> - if ( NumBLFeatures > 0 ) { <nl> - im_ . SetBaseLineMatch ( ) ; <nl> - im_ . Match ( ClassForClassId ( AdaptedTemplates - > Templates , ClassId ) , <nl> - AdaptedTemplates - > Class [ ClassId ] - > PermProtos , <nl> - AdaptedTemplates - > Class [ ClassId ] - > PermConfigs , <nl> - BlobLength , NumBLFeatures , BLFeatures , <nl> - BLAdjust [ ClassId ] , & BLResult , <nl> - classify_adapt_feature_threshold , NO_DEBUG , <nl> - matcher_debug_separate_windows ) ; <nl> - } <nl> - } <nl> - <nl> - / / Clean up . <nl> - delete [ ] CNAdjust ; <nl> - delete [ ] BLAdjust ; <nl> - <nl> - return MIN ( BLResult . Rating , CNResult . Rating ) ; <nl> - } / * GetBestRatingFor * / <nl> - <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - / * * <nl> - * This routine sets up the feature extractor to extract <nl> - * character normalization features and character normalized <nl> - * pico - features . The extracted pico - features are converted <nl> - * to integer form and placed in IntFeatures . The character <nl> - * normalization features are matched to each class in <nl> - * templates and the resulting adjustment factors are returned <nl> - * in CharNormArray . The total length of all blob outlines <nl> - * in baseline normalized units is also returned . <nl> - * <nl> - * @ param Blob blob to extract features from <nl> - * @ param Templates used to compute char norm adjustments <nl> - * @ param IntFeatures array to fill with integer features <nl> - * @ param CharNormArray array to fill with char norm adjustments <nl> - * @ param BlobLength length of blob in baseline - normalized units <nl> - * <nl> - * Globals : none <nl> - * <nl> - * @ return Number of pico - features returned ( 0 if an error occurred ) <nl> - * @ note Exceptions : none <nl> - * @ note History : Tue Mar 12 17 : 55 : 18 1991 , DSJ , Created . <nl> - * / <nl> - int Classify : : GetCharNormFeatures ( TBLOB * Blob , <nl> - INT_TEMPLATES Templates , <nl> - INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> - inT32 * BlobLength , <nl> - inT32 * FeatureOutlineIndex ) { <nl> - return GetIntCharNormFeatures ( Blob , Templates , IntFeatures , CharNormArray , <nl> - BlobLength , FeatureOutlineIndex ) ; <nl> - } / * GetCharNormFeatures * / <nl> - <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> / * * <nl> * This routine calls the integer ( Hardware ) feature <nl> int Classify : : GetCharNormFeatures ( TBLOB * Blob , <nl> * @ note Exceptions : none <nl> * @ note History : Tue May 28 10 : 40 : 52 1991 , DSJ , Created . <nl> * / <nl> - int Classify : : GetIntBaselineFeatures ( TBLOB * Blob , <nl> - INT_TEMPLATES Templates , <nl> - INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> - inT32 * BlobLength ) { <nl> + int Classify : : GetBaselineFeatures ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> + INT_TEMPLATES Templates , <nl> + INT_FEATURE_ARRAY IntFeatures , <nl> + uinT8 * CharNormArray , <nl> + inT32 * BlobLength ) { <nl> register INT_FEATURE Src , Dest , End ; <nl> <nl> if ( ! FeaturesHaveBeenExtracted ) { <nl> - FeaturesOK = ExtractIntFeat ( Blob , denorm_ , BaselineFeatures , <nl> - CharNormFeatures , & FXInfo ) ; <nl> + FeaturesOK = ExtractIntFeat ( Blob , denorm , BaselineFeatures , <nl> + CharNormFeatures , & FXInfo , NULL ) ; <nl> FeaturesHaveBeenExtracted = TRUE ; <nl> } <nl> <nl> int Classify : : GetIntBaselineFeatures ( TBLOB * Blob , <nl> Src < End ; <nl> * Dest + + = * Src + + ) ; <nl> <nl> - ClearCharNormArray ( Templates , CharNormArray ) ; <nl> + ClearCharNormArray ( CharNormArray ) ; <nl> * BlobLength = FXInfo . NumBL ; <nl> return FXInfo . NumBL ; <nl> - } / * GetIntBaselineFeatures * / <nl> + } / * GetBaselineFeatures * / <nl> <nl> void Classify : : ResetFeaturesHaveBeenExtracted ( ) { <nl> FeaturesHaveBeenExtracted = FALSE ; <nl> void Classify : : ResetFeaturesHaveBeenExtracted ( ) { <nl> <nl> / / Returns true if the given blob looks too dissimilar to any character <nl> / / present in the classifier templates . <nl> - bool Classify : : LooksLikeGarbage ( TBLOB * blob ) { <nl> + bool Classify : : LooksLikeGarbage ( const DENORM & denorm , TBLOB * blob ) { <nl> BLOB_CHOICE_LIST * ratings = new BLOB_CHOICE_LIST ( ) ; <nl> - AdaptiveClassifier ( blob , ratings , NULL ) ; <nl> + AdaptiveClassifier ( blob , denorm , ratings , NULL ) ; <nl> BLOB_CHOICE_IT ratings_it ( ratings ) ; <nl> const UNICHARSET & unicharset = getDict ( ) . getUnicharset ( ) ; <nl> if ( classify_debug_character_fragments ) { <nl> bool Classify : : LooksLikeGarbage ( TBLOB * blob ) { <nl> * @ note Exceptions : none <nl> * @ note History : Tue May 28 10 : 40 : 52 1991 , DSJ , Created . <nl> * / <nl> - int Classify : : GetIntCharNormFeatures ( TBLOB * Blob , <nl> - INT_TEMPLATES Templates , <nl> - INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> - inT32 * BlobLength , <nl> - inT32 * FeatureOutlineArray ) { <nl> + int Classify : : GetCharNormFeatures ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> + INT_TEMPLATES Templates , <nl> + INT_FEATURE_ARRAY IntFeatures , <nl> + uinT8 * PrunerNormArray , <nl> + uinT8 * CharNormArray , <nl> + inT32 * BlobLength , <nl> + inT32 * FeatureOutlineArray ) { <nl> register INT_FEATURE Src , Dest , End ; <nl> FEATURE NormFeature ; <nl> FLOAT32 Baseline , Scale ; <nl> inT32 FeatureOutlineIndex [ MAX_NUM_INT_FEATURES ] ; <nl> <nl> if ( ! FeaturesHaveBeenExtracted ) { <nl> - FeaturesOK = ExtractIntFeat ( Blob , denorm_ , BaselineFeatures , <nl> + FeaturesOK = ExtractIntFeat ( Blob , denorm , BaselineFeatures , <nl> CharNormFeatures , & FXInfo , <nl> FeatureOutlineIndex ) ; <nl> FeaturesHaveBeenExtracted = TRUE ; <nl> int Classify : : GetIntCharNormFeatures ( TBLOB * Blob , <nl> FXInfo . Length * Scale / LENGTH_COMPRESSION ; <nl> NormFeature - > Params [ CharNormRx ] = FXInfo . Rx * Scale ; <nl> NormFeature - > Params [ CharNormRy ] = FXInfo . Ry * Scale ; <nl> - ComputeIntCharNormArray ( NormFeature , Templates , CharNormArray ) ; <nl> - FreeFeature ( NormFeature ) ; <nl> - <nl> + ComputeCharNormArrays ( NormFeature , Templates , CharNormArray , PrunerNormArray ) ; <nl> * BlobLength = FXInfo . NumBL ; <nl> return ( FXInfo . NumCN ) ; <nl> - } / * GetIntCharNormFeatures * / <nl> + } / * GetCharNormFeatures * / <nl> + <nl> + / / Computes the char_norm_array for the unicharset and , if not NULL , the <nl> + / / pruner_array as appropriate according to the existence of the shape_table . <nl> + void Classify : : ComputeCharNormArrays ( FEATURE_STRUCT * norm_feature , <nl> + INT_TEMPLATES_STRUCT * templates , <nl> + uinT8 * char_norm_array , <nl> + uinT8 * pruner_array ) { <nl> + ComputeIntCharNormArray ( * norm_feature , char_norm_array ) ; <nl> + if ( pruner_array ! = NULL ) { <nl> + if ( shape_table_ = = NULL ) { <nl> + ComputeIntCharNormArray ( * norm_feature , pruner_array ) ; <nl> + } else { <nl> + memset ( pruner_array , MAX_UINT8 , <nl> + templates - > NumClasses * sizeof ( pruner_array [ 0 ] ) ) ; <nl> + / / Each entry in the pruner norm array is the MIN of all the entries of <nl> + / / the corresponding unichars in the CharNormArray . <nl> + for ( int id = 0 ; id < templates - > NumClasses ; + + id ) { <nl> + int font_set_id = templates - > Class [ id ] - > font_set_id ; <nl> + const FontSet & fs = fontset_table_ . get ( font_set_id ) ; <nl> + for ( int config = 0 ; config < fs . size ; + + config ) { <nl> + const Shape & shape = shape_table_ - > GetShape ( fs . configs [ config ] ) ; <nl> + for ( int c = 0 ; c < shape . size ( ) ; + + c ) { <nl> + if ( char_norm_array [ shape [ c ] . unichar_id ] < pruner_array [ id ] ) <nl> + pruner_array [ id ] = char_norm_array [ shape [ c ] . unichar_id ] ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + FreeFeature ( norm_feature ) ; <nl> + } <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> / * * <nl> PROTO_ID Classify : : MakeNewTempProtos ( FEATURE_SET Features , <nl> * @ param ClassId class containing config to be made permanent <nl> * @ param ConfigId config to be made permanent <nl> * @ param Blob current blob being adapted to <nl> - * <nl> + * <nl> * Globals : none <nl> * <nl> * @ note Exceptions : none <nl> PROTO_ID Classify : : MakeNewTempProtos ( FEATURE_SET Features , <nl> void Classify : : MakePermanent ( ADAPT_TEMPLATES Templates , <nl> CLASS_ID ClassId , <nl> int ConfigId , <nl> + const DENORM & denorm , <nl> TBLOB * Blob ) { <nl> UNICHAR_ID * Ambigs ; <nl> TEMP_CONFIG Config ; <nl> void Classify : : MakePermanent ( ADAPT_TEMPLATES Templates , <nl> Class - > NumPermConfigs + + ; <nl> <nl> / / Initialize permanent config . <nl> - Ambigs = GetAmbiguities ( Blob , ClassId ) ; <nl> + Ambigs = GetAmbiguities ( Blob , denorm , ClassId ) ; <nl> PERM_CONFIG Perm = ( PERM_CONFIG ) alloc_struct ( sizeof ( PERM_CONFIG_STRUCT ) , <nl> " PERM_CONFIG_STRUCT " ) ; <nl> Perm - > Ambigs = Ambigs ; <nl> void Classify : : MakePermanent ( ADAPT_TEMPLATES Templates , <nl> * This routine converts TempProto to be permanent if <nl> * its proto id is used by the configuration specified in <nl> * ProtoKey . <nl> - * <nl> + * <nl> * @ param TempProto temporary proto to compare to key <nl> * @ param ProtoKey defines which protos to make permanent <nl> - * <nl> + * <nl> * Globals : none <nl> - * <nl> + * <nl> * @ return TRUE if TempProto is converted , FALSE otherwise <nl> * @ note Exceptions : none <nl> * @ note History : Thu Mar 14 18 : 49 : 54 1991 , DSJ , Created . <nl> namespace tesseract { <nl> * / <nl> void Classify : : PrintAdaptiveMatchResults ( FILE * File , ADAPT_RESULTS * Results ) { <nl> for ( int i = 0 ; i < Results - > NumMatches ; + + i ) { <nl> - cprintf ( " % s ( % d ) % . 2f " , <nl> - unicharset . debug_str ( Results - > match [ i ] . id ) . string ( ) , <nl> - Results - > match [ i ] . id , <nl> + tprintf ( " % s ( % d ) , shape % d , % . 2f " , <nl> + unicharset . debug_str ( Results - > match [ i ] . unichar_id ) . string ( ) , <nl> + Results - > match [ i ] . unichar_id , Results - > match [ i ] . shape_id , <nl> Results - > match [ i ] . rating * 100 . 0 ) ; <nl> } <nl> - printf ( " \ n " ) ; <nl> + tprintf ( " \ n " ) ; <nl> } / * PrintAdaptiveMatchResults * / <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> void Classify : : PrintAdaptiveMatchResults ( FILE * File , ADAPT_RESULTS * Results ) { <nl> * <nl> * Globals : <nl> * - matcher_bad_match_pad defines a " bad match " <nl> - * <nl> + * <nl> * @ note Exceptions : none <nl> * @ note History : Tue Mar 12 13 : 51 : 03 1991 , DSJ , Created . <nl> * / <nl> void Classify : : RemoveBadMatches ( ADAPT_RESULTS * Results ) { <nl> for ( Next = NextGood = 0 ; Next < Results - > NumMatches ; Next + + ) { <nl> if ( Results - > match [ Next ] . rating < = BadMatchThreshold ) { <nl> ScoredClass match = Results - > match [ Next ] ; <nl> - if ( ! unicharset . get_isalpha ( match . id ) | | <nl> - strstr ( romans , unicharset . id_to_unichar ( match . id ) ) ! = NULL ) { <nl> + if ( ! unicharset . get_isalpha ( match . unichar_id ) | | <nl> + strstr ( romans , <nl> + unicharset . id_to_unichar ( match . unichar_id ) ) ! = NULL ) { <nl> Results - > match [ NextGood + + ] = Results - > match [ Next ] ; <nl> - } else if ( unicharset . eq ( match . id , " l " ) & & <nl> + } else if ( unicharset . eq ( match . unichar_id , " l " ) & & <nl> scored_one . rating > = BadMatchThreshold ) { <nl> Results - > match [ NextGood ] = scored_one ; <nl> Results - > match [ NextGood ] . rating = match . rating ; <nl> NextGood + + ; <nl> - } else if ( unicharset . eq ( match . id , " O " ) & & <nl> + } else if ( unicharset . eq ( match . unichar_id , " O " ) & & <nl> scored_zero . rating > = BadMatchThreshold ) { <nl> Results - > match [ NextGood ] = scored_zero ; <nl> Results - > match [ NextGood ] . rating = match . rating ; <nl> void Classify : : RemoveBadMatches ( ADAPT_RESULTS * Results ) { <nl> * <nl> * Globals : <nl> * - matcher_bad_match_pad defines a " bad match " <nl> - * <nl> + * <nl> * @ note Exceptions : none <nl> * @ note History : Tue Mar 12 13 : 51 : 03 1991 , DSJ , Created . <nl> * / <nl> void Classify : : RemoveExtraPuncs ( ADAPT_RESULTS * Results ) { <nl> digit_count = 0 ; <nl> for ( Next = NextGood = 0 ; Next < Results - > NumMatches ; Next + + ) { <nl> ScoredClass match = Results - > match [ Next ] ; <nl> - if ( strstr ( punc_chars , unicharset . id_to_unichar ( match . id ) ) ! = NULL ) { <nl> + if ( strstr ( punc_chars , <nl> + unicharset . id_to_unichar ( match . unichar_id ) ) ! = NULL ) { <nl> if ( punc_count < 2 ) <nl> Results - > match [ NextGood + + ] = match ; <nl> punc_count + + ; <nl> } else { <nl> - if ( strstr ( digit_chars , unicharset . id_to_unichar ( match . id ) ) ! = NULL ) { <nl> + if ( strstr ( digit_chars , <nl> + unicharset . id_to_unichar ( match . unichar_id ) ) ! = NULL ) { <nl> if ( digit_count < 1 ) <nl> Results - > match [ NextGood + + ] = match ; <nl> digit_count + + ; <nl> void Classify : : SetAdaptiveThreshold ( FLOAT32 Threshold ) { <nl> * @ note History : Fri Mar 22 08 : 43 : 52 1991 , DSJ , Created . <nl> * / <nl> void Classify : : ShowBestMatchFor ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> + int shape_id , <nl> BOOL8 AdaptiveOn , <nl> - BOOL8 PreTrainedOn ) { <nl> + BOOL8 PreTrainedOn , <nl> + ADAPT_RESULTS * Results ) { <nl> int NumCNFeatures = 0 , NumBLFeatures = 0 ; <nl> INT_FEATURE_ARRAY CNFeatures , BLFeatures ; <nl> INT_RESULT_STRUCT CNResult , BLResult ; <nl> void Classify : : ShowBestMatchFor ( TBLOB * Blob , <nl> uinT8 * CNAdjust = new uinT8 [ MAX_NUM_CLASSES ] ; <nl> uinT8 * BLAdjust = new uinT8 [ MAX_NUM_CLASSES ] ; <nl> <nl> - if ( PreTrainedOn ) { <nl> - if ( UnusedClassIdIn ( PreTrainedTemplates , ClassId ) ) <nl> - cprintf ( " No built - in templates for class % d = % s \ n " , <nl> - ClassId , unicharset . id_to_unichar ( ClassId ) ) ; <nl> - else { <nl> - NumCNFeatures = GetCharNormFeatures ( <nl> - Blob , PreTrainedTemplates , CNFeatures , CNAdjust , & BlobLength , NULL ) ; <nl> - if ( NumCNFeatures < = 0 ) <nl> - cprintf ( " Illegal blob ( char norm features ) ! \ n " ) ; <nl> - else { <nl> + if ( shape_table_ = = NULL ) <nl> + shape_id = ClassId ; <nl> + else <nl> + shape_id = ShapeIDToClassID ( shape_id ) ; <nl> + if ( PreTrainedOn & & shape_id > = 0 ) { <nl> + if ( UnusedClassIdIn ( PreTrainedTemplates , shape_id ) ) { <nl> + tprintf ( " No built - in templates for class / shape % d \ n " , shape_id ) ; <nl> + } else { <nl> + NumCNFeatures = GetCharNormFeatures ( Blob , denorm , PreTrainedTemplates , <nl> + CNFeatures , NULL , CNAdjust , <nl> + & BlobLength , NULL ) ; <nl> + if ( NumCNFeatures < = 0 ) { <nl> + tprintf ( " Illegal blob ( char norm features ) ! \ n " ) ; <nl> + } else { <nl> im_ . SetCharNormMatch ( classify_integer_matcher_multiplier ) ; <nl> - im_ . Match ( ClassForClassId ( PreTrainedTemplates , ClassId ) , <nl> + im_ . Match ( ClassForClassId ( PreTrainedTemplates , shape_id ) , <nl> AllProtosOn , AllConfigsOn , <nl> - BlobLength , NumCNFeatures , CNFeatures , <nl> - CNAdjust [ ClassId ] , & CNResult , <nl> + NumCNFeatures , CNFeatures , <nl> + & CNResult , <nl> classify_adapt_feature_threshold , NO_DEBUG , <nl> matcher_debug_separate_windows ) ; <nl> - <nl> - cprintf ( " Best built - in template match is config % 2d ( % 4 . 1f ) ( cn = % d ) \ n " , <nl> - CNResult . Config , CNResult . Rating * 100 . 0 , CNAdjust [ ClassId ] ) ; <nl> + ExpandShapesAndApplyCorrections ( NULL , false , shape_id , <nl> + Blob - > bounding_box ( ) . bottom ( ) , <nl> + Blob - > bounding_box ( ) . top ( ) , <nl> + 0 , BlobLength , CNAdjust , <nl> + CNResult , Results ) ; <nl> } <nl> } <nl> } <nl> <nl> if ( AdaptiveOn ) { <nl> - if ( UnusedClassIdIn ( AdaptedTemplates - > Templates , ClassId ) ) <nl> - cprintf ( " No AD templates for class % d = % s \ n " , <nl> - ClassId , unicharset . id_to_unichar ( ClassId ) ) ; <nl> - else { <nl> + if ( ClassId < 0 | | ClassId > = AdaptedTemplates - > Templates - > NumClasses ) { <nl> + tprintf ( " Invalid adapted class id : % d \ n " , ClassId ) ; <nl> + } else if ( UnusedClassIdIn ( AdaptedTemplates - > Templates , ClassId ) | | <nl> + AdaptedTemplates - > Class [ ClassId ] = = NULL | | <nl> + IsEmptyAdaptedClass ( AdaptedTemplates - > Class [ ClassId ] ) ) { <nl> + tprintf ( " No AD templates for class % d = % s \ n " , <nl> + ClassId , unicharset . id_to_unichar ( ClassId ) ) ; <nl> + } else { <nl> NumBLFeatures = GetBaselineFeatures ( Blob , <nl> + denorm , <nl> AdaptedTemplates - > Templates , <nl> BLFeatures , BLAdjust , <nl> & BlobLength ) ; <nl> if ( NumBLFeatures < = 0 ) <nl> - cprintf ( " Illegal blob ( baseline features ) ! \ n " ) ; <nl> + tprintf ( " Illegal blob ( baseline features ) ! \ n " ) ; <nl> else { <nl> im_ . SetBaseLineMatch ( ) ; <nl> - im_ . Match ( ClassForClassId <nl> - ( AdaptedTemplates - > Templates , ClassId ) , <nl> + im_ . Match ( ClassForClassId ( AdaptedTemplates - > Templates , ClassId ) , <nl> AllProtosOn , AllConfigsOn , <nl> - BlobLength , NumBLFeatures , BLFeatures , <nl> - BLAdjust [ ClassId ] , & BLResult , <nl> + NumBLFeatures , BLFeatures , <nl> + & BLResult , <nl> classify_adapt_feature_threshold , NO_DEBUG , <nl> matcher_debug_separate_windows ) ; <nl> - <nl> - # ifndef SECURE_NAMES <nl> - ADAPT_CLASS Class = AdaptedTemplates - > Class [ ClassId ] ; <nl> - cprintf ( " Best adaptive template match is config % 2d ( % 4 . 1f ) % s \ n " , <nl> - BLResult . Config , BLResult . Rating * 100 . 0 , <nl> - ConfigIsPermanent ( Class , BLResult . Config ) ? " Perm " : " Temp " ) ; <nl> - # endif <nl> + ExpandShapesAndApplyCorrections ( <nl> + AdaptedTemplates - > Class , false , <nl> + ClassId , Blob - > bounding_box ( ) . bottom ( ) , <nl> + Blob - > bounding_box ( ) . top ( ) , 0 , BlobLength , CNAdjust , <nl> + BLResult , Results ) ; <nl> } <nl> } <nl> } <nl> <nl> - cprintf ( " \ n " ) ; <nl> + tprintf ( " \ n " ) ; <nl> if ( BLResult . Rating < CNResult . Rating ) { <nl> if ( next_config < 0 ) { <nl> ConfigMask = 1 < < BLResult . Config ; <nl> void Classify : : ShowBestMatchFor ( TBLOB * Blob , <nl> classify_norm_method . set_value ( baseline ) ; <nl> <nl> im_ . SetBaseLineMatch ( ) ; <nl> + tprintf ( " Adaptive Class ID : % d \ n " , ClassId ) ; <nl> im_ . Match ( ClassForClassId ( AdaptedTemplates - > Templates , ClassId ) , <nl> AllProtosOn , ( BIT_VECTOR ) & ConfigMask , <nl> - BlobLength , NumBLFeatures , BLFeatures , <nl> - BLAdjust [ ClassId ] , & BLResult , <nl> + NumBLFeatures , BLFeatures , <nl> + & BLResult , <nl> classify_adapt_feature_threshold , <nl> matcher_debug_flags , <nl> matcher_debug_separate_windows ) ; <nl> - cprintf ( " Adaptive template match for config % 2d is % 4 . 1f \ n " , <nl> - BLResult . Config , BLResult . Rating * 100 . 0 ) ; <nl> - } <nl> - else { <nl> + ExpandShapesAndApplyCorrections ( <nl> + AdaptedTemplates - > Class , true , <nl> + ClassId , Blob - > bounding_box ( ) . bottom ( ) , <nl> + Blob - > bounding_box ( ) . top ( ) , 0 , BlobLength , CNAdjust , <nl> + BLResult , Results ) ; <nl> + } else if ( shape_id > = 0 ) { <nl> ConfigMask = 1 < < CNResult . Config ; <nl> classify_norm_method . set_value ( character ) ; <nl> <nl> + tprintf ( " Static Shape ID : % d \ n " , shape_id ) ; <nl> im_ . SetCharNormMatch ( classify_integer_matcher_multiplier ) ; <nl> - im_ . Match ( ClassForClassId ( PreTrainedTemplates , ClassId ) , <nl> + im_ . Match ( ClassForClassId ( PreTrainedTemplates , shape_id ) , <nl> AllProtosOn , ( BIT_VECTOR ) & ConfigMask , <nl> - BlobLength , NumCNFeatures , CNFeatures , <nl> - CNAdjust [ ClassId ] , & CNResult , <nl> + NumCNFeatures , CNFeatures , <nl> + & CNResult , <nl> classify_adapt_feature_threshold , <nl> matcher_debug_flags , <nl> matcher_debug_separate_windows ) ; <nl> + ExpandShapesAndApplyCorrections ( NULL , true , shape_id , <nl> + Blob - > bounding_box ( ) . bottom ( ) , <nl> + Blob - > bounding_box ( ) . top ( ) , <nl> + 0 , BlobLength , CNAdjust , <nl> + CNResult , Results ) ; <nl> } <nl> <nl> / / Clean up . <nl> void Classify : : ShowBestMatchFor ( TBLOB * Blob , <nl> delete [ ] BLAdjust ; <nl> } / * ShowBestMatchFor * / <nl> <nl> + / / Returns a string for the classifier class_id : either the corresponding <nl> + / / unicharset debug_str or the shape_table_ debug str . <nl> + STRING Classify : : ClassIDToDebugStr ( const INT_TEMPLATES_STRUCT * templates , <nl> + int class_id , int config_id ) const { <nl> + STRING class_string ; <nl> + if ( templates = = PreTrainedTemplates & & shape_table_ ! = NULL ) { <nl> + int shape_id = ClassAndConfigIDToFontOrShapeID ( class_id , config_id ) ; <nl> + class_string = shape_table_ - > DebugStr ( shape_id ) ; <nl> + } else { <nl> + class_string = unicharset . debug_str ( class_id ) ; <nl> + } <nl> + return class_string ; <nl> + } <nl> + <nl> + / / Converts a classifier class_id index to a shape_table_ index <nl> + int Classify : : ClassAndConfigIDToFontOrShapeID ( int class_id , <nl> + int int_result_config ) const { <nl> + int font_set_id = PreTrainedTemplates - > Class [ class_id ] - > font_set_id ; <nl> + / / Older inttemps have no font_ids . <nl> + if ( font_set_id < 0 ) <nl> + return kBlankFontinfoId ; <nl> + const FontSet & fs = fontset_table_ . get ( font_set_id ) ; <nl> + ASSERT_HOST ( int_result_config > = 0 & & int_result_config < fs . size ) ; <nl> + return fs . configs [ int_result_config ] ; <nl> + } <nl> + <nl> + / / Converts a shape_table_ index to a classifier class_id index ( not a <nl> + / / unichar - id ! ) . Uses a search , so not fast . <nl> + int Classify : : ShapeIDToClassID ( int shape_id ) const { <nl> + for ( int id = 0 ; id < PreTrainedTemplates - > NumClasses ; + + id ) { <nl> + int font_set_id = PreTrainedTemplates - > Class [ id ] - > font_set_id ; <nl> + ASSERT_HOST ( font_set_id > = 0 ) ; <nl> + const FontSet & fs = fontset_table_ . get ( font_set_id ) ; <nl> + for ( int config = 0 ; config < fs . size ; + + config ) { <nl> + if ( fs . configs [ config ] = = shape_id ) <nl> + return id ; <nl> + } <nl> + } <nl> + tprintf ( " Shape % d not found \ n " , shape_id ) ; <nl> + return - 1 ; <nl> + } <nl> + <nl> / / Returns true if the given TEMP_CONFIG is good enough to make it <nl> / / a permanent config . <nl> bool Classify : : TempConfigReliable ( CLASS_ID class_id , <nl> bool Classify : : TempConfigReliable ( CLASS_ID class_id , <nl> return true ; <nl> } <nl> <nl> - void Classify : : UpdateAmbigsGroup ( CLASS_ID class_id , TBLOB * Blob ) { <nl> + void Classify : : UpdateAmbigsGroup ( CLASS_ID class_id , const DENORM & denorm , <nl> + TBLOB * Blob ) { <nl> const UnicharIdVector * ambigs = <nl> getDict ( ) . getUnicharAmbigs ( ) . ReverseAmbigsForAdaption ( class_id ) ; <nl> int ambigs_size = ( ambigs = = NULL ) ? 0 : ambigs - > size ( ) ; <nl> void Classify : : UpdateAmbigsGroup ( CLASS_ID class_id , TBLOB * Blob ) { <nl> getDict ( ) . getUnicharset ( ) . debug_str ( <nl> ambig_class_id ) . string ( ) ) ; <nl> } <nl> - MakePermanent ( AdaptedTemplates , ambig_class_id , cfg , Blob ) ; <nl> + MakePermanent ( AdaptedTemplates , ambig_class_id , cfg , denorm , Blob ) ; <nl> } <nl> } <nl> } <nl> mmm a / classify / blobclass . cpp <nl> ppp b / classify / blobclass . cpp <nl> void LearnBlob ( const FEATURE_DEFS_STRUCT & FeatureDefs , FILE * FeatureFile , <nl> return ; <nl> } <nl> <nl> - / / label the features with a class name and font name <nl> - fprintf ( FeatureFile , " \ n % s % s " , FontName , BlobText ) ; <nl> - <nl> - / / write micro - features to file and clean up <nl> - WriteCharDescription ( FeatureDefs , FeatureFile , CharDesc ) ; <nl> + if ( ValidCharDescription ( FeatureDefs , CharDesc ) ) { <nl> + / / label the features with a class name and font name <nl> + fprintf ( FeatureFile , " \ n % s % s \ n " , FontName , BlobText ) ; <nl> + <nl> + / / write micro - features to file and clean up <nl> + WriteCharDescription ( FeatureDefs , FeatureFile , CharDesc ) ; <nl> + } else { <nl> + tprintf ( " Blob learned was invalid ! \ n " ) ; <nl> + } <nl> FreeCharDescription ( CharDesc ) ; <nl> <nl> } / / LearnBlob <nl> mmm a / classify / classify . cpp <nl> ppp b / classify / classify . cpp <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> # include " classify . h " <nl> + # include " fontinfo . h " <nl> # include " intproto . h " <nl> # include " mfoutline . h " <nl> # include " scrollview . h " <nl> + # include " shapetable . h " <nl> # include " unicity_table . h " <nl> # include < string . h > <nl> <nl> - namespace { <nl> - <nl> - / / Compare FontInfo structures . <nl> - bool compare_fontinfo ( const FontInfo & fi1 , const FontInfo & fi2 ) { <nl> - / / The font properties are required to be the same for two font with the same <nl> - / / name , so there is no need to test them . <nl> - / / Consequently , querying the table with only its font name as information is <nl> - / / enough to retrieve its properties . <nl> - return strcmp ( fi1 . name , fi2 . name ) = = 0 ; <nl> - } <nl> - / / Compare FontSet structures . <nl> - bool compare_font_set ( const FontSet & fs1 , const FontSet & fs2 ) { <nl> - if ( fs1 . size ! = fs2 . size ) <nl> - return false ; <nl> - for ( int i = 0 ; i < fs1 . size ; + + i ) { <nl> - if ( fs1 . configs [ i ] ! = fs2 . configs [ i ] ) <nl> - return false ; <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - void delete_callback ( FontInfo f ) { <nl> - if ( f . spacing_vec ! = NULL ) { <nl> - f . spacing_vec - > delete_data_pointers ( ) ; <nl> - delete f . spacing_vec ; <nl> - } <nl> - delete [ ] f . name ; <nl> - } <nl> - void delete_callback_fs ( FontSet fs ) { <nl> - delete [ ] fs . configs ; <nl> - } <nl> - <nl> - } <nl> - <nl> namespace tesseract { <nl> Classify : : Classify ( ) <nl> - : INT_MEMBER ( tessedit_single_match , FALSE , <nl> + : BOOL_MEMBER ( prioritize_division , FALSE , <nl> + " Prioritize blob division over chopping " , this - > params ( ) ) , <nl> + INT_MEMBER ( tessedit_single_match , FALSE , <nl> " Top choice only from CP " , this - > params ( ) ) , <nl> BOOL_MEMBER ( classify_enable_learning , true , <nl> " Enable adaptive classifier " , this - > params ( ) ) , <nl> Classify : : Classify ( ) <nl> " Penalty to apply when a non - alnum is vertically out of " <nl> " its expected textline position " , <nl> this - > params ( ) ) , <nl> - BOOL_MEMBER ( classify_enable_int_fx , 1 , " Enable integer fx " , <nl> - this - > params ( ) ) , <nl> - BOOL_MEMBER ( classify_enable_new_adapt_rules , 1 , <nl> - " Enable new adaptation rules " , this - > params ( ) ) , <nl> double_MEMBER ( rating_scale , 1 . 5 , " Rating scaling factor " , this - > params ( ) ) , <nl> double_MEMBER ( certainty_scale , 20 . 0 , " Certainty scaling factor " , <nl> this - > params ( ) ) , <nl> Classify : : Classify ( ) <nl> " One for the protos and one for the features . " , this - > params ( ) ) , <nl> STRING_MEMBER ( classify_learn_debug_str , " " , " Class str to debug learning " , <nl> this - > params ( ) ) , <nl> - INT_INIT_MEMBER ( classify_class_pruner_threshold , 229 , <nl> - " Class Pruner Threshold 0 - 255 : " , this - > params ( ) ) , <nl> - INT_INIT_MEMBER ( classify_class_pruner_multiplier , 30 , <nl> - " Class Pruner Multiplier 0 - 255 : " , this - > params ( ) ) , <nl> - INT_INIT_MEMBER ( classify_cp_cutoff_strength , 7 , <nl> - " Class Pruner CutoffStrength : " , this - > params ( ) ) , <nl> - INT_INIT_MEMBER ( classify_integer_matcher_multiplier , 14 , <nl> - " Integer Matcher Multiplier 0 - 255 : " , this - > params ( ) ) , <nl> + INT_MEMBER ( classify_class_pruner_threshold , 229 , <nl> + " Class Pruner Threshold 0 - 255 " , this - > params ( ) ) , <nl> + INT_MEMBER ( classify_class_pruner_multiplier , 30 , <nl> + " Class Pruner Multiplier 0 - 255 : " , this - > params ( ) ) , <nl> + INT_MEMBER ( classify_cp_cutoff_strength , 7 , <nl> + " Class Pruner CutoffStrength : " , this - > params ( ) ) , <nl> + INT_MEMBER ( classify_integer_matcher_multiplier , 14 , <nl> + " Integer Matcher Multiplier 0 - 255 : " , this - > params ( ) ) , <nl> EnableLearning ( true ) , <nl> INT_MEMBER ( il1_adaption_test , 0 , " Dont adapt to i / I at beginning of word " , <nl> this - > params ( ) ) , <nl> BOOL_MEMBER ( classify_bln_numeric_mode , 0 , <nl> " Assume the input is numbers [ 0 - 9 ] . " , this - > params ( ) ) , <nl> + shape_table_ ( NULL ) , <nl> dict_ ( & image_ ) { <nl> fontinfo_table_ . set_compare_callback ( <nl> - NewPermanentTessCallback ( compare_fontinfo ) ) ; <nl> + NewPermanentTessCallback ( CompareFontInfo ) ) ; <nl> fontinfo_table_ . set_clear_callback ( <nl> - NewPermanentTessCallback ( delete_callback ) ) ; <nl> + NewPermanentTessCallback ( FontInfoDeleteCallback ) ) ; <nl> fontset_table_ . set_compare_callback ( <nl> - NewPermanentTessCallback ( compare_font_set ) ) ; <nl> + NewPermanentTessCallback ( CompareFontSet ) ) ; <nl> fontset_table_ . set_clear_callback ( <nl> - NewPermanentTessCallback ( delete_callback_fs ) ) ; <nl> + NewPermanentTessCallback ( FontSetDeleteCallback ) ) ; <nl> AdaptedTemplates = NULL ; <nl> PreTrainedTemplates = NULL ; <nl> AllProtosOn = NULL ; <nl> Classify : : Classify ( ) <nl> learn_debug_win_ = NULL ; <nl> learn_fragmented_word_debug_win_ = NULL ; <nl> learn_fragments_debug_win_ = NULL ; <nl> + <nl> + CharNormCutoffs = new uinT16 [ MAX_NUM_CLASSES ] ; <nl> + BaselineCutoffs = new uinT16 [ MAX_NUM_CLASSES ] ; <nl> } <nl> <nl> Classify : : ~ Classify ( ) { <nl> Classify : : ~ Classify ( ) { <nl> delete learn_debug_win_ ; <nl> delete learn_fragmented_word_debug_win_ ; <nl> delete learn_fragments_debug_win_ ; <nl> + delete [ ] CharNormCutoffs ; <nl> + delete [ ] BaselineCutoffs ; <nl> } <nl> <nl> } / / namespace tesseract <nl> mmm a / classify / classify . h <nl> ppp b / classify / classify . h <nl> <nl> # include " classify . h " <nl> # include " dict . h " <nl> # include " featdefs . h " <nl> + # include " fontinfo . h " <nl> # include " intfx . h " <nl> # include " intmatcher . h " <nl> # include " normalis . h " <nl> static const int kBlankFontinfoId = - 2 ; <nl> <nl> namespace tesseract { <nl> <nl> + struct ShapeRating ; <nl> + class ShapeTable ; <nl> + <nl> / / How segmented is a blob . In this enum , character refers to a classifiable <nl> / / unit , but that is too long and character is usually easier to understand . <nl> enum CharSegmentationType { <nl> class Classify : public CCStruct { <nl> return dict_ ; <nl> } <nl> <nl> - / / Set the denorm for classification . Takes a copy . <nl> - void set_denorm ( const DENORM * denorm ) { <nl> - denorm_ = * denorm ; <nl> + const ShapeTable * shape_table ( ) const { <nl> + return shape_table_ ; <nl> } <nl> <nl> / * adaptive . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> ADAPT_TEMPLATES NewAdaptedTemplates ( bool InitFromUnicharset ) ; <nl> int GetFontinfoId ( ADAPT_CLASS Class , uinT8 ConfigId ) ; <nl> - int ClassPruner ( INT_TEMPLATES IntTemplates , <nl> - inT16 NumFeatures , <nl> - INT_FEATURE_ARRAY Features , <nl> - CLASS_NORMALIZATION_ARRAY NormalizationFactors , <nl> - CLASS_CUTOFF_ARRAY ExpectedNumFeatures , <nl> - CLASS_PRUNER_RESULTS Results ) ; <nl> - void ReadNewCutoffs ( FILE * CutoffFile , inT64 end_offset , <nl> + / / Runs the class pruner from int_templates on the given features , returning <nl> + / / the number of classes output in results . <nl> + / / int_templates Class pruner tables <nl> + / / num_features Number of features in blob <nl> + / / features Array of features <nl> + / / normalization_factors ( input ) Array of int_templates - > NumClasses fudge <nl> + / / factors from blob normalization process . <nl> + / / ( Indexed by CLASS_INDEX ) <nl> + / / expected_num_features ( input ) Array of int_templates - > NumClasses <nl> + / / expected number of features for each class . <nl> + / / ( Indexed by CLASS_INDEX ) <nl> + / / results ( output ) Sorted Array of pruned classes . <nl> + / / Array must be sized to take the maximum possible <nl> + / / number of outputs : int_templates - > NumClasses . <nl> + int PruneClasses ( const INT_TEMPLATES_STRUCT * int_templates , <nl> + int num_features , <nl> + const INT_FEATURE_STRUCT * features , <nl> + const uinT8 * normalization_factors , <nl> + const uinT16 * expected_num_features , <nl> + CP_RESULT_STRUCT * results ) ; <nl> + void ReadNewCutoffs ( FILE * CutoffFile , bool swap , inT64 end_offset , <nl> CLASS_CUTOFF_ARRAY Cutoffs ) ; <nl> void PrintAdaptedTemplates ( FILE * File , ADAPT_TEMPLATES Templates ) ; <nl> void WriteAdaptedTemplates ( FILE * File , ADAPT_TEMPLATES Templates ) ; <nl> ADAPT_TEMPLATES ReadAdaptedTemplates ( FILE * File ) ; <nl> / * normmatch . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - FLOAT32 ComputeNormMatch ( CLASS_ID ClassId , FEATURE Feature , BOOL8 DebugMatch ) ; <nl> + FLOAT32 ComputeNormMatch ( CLASS_ID ClassId , <nl> + const FEATURE_STRUCT & feature , BOOL8 DebugMatch ) ; <nl> void FreeNormProtos ( ) ; <nl> NORM_PROTOS * ReadNormProtos ( FILE * File , inT64 end_offset ) ; <nl> / * protos . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> class Classify : public CCStruct { <nl> INT_TEMPLATES CreateIntTemplates ( CLASSES FloatProtos , <nl> const UNICHARSET & target_unicharset ) ; <nl> / * adaptmatch . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> / / Learn the given word using its chopped_word , seam_array , denorm , <nl> / / box_word , best_state , and correct_text to learn both correctly and <nl> / / incorrectly segmented blobs . If filename is not NULL , then LearnBlob <nl> class Classify : public CCStruct { <nl> const char * correct_text , WERD_RES * word ) ; <nl> void InitAdaptiveClassifier ( bool load_pre_trained_templates ) ; <nl> void InitAdaptedClass ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> int FontinfoId , <nl> ADAPT_CLASS Class , <nl> ADAPT_TEMPLATES Templates ) ; <nl> void AdaptToPunc ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> int FontinfoId , <nl> FLOAT32 Threshold ) ; <nl> void AmbigClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> INT_TEMPLATES Templates , <nl> ADAPT_CLASS * Classes , <nl> UNICHAR_ID * Ambiguities , <nl> ADAPT_RESULTS * Results ) ; <nl> void MasterMatcher ( INT_TEMPLATES templates , <nl> inT16 num_features , <nl> - INT_FEATURE_ARRAY features , <nl> - CLASS_NORMALIZATION_ARRAY norm_factors , <nl> + const INT_FEATURE_STRUCT * features , <nl> + const uinT8 * norm_factors , <nl> ADAPT_CLASS * classes , <nl> int debug , <nl> int num_classes , <nl> const TBOX & blob_box , <nl> CLASS_PRUNER_RESULTS results , <nl> ADAPT_RESULTS * final_results ) ; <nl> - void ConvertMatchesToChoices ( ADAPT_RESULTS * Results , <nl> + / / Converts configs to fonts , and if the result is not adapted , and a <nl> + / / shape_table_ is present , the shape is expanded to include all <nl> + / / unichar_ids represented , before applying a set of corrections to the <nl> + / / distance rating in int_result , ( see ComputeCorrectedRating . ) <nl> + / / The results are added to the final_results output . <nl> + void ExpandShapesAndApplyCorrections ( ADAPT_CLASS * classes , <nl> + bool debug , <nl> + int class_id , <nl> + int bottom , int top , <nl> + float cp_rating , <nl> + int blob_length , <nl> + const uinT8 * cn_factors , <nl> + INT_RESULT_STRUCT & int_result , <nl> + ADAPT_RESULTS * final_results ) ; <nl> + / / Applies a set of corrections to the distance im_rating , <nl> + / / including the cn_correction , miss penalty and additional penalty <nl> + / / for non - alnums being vertical misfits . Returns the corrected distance . <nl> + double ComputeCorrectedRating ( bool debug , int unichar_id , double cp_rating , <nl> + double im_rating , int feature_misses , <nl> + int bottom , int top , <nl> + int blob_length , const uinT8 * cn_factors ) ; <nl> + void ConvertMatchesToChoices ( const DENORM & denorm , const TBOX & box , <nl> + ADAPT_RESULTS * Results , <nl> BLOB_CHOICE_LIST * Choices ) ; <nl> void AddNewResult ( ADAPT_RESULTS * results , <nl> - CLASS_ID class_dd , <nl> + CLASS_ID class_id , <nl> + int shape_id , <nl> FLOAT32 rating , <nl> + bool adapted , <nl> int config , <nl> - int config2 , <nl> int fontinfo_id , <nl> int fontinfo_id2 ) ; <nl> int GetAdaptiveFeatures ( TBLOB * Blob , <nl> class Classify : public CCStruct { <nl> <nl> # ifndef GRAPHICS_DISABLED <nl> void DebugAdaptiveClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> ADAPT_RESULTS * Results ) ; <nl> # endif <nl> void GetAdaptThresholds ( TWERD * Word , <nl> + const DENORM & denorm , <nl> const WERD_CHOICE & BestChoice , <nl> const WERD_CHOICE & BestRawChoice , <nl> FLOAT32 Thresholds [ ] ) ; <nl> class Classify : public CCStruct { <nl> void MakePermanent ( ADAPT_TEMPLATES Templates , <nl> CLASS_ID ClassId , <nl> int ConfigId , <nl> + const DENORM & denorm , <nl> TBLOB * Blob ) ; <nl> void PrintAdaptiveMatchResults ( FILE * File , ADAPT_RESULTS * Results ) ; <nl> void RemoveExtraPuncs ( ADAPT_RESULTS * Results ) ; <nl> void RemoveBadMatches ( ADAPT_RESULTS * Results ) ; <nl> void SetAdaptiveThreshold ( FLOAT32 Threshold ) ; <nl> void ShowBestMatchFor ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> + int shape_id , <nl> BOOL8 AdaptiveOn , <nl> - BOOL8 PreTrainedOn ) ; <nl> + BOOL8 PreTrainedOn , <nl> + ADAPT_RESULTS * Results ) ; <nl> + / / Returns a string for the classifier class_id : either the corresponding <nl> + / / unicharset debug_str or the shape_table_ debug str . <nl> + STRING ClassIDToDebugStr ( const INT_TEMPLATES_STRUCT * templates , <nl> + int class_id , int config_id ) const ; <nl> + / / Converts a classifier class_id index with a config ID to : <nl> + / / shape_table_ present : a shape_table_ index OR <nl> + / / No shape_table_ : a font ID . <nl> + / / Without shape training , each class_id , config pair represents a single <nl> + / / unichar id / font combination , so this function looks up the corresponding <nl> + / / font id . <nl> + / / With shape training , each class_id , config pair represents a single <nl> + / / shape table index , so the fontset_table stores the shape table index , <nl> + / / and the shape_table_ must be consulted to obtain the actual unichar_id / <nl> + / / font combinations that the shape represents . <nl> + int ClassAndConfigIDToFontOrShapeID ( int class_id , <nl> + int int_result_config ) const ; <nl> + / / Converts a shape_table_ index to a classifier class_id index ( not a <nl> + / / unichar - id ! ) . Uses a search , so not fast . <nl> + int ShapeIDToClassID ( int shape_id ) const ; <nl> UNICHAR_ID * BaselineClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> ADAPT_TEMPLATES Templates , <nl> ADAPT_RESULTS * Results ) ; <nl> int CharNormClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> INT_TEMPLATES Templates , <nl> ADAPT_RESULTS * Results ) ; <nl> + <nl> + / / As CharNormClassifier , but operates on a TrainingSample and outputs to <nl> + / / a GenericVector of ShapeRating without conversion to classes . <nl> + int CharNormTrainingSample ( bool pruner_only , const TrainingSample & sample , <nl> + GenericVector < ShapeRating > * results ) ; <nl> UNICHAR_ID * GetAmbiguities ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID CorrectClass ) ; <nl> void DoAdaptiveMatch ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> ADAPT_RESULTS * Results ) ; <nl> void AdaptToChar ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> CLASS_ID ClassId , <nl> int FontinfoId , <nl> FLOAT32 Threshold ) ; <nl> - void DisplayAdaptedChar ( TBLOB * blob , INT_CLASS_STRUCT * int_class ) ; <nl> + void DisplayAdaptedChar ( TBLOB * blob , const DENORM & denorm , <nl> + INT_CLASS_STRUCT * int_class ) ; <nl> int AdaptableWord ( TWERD * Word , <nl> const WERD_CHOICE & BestChoiceWord , <nl> const WERD_CHOICE & RawChoiceWord ) ; <nl> class Classify : public CCStruct { <nl> void SettupPass1 ( ) ; <nl> void SettupPass2 ( ) ; <nl> void AdaptiveClassifier ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> BLOB_CHOICE_LIST * Choices , <nl> CLASS_PRUNER_RESULTS cp_results ) ; <nl> void ClassifyAsNoise ( ADAPT_RESULTS * Results ) ; <nl> - void ResetAdaptiveClassifier ( ) ; <nl> + void ResetAdaptiveClassifierInternal ( ) ; <nl> <nl> int GetBaselineFeatures ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> INT_TEMPLATES Templates , <nl> INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> + uinT8 * CharNormArray , <nl> inT32 * BlobLength ) ; <nl> - FLOAT32 GetBestRatingFor ( TBLOB * Blob , <nl> - CLASS_ID ClassId ) ; <nl> int GetCharNormFeatures ( TBLOB * Blob , <nl> + const DENORM & denorm , <nl> INT_TEMPLATES Templates , <nl> INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> + uinT8 * PrunerNormArray , <nl> + uinT8 * CharNormArray , <nl> inT32 * BlobLength , <nl> inT32 * FeatureOutlineIndex ) ; <nl> - int GetIntBaselineFeatures ( TBLOB * Blob , <nl> - INT_TEMPLATES Templates , <nl> - INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> - inT32 * BlobLength ) ; <nl> - int GetIntCharNormFeatures ( TBLOB * Blob , <nl> - INT_TEMPLATES Templates , <nl> - INT_FEATURE_ARRAY IntFeatures , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray , <nl> - inT32 * BlobLength , <nl> - inT32 * FeatureOutlineArray ) ; <nl> + / / Computes the char_norm_array for the unicharset and , if not NULL , the <nl> + / / pruner_array as appropriate according to the existence of the shape_table . <nl> + / / The norm_feature is deleted as it is almost certainly no longer needed . <nl> + void ComputeCharNormArrays ( FEATURE_STRUCT * norm_feature , <nl> + INT_TEMPLATES_STRUCT * templates , <nl> + uinT8 * char_norm_array , <nl> + uinT8 * pruner_array ) ; <nl> <nl> bool TempConfigReliable ( CLASS_ID class_id , const TEMP_CONFIG & config ) ; <nl> - void UpdateAmbigsGroup ( CLASS_ID class_id , TBLOB * Blob ) ; <nl> + void UpdateAmbigsGroup ( CLASS_ID class_id , const DENORM & denorm , TBLOB * Blob ) ; <nl> <nl> void ResetFeaturesHaveBeenExtracted ( ) ; <nl> bool AdaptiveClassifierIsFull ( ) { return NumAdaptationsFailed > 0 ; } <nl> - bool LooksLikeGarbage ( TBLOB * blob ) ; <nl> + bool LooksLikeGarbage ( const DENORM & denorm , TBLOB * blob ) ; <nl> void RefreshDebugWindow ( ScrollView * * win , const char * msg , <nl> int y_offset , const TBOX & wbox ) ; <nl> / * float2int . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - void ComputeIntCharNormArray ( FEATURE NormFeature , <nl> - INT_TEMPLATES Templates , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ) ; <nl> + void ClearCharNormArray ( uinT8 * char_norm_array ) ; <nl> + void ComputeIntCharNormArray ( const FEATURE_STRUCT & norm_feature , <nl> + uinT8 * char_norm_array ) ; <nl> void ComputeIntFeatures ( FEATURE_SET Features , INT_FEATURE_ARRAY IntFeatures ) ; <nl> / * intproto . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> INT_TEMPLATES ReadIntTemplates ( FILE * File ) ; <nl> void WriteIntTemplates ( FILE * File , INT_TEMPLATES Templates , <nl> const UNICHARSET & target_unicharset ) ; <nl> CLASS_ID GetClassToDebug ( const char * Prompt , bool * adaptive_on , <nl> - bool * pretrained_on ) ; <nl> + bool * pretrained_on , int * shape_id ) ; <nl> void ShowMatchDisplay ( ) ; <nl> / * font detection * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> UnicityTable < FontInfo > & get_fontinfo_table ( ) { <nl> class Classify : public CCStruct { <nl> / / Member variables . <nl> <nl> / / Parameters . <nl> + BOOL_VAR_H ( prioritize_division , FALSE , <nl> + " Prioritize blob division over chopping " ) ; <nl> INT_VAR_H ( tessedit_single_match , FALSE , " Top choice only from CP " ) ; <nl> BOOL_VAR_H ( classify_enable_learning , true , " Enable adaptive classifier " ) ; <nl> INT_VAR_H ( classify_debug_level , 0 , " Classify debug level " ) ; <nl> class Classify : public CCStruct { <nl> double_VAR_H ( classify_misfit_junk_penalty , 0 . 0 , <nl> " Penalty to apply when a non - alnum is vertically out of " <nl> " its expected textline position " ) ; <nl> - BOOL_VAR_H ( classify_enable_int_fx , 1 , " Enable integer fx " ) ; <nl> - BOOL_VAR_H ( classify_enable_new_adapt_rules , 1 , " Enable new adaptation rules " ) ; <nl> double_VAR_H ( rating_scale , 1 . 5 , " Rating scaling factor " ) ; <nl> double_VAR_H ( certainty_scale , 20 . 0 , " Certainty scaling factor " ) ; <nl> double_VAR_H ( tessedit_class_miss_scale , 0 . 00390625 , <nl> class Classify : public CCStruct { <nl> <nl> / * intmatcher . cpp * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> INT_VAR_H ( classify_class_pruner_threshold , 229 , <nl> - " Class Pruner Threshold 0 - 255 : " ) ; <nl> + " Class Pruner Threshold 0 - 255 " ) ; <nl> INT_VAR_H ( classify_class_pruner_multiplier , 30 , <nl> " Class Pruner Multiplier 0 - 255 : " ) ; <nl> INT_VAR_H ( classify_cp_cutoff_strength , 7 , <nl> class Classify : public CCStruct { <nl> NORM_PROTOS * NormProtos ; <nl> / * font detection * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> UnicityTable < FontInfo > fontinfo_table_ ; <nl> + / / Without shape training , each class_id , config pair represents a single <nl> + / / unichar id / font combination , so each fontset_table_ entry holds font ids <nl> + / / for each config in the class . <nl> + / / With shape training , each class_id , config pair represents a single <nl> + / / shape_table_ index , so the fontset_table_ stores the shape_table_ index , <nl> + / / and the shape_table_ must be consulted to obtain the actual unichar_id / <nl> + / / font combinations that the shape represents . <nl> UnicityTable < FontSet > fontset_table_ ; <nl> <nl> INT_VAR_H ( il1_adaption_test , 0 , " Dont adapt to i / I at beginning of word " ) ; <nl> BOOL_VAR_H ( classify_bln_numeric_mode , 0 , <nl> " Assume the input is numbers [ 0 - 9 ] . " ) ; <nl> + <nl> protected : <nl> IntegerMatcher im_ ; <nl> FEATURE_DEFS_STRUCT feature_defs_ ; <nl> - / / Must be set for the classifier to operate . Ususally set in <nl> - / / Tesseract : : recog_word_recursive , being the main word - level entry point . <nl> - DENORM denorm_ ; <nl> + / / If a shape_table_ is present , it is used to remap classifier output in <nl> + / / ExpandShapesAndApplyCorrections . font_ids referenced by configs actually <nl> + / / mean an index to the shape_table_ and the choices returned are * all * the <nl> + / / shape_table_ entries at that index . <nl> + ShapeTable * shape_table_ ; <nl> <nl> private : <nl> <nl> class Classify : public CCStruct { <nl> INT_FEATURE_ARRAY CharNormFeatures ; <nl> INT_FX_RESULT_STRUCT FXInfo ; <nl> <nl> - CLASS_CUTOFF_ARRAY CharNormCutoffs ; <nl> - CLASS_CUTOFF_ARRAY BaselineCutoffs ; <nl> + / / Expected number of features in the class pruner , used to penalize <nl> + / / unknowns that have too few features ( like a c being classified as e ) so <nl> + / / it doesn ' t recognize everything as ' @ ' or ' # ' . <nl> + / / CharNormCutoffs is for the static classifier ( with no shapetable ) . <nl> + / / BaselineCutoffs gets a copy of CharNormCutoffs as an estimate of the real <nl> + / / value in the adaptive classifier . Both are indexed by unichar_id . <nl> + / / shapetable_cutoffs_ provides a similar value for each shape in the <nl> + / / shape_table_ <nl> + uinT16 * CharNormCutoffs ; <nl> + uinT16 * BaselineCutoffs ; <nl> + GenericVector < uinT16 > shapetable_cutoffs_ ; <nl> ScrollView * learn_debug_win_ ; <nl> ScrollView * learn_fragmented_word_debug_win_ ; <nl> ScrollView * learn_fragments_debug_win_ ; <nl> mmm a / classify / cluster . cpp <nl> ppp b / classify / cluster . cpp <nl> <nl> # include " cluster . h " <nl> # include " emalloc . h " <nl> # include " helpers . h " <nl> + # include " matrix . h " <nl> # include " tprintf . h " <nl> # include " danerror . h " <nl> # include " freelist . h " <nl> const double FTable [ FTABLE_Y ] [ FTABLE_X ] = { <nl> dimension of any feature . Since most features are calculated from numbers <nl> with a precision no better than 1 in 128 , the variance should never be <nl> less than the square of this number for parameters whose range is 1 . * / <nl> - # define MINVARIANCE 0 . 0001 <nl> + # define MINVARIANCE 0 . 0004 <nl> <nl> / * define the absolute minimum number of samples which must be present in <nl> order to accurately test hypotheses about underlying probability <nl> const double FTable [ FTABLE_Y ] [ FTABLE_X ] = { <nl> before a statistical analysis is attempted ; this number should be <nl> equal to MINSAMPLES but can be set to a lower number for early testing <nl> when very few samples are available . * / <nl> - # define MINBUCKETS 5 <nl> # define MINSAMPLESPERBUCKET 5 <nl> # define MINSAMPLES ( MINBUCKETS * MINSAMPLESPERBUCKET ) <nl> # define MINSAMPLESNEEDED 1 <nl> static const FLOAT64 kNormalMean = BUCKETTABLESIZE / 2 ; <nl> / * define lookup tables used to compute the number of histogram buckets <nl> that should be used for a given number of samples . * / <nl> # define LOOKUPTABLESIZE 8 <nl> - # define MAXBUCKETS 39 <nl> # define MAXDEGREESOFFREEDOM MAXBUCKETS <nl> <nl> static const uinT32 kCountTable [ LOOKUPTABLESIZE ] = { <nl> BOOL8 DistributionOK ( BUCKETS * Buckets ) ; <nl> <nl> void FreeStatistics ( STATISTICS * Statistics ) ; <nl> <nl> - void FreeBuckets ( CLUSTERER * clusterer , <nl> - BUCKETS * Buckets ) ; <nl> + void FreeBuckets ( BUCKETS * Buckets ) ; <nl> <nl> void FreeCluster ( CLUSTER * Cluster ) ; <nl> <nl> MakeClusterer ( inT16 SampleSize , const PARAM_DESC ParamDesc [ ] ) { <nl> / / allocate a kd tree to hold the samples <nl> Clusterer - > KDTree = MakeKDTree ( SampleSize , ParamDesc ) ; <nl> <nl> - / / keep a list of histogram buckets to minimize recomputing them <nl> - Clusterer - > bucket_cache [ 0 ] = NIL_LIST ; <nl> - Clusterer - > bucket_cache [ 1 ] = NIL_LIST ; <nl> - Clusterer - > bucket_cache [ 2 ] = NIL_LIST ; <nl> + / / Initialize cache of histogram buckets to minimize recomputing them . <nl> + for ( int d = 0 ; d < DISTRIBUTION_COUNT ; + + d ) { <nl> + for ( int c = 0 ; c < MAXBUCKETS + 1 - MINBUCKETS ; + + c ) <nl> + Clusterer - > bucket_cache [ d ] [ c ] = NULL ; <nl> + } <nl> <nl> return Clusterer ; <nl> } / / MakeClusterer <nl> Exceptions : ALREADYCLUSTERED MakeSample can ' t be called after <nl> ClusterSamples has been called <nl> History : 5 / 29 / 89 , DSJ , Created . <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - SAMPLE * <nl> - MakeSample ( CLUSTERER * Clusterer , FLOAT32 Feature [ ] , inT32 CharID ) { <nl> + SAMPLE * MakeSample ( CLUSTERER * Clusterer , const FLOAT32 * Feature , <nl> + inT32 CharID ) { <nl> SAMPLE * Sample ; <nl> int i ; <nl> <nl> void FreeClusterer ( CLUSTERER * Clusterer ) { <nl> FreeKDTree ( Clusterer - > KDTree ) ; <nl> if ( Clusterer - > Root ! = NULL ) <nl> FreeCluster ( Clusterer - > Root ) ; <nl> - iterate ( Clusterer - > ProtoList ) { <nl> - ( ( PROTOTYPE * ) ( first_node ( Clusterer - > ProtoList ) ) ) - > Cluster = NULL ; <nl> + / / Free up all used buckets structures . <nl> + for ( int d = 0 ; d < DISTRIBUTION_COUNT ; + + d ) { <nl> + for ( int c = 0 ; c < MAXBUCKETS + 1 - MINBUCKETS ; + + c ) <nl> + if ( Clusterer - > bucket_cache [ d ] [ c ] ! = NULL ) <nl> + FreeBuckets ( Clusterer - > bucket_cache [ d ] [ c ] ) ; <nl> } <nl> + <nl> memfree ( Clusterer ) ; <nl> } <nl> } / / FreeClusterer <nl> FLOAT32 StandardDeviation ( PROTOTYPE * Proto , uinT16 Dimension ) { <nl> case uniform : <nl> case D_random : <nl> return ( Proto - > Variance . Elliptical [ Dimension ] ) ; <nl> + case DISTRIBUTION_COUNT : <nl> + ASSERT_HOST ( ! " Distribution count not allowed ! " ) ; <nl> } <nl> } <nl> return 0 . 0f ; <nl> PROTOTYPE * MakePrototype ( CLUSTERER * Clusterer , <nl> Config - > Confidence ) ; <nl> break ; <nl> } <nl> - FreeBuckets ( Clusterer , Buckets ) ; <nl> FreeStatistics ( Statistics ) ; <nl> return Proto ; <nl> } / / MakePrototype <nl> PROTOTYPE * MakeMixedProto ( CLUSTERER * Clusterer , <nl> FreePrototype ( Proto ) ; <nl> Proto = NULL ; <nl> } <nl> - if ( UniformBuckets ! = NULL ) <nl> - FreeBuckets ( Clusterer , UniformBuckets ) ; <nl> - if ( RandomBuckets ! = NULL ) <nl> - FreeBuckets ( Clusterer , RandomBuckets ) ; <nl> return ( Proto ) ; <nl> } / / MakeMixedProto <nl> <nl> PROTOTYPE * NewSimpleProto ( inT16 N , CLUSTER * Cluster ) { <nl> Proto - > Distrib = NULL ; <nl> <nl> Proto - > Significant = TRUE ; <nl> + Proto - > Merged = FALSE ; <nl> Proto - > Style = spherical ; <nl> Proto - > NumSamples = Cluster - > SampleCount ; <nl> Proto - > Cluster = Cluster ; <nl> BUCKETS * GetBuckets ( CLUSTERER * clusterer , <nl> DISTRIBUTION Distribution , <nl> uinT32 SampleCount , <nl> FLOAT64 Confidence ) { <nl> - / / search for an old bucket structure with the same number of buckets <nl> - LIST * bucket_cache = clusterer - > bucket_cache ; <nl> + / / Get an old bucket structure with the same number of buckets . <nl> uinT16 NumberOfBuckets = OptimumNumberOfBuckets ( SampleCount ) ; <nl> - BUCKETS * Buckets = ( BUCKETS * ) first_node ( search ( <nl> - bucket_cache [ ( int ) Distribution ] , & NumberOfBuckets , <nl> - NumBucketsMatch ) ) ; <nl> - <nl> - / / if a matching bucket structure is found , delete it from the list <nl> - if ( Buckets ! = NULL ) { <nl> - bucket_cache [ ( int ) Distribution ] = <nl> - delete_d ( bucket_cache [ ( int ) Distribution ] , Buckets , ListEntryMatch ) ; <nl> + BUCKETS * Buckets = <nl> + clusterer - > bucket_cache [ Distribution ] [ NumberOfBuckets - MINBUCKETS ] ; <nl> + <nl> + / / If a matching bucket structure is not found , make one and save it . <nl> + if ( Buckets = = NULL ) { <nl> + Buckets = MakeBuckets ( Distribution , SampleCount , Confidence ) ; <nl> + clusterer - > bucket_cache [ Distribution ] [ NumberOfBuckets - MINBUCKETS ] = <nl> + Buckets ; <nl> + } else { <nl> + / / Just adjust the existing buckets . <nl> if ( SampleCount ! = Buckets - > SampleCount ) <nl> AdjustBuckets ( Buckets , SampleCount ) ; <nl> if ( Confidence ! = Buckets - > Confidence ) { <nl> BUCKETS * GetBuckets ( CLUSTERER * clusterer , <nl> Confidence ) ; <nl> } <nl> InitBuckets ( Buckets ) ; <nl> - } else { <nl> - / / otherwise create a new structure <nl> - Buckets = MakeBuckets ( Distribution , SampleCount , Confidence ) ; <nl> } <nl> return Buckets ; <nl> } / / GetBuckets <nl> BUCKETS * MakeBuckets ( DISTRIBUTION Distribution , <nl> BOOL8 Symmetrical ; <nl> <nl> / / allocate memory needed for data structure <nl> - Buckets = ( BUCKETS * ) Emalloc ( sizeof ( BUCKETS ) ) ; <nl> - Buckets - > NumberOfBuckets = OptimumNumberOfBuckets ( SampleCount ) ; <nl> + Buckets = reinterpret_cast < BUCKETS * > ( Emalloc ( sizeof ( BUCKETS ) ) ) ; <nl> + Buckets - > NumberOfBuckets = OptimumNumberOfBuckets ( SampleCount ) ; <nl> Buckets - > SampleCount = SampleCount ; <nl> Buckets - > Confidence = Confidence ; <nl> - Buckets - > Count = <nl> - ( uinT32 * ) Emalloc ( Buckets - > NumberOfBuckets * sizeof ( uinT32 ) ) ; <nl> - Buckets - > ExpectedCount = <nl> - ( FLOAT32 * ) Emalloc ( Buckets - > NumberOfBuckets * sizeof ( FLOAT32 ) ) ; <nl> + Buckets - > Count = reinterpret_cast < uinT32 * > ( <nl> + Emalloc ( Buckets - > NumberOfBuckets * sizeof ( uinT32 ) ) ) ; <nl> + Buckets - > ExpectedCount = reinterpret_cast < FLOAT32 * > ( <nl> + Emalloc ( Buckets - > NumberOfBuckets * sizeof ( FLOAT32 ) ) ) ; <nl> <nl> / / initialize simple fields <nl> Buckets - > Distribution = Distribution ; <nl> void FreeStatistics ( STATISTICS * Statistics ) { <nl> <nl> <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm <nl> - void FreeBuckets ( CLUSTERER * clusterer , BUCKETS * buckets ) { <nl> + void FreeBuckets ( BUCKETS * buckets ) { <nl> / * <nl> * * Parameters : <nl> - * * clusterer - > bucket_cache <nl> - * * distribution - indexed cache of old bucket structures . <nl> * * buckets pointer to data structure to be freed <nl> * * Operation : <nl> - * * This routine places the specified histogram data structure <nl> - * * at the front of a list of histograms so that it can be reused <nl> - * * later if necessary . A separate list is maintained for each <nl> - * * different type of distribution . <nl> + * * This routine properly frees the memory used by a BUCKETS . <nl> * / <nl> - LIST * bucket_cache = clusterer - > bucket_cache ; <nl> - if ( buckets ! = NULL ) { <nl> - int dist = ( int ) buckets - > Distribution ; <nl> - bucket_cache [ dist ] = ( LIST ) push ( bucket_cache [ dist ] , buckets ) ; <nl> - } <nl> + Efree ( buckets - > Count ) ; <nl> + Efree ( buckets - > ExpectedCount ) ; <nl> + Efree ( buckets ) ; <nl> } / / FreeBuckets <nl> <nl> <nl> CLUSTER * Cluster , FLOAT32 MaxIllegal ) <nl> } <nl> NumCharInCluster - - ; <nl> PercentIllegal = ( FLOAT32 ) NumIllegalInCluster / NumCharInCluster ; <nl> - if ( PercentIllegal > MaxIllegal ) <nl> + if ( PercentIllegal > MaxIllegal ) { <nl> + destroy ( SearchState ) ; <nl> return ( TRUE ) ; <nl> + } <nl> } <nl> } <nl> return ( FALSE ) ; <nl> CLUSTER * Cluster , FLOAT32 MaxIllegal ) <nl> / / The return value is the sum of norms of the off - diagonal terms of the <nl> / / product of a and inv . ( A measure of the error . ) <nl> double InvertMatrix ( const float * input , int size , float * inv ) { <nl> - double * * U ; / / The upper triangular array . <nl> - double * Umem ; <nl> - double * * U_inv ; / / The inverse of U . <nl> - double * U_invmem ; <nl> - double * * L ; / / The lower triangular array . <nl> - double * Lmem ; <nl> - <nl> / / Allocate memory for the 2D arrays . <nl> - ALLOC_2D_ARRAY ( size , size , Umem , U , double ) ; <nl> - ALLOC_2D_ARRAY ( size , size , U_invmem , U_inv , double ) ; <nl> - ALLOC_2D_ARRAY ( size , size , Lmem , L , double ) ; <nl> + GENERIC_2D_ARRAY < double > U ( size , size , 0 . 0 ) ; <nl> + GENERIC_2D_ARRAY < double > U_inv ( size , size , 0 . 0 ) ; <nl> + GENERIC_2D_ARRAY < double > L ( size , size , 0 . 0 ) ; <nl> <nl> / / Initialize the working matrices . U starts as input , L as I and U_inv as O . <nl> int row ; <nl> mmm a / classify / cluster . h <nl> ppp b / classify / cluster . h <nl> <nl> # include " kdtree . h " <nl> # include " oldlist . h " <nl> <nl> + struct BUCKETS ; <nl> + <nl> + # define MINBUCKETS 5 <nl> + # define MAXBUCKETS 39 <nl> + <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Types <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * / <nl> typedef struct { / / parameters to control clustering <nl> } CLUSTERCONFIG ; <nl> <nl> typedef enum { <nl> - normal , uniform , D_random <nl> + normal , uniform , D_random , DISTRIBUTION_COUNT <nl> } DISTRIBUTION ; <nl> <nl> typedef union { <nl> typedef struct { <nl> CLUSTER * Root ; / / ptr to root cluster of cluster tree <nl> LIST ProtoList ; / / list of prototypes <nl> inT32 NumChar ; / / # of characters represented by samples <nl> - LIST bucket_cache [ 3 ] ; / / cache of reusable histograms by distribution type <nl> + / / cache of reusable histograms by distribution type and number of buckets . <nl> + BUCKETS * bucket_cache [ DISTRIBUTION_COUNT ] [ MAXBUCKETS + 1 - MINBUCKETS ] ; <nl> } CLUSTERER ; <nl> <nl> typedef struct { <nl> typedef struct { <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> CLUSTERER * MakeClusterer ( inT16 SampleSize , const PARAM_DESC ParamDesc [ ] ) ; <nl> <nl> - SAMPLE * MakeSample ( CLUSTERER * Clusterer , FLOAT32 Feature [ ] , inT32 CharID ) ; <nl> + SAMPLE * MakeSample ( CLUSTERER * Clusterer , const FLOAT32 * Feature , inT32 CharID ) ; <nl> <nl> LIST ClusterSamples ( CLUSTERER * Clusterer , CLUSTERCONFIG * Config ) ; <nl> <nl> mmm a / classify / clusttool . cpp <nl> ppp b / classify / clusttool . cpp <nl> PROTOTYPE * ReadPrototype ( FILE * File , uinT16 N ) { <nl> Proto - > Magnitude . Elliptical [ i ] = 1 . 0 / <nl> ( 2 . 0 * Proto - > Variance . Elliptical [ i ] ) ; <nl> break ; <nl> + case DISTRIBUTION_COUNT : <nl> + ASSERT_HOST ( ! " Distribution count not allowed ! " ) ; <nl> } <nl> Proto - > TotalMagnitude * = Proto - > Magnitude . Elliptical [ i ] ; <nl> } <nl> void WritePrototype ( FILE * File , uinT16 N , PROTOTYPE * Proto ) { <nl> case D_random : <nl> fprintf ( File , " % 9s " , " random " ) ; <nl> break ; <nl> + case DISTRIBUTION_COUNT : <nl> + ASSERT_HOST ( ! " Distribution count not allowed ! " ) ; <nl> } <nl> fprintf ( File , " \ n \ t " ) ; <nl> WriteNFloats ( File , N , Proto - > Variance . Elliptical ) ; <nl> Return : None <nl> Exceptions : None <nl> History : 6 / 6 / 89 , DSJ , Created . <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - void <nl> - WriteNFloats ( FILE * File , uinT16 N , FLOAT32 Array [ ] ) { <nl> - int i ; <nl> - <nl> - for ( i = 0 ; i < N ; i + + ) <nl> - fprintf ( File , " % 9 . 6f " , Array [ i ] ) ; <nl> - fprintf ( File , " \ n " ) ; <nl> + void WriteNFloats ( FILE * File , uinT16 N , FLOAT32 Array [ ] ) { <nl> + for ( int i = 0 ; i < N ; i + + ) <nl> + fprintf ( File , " % 9 . 6f " , Array [ i ] ) ; <nl> + fprintf ( File , " \ n " ) ; <nl> } / / WriteNFloats <nl> <nl> <nl> void WriteProtoList ( <nl> } <nl> } / * WriteProtoList * / <nl> <nl> - / * * UniformRandomNumber * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - Parameters : MMin lower range of uniform distribution <nl> - MMax upper range of uniform distribution <nl> - Globals : None <nl> - Operation : This routine computes a random number which comes from a <nl> - uniform distribution over the range from MMin to MMax . <nl> - Return : Uniform random number <nl> - Exceptions : None <nl> - History : 6 / 6 / 89 , DSJ , Created . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - FLOAT32 UniformRandomNumber ( FLOAT32 MMin , FLOAT32 MMax ) { <nl> - double fake_drand48 ( ) ; <nl> - FLOAT32 RandomNumber ; <nl> - <nl> - RandomNumber = fake_drand48 ( ) ; <nl> - return ( MMin + ( RandomNumber * ( MMax - MMin ) ) ) ; <nl> - } / / UniformRandomNumber <nl> - <nl> - <nl> - / * * drand48 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - Cheap replacement for drand48 which is not available on the PC . <nl> - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - double fake_drand48 ( ) { <nl> - return rand ( ) / ( RAND_MAX + 1 . 0 ) ; <nl> - } <nl> mmm a / classify / clusttool . h <nl> ppp b / classify / clusttool . h <nl> void WriteProtoList ( <nl> BOOL8 WriteSigProtos , <nl> BOOL8 WriteInsigProtos ) ; <nl> <nl> - FLOAT32 UniformRandomNumber ( FLOAT32 MMin , FLOAT32 MMax ) ; <nl> - <nl> / / mmmmmmmmmmmm - - Global Data Definitions and Declarationsmmmmmmmmmmmmmmmmmmmmm <nl> / / define errors that can be trapped <nl> # define ILLEGALSAMPLESIZE 5000 <nl> mmm a / classify / cutoffs . cpp <nl> ppp b / classify / cutoffs . cpp <nl> <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> namespace tesseract { <nl> - void Classify : : ReadNewCutoffs ( FILE * CutoffFile , inT64 end_offset , <nl> + void Classify : : ReadNewCutoffs ( FILE * CutoffFile , bool swap , inT64 end_offset , <nl> CLASS_CUTOFF_ARRAY Cutoffs ) { <nl> / * <nl> * * Parameters : <nl> void Classify : : ReadNewCutoffs ( FILE * CutoffFile , inT64 end_offset , <nl> int Cutoff ; <nl> int i ; <nl> <nl> + if ( shape_table_ ! = NULL ) { <nl> + if ( ! shapetable_cutoffs_ . DeSerialize ( swap , CutoffFile ) ) { <nl> + tprintf ( " Error during read of shapetable pffmtable ! \ n " ) ; <nl> + } <nl> + } <nl> for ( i = 0 ; i < MAX_NUM_CLASSES ; i + + ) <nl> Cutoffs [ i ] = MAX_CUTOFF ; <nl> <nl> new file mode 100644 <nl> index 000000000 . . 52d5ac560 <nl> mmm / dev / null <nl> ppp b / classify / errorcounter . cpp <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " errorcounter . h " <nl> + <nl> + # include " fontinfo . h " <nl> + # include " ndminx . h " <nl> + # include " sampleiterator . h " <nl> + # include " shapeclassifier . h " <nl> + # include " shapetable . h " <nl> + # include " trainingsample . h " <nl> + # include " trainingsampleset . h " <nl> + # include " unicity_table . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + / / Tests a classifier , computing its error rate . <nl> + / / See errorcounter . h for description of arguments . <nl> + / / Iterates over the samples , calling the classifier in normal / silent mode . <nl> + / / If the classifier makes a CT_UNICHAR_TOPN_ERR error , and the appropriate <nl> + / / report_level is set ( 4 or greater ) , it will then call the classifier again <nl> + / / with a debug flag and a keep_this argument to find out what is going on . <nl> + double ErrorCounter : : ComputeErrorRate ( ShapeClassifier * classifier , <nl> + int report_level , CountTypes boosting_mode , <nl> + const UnicityTable < FontInfo > & fontinfo_table , <nl> + const GenericVector < Pix * > & page_images , SampleIterator * it , <nl> + double * unichar_error , double * scaled_error , STRING * fonts_report ) { <nl> + int charsetsize = it - > shape_table ( ) - > unicharset ( ) . size ( ) ; <nl> + int shapesize = it - > CompactCharsetSize ( ) ; <nl> + int fontsize = it - > sample_set ( ) - > NumFonts ( ) ; <nl> + ErrorCounter counter ( charsetsize , shapesize , fontsize ) ; <nl> + GenericVector < ShapeRating > results ; <nl> + <nl> + clock_t start = clock ( ) ; <nl> + int total_samples = 0 ; <nl> + double unscaled_error = 0 . 0 ; <nl> + / / Set a number of samples on which to run the classify debug mode . <nl> + int error_samples = report_level > 3 ? report_level * report_level : 0 ; <nl> + / / Iterate over all the samples , accumulating errors . <nl> + for ( it - > Begin ( ) ; ! it - > AtEnd ( ) ; it - > Next ( ) ) { <nl> + TrainingSample * mutable_sample = it - > MutableSample ( ) ; <nl> + int page_index = mutable_sample - > page_num ( ) ; <nl> + Pix * page_pix = 0 < = page_index & & page_index < page_images . size ( ) <nl> + ? page_images [ page_index ] : NULL ; <nl> + / / No debug , no keep this . <nl> + classifier - > ClassifySample ( * mutable_sample , page_pix , 0 , INVALID_UNICHAR_ID , <nl> + & results ) ; <nl> + if ( mutable_sample - > class_id ( ) = = 0 ) { <nl> + / / This is junk so use the special counter . <nl> + counter . AccumulateJunk ( * it - > shape_table ( ) , results , mutable_sample ) ; <nl> + } else if ( counter . AccumulateErrors ( report_level > 3 , boosting_mode , <nl> + fontinfo_table , * it - > shape_table ( ) , <nl> + results , mutable_sample ) & & <nl> + error_samples > 0 ) { <nl> + / / Running debug , keep the correct answer , and debug the classifier . <nl> + tprintf ( " Error on sample % d : Classifier debug output : \ n " , <nl> + it - > GlobalSampleIndex ( ) ) ; <nl> + int keep_this = it - > GetSparseClassID ( ) ; <nl> + classifier - > ClassifySample ( * mutable_sample , page_pix , 1 , keep_this , <nl> + & results ) ; <nl> + - - error_samples ; <nl> + } <nl> + + + total_samples ; <nl> + } <nl> + double total_time = 1 . 0 * ( clock ( ) - start ) / CLOCKS_PER_SEC ; <nl> + / / Create the appropriate error report . <nl> + unscaled_error = counter . ReportErrors ( report_level , boosting_mode , <nl> + fontinfo_table , <nl> + * it , unichar_error , fonts_report ) ; <nl> + if ( scaled_error ! = NULL ) * scaled_error = counter . scaled_error_ ; <nl> + if ( report_level > 1 ) { <nl> + / / It is useful to know the time in microseconds / char . <nl> + tprintf ( " Errors computed in % . 2fs at % . 1f μs / char \ n " , <nl> + total_time , 1000000 . 0 * total_time / total_samples ) ; <nl> + } <nl> + return unscaled_error ; <nl> + } <nl> + <nl> + / / Constructor is private . Only anticipated use of ErrorCounter is via <nl> + / / the static ComputeErrorRate . <nl> + ErrorCounter : : ErrorCounter ( int charsetsize , int shapesize , int fontsize ) <nl> + : scaled_error_ ( 0 . 0 ) , unichar_counts_ ( charsetsize , shapesize , 0 ) { <nl> + Counts empty_counts ; <nl> + font_counts_ . init_to_size ( fontsize , empty_counts ) ; <nl> + } <nl> + ErrorCounter : : ~ ErrorCounter ( ) { <nl> + } <nl> + <nl> + / / Accumulates the errors from the classifier results on a single sample . <nl> + / / Returns true if debug is true and a CT_UNICHAR_TOPN_ERR error occurred . <nl> + / / boosting_mode selects the type of error to be used for boosting and the <nl> + / / is_error_ member of sample is set according to whether the required type <nl> + / / of error occurred . The font_table provides access to font properties <nl> + / / for error counting and shape_table is used to understand the relationship <nl> + / / between unichar_ids and shape_ids in the results <nl> + bool ErrorCounter : : AccumulateErrors ( bool debug , CountTypes boosting_mode , <nl> + const UnicityTable < FontInfo > & font_table , <nl> + const ShapeTable & shape_table , <nl> + const GenericVector < ShapeRating > & results , <nl> + TrainingSample * sample ) { <nl> + int num_results = results . size ( ) ; <nl> + int res_index = 0 ; <nl> + bool debug_it = false ; <nl> + int font_id = sample - > font_id ( ) ; <nl> + int unichar_id = sample - > class_id ( ) ; <nl> + sample - > set_is_error ( false ) ; <nl> + if ( num_results = = 0 ) { <nl> + / / Reject . We count rejects as a separate category , but still mark the <nl> + / / sample as an error in case any training module wants to use that to <nl> + / / improve the classifier . <nl> + sample - > set_is_error ( true ) ; <nl> + + + font_counts_ [ font_id ] . n [ CT_REJECT ] ; <nl> + } else if ( shape_table . GetShape ( results [ 0 ] . shape_id ) . <nl> + ContainsUnicharAndFont ( unichar_id , font_id ) ) { <nl> + + + font_counts_ [ font_id ] . n [ CT_SHAPE_TOP_CORRECT ] ; <nl> + / / Unichar and font OK , but count if multiple unichars . <nl> + if ( shape_table . GetShape ( results [ 0 ] . shape_id ) . size ( ) > 1 ) <nl> + + + font_counts_ [ font_id ] . n [ CT_OK_MULTI_UNICHAR ] ; <nl> + } else { <nl> + / / This is a top shape error . <nl> + + + font_counts_ [ font_id ] . n [ CT_SHAPE_TOP_ERR ] ; <nl> + / / Check to see if any font in the top choice has attributes that match . <nl> + bool attributes_match = false ; <nl> + uinT32 font_props = font_table . get ( font_id ) . properties ; <nl> + const Shape & shape = shape_table . GetShape ( results [ 0 ] . shape_id ) ; <nl> + for ( int c = 0 ; c < shape . size ( ) & & ! attributes_match ; + + c ) { <nl> + for ( int f = 0 ; f < shape [ c ] . font_ids . size ( ) ; + + f ) { <nl> + if ( font_table . get ( shape [ c ] . font_ids [ f ] ) . properties = = font_props ) { <nl> + attributes_match = true ; <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + / / TODO ( rays ) It is easy to add counters for individual font attributes <nl> + / / here if we want them . <nl> + if ( ! attributes_match ) <nl> + + + font_counts_ [ font_id ] . n [ CT_FONT_ATTR_ERR ] ; <nl> + if ( boosting_mode = = CT_SHAPE_TOP_ERR ) sample - > set_is_error ( true ) ; <nl> + / / Find rank of correct unichar answer . ( Ignoring the font . ) <nl> + while ( res_index < num_results & & <nl> + ! shape_table . GetShape ( results [ res_index ] . shape_id ) . <nl> + ContainsUnichar ( unichar_id ) ) { <nl> + + + res_index ; <nl> + } <nl> + if ( res_index = = 0 ) { <nl> + / / Unichar OK , but count if multiple unichars . <nl> + if ( shape_table . GetShape ( results [ res_index ] . shape_id ) . size ( ) > 1 ) { <nl> + + + font_counts_ [ font_id ] . n [ CT_OK_MULTI_UNICHAR ] ; <nl> + } <nl> + } else { <nl> + / / Count maps from unichar id to shape id . <nl> + if ( num_results > 0 ) <nl> + + + unichar_counts_ ( unichar_id , results [ 0 ] . shape_id ) ; <nl> + / / This is a unichar error . <nl> + + + font_counts_ [ font_id ] . n [ CT_UNICHAR_TOP1_ERR ] ; <nl> + if ( boosting_mode = = CT_UNICHAR_TOP1_ERR ) sample - > set_is_error ( true ) ; <nl> + if ( res_index > = MIN ( 2 , num_results ) ) { <nl> + / / It is also a 2nd choice unichar error . <nl> + + + font_counts_ [ font_id ] . n [ CT_UNICHAR_TOP2_ERR ] ; <nl> + if ( boosting_mode = = CT_UNICHAR_TOP2_ERR ) sample - > set_is_error ( true ) ; <nl> + } <nl> + if ( res_index > = num_results ) { <nl> + / / It is also a top - n choice unichar error . <nl> + + + font_counts_ [ font_id ] . n [ CT_UNICHAR_TOPN_ERR ] ; <nl> + if ( boosting_mode = = CT_UNICHAR_TOPN_ERR ) sample - > set_is_error ( true ) ; <nl> + debug_it = debug ; <nl> + } <nl> + } <nl> + } <nl> + / / Compute mean number of return values and mean rank of correct answer . <nl> + font_counts_ [ font_id ] . n [ CT_NUM_RESULTS ] + = num_results ; <nl> + font_counts_ [ font_id ] . n [ CT_RANK ] + = res_index ; <nl> + / / If it was an error for boosting then sum the weight . <nl> + if ( sample - > is_error ( ) ) { <nl> + scaled_error_ + = sample - > weight ( ) ; <nl> + } <nl> + if ( debug_it ) { <nl> + tprintf ( " % d results for char % s font % d : " , <nl> + num_results , shape_table . unicharset ( ) . id_to_unichar ( unichar_id ) , <nl> + font_id ) ; <nl> + for ( int i = 0 ; i < num_results ; + + i ) { <nl> + tprintf ( " % . 3f / % . 3f : % s " , <nl> + results [ i ] . rating , results [ i ] . font , <nl> + shape_table . DebugStr ( results [ i ] . shape_id ) . string ( ) ) ; <nl> + } <nl> + tprintf ( " \ n " ) ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + / / Accumulates counts for junk . Counts only whether the junk was correctly <nl> + / / rejected or not . <nl> + void ErrorCounter : : AccumulateJunk ( const ShapeTable & shape_table , <nl> + const GenericVector < ShapeRating > & results , <nl> + TrainingSample * sample ) { <nl> + / / For junk we accept no answer , or an explicit shape answer matching the <nl> + / / class id of the sample . <nl> + int num_results = results . size ( ) ; <nl> + int font_id = sample - > font_id ( ) ; <nl> + int unichar_id = sample - > class_id ( ) ; <nl> + if ( num_results > 0 & & <nl> + ! shape_table . GetShape ( results [ 0 ] . shape_id ) . ContainsUnichar ( unichar_id ) ) { <nl> + / / This is a junk error . <nl> + + + font_counts_ [ font_id ] . n [ CT_ACCEPTED_JUNK ] ; <nl> + sample - > set_is_error ( true ) ; <nl> + / / It counts as an error for boosting too so sum the weight . <nl> + scaled_error_ + = sample - > weight ( ) ; <nl> + } else { <nl> + / / Correctly rejected . <nl> + + + font_counts_ [ font_id ] . n [ CT_REJECTED_JUNK ] ; <nl> + sample - > set_is_error ( false ) ; <nl> + } <nl> + } <nl> + <nl> + / / Creates a report of the error rate . The report_level controls the detail <nl> + / / that is reported to stderr via tprintf : <nl> + / / 0 - > no output . <nl> + / / > = 1 - > bottom - line error rate . <nl> + / / > = 3 - > font - level error rate . <nl> + / / boosting_mode determines the return value . It selects which ( un - weighted ) <nl> + / / error rate to return . <nl> + / / The fontinfo_table from MasterTrainer provides the names of fonts . <nl> + / / The it determines the current subset of the training samples . <nl> + / / If not NULL , the top - choice unichar error rate is saved in unichar_error . <nl> + / / If not NULL , the report string is saved in fonts_report . <nl> + / / ( Ignoring report_level ) . <nl> + double ErrorCounter : : ReportErrors ( int report_level , CountTypes boosting_mode , <nl> + const UnicityTable < FontInfo > & fontinfo_table , <nl> + const SampleIterator & it , <nl> + double * unichar_error , <nl> + STRING * fonts_report ) { <nl> + / / Compute totals over all the fonts and report individual font results <nl> + / / when required . <nl> + Counts totals ; <nl> + int fontsize = font_counts_ . size ( ) ; <nl> + for ( int f = 0 ; f < fontsize ; + + f ) { <nl> + / / Accumulate counts over fonts . <nl> + totals + = font_counts_ [ f ] ; <nl> + STRING font_report ; <nl> + if ( ReportString ( font_counts_ [ f ] , & font_report ) ) { <nl> + if ( fonts_report ! = NULL ) { <nl> + * fonts_report + = fontinfo_table . get ( f ) . name ; <nl> + * fonts_report + = " : " ; <nl> + * fonts_report + = font_report ; <nl> + * fonts_report + = " \ n " ; <nl> + } <nl> + if ( report_level > 2 ) { <nl> + / / Report individual font error rates . <nl> + tprintf ( " % s : % s \ n " , fontinfo_table . get ( f ) . name , font_report . string ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + if ( report_level > 0 ) { <nl> + / / Report the totals . <nl> + STRING total_report ; <nl> + if ( ReportString ( totals , & total_report ) ) { <nl> + tprintf ( " TOTAL Scaled Err = % . 4g % % , % s \ n " , <nl> + scaled_error_ * 100 . 0 , total_report . string ( ) ) ; <nl> + } <nl> + / / Report the worst substitution error only for now . <nl> + if ( totals . n [ CT_UNICHAR_TOP1_ERR ] > 0 ) { <nl> + const UNICHARSET & unicharset = it . shape_table ( ) - > unicharset ( ) ; <nl> + int charsetsize = unicharset . size ( ) ; <nl> + int shapesize = it . CompactCharsetSize ( ) ; <nl> + int worst_uni_id = 0 ; <nl> + int worst_shape_id = 0 ; <nl> + int worst_err = 0 ; <nl> + for ( int u = 0 ; u < charsetsize ; + + u ) { <nl> + for ( int s = 0 ; s < shapesize ; + + s ) { <nl> + if ( unichar_counts_ ( u , s ) > worst_err ) { <nl> + worst_err = unichar_counts_ ( u , s ) ; <nl> + worst_uni_id = u ; <nl> + worst_shape_id = s ; <nl> + } <nl> + } <nl> + } <nl> + if ( worst_err > 0 ) { <nl> + tprintf ( " Worst error = % d : % s - > % s with % d / % d = % . 2f % % errors \ n " , <nl> + worst_uni_id , unicharset . id_to_unichar ( worst_uni_id ) , <nl> + it . shape_table ( ) - > DebugStr ( worst_shape_id ) . string ( ) , <nl> + worst_err , totals . n [ CT_UNICHAR_TOP1_ERR ] , <nl> + 100 . 0 * worst_err / totals . n [ CT_UNICHAR_TOP1_ERR ] ) ; <nl> + } <nl> + } <nl> + } <nl> + double rates [ CT_SIZE ] ; <nl> + if ( ! ComputeRates ( totals , rates ) ) <nl> + return 0 . 0 ; <nl> + / / Set output values if asked for . <nl> + if ( unichar_error ! = NULL ) <nl> + * unichar_error = rates [ CT_UNICHAR_TOP1_ERR ] ; <nl> + return rates [ boosting_mode ] ; <nl> + } <nl> + <nl> + / / Sets the report string to a combined human and machine - readable report <nl> + / / string of the error rates . <nl> + / / Returns false if there is no data , leaving report unchanged . <nl> + bool ErrorCounter : : ReportString ( const Counts & counts , STRING * report ) { <nl> + / / Compute the error rates . <nl> + double rates [ CT_SIZE ] ; <nl> + if ( ! ComputeRates ( counts , rates ) ) <nl> + return false ; <nl> + / / Using % . 4g % % , the length of the output string should exactly match the <nl> + / / length of the format string , but in case of overflow , allow for + eddd <nl> + / / on each number . <nl> + const int kMaxExtraLength = 5 ; / / Length of + eddd . <nl> + / / Keep this format string and the snprintf in sync with the CountTypes enum . <nl> + const char * format_str = " ShapeErr = % . 4g % % , FontAttr = % . 4g % % , " <nl> + " Unichar = % . 4g % % [ 1 ] , % . 4g % % [ 2 ] , % . 4g % % [ n ] , " <nl> + " Multi = % . 4g % % , Rej = % . 4g % % , " <nl> + " Answers = % . 3g , Rank = % . 3g , " <nl> + " OKjunk = % . 4g % % , Badjunk = % . 4g % % " ; <nl> + int max_str_len = strlen ( format_str ) + kMaxExtraLength * ( CT_SIZE - 1 ) + 1 ; <nl> + char * formatted_str = new char [ max_str_len ] ; <nl> + snprintf ( formatted_str , max_str_len , format_str , <nl> + rates [ CT_SHAPE_TOP_ERR ] * 100 . 0 , <nl> + rates [ CT_FONT_ATTR_ERR ] * 100 . 0 , <nl> + rates [ CT_UNICHAR_TOP1_ERR ] * 100 . 0 , <nl> + rates [ CT_UNICHAR_TOP2_ERR ] * 100 . 0 , <nl> + rates [ CT_UNICHAR_TOPN_ERR ] * 100 . 0 , <nl> + rates [ CT_OK_MULTI_UNICHAR ] * 100 . 0 , <nl> + rates [ CT_REJECT ] * 100 . 0 , <nl> + rates [ CT_NUM_RESULTS ] , <nl> + rates [ CT_RANK ] , <nl> + 100 . 0 * rates [ CT_REJECTED_JUNK ] , <nl> + 100 . 0 * rates [ CT_ACCEPTED_JUNK ] ) ; <nl> + * report = formatted_str ; <nl> + delete [ ] formatted_str ; <nl> + / / Now append each field of counts with a tab in front so the result can <nl> + / / be loaded into a spreadsheet . <nl> + for ( int ct = 0 ; ct < CT_SIZE ; + + ct ) <nl> + report - > add_str_int ( " \ t " , counts . n [ ct ] ) ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Computes the error rates and returns in rates which is an array of size <nl> + / / CT_SIZE . Returns false if there is no data , leaving rates unchanged . <nl> + bool ErrorCounter : : ComputeRates ( const Counts & counts , double rates [ CT_SIZE ] ) { <nl> + int ok_samples = counts . n [ CT_SHAPE_TOP_CORRECT ] + counts . n [ CT_SHAPE_TOP_ERR ] + <nl> + counts . n [ CT_REJECT ] ; <nl> + int junk_samples = counts . n [ CT_REJECTED_JUNK ] + counts . n [ CT_ACCEPTED_JUNK ] ; <nl> + if ( ok_samples = = 0 & & junk_samples = = 0 ) { <nl> + / / There is no data . <nl> + return false ; <nl> + } <nl> + / / Compute rates for normal chars . <nl> + double denominator = static_cast < double > ( MAX ( ok_samples , 1 ) ) ; <nl> + for ( int ct = 0 ; ct < = CT_RANK ; + + ct ) <nl> + rates [ ct ] = counts . n [ ct ] / denominator ; <nl> + / / Compute rates for junk . <nl> + denominator = static_cast < double > ( MAX ( junk_samples , 1 ) ) ; <nl> + for ( int ct = CT_REJECTED_JUNK ; ct < = CT_ACCEPTED_JUNK ; + + ct ) <nl> + rates [ ct ] = counts . n [ ct ] / denominator ; <nl> + return true ; <nl> + } <nl> + <nl> + ErrorCounter : : Counts : : Counts ( ) { <nl> + memset ( n , 0 , sizeof ( n [ 0 ] ) * CT_SIZE ) ; <nl> + } <nl> + / / Adds other into this for computing totals . <nl> + void ErrorCounter : : Counts : : operator + = ( const Counts & other ) { <nl> + for ( int ct = 0 ; ct < CT_SIZE ; + + ct ) <nl> + n [ ct ] + = other . n [ ct ] ; <nl> + } <nl> + <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + <nl> + <nl> + <nl> + <nl> new file mode 100644 <nl> index 000000000 . . 618d56878 <nl> mmm / dev / null <nl> ppp b / classify / errorcounter . h <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef THIRD_PARTY_TESSERACT_CLASSIFY_ERRORCOUNTER_H_ <nl> + # define THIRD_PARTY_TESSERACT_CLASSIFY_ERRORCOUNTER_H_ <nl> + <nl> + # include " genericvector . h " <nl> + # include " matrix . h " <nl> + <nl> + struct Pix ; <nl> + template < typename T > class UnicityTable ; <nl> + <nl> + namespace tesseract { <nl> + <nl> + struct FontInfo ; <nl> + class SampleIterator ; <nl> + class ShapeClassifier ; <nl> + class ShapeRating ; <nl> + class ShapeTable ; <nl> + class TrainingSample ; <nl> + <nl> + / / Enumeration of the different types of error count . <nl> + / / Error counts work as follows : <nl> + / / <nl> + / / Ground truth is a valid unichar - id / font - id pair : <nl> + / / Number of classifier answers ? <nl> + / / 0 > 0 <nl> + / / CT_REJECT BOTH unichar - id and font - id match top shape ? <nl> + / / __________ yes ! no <nl> + / / CT_SHAPE_TOP_CORRECT CT_SHAPE_TOP_ERR <nl> + / / | Font attributes match ? <nl> + / / | yes ! no <nl> + / / | | CT_FONT_ATTR_ERROR <nl> + / / | Top unichar - id matches ? <nl> + / / | yes ! no <nl> + / / Top shape - id has multiple unichars ? CT_UNICHAR_TOP1_ERR <nl> + / / yes ! no 2nd shape unichar id matches ? <nl> + / / CT_OK_MULTI_UNICHAR ________ yes ! no <nl> + / / ___________________ _____ CT_UNICHAR_TOP2_ERR <nl> + / / Any unichar - id matches ? <nl> + / / yes ! no <nl> + / / ______ CT_UNICHAR_TOPN_ERR <nl> + / / _________________ <nl> + / / Note that multiple counts may be activated for a single sample ! <nl> + / / <nl> + / / Ground truth is for a fragment / n - gram that is NOT in the unicharset . <nl> + / / This is called junk and is expected to be rejected : <nl> + / / Number of classifier answers ? <nl> + / / 0 > 0 <nl> + / / CT_REJECTED_JUNK CT_ACCEPTED_JUNK <nl> + / / <nl> + / / Also , CT_NUM_RESULTS stores the mean number of results , and CT_RANK stores <nl> + / / the mean rank of the correct result , counting from 0 , and with an error <nl> + / / receiving the number of answers as the correct rank . <nl> + / / <nl> + / / Keep in sync with the ReportString function . <nl> + enum CountTypes { <nl> + CT_SHAPE_TOP_CORRECT , / / Top shape id is actually correct . <nl> + CT_SHAPE_TOP_ERR , / / Top shape id is not correct . <nl> + CT_FONT_ATTR_ERR , / / Font attributes incorrect , ignoring unichar . <nl> + CT_UNICHAR_TOP1_ERR , / / Top shape does not contain correct unichar id . <nl> + CT_UNICHAR_TOP2_ERR , / / Top 2 shapes don ' t contain correct unichar id . <nl> + CT_UNICHAR_TOPN_ERR , / / No output shape contains correct unichar id . <nl> + CT_OK_MULTI_UNICHAR , / / Top shape id has correct unichar id , and others . <nl> + CT_REJECT , / / Classifier hates this . <nl> + CT_NUM_RESULTS , / / Number of answers produced . <nl> + CT_RANK , / / Rank of correct answer . <nl> + CT_REJECTED_JUNK , / / Junk that was correctly rejected . <nl> + CT_ACCEPTED_JUNK , / / Junk that was incorrectly classified otherwise . <nl> + <nl> + CT_SIZE / / Number of types for array sizing . <nl> + } ; <nl> + <nl> + / / Class to encapsulate all the functionality and sub - structures required <nl> + / / to count errors for an isolated character classifier ( ShapeClassifier ) . <nl> + class ErrorCounter { <nl> + public : <nl> + / / Computes and returns the unweighted boosting_mode error rate of the given <nl> + / / classifier . Can be used for testing , or inside an iterative training <nl> + / / system , including one that uses boosting . <nl> + / / report_levels : <nl> + / / 0 = no output . <nl> + / / 1 = bottom - line error rate . <nl> + / / 2 = bottom - line error rate + time . <nl> + / / 3 = font - level error rate + time . <nl> + / / 4 = list of all errors + short classifier debug output on 16 errors . <nl> + / / 5 = list of all errors + short classifier debug output on 25 errors . <nl> + / / * The boosting_mode determines which error type is used for computing the <nl> + / / scaled_error output , and setting the is_error flag in the samples . <nl> + / / * The fontinfo_table is used to get string font names for the debug <nl> + / / output , and also to count font attributes errors . <nl> + / / * The page_images vector may contain a Pix * ( which may be NULL ) for each <nl> + / / page index assigned to the samples . <nl> + / / * The it provides encapsulated iteration over some sample set . <nl> + / / * The outputs unichar_error , scaled_error and totals_report are all <nl> + / / optional . <nl> + / / * If not NULL , unichar error gets the top1 unichar error rate . <nl> + / / * Scaled_error gets the error chosen by boosting_mode weighted by the <nl> + / / weights on the samples . <nl> + / / * Fonts_report gets a string summarizing the error rates for each font in <nl> + / / both human - readable form and as a tab - separated list of error counts . <nl> + / / The human - readable form is all before the first tab . <nl> + / / * The return value is the un - weighted version of the scaled_error . <nl> + static double ComputeErrorRate ( ShapeClassifier * classifier , <nl> + int report_level , CountTypes boosting_mode , <nl> + const UnicityTable < FontInfo > & fontinfo_table , <nl> + const GenericVector < Pix * > & page_images , <nl> + SampleIterator * it , <nl> + double * unichar_error , <nl> + double * scaled_error , <nl> + STRING * fonts_report ) ; <nl> + <nl> + private : <nl> + / / Simple struct to hold an array of counts . <nl> + struct Counts { <nl> + Counts ( ) ; <nl> + / / Adds other into this for computing totals . <nl> + void operator + = ( const Counts & other ) ; <nl> + <nl> + int n [ CT_SIZE ] ; <nl> + } ; <nl> + <nl> + / / Constructor is private . Only anticipated use of ErrorCounter is via <nl> + / / the static ComputeErrorRate . <nl> + ErrorCounter ( int charsetsize , int shapesize , int fontsize ) ; <nl> + ~ ErrorCounter ( ) ; <nl> + <nl> + / / Accumulates the errors from the classifier results on a single sample . <nl> + / / Returns true if debug is true and a CT_UNICHAR_TOPN_ERR error occurred . <nl> + / / boosting_mode selects the type of error to be used for boosting and the <nl> + / / is_error_ member of sample is set according to whether the required type <nl> + / / of error occurred . The font_table provides access to font properties <nl> + / / for error counting and shape_table is used to understand the relationship <nl> + / / between unichar_ids and shape_ids in the results <nl> + bool AccumulateErrors ( bool debug , CountTypes boosting_mode , <nl> + const UnicityTable < FontInfo > & font_table , <nl> + const ShapeTable & shape_table , <nl> + const GenericVector < ShapeRating > & results , <nl> + TrainingSample * sample ) ; <nl> + <nl> + / / Accumulates counts for junk . Counts only whether the junk was correctly <nl> + / / rejected or not . <nl> + void AccumulateJunk ( const ShapeTable & shape_table , <nl> + const GenericVector < ShapeRating > & results , <nl> + TrainingSample * sample ) ; <nl> + <nl> + / / Creates a report of the error rate . The report_level controls the detail <nl> + / / that is reported to stderr via tprintf : <nl> + / / 0 - > no output . <nl> + / / > = 1 - > bottom - line error rate . <nl> + / / > = 3 - > font - level error rate . <nl> + / / boosting_mode determines the return value . It selects which ( un - weighted ) <nl> + / / error rate to return . <nl> + / / The fontinfo_table from MasterTrainer provides the names of fonts . <nl> + / / The it determines the current subset of the training samples . <nl> + / / If not NULL , the top - choice unichar error rate is saved in unichar_error . <nl> + / / If not NULL , the report string is saved in fonts_report . <nl> + / / ( Ignoring report_level ) . <nl> + double ReportErrors ( int report_level , CountTypes boosting_mode , <nl> + const UnicityTable < FontInfo > & fontinfo_table , <nl> + const SampleIterator & it , <nl> + double * unichar_error , <nl> + STRING * fonts_report ) ; <nl> + <nl> + / / Sets the report string to a combined human and machine - readable report <nl> + / / string of the error rates . <nl> + / / Returns false if there is no data , leaving report unchanged . <nl> + static bool ReportString ( const Counts & counts , STRING * report ) ; <nl> + <nl> + / / Computes the error rates and returns in rates which is an array of size <nl> + / / CT_SIZE . Returns false if there is no data , leaving rates unchanged . <nl> + static bool ComputeRates ( const Counts & counts , double rates [ CT_SIZE ] ) ; <nl> + <nl> + <nl> + / / Total scaled error used by boosting algorithms . <nl> + double scaled_error_ ; <nl> + / / Vector indexed by font_id from the samples of error accumulators . <nl> + GenericVector < Counts > font_counts_ ; <nl> + / / Counts of the results that map each unichar_id ( from samples ) to an <nl> + / / incorrect shape_id . <nl> + GENERIC_2D_ARRAY < int > unichar_counts_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + # endif / * THIRD_PARTY_TESSERACT_CLASSIFY_ERRORCOUNTER_H_ * / <nl> mmm a / classify / extract . cpp <nl> ppp b / classify / extract . cpp <nl> typedef CHAR_FEATURES ( * CF_FUNC ) ( ) ; <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> void ExtractorStub ( ) ; <nl> <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - Global Data Definitions and Declarations <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - / * * tables to keep track of the different low level feature extractors * / <nl> - # define NUM_FX 3 <nl> - # define DEFAULT_FX 2 <nl> - <nl> - int CurrentFx = DEFAULT_FX ; <nl> - <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Public Code <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> mmm a / classify / featdefs . cpp <nl> ppp b / classify / featdefs . cpp <nl> <nl> # define ILLEGAL_NUM_SETS 3001 <nl> <nl> # define PICO_FEATURE_LENGTH 0 . 05 <nl> - # define MAX_OUTLINE_FEATURES 100 <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Global Data Definitions and Declarations <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> - / * define all of the parameters for the MicroFeature type * / <nl> - StartParamDesc ( MicroFeatureParams ) <nl> - DefineParam ( 0 , 0 , - 0 . 5 , 0 . 5 ) <nl> - DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> - DefineParam ( 0 , 1 , 0 . 0 , 1 . 0 ) <nl> - DefineParam ( 1 , 0 , 0 . 0 , 1 . 0 ) <nl> + const char * kMicroFeatureType = " mf " ; <nl> + const char * kCNFeatureType = " cn " ; <nl> + const char * kIntFeatureType = " if " ; <nl> + const char * kGeoFeatureType = " tb " ; <nl> + <nl> + / / Define all of the parameters for the MicroFeature type . <nl> + StartParamDesc ( MicroFeatureParams ) <nl> + DefineParam ( 0 , 0 , - 0 . 5 , 0 . 5 ) <nl> + DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> + DefineParam ( 0 , 1 , 0 . 0 , 1 . 0 ) <nl> + DefineParam ( 1 , 0 , 0 . 0 , 1 . 0 ) <nl> DefineParam ( 0 , 1 , - 0 . 5 , 0 . 5 ) <nl> DefineParam ( 0 , 1 , - 0 . 5 , 0 . 5 ) <nl> EndParamDesc <nl> - / * now define the feature type itself ( see features . h for info about each <nl> - parameter ) . * / <nl> - DefineFeature ( MicroFeatureDesc , 5 , 1 , 4 , 50 , " Micro " , " mf " , MicroFeatureParams ) <nl> + / / Now define the feature type itself ( see features . h for parameters ) . <nl> + DefineFeature ( MicroFeatureDesc , 5 , 1 , kMicroFeatureType , MicroFeatureParams ) <nl> <nl> - / / define all of the parameters for the PicoFeature type <nl> - / * define knob that can be used to adjust pico - feature length * / <nl> - FLOAT32 PicoFeatureLength = PICO_FEATURE_LENGTH ; <nl> - StartParamDesc ( PicoFeatParams ) <nl> - DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> - DefineParam ( 1 , 0 , 0 . 0 , 1 . 0 ) <nl> - DefineParam ( 0 , 0 , - 0 . 5 , 0 . 5 ) <nl> + / / Define all of the parameters for the NormFeat type . <nl> + StartParamDesc ( CharNormParams ) <nl> + DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> + DefineParam ( 0 , 1 , 0 . 0 , 1 . 0 ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 1 . 0 ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 1 . 0 ) <nl> EndParamDesc <nl> - / * now define the feature type itself ( see features . h for info about each <nl> - parameter ) . * / <nl> - DefineFeature ( PicoFeatDesc , 2 , 1 , 1 , MAX_UINT8 , " Pico " , " pf " , PicoFeatParams ) <nl> + / / Now define the feature type itself ( see features . h for parameters ) . <nl> + DefineFeature ( CharNormDesc , 4 , 0 , kCNFeatureType , CharNormParams ) <nl> <nl> - / * define all of the parameters for the NormFeat type * / <nl> - StartParamDesc ( CharNormParams ) <nl> - DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> - DefineParam ( 0 , 1 , 0 . 0 , 1 . 0 ) <nl> - DefineParam ( 0 , 0 , 0 . 0 , 1 . 0 ) <nl> - DefineParam ( 0 , 0 , 0 . 0 , 1 . 0 ) <nl> + / / Define all of the parameters for the IntFeature type <nl> + StartParamDesc ( IntFeatParams ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 255 . 0 ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 255 . 0 ) <nl> + DefineParam ( 1 , 0 , 0 . 0 , 255 . 0 ) <nl> + EndParamDesc <nl> + / / Now define the feature type itself ( see features . h for parameters ) . <nl> + DefineFeature ( IntFeatDesc , 2 , 1 , kIntFeatureType , IntFeatParams ) <nl> + <nl> + / / Define all of the parameters for the GeoFeature type <nl> + StartParamDesc ( GeoFeatParams ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 255 . 0 ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 255 . 0 ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 255 . 0 ) <nl> EndParamDesc <nl> - / * now define the feature type itself ( see features . h for info about each <nl> - parameter ) . * / <nl> - DefineFeature ( CharNormDesc , 4 , 0 , 1 , 1 , " CharNorm " , " cn " , CharNormParams ) <nl> - <nl> - / / define all of the parameters for the OutlineFeature type <nl> - StartParamDesc ( OutlineFeatParams ) <nl> - DefineParam ( 0 , 0 , - 0 . 5 , 0 . 5 ) <nl> - DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> - DefineParam ( 0 , 0 , 0 . 0 , 1 . 0 ) <nl> - DefineParam ( 1 , 0 , 0 . 0 , 1 . 0 ) <nl> + / / Now define the feature type itself ( see features . h for parameters ) . <nl> + DefineFeature ( GeoFeatDesc , 3 , 0 , kGeoFeatureType , GeoFeatParams ) <nl> + <nl> + / / Other features used for training the adaptive classifier , but not used <nl> + / / during normal training , therefore not in the DescDefs array . <nl> + <nl> + / / Define all of the parameters for the PicoFeature type <nl> + / / define knob that can be used to adjust pico - feature length . <nl> + FLOAT32 PicoFeatureLength = PICO_FEATURE_LENGTH ; <nl> + StartParamDesc ( PicoFeatParams ) <nl> + DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> + DefineParam ( 1 , 0 , 0 . 0 , 1 . 0 ) <nl> + DefineParam ( 0 , 0 , - 0 . 5 , 0 . 5 ) <nl> EndParamDesc <nl> - / * now define the feature type itself ( see features . h for info about each <nl> - parameter ) . * / <nl> - DefineFeature ( OutlineFeatDesc , 3 , 1 , 1 , MAX_OUTLINE_FEATURES , " Outline " , <nl> - " of " , OutlineFeatParams ) <nl> + / / Now define the feature type itself ( see features . h for parameters ) . <nl> + DefineFeature ( PicoFeatDesc , 2 , 1 , " pf " , PicoFeatParams ) <nl> <nl> + / / Define all of the parameters for the OutlineFeature type . <nl> + StartParamDesc ( OutlineFeatParams ) <nl> + DefineParam ( 0 , 0 , - 0 . 5 , 0 . 5 ) <nl> + DefineParam ( 0 , 0 , - 0 . 25 , 0 . 75 ) <nl> + DefineParam ( 0 , 0 , 0 . 0 , 1 . 0 ) <nl> + DefineParam ( 1 , 0 , 0 . 0 , 1 . 0 ) <nl> + EndParamDesc <nl> + / / Now define the feature type itself ( see features . h for parameters ) . <nl> + DefineFeature ( OutlineFeatDesc , 3 , 1 , " of " , OutlineFeatParams ) <nl> + <nl> + / / MUST be kept in - sync with ExtractorDefs in fxdefs . cpp . <nl> static const FEATURE_DESC_STRUCT * DescDefs [ NUM_FEATURE_TYPES ] = { <nl> & MicroFeatureDesc , <nl> - & PicoFeatDesc , <nl> - & OutlineFeatDesc , <nl> - & CharNormDesc <nl> + & CharNormDesc , <nl> + & IntFeatDesc , <nl> + & GeoFeatDesc <nl> } ; <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> void WriteCharDescription ( const FEATURE_DEFS_STRUCT & FeatureDefs , <nl> } <nl> } / * WriteCharDescription * / <nl> <nl> + / / Return whether all of the fields of the given feature set <nl> + / / are well defined ( not inf or nan ) . <nl> + bool ValidCharDescription ( const FEATURE_DEFS_STRUCT & FeatureDefs , <nl> + CHAR_DESC CharDesc ) { <nl> + bool anything_written = false ; <nl> + bool well_formed = true ; <nl> + for ( int Type = 0 ; Type < CharDesc - > NumFeatureSets ; Type + + ) { <nl> + if ( CharDesc - > FeatureSets [ Type ] ) { <nl> + for ( int i = 0 ; i < CharDesc - > FeatureSets [ Type ] - > NumFeatures ; i + + ) { <nl> + FEATURE feat = CharDesc - > FeatureSets [ Type ] - > Features [ i ] ; <nl> + for ( int p = 0 ; p < feat - > Type - > NumParams ; p + + ) { <nl> + if ( isnan ( feat - > Params [ p ] ) | | isinf ( feat - > Params [ p ] ) ) <nl> + well_formed = false ; <nl> + else <nl> + anything_written = true ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + return anything_written & & well_formed ; <nl> + } / * ValidCharDescription * / <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> / * * <nl> mmm a / classify / featdefs . h <nl> ppp b / classify / featdefs . h <nl> <nl> <nl> / * Enumerate the different types of features currently defined . * / <nl> # define NUM_FEATURE_TYPES 4 <nl> + extern const char * kMicroFeatureType ; <nl> + extern const char * kCNFeatureType ; <nl> + extern const char * kIntFeatureType ; <nl> + extern const char * kGeoFeatureType ; <nl> <nl> / * define error traps which can be triggered by this module . * / <nl> # define ILLEGAL_SHORT_NAME 2000 <nl> void FreeCharDescription ( CHAR_DESC CharDesc ) ; <nl> <nl> CHAR_DESC NewCharDescription ( const FEATURE_DEFS_STRUCT & FeatureDefs ) ; <nl> <nl> + bool ValidCharDescription ( const FEATURE_DEFS_STRUCT & FeatureDefs , <nl> + CHAR_DESC CharDesc ) ; <nl> + <nl> void WriteCharDescription ( const FEATURE_DEFS_STRUCT & FeatureDefs , <nl> FILE * File , CHAR_DESC CharDesc ) ; <nl> <nl> extern const FEATURE_DESC_STRUCT MicroFeatureDesc ; <nl> extern const FEATURE_DESC_STRUCT PicoFeatDesc ; <nl> extern const FEATURE_DESC_STRUCT CharNormDesc ; <nl> extern const FEATURE_DESC_STRUCT OutlineFeatDesc ; <nl> + extern const FEATURE_DESC_STRUCT IntFeatDesc ; <nl> + extern const FEATURE_DESC_STRUCT GeoFeatDesc ; <nl> # endif <nl> mmm a / classify / float2int . cpp <nl> ppp b / classify / float2int . cpp <nl> <nl> # include " normmatch . h " <nl> # include " mfoutline . h " <nl> # include " classify . h " <nl> + # include " helpers . h " <nl> # include " picofeat . h " <nl> <nl> # define MAX_INT_CHAR_NORM ( INT_CHAR_NORM_RANGE - 1 ) <nl> <nl> namespace tesseract { <nl> <nl> / * * <nl> - * For each class in Templates , clear the corresponding <nl> - * entry in CharNormArray . CharNormArray is indexed by class <nl> - * indicies ( as obtained from Templates ) rather than class id ' s . <nl> + * For each class in the unicharset , clears the corresponding <nl> + * entry in char_norm_array . char_norm_array is indexed by unichar_id . <nl> * <nl> * Globals : <nl> * - none <nl> * <nl> - * @ param Templates specifies classes currently defined <nl> - * @ param CharNormArray array to be cleared <nl> + * @ param char_norm_array array to be cleared <nl> * <nl> * @ note Exceptions : none <nl> * @ note History : Wed Feb 20 11 : 20 : 54 1991 , DSJ , Created . <nl> * / <nl> - void ClearCharNormArray ( INT_TEMPLATES Templates , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ) { <nl> - int i ; <nl> - <nl> - for ( i = 0 ; i < Templates - > NumClasses ; i + + ) { <nl> - CharNormArray [ i ] = 0 ; <nl> - } <nl> - <nl> + void Classify : : ClearCharNormArray ( uinT8 * char_norm_array ) { <nl> + memset ( char_norm_array , 0 , sizeof ( * char_norm_array ) * unicharset . size ( ) ) ; <nl> } / * ClearCharNormArray * / <nl> <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> / * * <nl> - * For each class in Templates , compute the match between <nl> - * NormFeature and the normalization protos for that class . <nl> - * Convert this number to the range from 0 - 255 and store it <nl> - * into CharNormArray . CharNormArray is indexed by class <nl> - * indicies ( as obtained from Templates ) rather than class id ' s . <nl> + * For each class in unicharset , computes the match between <nl> + * norm_feature and the normalization protos for that class . <nl> + * Converts this number to the range from 0 - 255 and stores it <nl> + * into char_norm_array . CharNormArray is indexed by unichar_id . <nl> * <nl> * Globals : <nl> * - none <nl> * <nl> - * @ param NormFeature character normalization feature <nl> - * @ param Templates specifies classes currently defined <nl> - * @ param [ out ] CharNormArray place to put results <nl> + * @ param norm_feature character normalization feature <nl> + * @ param [ out ] char_norm_array place to put results of size unicharset . size ( ) <nl> * <nl> * @ note Exceptions : none <nl> * @ note History : Wed Feb 20 11 : 20 : 54 1991 , DSJ , Created . <nl> * / <nl> - void Classify : : ComputeIntCharNormArray ( <nl> - FEATURE NormFeature , INT_TEMPLATES Templates , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ) { <nl> - int i ; <nl> - int NormAdjust ; <nl> - <nl> - for ( i = 0 ; i < Templates - > NumClasses ; i + + ) { <nl> - NormAdjust = ( int ) ( INT_CHAR_NORM_RANGE * <nl> - ComputeNormMatch ( i , NormFeature , FALSE ) ) ; <nl> - if ( NormAdjust < 0 ) <nl> - NormAdjust = 0 ; <nl> - else if ( NormAdjust > MAX_INT_CHAR_NORM ) <nl> - NormAdjust = MAX_INT_CHAR_NORM ; <nl> - <nl> - CharNormArray [ i ] = NormAdjust ; <nl> + void Classify : : ComputeIntCharNormArray ( const FEATURE_STRUCT & norm_feature , <nl> + uinT8 * char_norm_array ) { <nl> + for ( int i = 0 ; i < unicharset . size ( ) ; i + + ) { <nl> + int norm_adjust = static_cast < int > ( INT_CHAR_NORM_RANGE * <nl> + ComputeNormMatch ( i , norm_feature , FALSE ) ) ; <nl> + char_norm_array [ i ] = ClipToRange ( norm_adjust , 0 , MAX_INT_CHAR_NORM ) ; <nl> } <nl> } / * ComputeIntCharNormArray * / <nl> <nl> mmm a / classify / float2int . h <nl> ppp b / classify / float2int . h <nl> <nl> # define INT_FEAT_RANGE 256 <nl> # define BASELINE_Y_SHIFT ( 0 . 25 ) <nl> <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - Public Function Prototypes <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - namespace tesseract { <nl> - void ClearCharNormArray ( INT_TEMPLATES Templates , <nl> - CLASS_NORMALIZATION_ARRAY CharNormArray ) ; <nl> - } / / namespace tesseract . <nl> - <nl> # endif <nl> mmm a / classify / fxdefs . cpp <nl> ppp b / classify / fxdefs . cpp <nl> <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> / / Definitions of extractors separated from feature definitions . <nl> const FEATURE_EXT_STRUCT MicroFeatureExt = { ExtractMicros } ; <nl> - const FEATURE_EXT_STRUCT PicoFeatExt = { NULL } ; <nl> - const FEATURE_EXT_STRUCT OutlineFeatExt = { NULL } ; <nl> const FEATURE_EXT_STRUCT CharNormExt = { ExtractCharNormFeatures } ; <nl> + const FEATURE_EXT_STRUCT IntFeatExt = { ExtractIntCNFeatures } ; <nl> + const FEATURE_EXT_STRUCT GeoFeatExt = { ExtractIntGeoFeatures } ; <nl> <nl> + / / MUST be kept in - sync with DescDefs in featdefs . cpp . <nl> const FEATURE_EXT_STRUCT * ExtractorDefs [ NUM_FEATURE_TYPES ] = { <nl> & MicroFeatureExt , <nl> - & PicoFeatExt , <nl> - & OutlineFeatExt , <nl> - & CharNormExt <nl> + & CharNormExt , <nl> + & IntFeatExt , <nl> + & GeoFeatExt <nl> } ; <nl> <nl> void SetupExtractors ( FEATURE_DEFS_STRUCT * FeatureDefs ) { <nl> new file mode 100644 <nl> index 000000000 . . 02dd22863 <nl> mmm / dev / null <nl> ppp b / classify / intfeaturedist . cpp <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : intfeaturedist . cpp <nl> + / / Description : Fast set - difference - based feature distance calculator . <nl> + / / Created : Thu Sep 01 13 : 07 : 30 PDT 2011 <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " intfeaturedist . h " <nl> + # include " intfeaturemap . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + IntFeatureDist : : IntFeatureDist ( ) <nl> + : size_ ( 0 ) , total_feature_weight_ ( 0 . 0 ) , <nl> + feature_map_ ( NULL ) , features_ ( NULL ) , <nl> + features_delta_one_ ( NULL ) , features_delta_two_ ( NULL ) { <nl> + } <nl> + <nl> + IntFeatureDist : : ~ IntFeatureDist ( ) { <nl> + Clear ( ) ; <nl> + } <nl> + <nl> + / / Initialize the table to the given size of feature space . <nl> + void IntFeatureDist : : Init ( const IntFeatureMap * feature_map ) { <nl> + size_ = feature_map - > sparse_size ( ) ; <nl> + Clear ( ) ; <nl> + feature_map_ = feature_map ; <nl> + features_ = new bool [ size_ ] ; <nl> + features_delta_one_ = new bool [ size_ ] ; <nl> + features_delta_two_ = new bool [ size_ ] ; <nl> + memset ( features_ , false , size_ * sizeof ( features_ [ 0 ] ) ) ; <nl> + memset ( features_delta_one_ , false , size_ * sizeof ( features_delta_one_ [ 0 ] ) ) ; <nl> + memset ( features_delta_two_ , false , size_ * sizeof ( features_delta_two_ [ 0 ] ) ) ; <nl> + total_feature_weight_ = 0 . 0 ; <nl> + } <nl> + <nl> + / / Setup the map for the given indexed_features that have been indexed by <nl> + / / feature_map . <nl> + void IntFeatureDist : : Set ( const GenericVector < int > & indexed_features , <nl> + int canonical_count , bool value ) { <nl> + total_feature_weight_ = canonical_count ; <nl> + for ( int i = 0 ; i < indexed_features . size ( ) ; + + i ) { <nl> + int f = indexed_features [ i ] ; <nl> + features_ [ f ] = value ; <nl> + for ( int dir = - kNumOffsetMaps ; dir < = kNumOffsetMaps ; + + dir ) { <nl> + if ( dir = = 0 ) continue ; <nl> + int mapped_f = feature_map_ - > OffsetFeature ( f , dir ) ; <nl> + if ( mapped_f > = 0 ) { <nl> + features_delta_one_ [ mapped_f ] = value ; <nl> + for ( int dir2 = - kNumOffsetMaps ; dir2 < = kNumOffsetMaps ; + + dir2 ) { <nl> + if ( dir2 = = 0 ) continue ; <nl> + int mapped_f2 = feature_map_ - > OffsetFeature ( mapped_f , dir2 ) ; <nl> + if ( mapped_f2 > = 0 ) <nl> + features_delta_two_ [ mapped_f2 ] = value ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Compute the distance between the given feature vector and the last <nl> + / / Set feature vector . <nl> + double IntFeatureDist : : FeatureDistance ( <nl> + const GenericVector < int > & features ) const { <nl> + int num_test_features = features . size ( ) ; <nl> + double denominator = total_feature_weight_ + num_test_features ; <nl> + double misses = denominator ; <nl> + for ( int i = 0 ; i < num_test_features ; + + i ) { <nl> + int index = features [ i ] ; <nl> + double weight = 1 . 0 ; <nl> + if ( features_ [ index ] ) { <nl> + / / A perfect match . <nl> + misses - = 2 . 0 * weight ; <nl> + } else if ( features_delta_one_ [ index ] ) { <nl> + misses - = 1 . 5 * weight ; <nl> + } else if ( features_delta_two_ [ index ] ) { <nl> + / / A near miss . <nl> + misses - = 1 . 0 * weight ; <nl> + } <nl> + } <nl> + return misses / denominator ; <nl> + } <nl> + <nl> + / / Compute the distance between the given feature vector and the last <nl> + / / Set feature vector . <nl> + double IntFeatureDist : : DebugFeatureDistance ( <nl> + const GenericVector < int > & features ) const { <nl> + int num_test_features = features . size ( ) ; <nl> + double denominator = total_feature_weight_ + num_test_features ; <nl> + double misses = denominator ; <nl> + for ( int i = 0 ; i < num_test_features ; + + i ) { <nl> + int index = features [ i ] ; <nl> + double weight = 1 . 0 ; <nl> + INT_FEATURE_STRUCT f = feature_map_ - > InverseMapFeature ( features [ i ] ) ; <nl> + tprintf ( " Testing feature weight % g : " , weight ) ; <nl> + f . print ( ) ; <nl> + if ( features_ [ index ] ) { <nl> + / / A perfect match . <nl> + misses - = 2 . 0 * weight ; <nl> + tprintf ( " Perfect hit \ n " ) ; <nl> + } else if ( features_delta_one_ [ index ] ) { <nl> + misses - = 1 . 5 * weight ; <nl> + tprintf ( " - 1 hit \ n " ) ; <nl> + } else if ( features_delta_two_ [ index ] ) { <nl> + / / A near miss . <nl> + misses - = 1 . 0 * weight ; <nl> + tprintf ( " - 2 hit \ n " ) ; <nl> + } else { <nl> + tprintf ( " Total miss \ n " ) ; <nl> + } <nl> + } <nl> + tprintf ( " Features present : " ) ; <nl> + for ( int i = 0 ; i < size_ ; + + i ) { <nl> + if ( features_ [ i ] ) { <nl> + INT_FEATURE_STRUCT f = feature_map_ - > InverseMapFeature ( i ) ; <nl> + f . print ( ) ; <nl> + } <nl> + } <nl> + tprintf ( " \ nMinus one features : " ) ; <nl> + for ( int i = 0 ; i < size_ ; + + i ) { <nl> + if ( features_delta_one_ [ i ] ) { <nl> + INT_FEATURE_STRUCT f = feature_map_ - > InverseMapFeature ( i ) ; <nl> + f . print ( ) ; <nl> + } <nl> + } <nl> + tprintf ( " \ nMinus two features : " ) ; <nl> + for ( int i = 0 ; i < size_ ; + + i ) { <nl> + if ( features_delta_two_ [ i ] ) { <nl> + INT_FEATURE_STRUCT f = feature_map_ - > InverseMapFeature ( i ) ; <nl> + f . print ( ) ; <nl> + } <nl> + } <nl> + tprintf ( " \ n " ) ; <nl> + return misses / denominator ; <nl> + } <nl> + <nl> + / / Clear all data . <nl> + void IntFeatureDist : : Clear ( ) { <nl> + delete [ ] features_ ; <nl> + features_ = NULL ; <nl> + delete [ ] features_delta_one_ ; <nl> + features_delta_one_ = NULL ; <nl> + delete [ ] features_delta_two_ ; <nl> + features_delta_two_ = NULL ; <nl> + } <nl> + <nl> + } / / namespace tesseract <nl> new file mode 100644 <nl> index 000000000 . . 8cfcb3bed <nl> mmm / dev / null <nl> ppp b / classify / intfeaturedist . h <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : intfeaturedist . h <nl> + / / Description : Fast set - difference - based feature distance calculator . <nl> + / / Created : Thu Sep 01 12 : 14 : 30 PDT 2011 <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_CLASSIFY_INTFEATUREDIST_H_ <nl> + # define TESSERACT_CLASSIFY_INTFEATUREDIST_H_ <nl> + <nl> + # include " genericvector . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + class IntFeatureMap ; <nl> + <nl> + / / Feature distance calculator designed to provide a fast distance calculation <nl> + / / based on set difference between a given feature set and many other feature <nl> + / / sets in turn . <nl> + / / Representation of a feature set as an array of bools that are sparsely <nl> + / / true , and companion arrays that allow fast feature set distance <nl> + / / calculations with allowance of offsets in position . <nl> + / / Init is expensive , so for greatest efficiency , to re - initialize for a new <nl> + / / feature set , use Set ( . . . , false ) on the SAME feature set as was used to <nl> + / / setup with Set ( . . . , true ) , to return to its initialized state before <nl> + / / reuse with Set ( . . . , true ) on a new feature set . <nl> + class IntFeatureDist { <nl> + public : <nl> + IntFeatureDist ( ) ; <nl> + ~ IntFeatureDist ( ) ; <nl> + <nl> + / / Initialize the bool array to the given size of feature space . <nl> + / / The feature_map is just borrowed , and must exist for the entire <nl> + / / lifetime of the IntFeatureDist . <nl> + void Init ( const IntFeatureMap * feature_map ) ; <nl> + <nl> + / / Setup the map for the given indexed_features that have been indexed by <nl> + / / feature_map . After use , use Set ( . . . , false ) to reset to the initial state <nl> + / / as this is faster than calling Init for sparse spaces . <nl> + void Set ( const GenericVector < int > & indexed_features , <nl> + int canonical_count , bool value ) ; <nl> + <nl> + / / Compute the distance between the given feature vector and the last <nl> + / / Set feature vector . <nl> + double FeatureDistance ( const GenericVector < int > & features ) const ; <nl> + double DebugFeatureDistance ( const GenericVector < int > & features ) const ; <nl> + <nl> + private : <nl> + / / Clear all data . <nl> + void Clear ( ) ; <nl> + <nl> + / / Size of the indexed feature space . <nl> + int size_ ; <nl> + / / Total weight of features currently stored in the maps . <nl> + double total_feature_weight_ ; <nl> + / / Pointer to IntFeatureMap given at Init to find offset features . <nl> + const IntFeatureMap * feature_map_ ; <nl> + / / Array of bools indicating presence of a feature . <nl> + bool * features_ ; <nl> + / / Array indicating the presence of a feature offset by one unit . <nl> + bool * features_delta_one_ ; <nl> + / / Array indicating the presence of a feature offset by two units . <nl> + bool * features_delta_two_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract <nl> + <nl> + # endif / / TESSERACT_CLASSIFY_INTFEATUREDIST_H_ <nl> new file mode 100644 <nl> index 000000000 . . 79c5040e9 <nl> mmm / dev / null <nl> ppp b / classify / intfeaturemap . cpp <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : intfeaturemap . cpp <nl> + / / Description : Encapsulation of IntFeatureSpace with IndexMapBiDi <nl> + / / to provide a subspace mapping and fast feature lookup . <nl> + / / Created : Tue Oct 26 08 : 58 : 30 PDT 2010 <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " intfeaturemap . h " <nl> + <nl> + # include " intfeaturespace . h " <nl> + # include " intfx . h " <nl> + / / These includes do not exist yet , but will be coming soon . <nl> + / / # include " sampleiterator . h " <nl> + / / # include " trainingsample . h " <nl> + / / # include " trainingsampleset . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + const int kMaxOffsetDist = 32 ; <nl> + const double kMinPCLengthIncrease = 1 . 0 / 1024 ; <nl> + <nl> + IntFeatureMap : : IntFeatureMap ( ) <nl> + : mapping_changed_ ( true ) , compact_size_ ( 0 ) { <nl> + for ( int dir = 0 ; dir < kNumOffsetMaps ; + + dir ) { <nl> + offset_plus_ [ dir ] = NULL ; <nl> + offset_minus_ [ dir ] = NULL ; <nl> + } <nl> + } <nl> + <nl> + IntFeatureMap : : ~ IntFeatureMap ( ) { <nl> + Clear ( ) ; <nl> + } <nl> + <nl> + / / Pseudo - accessors . <nl> + int IntFeatureMap : : IndexFeature ( const INT_FEATURE_STRUCT & f ) const { <nl> + return feature_space_ . Index ( f ) ; <nl> + } <nl> + int IntFeatureMap : : MapFeature ( const INT_FEATURE_STRUCT & f ) const { <nl> + return feature_map_ . SparseToCompact ( feature_space_ . Index ( f ) ) ; <nl> + } <nl> + int IntFeatureMap : : MapIndexFeature ( int index_feature ) const { <nl> + return feature_map_ . SparseToCompact ( index_feature ) ; <nl> + } <nl> + INT_FEATURE_STRUCT IntFeatureMap : : InverseIndexFeature ( int index_feature ) const { <nl> + return feature_space_ . PositionFromIndex ( index_feature ) ; <nl> + } <nl> + INT_FEATURE_STRUCT IntFeatureMap : : InverseMapFeature ( int map_feature ) const { <nl> + int index = feature_map_ . CompactToSparse ( map_feature ) ; <nl> + return feature_space_ . PositionFromIndex ( index ) ; <nl> + } <nl> + void IntFeatureMap : : DeleteMapFeature ( int map_feature ) { <nl> + feature_map_ . Merge ( - 1 , map_feature ) ; <nl> + mapping_changed_ = true ; <nl> + } <nl> + bool IntFeatureMap : : IsMapFeatureDeleted ( int map_feature ) const { <nl> + return feature_map_ . IsCompactDeleted ( map_feature ) ; <nl> + } <nl> + <nl> + / / Copies the given feature_space and uses it as the index feature map <nl> + / / from INT_FEATURE_STRUCT . <nl> + void IntFeatureMap : : Init ( const IntFeatureSpace & feature_space ) { <nl> + feature_space_ = feature_space ; <nl> + mapping_changed_ = false ; <nl> + int sparse_size = feature_space_ . Size ( ) ; <nl> + feature_map_ . Init ( sparse_size , true ) ; <nl> + feature_map_ . Setup ( ) ; <nl> + compact_size_ = feature_map_ . CompactSize ( ) ; <nl> + / / Initialize look - up tables if needed . <nl> + FCOORD dir = FeatureDirection ( 0 ) ; <nl> + if ( dir . x ( ) = = 0 . 0f & & dir . y ( ) = = 0 . 0f ) <nl> + InitIntegerFX ( ) ; <nl> + / / Compute look - up tables to generate offset features . <nl> + for ( int dir = 0 ; dir < kNumOffsetMaps ; + + dir ) { <nl> + delete [ ] offset_plus_ [ dir ] ; <nl> + delete [ ] offset_minus_ [ dir ] ; <nl> + offset_plus_ [ dir ] = new int [ sparse_size ] ; <nl> + offset_minus_ [ dir ] = new int [ sparse_size ] ; <nl> + } <nl> + for ( int dir = 1 ; dir < = kNumOffsetMaps ; + + dir ) { <nl> + for ( int i = 0 ; i < sparse_size ; + + i ) { <nl> + int offset_index = ComputeOffsetFeature ( i , dir ) ; <nl> + offset_plus_ [ dir - 1 ] [ i ] = offset_index ; <nl> + offset_index = ComputeOffsetFeature ( i , - dir ) ; <nl> + offset_minus_ [ dir - 1 ] [ i ] = offset_index ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Helper to return an offset index feature . In this context an offset <nl> + / / feature with a dir of + / - 1 is a feature of a similar direction , <nl> + / / but shifted perpendicular to the direction of the feature . An offset <nl> + / / feature with a dir of + / - 2 is feature at the same position , but rotated <nl> + / / by + / - one [ compact ] quantum . Returns the index of the generated offset <nl> + / / feature , or - 1 if it doesn ' t exist . Dir should be in <nl> + / / [ - kNumOffsetMaps , kNumOffsetMaps ] to indicate the relative direction . <nl> + / / A dir of 0 is an identity transformation . <nl> + / / Both input and output are from the index ( sparse ) feature space , not <nl> + / / the mapped / compact feature space , but the offset feature is the minimum <nl> + / / distance moved from the input to guarantee that it maps to the next <nl> + / / available quantum in the mapped / compact space . <nl> + int IntFeatureMap : : OffsetFeature ( int index_feature , int dir ) const { <nl> + if ( dir > 0 & & dir < = kNumOffsetMaps ) <nl> + return offset_plus_ [ dir - 1 ] [ index_feature ] ; <nl> + else if ( dir < 0 & & - dir < = kNumOffsetMaps ) <nl> + return offset_minus_ [ - dir - 1 ] [ index_feature ] ; <nl> + else if ( dir = = 0 ) <nl> + return index_feature ; <nl> + else <nl> + return - 1 ; <nl> + } <nl> + <nl> + <nl> + / / # define EXPERIMENT_ON <nl> + # ifdef EXPERIMENT_ON / / This code is commented out as SampleIterator and <nl> + / / TrainingSample are not reviewed / checked in yet , but these functions are a <nl> + / / useful indicator of how an IntFeatureMap is setup . <nl> + <nl> + / / Computes the features used by the subset of samples defined by <nl> + / / the iterator and sets up the feature mapping . <nl> + / / Returns the size of the compacted feature space . <nl> + int IntFeatureMap : : FindNZFeatureMapping ( SampleIterator * it ) { <nl> + feature_map_ . Init ( feature_space_ . Size ( ) , false ) ; <nl> + int total_samples = 0 ; <nl> + for ( it - > Begin ( ) ; ! it - > AtEnd ( ) ; it - > Next ( ) ) { <nl> + const TrainingSample & sample = it - > GetSample ( ) ; <nl> + GenericVector < int > features ; <nl> + feature_space_ . IndexAndSortFeatures ( sample . features ( ) , <nl> + sample . num_features ( ) , <nl> + & features ) ; <nl> + int num_features = features . size ( ) ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) <nl> + feature_map_ . SetMap ( features [ f ] , true ) ; <nl> + + + total_samples ; <nl> + } <nl> + feature_map_ . Setup ( ) ; <nl> + compact_size_ = feature_map_ . CompactSize ( ) ; <nl> + mapping_changed_ = true ; <nl> + FinalizeMapping ( it ) ; <nl> + tprintf ( " % d non - zero features found in % d samples \ n " , <nl> + compact_size_ , total_samples ) ; <nl> + return compact_size_ ; <nl> + } <nl> + # endif <nl> + <nl> + / / After deleting some features , finish setting up the mapping , and map <nl> + / / all the samples . Returns the size of the compacted feature space . <nl> + int IntFeatureMap : : FinalizeMapping ( SampleIterator * it ) { <nl> + if ( mapping_changed_ ) { <nl> + feature_map_ . CompleteMerges ( ) ; <nl> + compact_size_ = feature_map_ . CompactSize ( ) ; <nl> + # ifdef EXPERIMENT_ON <nl> + it - > MapSampleFeatures ( * this ) ; <nl> + # endif <nl> + mapping_changed_ = false ; <nl> + } <nl> + return compact_size_ ; <nl> + } <nl> + <nl> + / / Prints the map features from the set in human - readable form . <nl> + void IntFeatureMap : : DebugMapFeatures ( <nl> + const GenericVector < int > & map_features ) const { <nl> + for ( int i = 0 ; i < map_features . size ( ) ; + + i ) { <nl> + INT_FEATURE_STRUCT f = InverseMapFeature ( map_features [ i ] ) ; <nl> + f . print ( ) ; <nl> + } <nl> + } <nl> + <nl> + void IntFeatureMap : : Clear ( ) { <nl> + for ( int dir = 0 ; dir < kNumOffsetMaps ; + + dir ) { <nl> + delete [ ] offset_plus_ [ dir ] ; <nl> + delete [ ] offset_minus_ [ dir ] ; <nl> + offset_plus_ [ dir ] = NULL ; <nl> + offset_minus_ [ dir ] = NULL ; <nl> + } <nl> + } <nl> + <nl> + / / Helper to compute an offset index feature . In this context an offset <nl> + / / feature with a dir of + / - 1 is a feature of a similar direction , <nl> + / / but shifted perpendicular to the direction of the feature . An offset <nl> + / / feature with a dir of + / - 2 is feature at the same position , but rotated <nl> + / / by + / - one [ compact ] quantum . Returns the index of the generated offset <nl> + / / feature , or - 1 if it doesn ' t exist . Dir should be in <nl> + / / [ - kNumOffsetMaps , kNumOffsetMaps ] to indicate the relative direction . <nl> + / / A dir of 0 is an identity transformation . <nl> + / / Both input and output are from the index ( sparse ) feature space , not <nl> + / / the mapped / compact feature space , but the offset feature is the minimum <nl> + / / distance moved from the input to guarantee that it maps to the next <nl> + / / available quantum in the mapped / compact space . <nl> + int IntFeatureMap : : ComputeOffsetFeature ( int index_feature , int dir ) const { <nl> + INT_FEATURE_STRUCT f = InverseIndexFeature ( index_feature ) ; <nl> + ASSERT_HOST ( IndexFeature ( f ) = = index_feature ) ; <nl> + if ( dir = = 0 ) { <nl> + return index_feature ; <nl> + } else if ( dir = = 1 | | dir = = - 1 ) { <nl> + FCOORD feature_dir = FeatureDirection ( f . Theta ) ; <nl> + FCOORD rotation90 ( 0 . 0f , 1 . 0f ) ; <nl> + feature_dir . rotate ( rotation90 ) ; <nl> + / / Find the nearest existing feature . <nl> + for ( int m = 1 ; m < kMaxOffsetDist ; + + m ) { <nl> + double x_pos = f . X + feature_dir . x ( ) * ( m * dir ) ; <nl> + double y_pos = f . Y + feature_dir . y ( ) * ( m * dir ) ; <nl> + int x = IntCastRounded ( x_pos ) ; <nl> + int y = IntCastRounded ( y_pos ) ; <nl> + if ( x > = 0 & & x < = MAX_UINT8 & & y > = 0 & & y < = MAX_UINT8 ) { <nl> + INT_FEATURE_STRUCT offset_f ; <nl> + offset_f . X = x ; <nl> + offset_f . Y = y ; <nl> + offset_f . Theta = f . Theta ; <nl> + int offset_index = IndexFeature ( offset_f ) ; <nl> + if ( offset_index ! = index_feature & & offset_index > = 0 ) <nl> + return offset_index ; / / Found one . <nl> + } else { <nl> + return - 1 ; / / Hit the edge of feature space . <nl> + } <nl> + } <nl> + } else if ( dir = = 2 | | dir = = - 2 ) { <nl> + / / Find the nearest existing index_feature . <nl> + for ( int m = 1 ; m < kMaxOffsetDist ; + + m ) { <nl> + int theta = f . Theta + m * dir / 2 ; <nl> + INT_FEATURE_STRUCT offset_f ; <nl> + offset_f . X = f . X ; <nl> + offset_f . Y = f . Y ; <nl> + offset_f . Theta = Modulo ( theta , 256 ) ; <nl> + int offset_index = IndexFeature ( offset_f ) ; <nl> + if ( offset_index ! = index_feature & & offset_index > = 0 ) <nl> + return offset_index ; / / Found one . <nl> + } <nl> + } <nl> + return - 1 ; / / Nothing within the max distance . <nl> + } <nl> + <nl> + } / / namespace tesseract . <nl> new file mode 100644 <nl> index 000000000 . . 55c5b5cf5 <nl> mmm / dev / null <nl> ppp b / classify / intfeaturemap . h <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : intfeaturemap . h <nl> + / / Description : Encapsulation of IntFeatureSpace with IndexMapBiDi <nl> + / / to provide a subspace mapping and fast feature lookup . <nl> + / / Created : Tue Oct 26 08 : 58 : 30 PDT 2010 <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_CLASSIFY_INTFEATUREMAP_H__ <nl> + # define TESSERACT_CLASSIFY_INTFEATUREMAP_H__ <nl> + <nl> + # include " intfeaturespace . h " <nl> + # include " indexmapbidi . h " <nl> + # include " intproto . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + class SampleIterator ; <nl> + <nl> + / / Number of positive and negative offset maps . <nl> + static const int kNumOffsetMaps = 2 ; <nl> + <nl> + / / Class to map a feature space defined by INT_FEATURE_STRUCT to a compact <nl> + / / down - sampled subspace of actually used features . <nl> + / / The IntFeatureMap copes with 2 stages of transformation : <nl> + / / The first step is down - sampling ( re - quantization ) and converting to a <nl> + / / single index value from the 3 - D input : <nl> + / / INT_FEATURE_STRUCT < - > index feature ( via IntFeatureSpace ) and <nl> + / / the second is a feature - space compaction to map only the feature indices <nl> + / / that are actually used . This saves space in classifiers that are built <nl> + / / using the mapped feature space . <nl> + / / index ( sparse ) feature < - > map ( compact ) feature via IndexMapBiDi . <nl> + / / Although the transformations are reversible , the inverses are lossy and do <nl> + / / not return the exact input INT_FEATURE_STRUCT , due to the many - > one nature <nl> + / / of both transformations . <nl> + class IntFeatureMap { <nl> + public : <nl> + IntFeatureMap ( ) ; <nl> + ~ IntFeatureMap ( ) ; <nl> + <nl> + / / Accessors . <nl> + int sparse_size ( ) const { <nl> + return feature_space_ . Size ( ) ; <nl> + } <nl> + int compact_size ( ) const { <nl> + return compact_size_ ; <nl> + } <nl> + const IntFeatureSpace & feature_space ( ) const { <nl> + return feature_space_ ; <nl> + } <nl> + const IndexMapBiDi & feature_map ( ) const { <nl> + return feature_map_ ; <nl> + } <nl> + <nl> + / / Pseudo - accessors . <nl> + int IndexFeature ( const INT_FEATURE_STRUCT & f ) const ; <nl> + int MapFeature ( const INT_FEATURE_STRUCT & f ) const ; <nl> + int MapIndexFeature ( int index_feature ) const ; <nl> + INT_FEATURE_STRUCT InverseIndexFeature ( int index_feature ) const ; <nl> + INT_FEATURE_STRUCT InverseMapFeature ( int map_feature ) const ; <nl> + void DeleteMapFeature ( int map_feature ) ; <nl> + bool IsMapFeatureDeleted ( int map_feature ) const ; <nl> + <nl> + / / Copies the given feature_space and uses it as the index feature map <nl> + / / from INT_FEATURE_STRUCT . <nl> + void Init ( const IntFeatureSpace & feature_space ) ; <nl> + <nl> + / / Helper to return an offset index feature . In this context an offset <nl> + / / feature with a dir of + / - 1 is a feature of a similar direction , <nl> + / / but shifted perpendicular to the direction of the feature . An offset <nl> + / / feature with a dir of + / - 2 is feature at the same position , but rotated <nl> + / / by + / - one [ compact ] quantum . Returns the index of the generated offset <nl> + / / feature , or - 1 if it doesn ' t exist . Dir should be in <nl> + / / [ - kNumOffsetMaps , kNumOffsetMaps ] to indicate the relative direction . <nl> + / / A dir of 0 is an identity transformation . <nl> + / / Both input and output are from the index ( sparse ) feature space , not <nl> + / / the mapped / compact feature space , but the offset feature is the minimum <nl> + / / distance moved from the input to guarantee that it maps to the next <nl> + / / available quantum in the mapped / compact space . <nl> + int OffsetFeature ( int index_feature , int dir ) const ; <nl> + <nl> + / / Computes the features used by the subset of samples defined by <nl> + / / the iterator and sets up the feature mapping . <nl> + / / Returns the size of the compacted feature space . <nl> + int FindNZFeatureMapping ( SampleIterator * it ) ; <nl> + <nl> + / / After deleting some features , finish setting up the mapping , and map <nl> + / / all the samples . Returns the size of the compacted feature space . <nl> + int FinalizeMapping ( SampleIterator * it ) ; <nl> + <nl> + / / Indexes the given array of features to a vector of sorted indices . <nl> + void IndexAndSortFeatures ( const INT_FEATURE_STRUCT * features , <nl> + int num_features , <nl> + GenericVector < int > * sorted_features ) const { <nl> + feature_space_ . IndexAndSortFeatures ( features , num_features , <nl> + sorted_features ) ; <nl> + } <nl> + / / Maps the given array of index / sparse features to an array of map / compact <nl> + / / features . <nl> + / / Assumes the input is sorted . The output indices are sorted and uniqued . <nl> + / / Returns the number of " missed " features , being features that <nl> + / / don ' t map to the compact feature space . <nl> + int MapIndexedFeatures ( const GenericVector < int > & index_features , <nl> + GenericVector < int > * map_features ) const { <nl> + return feature_map_ . MapFeatures ( index_features , map_features ) ; <nl> + } <nl> + <nl> + / / Prints the map features from the set in human - readable form . <nl> + void DebugMapFeatures ( const GenericVector < int > & map_features ) const ; <nl> + <nl> + private : <nl> + void Clear ( ) ; <nl> + <nl> + / / Helper to compute an offset index feature . In this context an offset <nl> + / / feature with a dir of + / - 1 is a feature of a similar direction , <nl> + / / but shifted perpendicular to the direction of the feature . An offset <nl> + / / feature with a dir of + / - 2 is feature at the same position , but rotated <nl> + / / by + / - one [ compact ] quantum . Returns the index of the generated offset <nl> + / / feature , or - 1 if it doesn ' t exist . Dir should be in <nl> + / / [ - kNumOffsetMaps , kNumOffsetMaps ] to indicate the relative direction . <nl> + / / A dir of 0 is an identity transformation . <nl> + / / Both input and output are from the index ( sparse ) feature space , not <nl> + / / the mapped / compact feature space , but the offset feature is the minimum <nl> + / / distance moved from the input to guarantee that it maps to the next <nl> + / / available quantum in the mapped / compact space . <nl> + int ComputeOffsetFeature ( int index_feature , int dir ) const ; <nl> + <nl> + / / True if the mapping has changed since it was last finalized . <nl> + bool mapping_changed_ ; <nl> + / / Size of the compacted feature space , after unused features are removed . <nl> + int compact_size_ ; <nl> + / / Feature space quantization definition and indexing from INT_FEATURE_STRUCT . <nl> + IntFeatureSpace feature_space_ ; <nl> + / / Mapping from indexed feature space to the compacted space with unused <nl> + / / features mapping to - 1 . <nl> + IndexMapBiDi feature_map_ ; <nl> + / / Index tables to map a feature index to the corresponding feature after a <nl> + / / shift perpendicular to the feature direction , or a rotation in place . <nl> + / / An entry of - 1 indicates that there is no corresponding feature . <nl> + / / Array of arrays of size feature_space_ . Size ( ) owned by this class . <nl> + int * offset_plus_ [ kNumOffsetMaps ] ; <nl> + int * offset_minus_ [ kNumOffsetMaps ] ; <nl> + <nl> + / / Don ' t use default copy and assign ! <nl> + IntFeatureMap ( const IntFeatureMap & ) ; <nl> + void operator = ( const IntFeatureMap & ) ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + # endif / / TESSERACT_CLASSIFY_INTFEATUREMAP_H__ <nl> new file mode 100644 <nl> index 000000000 . . 5f911dcee <nl> mmm / dev / null <nl> ppp b / classify / intfeaturespace . cpp <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : intfeaturespace . cpp <nl> + / / Description : Indexed feature space based on INT_FEATURE_STRUCT . <nl> + / / Created : Wed Mar 24 11 : 21 : 27 PDT 2010 <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " intfeaturespace . h " <nl> + # include " intfx . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + IntFeatureSpace : : IntFeatureSpace ( ) <nl> + : x_buckets_ ( 0 ) , y_buckets_ ( 0 ) , theta_buckets_ ( 0 ) { <nl> + } <nl> + <nl> + void IntFeatureSpace : : Init ( uinT8 xbuckets , uinT8 ybuckets , uinT8 thetabuckets ) { <nl> + x_buckets_ = xbuckets ; <nl> + y_buckets_ = ybuckets ; <nl> + theta_buckets_ = thetabuckets ; <nl> + } <nl> + <nl> + / / Serializes the feature space definition to the given file . <nl> + / / Returns false on error . <nl> + bool IntFeatureSpace : : Serialize ( FILE * fp ) const { <nl> + if ( fwrite ( & x_buckets_ , sizeof ( x_buckets_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fwrite ( & y_buckets_ , sizeof ( y_buckets_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fwrite ( & theta_buckets_ , sizeof ( theta_buckets_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / DeSerializes the feature space definition from the given file . <nl> + / / If swap is true , the data is big / little - endian swapped . <nl> + / / Returns false on error . <nl> + bool IntFeatureSpace : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( fread ( & x_buckets_ , sizeof ( x_buckets_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fread ( & y_buckets_ , sizeof ( y_buckets_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fread ( & theta_buckets_ , sizeof ( theta_buckets_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Returns an INT_FEATURE_STRUCT corresponding to the given index . <nl> + / / This is the inverse of the Index member . <nl> + INT_FEATURE_STRUCT IntFeatureSpace : : PositionFromIndex ( int index ) const { <nl> + return PositionFromBuckets ( index / ( y_buckets_ * theta_buckets_ ) , <nl> + index / theta_buckets_ % y_buckets_ , <nl> + index % theta_buckets_ ) ; <nl> + } <nl> + <nl> + / / Bulk calls to Index . Maps the given array of features to a vector of <nl> + / / inT32 indices in the same order as the input . <nl> + void IntFeatureSpace : : IndexFeatures ( const INT_FEATURE_STRUCT * features , <nl> + int num_features , <nl> + GenericVector < int > * mapped_features ) const { <nl> + mapped_features - > truncate ( 0 ) ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) <nl> + mapped_features - > push_back ( Index ( features [ f ] ) ) ; <nl> + } <nl> + <nl> + / / Bulk calls to Index . Maps the given array of features to a vector of <nl> + / / sorted inT32 indices . <nl> + void IntFeatureSpace : : IndexAndSortFeatures ( <nl> + const INT_FEATURE_STRUCT * features , int num_features , <nl> + GenericVector < int > * sorted_features ) const { <nl> + sorted_features - > truncate ( 0 ) ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) <nl> + sorted_features - > push_back ( Index ( features [ f ] ) ) ; <nl> + sorted_features - > sort ( ) ; <nl> + } <nl> + <nl> + / / Returns a feature space index for the given x , y position in a display <nl> + / / window , or - 1 if the feature is a miss . <nl> + int IntFeatureSpace : : XYToFeatureIndex ( int x , int y ) const { <nl> + / / Round the x , y position to a feature . Search for a valid theta . <nl> + INT_FEATURE_STRUCT feature = { static_cast < uinT8 > ( x ) , static_cast < uinT8 > ( y ) , <nl> + 0 , 0 } ; <nl> + int index = - 1 ; <nl> + for ( int theta = 0 ; theta < = MAX_UINT8 & & index < 0 ; + + theta ) { <nl> + feature . Theta = theta ; <nl> + index = Index ( feature ) ; <nl> + } <nl> + if ( index < 0 ) { <nl> + tprintf ( " ( % d , % d ) does not exist in feature space ! \ n " , x , y ) ; <nl> + return - 1 ; <nl> + } <nl> + feature = PositionFromIndex ( index ) ; <nl> + tprintf ( " Click at ( % d , % d ) - > ( % d , % d ) , - > ( % d , % d ) \ n " , <nl> + x , y , feature . X , feature . Y , x - feature . X , y - feature . Y ) ; <nl> + / / Get the relative position of x , y from the rounded feature . <nl> + x - = feature . X ; <nl> + y - = feature . Y ; <nl> + if ( x ! = 0 | | y ! = 0 ) { <nl> + double angle = atan2 ( static_cast < double > ( y ) , static_cast < double > ( x ) ) + PI ; <nl> + angle * = kIntFeatureExtent / ( 2 . 0 * PI ) ; <nl> + feature . Theta = static_cast < uinT8 > ( angle + 0 . 5 ) ; <nl> + index = Index ( feature ) ; <nl> + if ( index < 0 ) { <nl> + tprintf ( " Feature failed to map to a valid index : " ) ; <nl> + feature . print ( ) ; <nl> + return - 1 ; <nl> + } <nl> + feature = PositionFromIndex ( index ) ; <nl> + } <nl> + feature . print ( ) ; <nl> + return index ; <nl> + } <nl> + <nl> + / / Returns an INT_FEATURE_STRUCT corresponding to the given bucket coords . <nl> + INT_FEATURE_STRUCT IntFeatureSpace : : PositionFromBuckets ( int x , <nl> + int y , <nl> + int theta ) const { <nl> + INT_FEATURE_STRUCT pos = { <nl> + static_cast < uinT8 > ( ClipToRange ( <nl> + ( x * kIntFeatureExtent + kIntFeatureExtent / 2 ) / x_buckets_ , <nl> + 0 , MAX_UINT8 ) ) , <nl> + static_cast < uinT8 > ( ClipToRange ( <nl> + ( y * kIntFeatureExtent + kIntFeatureExtent / 2 ) / y_buckets_ , <nl> + 0 , MAX_UINT8 ) ) , <nl> + static_cast < uinT8 > ( ClipToRange ( <nl> + DivRounded ( theta * kIntFeatureExtent , theta_buckets_ ) , <nl> + 0 , MAX_UINT8 ) ) } ; <nl> + return pos ; <nl> + } <nl> + <nl> + } / / namespace tesseract . <nl> new file mode 100644 <nl> index 000000000 . . e1e8e6ec9 <nl> mmm / dev / null <nl> ppp b / classify / intfeaturespace . h <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : intfeaturespace . h <nl> + / / Description : Indexed feature space based on INT_FEATURE_STRUCT . <nl> + / / Created : Wed Mar 24 10 : 55 : 30 PDT 2010 <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_CLASSIFY_INTFEATURESPACE_H__ <nl> + # define TESSERACT_CLASSIFY_INTFEATURESPACE_H__ <nl> + <nl> + # include " genericvector . h " <nl> + # include " intproto . h " <nl> + <nl> + / / Extent of x , y , theta in the input feature space . [ 0 , 255 ] . <nl> + const int kIntFeatureExtent = 256 ; <nl> + / / Extent of x , y , theta dimensions in the quantized feature space . <nl> + const int kBoostXYBuckets = 16 ; <nl> + const int kBoostDirBuckets = 16 ; <nl> + <nl> + namespace tesseract { <nl> + <nl> + class IndexMap ; <nl> + <nl> + / / Down - sampling quantization of the INT_FEATURE_STRUCT feature space and <nl> + / / conversion to a single scalar index value , used as a binary feature space . <nl> + class IntFeatureSpace { <nl> + public : <nl> + IntFeatureSpace ( ) ; <nl> + / / Default copy constructors and assignment OK ! <nl> + <nl> + / / Setup the feature space with the given dimensions . <nl> + void Init ( uinT8 xbuckets , uinT8 ybuckets , uinT8 thetabuckets ) ; <nl> + <nl> + / / Serializes the feature space definition to the given file . <nl> + / / Returns false on error . <nl> + bool Serialize ( FILE * fp ) const ; <nl> + <nl> + / / DeSerializes the feature space definition from the given file . <nl> + / / If swap is true , the data is big / little - endian swapped . <nl> + / / Returns false on error . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Returns the total size of the feature space . <nl> + int Size ( ) const { <nl> + return static_cast < int > ( x_buckets_ ) * y_buckets_ * theta_buckets_ ; <nl> + } <nl> + / / Returns an INT_FEATURE_STRUCT corresponding to the given index . <nl> + / / This is the inverse of the Index member . <nl> + INT_FEATURE_STRUCT PositionFromIndex ( int index ) const ; <nl> + <nl> + / / Returns a 1 - dimensional index corresponding to the given feature value . <nl> + / / Range is [ 0 , Size ( ) - 1 ] . Inverse of PositionFromIndex member . <nl> + int Index ( const INT_FEATURE_STRUCT & f ) const { <nl> + return ( XBucket ( f . X ) * y_buckets_ + YBucket ( f . Y ) ) * theta_buckets_ + <nl> + ThetaBucket ( f . Theta ) ; <nl> + } <nl> + / / Bulk calls to Index . Maps the given array of features to a vector of <nl> + / / inT32 indices in the same order as the input . <nl> + void IndexFeatures ( const INT_FEATURE_STRUCT * features , int num_features , <nl> + GenericVector < int > * mapped_features ) const ; <nl> + / / Bulk calls to Index . Maps the given array of features to a vector of <nl> + / / sorted inT32 indices . <nl> + void IndexAndSortFeatures ( const INT_FEATURE_STRUCT * features , <nl> + int num_features , <nl> + GenericVector < int > * sorted_features ) const ; <nl> + / / Returns a feature space index for the given x , y position in a display <nl> + / / window , or - 1 if the feature is a miss . <nl> + int XYToFeatureIndex ( int x , int y ) const ; <nl> + <nl> + protected : <nl> + / / Converters to generate indices for individual feature dimensions . <nl> + int XBucket ( int x ) const { <nl> + int bucket = x * x_buckets_ / kIntFeatureExtent ; <nl> + return ClipToRange ( bucket , 0 , static_cast < int > ( x_buckets_ ) - 1 ) ; <nl> + } <nl> + int YBucket ( int y ) const { <nl> + int bucket = y * y_buckets_ / kIntFeatureExtent ; <nl> + return ClipToRange ( bucket , 0 , static_cast < int > ( y_buckets_ ) - 1 ) ; <nl> + } <nl> + / / Use DivRounded for theta so that exactly vertical and horizontal are in <nl> + / / the middle of a bucket . The Modulo takes care of the wrap - around . <nl> + int ThetaBucket ( int theta ) const { <nl> + int bucket = DivRounded ( theta * theta_buckets_ , kIntFeatureExtent ) ; <nl> + return Modulo ( bucket , theta_buckets_ ) ; <nl> + } <nl> + / / Returns an INT_FEATURE_STRUCT corresponding to the given buckets . <nl> + INT_FEATURE_STRUCT PositionFromBuckets ( int x , int y , int theta ) const ; <nl> + <nl> + / / Feature space definition - serialized . <nl> + uinT8 x_buckets_ ; <nl> + uinT8 y_buckets_ ; <nl> + uinT8 theta_buckets_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + <nl> + # endif / / TESSERACT_CLASSIFY_INTFEATURESPACE_H__ <nl> mmm a / classify / intfx . cpp <nl> ppp b / classify / intfx . cpp <nl> <nl> # include " const . h " <nl> # include " helpers . h " <nl> # include " ccutil . h " <nl> + # include " statistc . h " <nl> + # include " trainingsample . h " <nl> # ifdef __UNIX__ <nl> # endif <nl> <nl> + using tesseract : : TrainingSample ; <nl> + <nl> / * * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Private Function Prototypes <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> INT_VAR ( classify_radius_gyr_max_exp , 8 , <nl> / / atan ( 0 . 0 ) . . . atan ( ATAN_TABLE_SIZE - 1 / ATAN_TABLE_SIZE ) <nl> / / The entries are in binary degrees where a full circle is 256 binary degrees . <nl> static uinT8 AtanTable [ ATAN_TABLE_SIZE ] ; <nl> + / / Look up table for cos and sin to turn the intfx feature angle to a vector . <nl> + / / Also protected by atan_table_mutex . <nl> + static float cos_table [ INT_CHAR_NORM_RANGE ] ; <nl> + static float sin_table [ INT_CHAR_NORM_RANGE ] ; <nl> / / Guards write access to AtanTable so we dont create it more than once . <nl> tesseract : : CCUtilMutex atan_table_mutex ; <nl> <nl> void InitIntegerFX ( ) { <nl> AtanTable [ i ] = <nl> ( uinT8 ) ( atan ( ( i / ( float ) ATAN_TABLE_SIZE ) ) * 128 . 0 / PI + 0 . 5 ) ; <nl> } <nl> + for ( int i = 0 ; i < INT_CHAR_NORM_RANGE ; + + i ) { <nl> + cos_table [ i ] = cos ( i * 2 * PI / INT_CHAR_NORM_RANGE + PI ) ; <nl> + sin_table [ i ] = sin ( i * 2 * PI / INT_CHAR_NORM_RANGE + PI ) ; <nl> + } <nl> atan_table_init = true ; <nl> } <nl> atan_table_mutex . Unlock ( ) ; <nl> } <nl> <nl> + / / Returns a vector representing the direction of a feature with the given <nl> + / / theta direction in an INT_FEATURE_STRUCT . <nl> + FCOORD FeatureDirection ( uinT8 theta ) { <nl> + return FCOORD ( cos_table [ theta ] , sin_table [ theta ] ) ; <nl> + } <nl> + <nl> + TrainingSample * GetIntFeatures ( tesseract : : NormalizationMode mode , <nl> + TBLOB * blob , const DENORM & denorm ) { <nl> + INT_FEATURE_ARRAY blfeatures ; <nl> + INT_FEATURE_ARRAY cnfeatures ; <nl> + INT_FX_RESULT_STRUCT fx_info ; <nl> + ExtractIntFeat ( blob , denorm , blfeatures , cnfeatures , & fx_info , NULL ) ; <nl> + TrainingSample * sample = NULL ; <nl> + if ( mode = = tesseract : : NM_CHAR_ANISOTROPIC ) { <nl> + int num_features = fx_info . NumCN ; <nl> + if ( num_features > 0 ) { <nl> + sample = TrainingSample : : CopyFromFeatures ( fx_info , cnfeatures , <nl> + num_features ) ; <nl> + } <nl> + } else if ( mode = = tesseract : : NM_BASELINE ) { <nl> + int num_features = fx_info . NumBL ; <nl> + if ( num_features > 0 ) { <nl> + sample = TrainingSample : : CopyFromFeatures ( fx_info , blfeatures , <nl> + num_features ) ; <nl> + } <nl> + } else { <nl> + ASSERT_HOST ( ! " Unsupported normalization mode ! " ) ; <nl> + } <nl> + return sample ; <nl> + } <nl> + <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> / / Extract a set of standard - sized features from Blobs and write them out in <nl> int ExtractIntFeat ( TBLOB * Blob , <nl> const DENORM & denorm , <nl> INT_FEATURE_ARRAY BLFeat , <nl> INT_FEATURE_ARRAY CNFeat , <nl> - INT_FX_RESULT Results , <nl> + INT_FX_RESULT_STRUCT * Results , <nl> inT32 * FeatureOutlineArray ) { <nl> <nl> TESSLINE * OutLine ; <nl> int ExtractIntFeat ( TBLOB * Blob , <nl> Results - > Ry = 0 ; <nl> Results - > NumBL = 0 ; <nl> Results - > NumCN = 0 ; <nl> + Results - > YBottom = MAX_UINT8 ; <nl> + Results - > YTop = 0 ; <nl> <nl> / / Calculate the centroid ( Xmean , Ymean ) for the blob . <nl> / / We use centroid ( instead of center of bounding box or center of smallest <nl> int ExtractIntFeat ( TBLOB * Blob , <nl> Iy = 0 ; <nl> NumBLFeatures = 0 ; <nl> OutLine = Blob - > outlines ; <nl> + int min_x = 0 ; <nl> + int max_x = 0 ; <nl> while ( OutLine ! = NULL ) { <nl> LoopStart = OutLine - > loop ; <nl> Loop = LoopStart ; <nl> int ExtractIntFeat ( TBLOB * Blob , <nl> Loop = Loop - > next ; <nl> NormX = Loop - > pos . x - Xmean ; <nl> NormY = Loop - > pos . y ; <nl> + if ( NormY < Results - > YBottom ) <nl> + Results - > YBottom = ClipToRange ( NormY , 0 , MAX_UINT8 ) ; <nl> + if ( NormY > Results - > YTop ) <nl> + Results - > YTop = ClipToRange ( NormY , 0 , MAX_UINT8 ) ; <nl> + UpdateRange ( NormX , & min_x , & max_x ) ; <nl> <nl> n = 1 ; <nl> if ( ! Segment - > IsHidden ( ) ) { <nl> int ExtractIntFeat ( TBLOB * Blob , <nl> while ( Loop ! = LoopStart ) ; <nl> OutLine = OutLine - > next ; <nl> } <nl> + Results - > Width = max_x - min_x ; <nl> if ( Ix = = 0 ) <nl> Ix = 1 ; <nl> if ( Iy = = 0 ) <nl> int SaveFeature ( INT_FEATURE_ARRAY FeatureArray , <nl> Feature - > X = ClipToRange < inT16 > ( X , 0 , 255 ) ; <nl> Feature - > Y = ClipToRange < inT16 > ( Y , 0 , 255 ) ; <nl> Feature - > Theta = Theta ; <nl> + Feature - > CP_misses = 0 ; <nl> <nl> return TRUE ; <nl> } <nl> mmm a / classify / intfx . h <nl> ppp b / classify / intfx . h <nl> <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> # include " blobs . h " <nl> # include " intproto . h " <nl> + # include " normalis . h " <nl> # include < math . h > <nl> <nl> class DENORM ; <nl> <nl> - typedef struct <nl> - { <nl> - inT32 Length ; / * total length of all outlines * / <nl> - inT16 Xmean , Ymean ; / * center of mass of all outlines * / <nl> - inT16 Rx , Ry ; / * radius of gyration * / <nl> - inT16 NumBL , NumCN ; / * number of features extracted * / <nl> + namespace tesseract { <nl> + class TrainingSample ; <nl> } <nl> <nl> - <nl> - INT_FX_RESULT_STRUCT , * INT_FX_RESULT ; <nl> + struct INT_FX_RESULT_STRUCT { <nl> + inT32 Length ; / / total length of all outlines <nl> + inT16 Xmean , Ymean ; / / center of mass of all outlines <nl> + inT16 Rx , Ry ; / / radius of gyration <nl> + inT16 NumBL , NumCN ; / / number of features extracted <nl> + inT16 Width ; / / Width of blob in BLN coords . <nl> + uinT8 YBottom ; / / Bottom of blob in BLN coords . <nl> + uinT8 YTop ; / / Top of blob in BLN coords . <nl> + } ; <nl> <nl> / * * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Public Function Prototypes <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> void InitIntegerFX ( ) ; <nl> <nl> + / / Returns a vector representing the direction of a feature with the given <nl> + / / theta direction in an INT_FEATURE_STRUCT . <nl> + FCOORD FeatureDirection ( uinT8 theta ) ; <nl> + <nl> + tesseract : : TrainingSample * GetIntFeatures ( <nl> + tesseract : : NormalizationMode mode , TBLOB * blob , <nl> + const DENORM & denorm ) ; <nl> + <nl> int ExtractIntFeat ( TBLOB * Blob , <nl> const DENORM & denorm , <nl> INT_FEATURE_ARRAY BLFeat , <nl> INT_FEATURE_ARRAY CNFeat , <nl> - INT_FX_RESULT Results , <nl> + INT_FX_RESULT_STRUCT * Results , <nl> inT32 * FeatureOutlineArray = 0 ) ; <nl> <nl> uinT8 BinaryAnglePlusPi ( inT32 Y , inT32 X ) ; <nl> mmm a / classify / intmatcher . cpp <nl> ppp b / classify / intmatcher . cpp <nl> <nl> # include " intproto . h " <nl> # include " callcpp . h " <nl> # include " scrollview . h " <nl> + # include " float2int . h " <nl> # include " globals . h " <nl> + # include " helpers . h " <nl> # include " classify . h " <nl> + # include " shapetable . h " <nl> # include < math . h > <nl> <nl> / / Include automatically generated configuration file if running autoconf . <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Global Data Definitions and Declarations <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * / <nl> + / / Parameters of the sigmoid used to convert similarity to evidence in the <nl> + / / similarity_evidence_table_ that is used to convert distance metric to an <nl> + / / 8 bit evidence value in the secondary matcher . ( See IntMatcher : : Init ) . <nl> + const float IntegerMatcher : : kSEExponentialMultiplier = 0 . 0 ; <nl> + const float IntegerMatcher : : kSimilarityCenter = 0 . 0075 ; <nl> <nl> static const uinT8 offset_table [ 256 ] = { <nl> 255 , 0 , 1 , 0 , 2 , 0 , 1 , 0 , 3 , 0 , 1 , 0 , 2 , 0 , 1 , 0 , <nl> static const uinT8 next_table [ 256 ] = { <nl> 0xf8 , 0xfc , 0xfc , 0xfe <nl> } ; <nl> <nl> - struct ClassPrunerData { <nl> - int * class_count_ ; <nl> - int * norm_count_ ; <nl> - int * sort_key_ ; <nl> - int * sort_index_ ; <nl> - int max_classes_ ; <nl> + namespace tesseract { <nl> <nl> - ClassPrunerData ( int max_classes ) { <nl> - / / class_count_ and friends are referenced by indexing off of data in <nl> - / / class pruner word sized chunks . Each pruner word is of sized <nl> - / / BITS_PER_WERD and each entry is NUM_BITS_PER_CLASS , so there are <nl> - / / BITS_PER_WERD / NUM_BITS_PER_CLASS entries . <nl> - / / See Classify : : ClassPruner in intmatcher . cpp . <nl> - max_classes_ = RoundUp ( <nl> + / / Encapsulation of the intermediate data and computations made by the class <nl> + / / pruner . The class pruner implements a simple linear classifier on binary <nl> + / / features by heavily quantizing the feature space , and applying <nl> + / / NUM_BITS_PER_CLASS ( 2 ) - bit weights to the features . Lack of resolution in <nl> + / / weights is compensated by a non - constant bias that is dependent on the <nl> + / / number of features present . <nl> + class ClassPruner { <nl> + public : <nl> + ClassPruner ( int max_classes ) { <nl> + / / The unrolled loop in ComputeScores means that the array sizes need to <nl> + / / be rounded up so that the array is big enough to accommodate the extra <nl> + / / entries accessed by the unrolling . Each pruner word is of sized <nl> + / / BITS_PER_WERD and each entry is NUM_BITS_PER_CLASS , so there are <nl> + / / BITS_PER_WERD / NUM_BITS_PER_CLASS entries . <nl> + / / See ComputeScores . <nl> + max_classes_ = max_classes ; <nl> + rounded_classes_ = RoundUp ( <nl> max_classes , WERDS_PER_CP_VECTOR * BITS_PER_WERD / NUM_BITS_PER_CLASS ) ; <nl> - class_count_ = new int [ max_classes_ ] ; <nl> - norm_count_ = new int [ max_classes_ ] ; <nl> - sort_key_ = new int [ max_classes_ + 1 ] ; <nl> - sort_index_ = new int [ max_classes_ + 1 ] ; <nl> - for ( int i = 0 ; i < max_classes_ ; i + + ) { <nl> + class_count_ = new int [ rounded_classes_ ] ; <nl> + norm_count_ = new int [ rounded_classes_ ] ; <nl> + sort_key_ = new int [ rounded_classes_ + 1 ] ; <nl> + sort_index_ = new int [ rounded_classes_ + 1 ] ; <nl> + for ( int i = 0 ; i < rounded_classes_ ; i + + ) { <nl> class_count_ [ i ] = 0 ; <nl> } <nl> + pruning_threshold_ = 0 ; <nl> + num_features_ = 0 ; <nl> + num_classes_ = 0 ; <nl> } <nl> <nl> - ~ ClassPrunerData ( ) { <nl> + ~ ClassPruner ( ) { <nl> delete [ ] class_count_ ; <nl> delete [ ] norm_count_ ; <nl> delete [ ] sort_key_ ; <nl> delete [ ] sort_index_ ; <nl> } <nl> <nl> - } ; <nl> - <nl> - const float IntegerMatcher : : kSEExponentialMultiplier = 0 . 0 ; <nl> - const float IntegerMatcher : : kSimilarityCenter = 0 . 0075 ; <nl> - <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - Public Code <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - namespace tesseract { <nl> - int Classify : : ClassPruner ( INT_TEMPLATES IntTemplates , <nl> - inT16 NumFeatures , <nl> - INT_FEATURE_ARRAY Features , <nl> - CLASS_NORMALIZATION_ARRAY NormalizationFactors , <nl> - CLASS_CUTOFF_ARRAY ExpectedNumFeatures , <nl> - CLASS_PRUNER_RESULTS Results ) { <nl> - / * <nl> - * * Parameters : <nl> - * * IntTemplates Class pruner tables <nl> - * * NumFeatures Number of features in blob <nl> - * * Features Array of features <nl> - * * NormalizationFactors Array of fudge factors from blob <nl> - * * normalization process <nl> - * * ( by CLASS_INDEX ) <nl> - * * ExpectedNumFeatures Array of expected number of features <nl> - * * for each class <nl> - * * ( by CLASS_INDEX ) <nl> - * * Results Sorted Array of pruned classes <nl> - * * ( by CLASS_ID ) <nl> - * * Operation : <nl> - * * Prune the classes using a modified fast match table . <nl> - * * Return a sorted list of classes along with the number <nl> - * * of pruned classes in that list . <nl> - * * Return : Number of pruned classes . <nl> - * * Exceptions : none <nl> - * * History : Tue Feb 19 10 : 24 : 24 MST 1991 , RWM , Created . <nl> - * / <nl> - uinT32 PrunerWord ; <nl> - inT32 class_index ; / / index to class <nl> - int Word ; <nl> - uinT32 * BasePrunerAddress ; <nl> - uinT32 feature_address ; / / current feature index <nl> - INT_FEATURE feature ; / / current feature <nl> - CLASS_PRUNER * ClassPruner ; <nl> - int PrunerSet ; <nl> - int NumPruners ; <nl> - inT32 feature_index ; / / current feature <nl> - <nl> - int MaxNumClasses = IntTemplates - > NumClasses ; <nl> - ClassPrunerData data ( IntTemplates - > NumClasses ) ; <nl> - int * ClassCount = data . class_count_ ; <nl> - int * NormCount = data . norm_count_ ; <nl> - int * SortKey = data . sort_key_ ; <nl> - int * SortIndex = data . sort_index_ ; <nl> - <nl> - int out_class ; <nl> - int MaxCount ; <nl> - int NumClasses ; <nl> - FLOAT32 max_rating ; / / max allowed rating <nl> - CLASS_ID class_id ; <nl> - <nl> - / * Update Class Counts * / <nl> - NumPruners = IntTemplates - > NumClassPruners ; <nl> - for ( feature_index = 0 ; feature_index < NumFeatures ; feature_index + + ) { <nl> - feature = & Features [ feature_index ] ; <nl> - feature_address = ( ( ( feature - > X * NUM_CP_BUCKETS > > 8 ) * NUM_CP_BUCKETS + <nl> - ( feature - > Y * NUM_CP_BUCKETS > > 8 ) ) * NUM_CP_BUCKETS + <nl> - ( feature - > Theta * NUM_CP_BUCKETS > > 8 ) ) < < 1 ; <nl> - ClassPruner = IntTemplates - > ClassPruner ; <nl> - class_index = 0 ; <nl> - <nl> - for ( PrunerSet = 0 ; PrunerSet < NumPruners ; PrunerSet + + , ClassPruner + + ) { <nl> - BasePrunerAddress = ( uinT32 * ) ( * ClassPruner ) + feature_address ; <nl> - <nl> - for ( Word = 0 ; Word < WERDS_PER_CP_VECTOR ; Word + + ) { <nl> - PrunerWord = * BasePrunerAddress + + ; <nl> - / / This inner loop is unrolled to speed up the ClassPruner . <nl> - / / Currently gcc would not unroll it unless it is set to O3 <nl> - / / level of optimization or - funroll - loops is specified . <nl> - / * <nl> - uinT32 class_mask = ( 1 < < NUM_BITS_PER_CLASS ) - 1 ; <nl> - for ( int bit = 0 ; bit < BITS_PER_WERD / NUM_BITS_PER_CLASS ; bit + + ) { <nl> - ClassCount [ class_index + + ] + = PrunerWord & class_mask ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> + / / Computes the scores for every class in the character set , by summing the <nl> + / / weights for each feature and stores the sums internally in class_count_ . <nl> + void ComputeScores ( const INT_TEMPLATES_STRUCT * int_templates , <nl> + int num_features , const INT_FEATURE_STRUCT * features ) { <nl> + num_features_ = num_features ; <nl> + int num_pruners = int_templates - > NumClassPruners ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) { <nl> + const INT_FEATURE_STRUCT * feature = & features [ f ] ; <nl> + / / Quantize the feature to NUM_CP_BUCKETS * NUM_CP_BUCKETS * NUM_CP_BUCKETS . <nl> + int x = feature - > X * NUM_CP_BUCKETS > > 8 ; <nl> + int y = feature - > Y * NUM_CP_BUCKETS > > 8 ; <nl> + int theta = feature - > Theta * NUM_CP_BUCKETS > > 8 ; <nl> + int class_id = 0 ; <nl> + / / Each CLASS_PRUNER_STRUCT only covers CLASSES_PER_CP ( 32 ) classes , so <nl> + / / we need a collection of them , indexed by pruner_set . <nl> + for ( int pruner_set = 0 ; pruner_set < num_pruners ; + + pruner_set ) { <nl> + / / Look up quantized feature in a 3 - D array , an array of weights for <nl> + / / each class . <nl> + const uinT32 * pruner_word_ptr = <nl> + int_templates - > ClassPruners [ pruner_set ] - > p [ x ] [ y ] [ theta ] ; <nl> + for ( int word = 0 ; word < WERDS_PER_CP_VECTOR ; + + word ) { <nl> + uinT32 pruner_word = * pruner_word_ptr + + ; <nl> + / / This inner loop is unrolled to speed up the ClassPruner . <nl> + / / Currently gcc would not unroll it unless it is set to O3 <nl> + / / level of optimization or - funroll - loops is specified . <nl> + / * <nl> + uinT32 class_mask = ( 1 < < NUM_BITS_PER_CLASS ) - 1 ; <nl> + for ( int bit = 0 ; bit < BITS_PER_WERD / NUM_BITS_PER_CLASS ; bit + + ) { <nl> + class_count_ [ class_id + + ] + = pruner_word & class_mask ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + } <nl> + * / <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> + class_count_ [ class_id + + ] + = pruner_word & CLASS_PRUNER_CLASS_MASK ; <nl> } <nl> - * / <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> - ClassCount [ class_index + + ] + = PrunerWord & CLASS_PRUNER_CLASS_MASK ; <nl> } <nl> } <nl> } <nl> <nl> - / * Adjust Class Counts for Number of Expected Features * / <nl> - for ( class_id = 0 ; class_id < MaxNumClasses ; class_id + + ) { <nl> - if ( NumFeatures < ExpectedNumFeatures [ class_id ] ) { <nl> - int deficit = ExpectedNumFeatures [ class_id ] - NumFeatures ; <nl> - ClassCount [ class_id ] - = ClassCount [ class_id ] * deficit / <nl> - ( NumFeatures * classify_cp_cutoff_strength + deficit ) ; <nl> + / / Adjusts the scores according to the number of expected features . Used <nl> + / / in lieu of a constant bias , this penalizes classes that expect more <nl> + / / features than there are present . Thus an actual c will score higher for c <nl> + / / than e , even though almost all the features match e as well as c , because <nl> + / / e expects more features to be present . <nl> + void AdjustForExpectedNumFeatures ( const uinT16 * expected_num_features , <nl> + int cutoff_strength ) { <nl> + for ( int class_id = 0 ; class_id < max_classes_ ; + + class_id ) { <nl> + if ( num_features_ < expected_num_features [ class_id ] ) { <nl> + int deficit = expected_num_features [ class_id ] - num_features_ ; <nl> + class_count_ [ class_id ] - = class_count_ [ class_id ] * deficit / <nl> + ( num_features_ * cutoff_strength + deficit ) ; <nl> + } <nl> } <nl> - if ( ! unicharset . get_enabled ( class_id ) ) <nl> - ClassCount [ class_id ] = 0 ; / / This char is disabled ! <nl> + } <nl> <nl> - / / Do not include character fragments in the class pruner <nl> - / / results if disable_character_fragments is true . <nl> - if ( disable_character_fragments & & unicharset . get_fragment ( class_id ) ) { <nl> - ClassCount [ class_id ] = 0 ; <nl> + / / Zeros the scores for classes disabled in the unicharset . <nl> + / / Implements the black - list to recognize a subset of the character set . <nl> + void DisableDisabledClasses ( const UNICHARSET & unicharset ) { <nl> + for ( int class_id = 0 ; class_id < max_classes_ ; + + class_id ) { <nl> + if ( ! unicharset . get_enabled ( class_id ) ) <nl> + class_count_ [ class_id ] = 0 ; / / This char is disabled ! <nl> } <nl> } <nl> <nl> - / * Adjust Class Counts for Normalization Factors * / <nl> - MaxCount = 0 ; <nl> - for ( class_id = 0 ; class_id < MaxNumClasses ; class_id + + ) { <nl> - NormCount [ class_id ] = ClassCount [ class_id ] <nl> - - ( ( classify_class_pruner_multiplier * NormalizationFactors [ class_id ] ) <nl> - > > 8 ) ; <nl> - if ( NormCount [ class_id ] > MaxCount & & <nl> - / / This additional check is added in order to ensure that <nl> - / / the classifier will return at least one non - fragmented <nl> - / / character match . <nl> - / / TODO ( daria ) : verify that this helps accuracy and does not <nl> - / / hurt performance . <nl> - ! unicharset . get_fragment ( class_id ) ) { <nl> - MaxCount = NormCount [ class_id ] ; <nl> + / / Zeros the scores of fragments . <nl> + void DisableFragments ( const UNICHARSET & unicharset ) { <nl> + for ( int class_id = 0 ; class_id < max_classes_ ; + + class_id ) { <nl> + / / Do not include character fragments in the class pruner <nl> + / / results if disable_character_fragments is true . <nl> + if ( unicharset . get_fragment ( class_id ) ) { <nl> + class_count_ [ class_id ] = 0 ; <nl> + } <nl> } <nl> } <nl> <nl> - / * Prune Classes * / <nl> - MaxCount * = classify_class_pruner_threshold ; <nl> - MaxCount > > = 8 ; <nl> - / * Select Classes * / <nl> - if ( MaxCount < 1 ) <nl> - MaxCount = 1 ; <nl> - NumClasses = 0 ; <nl> - for ( class_id = 0 ; class_id < MaxNumClasses ; class_id + + ) { <nl> - if ( NormCount [ class_id ] > = MaxCount ) { <nl> - NumClasses + + ; <nl> - SortIndex [ NumClasses ] = class_id ; <nl> - SortKey [ NumClasses ] = NormCount [ class_id ] ; <nl> + / / Normalizes the counts for xheight , putting the normalized result in <nl> + / / norm_count_ . Applies a simple subtractive penalty for incorrect vertical <nl> + / / position provided by the normalization_factors array , indexed by <nl> + / / character class , and scaled by the norm_multiplier . <nl> + void NormalizeForXheight ( int norm_multiplier , <nl> + const uinT8 * normalization_factors ) { <nl> + for ( int class_id = 0 ; class_id < max_classes_ ; class_id + + ) { <nl> + norm_count_ [ class_id ] = class_count_ [ class_id ] - <nl> + ( ( norm_multiplier * normalization_factors [ class_id ] ) > > 8 ) ; <nl> } <nl> } <nl> <nl> - / * Sort Classes using Heapsort Algorithm * / <nl> - if ( NumClasses > 1 ) <nl> - HeapSort ( NumClasses , SortKey , SortIndex ) ; <nl> + / / The nop normalization copies the class_count_ array to norm_count_ . <nl> + void NoNormalization ( ) { <nl> + for ( int class_id = 0 ; class_id < max_classes_ ; class_id + + ) { <nl> + norm_count_ [ class_id ] = class_count_ [ class_id ] ; <nl> + } <nl> + } <nl> <nl> - if ( classify_debug_level > 1 ) { <nl> - cprintf ( " CP : % d classes , % d features : \ n " , NumClasses , NumFeatures ) ; <nl> - for ( class_id = 0 ; class_id < NumClasses ; class_id + + ) { <nl> - cprintf ( " % s : C = % d , E = % d , N = % d , Rat = % d \ n " , <nl> - unicharset . debug_str ( SortIndex [ NumClasses - class_id ] ) . string ( ) , <nl> - ClassCount [ SortIndex [ NumClasses - class_id ] ] , <nl> - ExpectedNumFeatures [ SortIndex [ NumClasses - class_id ] ] , <nl> - SortKey [ NumClasses - class_id ] , <nl> - 1010 - 1000 * SortKey [ NumClasses - class_id ] / <nl> - ( CLASS_PRUNER_CLASS_MASK * NumFeatures ) ) ; <nl> + / / Prunes the classes using < the maximum count > * pruning_factor / 256 as a <nl> + / / threshold for keeping classes . If max_of_non_fragments , then ignore <nl> + / / fragments in computing the maximum count . <nl> + void PruneAndSort ( int pruning_factor , bool max_of_non_fragments , <nl> + const UNICHARSET & unicharset ) { <nl> + int max_count = 0 ; <nl> + for ( int c = 0 ; c < max_classes_ ; + + c ) { <nl> + if ( norm_count_ [ c ] > max_count & & <nl> + / / This additional check is added in order to ensure that <nl> + / / the classifier will return at least one non - fragmented <nl> + / / character match . <nl> + / / TODO ( daria ) : verify that this helps accuracy and does not <nl> + / / hurt performance . <nl> + ( ! max_of_non_fragments | | ! unicharset . get_fragment ( c ) ) ) { <nl> + max_count = norm_count_ [ c ] ; <nl> + } <nl> + } <nl> + / / Prune Classes . <nl> + pruning_threshold_ = ( max_count * pruning_factor ) > > 8 ; <nl> + / / Select Classes . <nl> + if ( pruning_threshold_ < 1 ) <nl> + pruning_threshold_ = 1 ; <nl> + num_classes_ = 0 ; <nl> + for ( int class_id = 0 ; class_id < max_classes_ ; class_id + + ) { <nl> + if ( norm_count_ [ class_id ] > = pruning_threshold_ ) { <nl> + + + num_classes_ ; <nl> + sort_index_ [ num_classes_ ] = class_id ; <nl> + sort_key_ [ num_classes_ ] = norm_count_ [ class_id ] ; <nl> + } <nl> } <nl> - if ( classify_debug_level > 2 ) { <nl> - NumPruners = IntTemplates - > NumClassPruners ; <nl> - for ( feature_index = 0 ; feature_index < NumFeatures ; <nl> - feature_index + + ) { <nl> - cprintf ( " F = % 3d , " , feature_index ) ; <nl> - feature = & Features [ feature_index ] ; <nl> - feature_address = <nl> - ( ( ( feature - > X * NUM_CP_BUCKETS > > 8 ) * NUM_CP_BUCKETS + <nl> - ( feature - > Y * NUM_CP_BUCKETS > > 8 ) ) * NUM_CP_BUCKETS + <nl> - ( feature - > Theta * NUM_CP_BUCKETS > > 8 ) ) < < 1 ; <nl> - ClassPruner = IntTemplates - > ClassPruner ; <nl> - class_index = 0 ; <nl> - for ( PrunerSet = 0 ; PrunerSet < NumPruners ; <nl> - PrunerSet + + , ClassPruner + + ) { <nl> - BasePrunerAddress = ( uinT32 * ) ( * ClassPruner ) <nl> - + feature_address ; <nl> - <nl> - for ( Word = 0 ; Word < WERDS_PER_CP_VECTOR ; Word + + ) { <nl> - PrunerWord = * BasePrunerAddress + + ; <nl> - for ( class_id = 0 ; class_id < 16 ; class_id + + , class_index + + ) { <nl> - if ( NormCount [ class_index ] > = MaxCount ) <nl> - cprintf ( " % s = % d , " , <nl> - unicharset . id_to_unichar ( class_index ) , <nl> - PrunerWord & CLASS_PRUNER_CLASS_MASK ) ; <nl> - PrunerWord > > = NUM_BITS_PER_CLASS ; <nl> + <nl> + / / Sort Classes using Heapsort Algorithm . <nl> + if ( num_classes_ > 1 ) <nl> + HeapSort ( num_classes_ , sort_key_ , sort_index_ ) ; <nl> + } <nl> + <nl> + / / Prints debug info on the class pruner matches for the pruned classes only . <nl> + void DebugMatch ( const Classify & classify , <nl> + const INT_TEMPLATES_STRUCT * int_templates , <nl> + const INT_FEATURE_STRUCT * features ) const { <nl> + int num_pruners = int_templates - > NumClassPruners ; <nl> + int max_num_classes = int_templates - > NumClasses ; <nl> + for ( int f = 0 ; f < num_features_ ; + + f ) { <nl> + const INT_FEATURE_STRUCT * feature = & features [ f ] ; <nl> + tprintf ( " F = % 3d ( % d , % d , % d ) , " , f , feature - > X , feature - > Y , feature - > Theta ) ; <nl> + / / Quantize the feature to NUM_CP_BUCKETS * NUM_CP_BUCKETS * NUM_CP_BUCKETS . <nl> + int x = feature - > X * NUM_CP_BUCKETS > > 8 ; <nl> + int y = feature - > Y * NUM_CP_BUCKETS > > 8 ; <nl> + int theta = feature - > Theta * NUM_CP_BUCKETS > > 8 ; <nl> + int class_id = 0 ; <nl> + for ( int pruner_set = 0 ; pruner_set < num_pruners ; + + pruner_set ) { <nl> + / / Look up quantized feature in a 3 - D array , an array of weights for <nl> + / / each class . <nl> + const uinT32 * pruner_word_ptr = <nl> + int_templates - > ClassPruners [ pruner_set ] - > p [ x ] [ y ] [ theta ] ; <nl> + for ( int word = 0 ; word < WERDS_PER_CP_VECTOR ; + + word ) { <nl> + uinT32 pruner_word = * pruner_word_ptr + + ; <nl> + for ( int word_class = 0 ; word_class < 16 & & <nl> + class_id < max_num_classes ; + + word_class , + + class_id ) { <nl> + if ( norm_count_ [ class_id ] > = pruning_threshold_ ) { <nl> + tprintf ( " % s = % d , " , <nl> + classify . ClassIDToDebugStr ( int_templates , <nl> + class_id , 0 ) . string ( ) , <nl> + pruner_word & CLASS_PRUNER_CLASS_MASK ) ; <nl> } <nl> + pruner_word > > = NUM_BITS_PER_CLASS ; <nl> } <nl> } <nl> - cprintf ( " \ n " ) ; <nl> - } <nl> - cprintf ( " Adjustments : " ) ; <nl> - for ( class_id = 0 ; class_id < MaxNumClasses ; class_id + + ) { <nl> - if ( NormCount [ class_id ] > MaxCount ) <nl> - cprintf ( " % s = % d , " , <nl> - unicharset . id_to_unichar ( class_id ) , <nl> - - ( ( classify_class_pruner_multiplier * <nl> - NormalizationFactors [ class_id ] ) > > 8 ) ) ; <nl> + tprintf ( " \ n " ) ; <nl> } <nl> - cprintf ( " \ n " ) ; <nl> } <nl> } <nl> <nl> - / * Set Up Results * / <nl> - max_rating = 0 . 0f ; <nl> - for ( class_id = 0 , out_class = 0 ; class_id < NumClasses ; class_id + + ) { <nl> - Results [ out_class ] . Class = SortIndex [ NumClasses - class_id ] ; <nl> - Results [ out_class ] . Rating = <nl> - 1 . 0 - SortKey [ NumClasses - class_id ] / <nl> - ( static_cast < float > ( CLASS_PRUNER_CLASS_MASK ) * NumFeatures ) ; <nl> - out_class + + ; <nl> + / / Prints a summary of the pruner result . <nl> + void SummarizeResult ( const Classify & classify , <nl> + const INT_TEMPLATES_STRUCT * int_templates , <nl> + const uinT16 * expected_num_features , <nl> + int norm_multiplier , <nl> + const uinT8 * normalization_factors ) const { <nl> + tprintf ( " CP : % d classes , % d features : \ n " , num_classes_ , num_features_ ) ; <nl> + for ( int i = 0 ; i < num_classes_ ; + + i ) { <nl> + int class_id = sort_index_ [ num_classes_ - i ] ; <nl> + STRING class_string = classify . ClassIDToDebugStr ( int_templates , <nl> + class_id , 0 ) ; <nl> + tprintf ( " % s : Initial = % d , E = % d , Xht - adj = % d , N = % d , Rat = % . 2f \ n " , <nl> + class_string . string ( ) , <nl> + class_count_ [ class_id ] , <nl> + expected_num_features [ class_id ] , <nl> + ( norm_multiplier * normalization_factors [ class_id ] ) > > 8 , <nl> + sort_key_ [ num_classes_ - i ] , <nl> + 100 . 0 - 100 . 0 * sort_key_ [ num_classes_ - i ] / <nl> + ( CLASS_PRUNER_CLASS_MASK * num_features_ ) ) ; <nl> + } <nl> + } <nl> + <nl> + / / Copies the pruned , sorted classes into the output results and returns <nl> + / / the number of classes . <nl> + int SetupResults ( CP_RESULT_STRUCT * results ) const { <nl> + for ( int c = 0 ; c < num_classes_ ; + + c ) { <nl> + results [ c ] . Class = sort_index_ [ num_classes_ - c ] ; <nl> + results [ c ] . Rating = 1 . 0 - sort_key_ [ num_classes_ - c ] / <nl> + ( static_cast < float > ( CLASS_PRUNER_CLASS_MASK ) * num_features_ ) ; <nl> + } <nl> + return num_classes_ ; <nl> } <nl> - NumClasses = out_class ; <nl> - return NumClasses ; <nl> + <nl> + private : <nl> + / / Array [ rounded_classes_ ] of initial counts for each class . <nl> + int * class_count_ ; <nl> + / / Array [ rounded_classes_ ] of modified counts for each class after normalizing <nl> + / / for expected number of features , disabled classes , fragments , and xheights . <nl> + int * norm_count_ ; <nl> + / / Array [ rounded_classes_ + 1 ] of pruned counts that gets sorted <nl> + int * sort_key_ ; <nl> + / / Array [ rounded_classes_ + 1 ] of classes corresponding to sort_key_ . <nl> + int * sort_index_ ; <nl> + / / Number of classes in this class pruner . <nl> + int max_classes_ ; <nl> + / / Rounded up number of classes used for array sizes . <nl> + int rounded_classes_ ; <nl> + / / Threshold count applied to prune classes . <nl> + int pruning_threshold_ ; <nl> + / / The number of features used to compute the scores . <nl> + int num_features_ ; <nl> + / / Final number of pruned classes . <nl> + int num_classes_ ; <nl> + } ; <nl> + <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> + Public Code <nl> + mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * / <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> + / / Runs the class pruner from int_templates on the given features , returning <nl> + / / the number of classes output in results . <nl> + / / int_templates Class pruner tables <nl> + / / num_features Number of features in blob <nl> + / / features Array of features <nl> + / / normalization_factors Array of fudge factors from blob <nl> + / / normalization process ( by CLASS_INDEX ) <nl> + / / expected_num_features Array of expected number of features <nl> + / / for each class ( by CLASS_INDEX ) <nl> + / / results Sorted Array of pruned classes . Must be an array <nl> + / / of size at least int_templates - > NumClasses . <nl> + int Classify : : PruneClasses ( const INT_TEMPLATES_STRUCT * int_templates , <nl> + int num_features , <nl> + const INT_FEATURE_STRUCT * features , <nl> + const uinT8 * normalization_factors , <nl> + const uinT16 * expected_num_features , <nl> + CP_RESULT_STRUCT * results ) { <nl> + / * <nl> + * * Operation : <nl> + * * Prunes the classes using a modified fast match table . <nl> + * * Returns a sorted list of classes along with the number <nl> + * * of pruned classes in that list . <nl> + * * Return : Number of pruned classes . <nl> + * * Exceptions : none <nl> + * * History : Tue Feb 19 10 : 24 : 24 MST 1991 , RWM , Created . <nl> + * / <nl> + ClassPruner pruner ( int_templates - > NumClasses ) ; <nl> + / / Compute initial match scores for all classes . <nl> + pruner . ComputeScores ( int_templates , num_features , features ) ; <nl> + / / Adjust match scores for number of expected features . <nl> + pruner . AdjustForExpectedNumFeatures ( expected_num_features , <nl> + classify_cp_cutoff_strength ) ; <nl> + / / Apply disabled classes in unicharset - only works without a shape_table . <nl> + if ( shape_table_ = = NULL ) <nl> + pruner . DisableDisabledClasses ( unicharset ) ; <nl> + / / If fragments are disabled , remove them , also only without a shape table . <nl> + if ( disable_character_fragments & & shape_table_ = = NULL ) <nl> + pruner . DisableFragments ( unicharset ) ; <nl> + <nl> + / / If we have good x - heights , apply the given normalization factors . <nl> + if ( normalization_factors ! = NULL ) { <nl> + pruner . NormalizeForXheight ( classify_class_pruner_multiplier , <nl> + normalization_factors ) ; <nl> + } else { <nl> + pruner . NoNormalization ( ) ; <nl> + } <nl> + / / Do the actual pruning and sort the short - list . <nl> + pruner . PruneAndSort ( classify_class_pruner_threshold , <nl> + shape_table_ = = NULL , unicharset ) ; <nl> + <nl> + if ( classify_debug_level > 2 ) { <nl> + pruner . DebugMatch ( * this , int_templates , features ) ; <nl> + } <nl> + if ( classify_debug_level > 1 ) { <nl> + pruner . SummarizeResult ( * this , int_templates , expected_num_features , <nl> + classify_class_pruner_multiplier , <nl> + normalization_factors ) ; <nl> + } <nl> + / / Convert to the expected output format . <nl> + return pruner . SetupResults ( results ) ; <nl> } <nl> <nl> } / / namespace tesseract <nl> int Classify : : ClassPruner ( INT_TEMPLATES IntTemplates , <nl> void IntegerMatcher : : Match ( INT_CLASS ClassTemplate , <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> - uinT16 BlobLength , <nl> inT16 NumFeatures , <nl> - INT_FEATURE_ARRAY Features , <nl> - uinT8 NormalizationFactor , <nl> + const INT_FEATURE_STRUCT * Features , <nl> INT_RESULT Result , <nl> int AdaptFeatureThreshold , <nl> int Debug , <nl> void IntegerMatcher : : Match ( INT_CLASS ClassTemplate , <nl> tables - > UpdateSumOfProtoEvidences ( ClassTemplate , ConfigMask , NumFeatures ) ; <nl> tables - > NormalizeSums ( ClassTemplate , NumFeatures , NumFeatures ) ; <nl> <nl> - BestMatch = FindBestMatch ( ClassTemplate , * tables , BlobLength , <nl> - NormalizationFactor , Result ) ; <nl> + BestMatch = FindBestMatch ( ClassTemplate , * tables , Result ) ; <nl> <nl> # ifndef GRAPHICS_DISABLED <nl> if ( PrintMatchSummaryOn ( Debug ) ) <nl> - DebugBestMatch ( BestMatch , Result , BlobLength , NormalizationFactor ) ; <nl> + DebugBestMatch ( BestMatch , Result ) ; <nl> <nl> if ( MatchDebuggingOn ( Debug ) ) <nl> cprintf ( " Match Complete mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - \ n " ) ; <nl> int IntegerMatcher : : UpdateTablesForFeature ( <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> int FeatureNum , <nl> - INT_FEATURE Feature , <nl> + const INT_FEATURE_STRUCT * Feature , <nl> ScratchEvidence * tables , <nl> int Debug ) { <nl> / * <nl> void IntegerMatcher : : DisplayFeatureDebugInfo ( <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> inT16 NumFeatures , <nl> - INT_FEATURE_ARRAY Features , <nl> + const INT_FEATURE_STRUCT * Features , <nl> int AdaptFeatureThreshold , <nl> int Debug , <nl> bool SeparateDebugWindows ) { <nl> void ScratchEvidence : : NormalizeSums ( <nl> int IntegerMatcher : : FindBestMatch ( <nl> INT_CLASS ClassTemplate , <nl> const ScratchEvidence & tables , <nl> - uinT16 BlobLength , <nl> - uinT8 NormalizationFactor , <nl> INT_RESULT Result ) { <nl> / * <nl> * * Parameters : <nl> int IntegerMatcher : : FindBestMatch ( <nl> / * Find best match * / <nl> for ( int ConfigNum = 0 ; ConfigNum < ClassTemplate - > NumConfigs ; ConfigNum + + ) { <nl> int rating = tables . sum_feature_evidence_ [ ConfigNum ] ; <nl> - if ( * classify_debug_level_ > 1 ) <nl> + if ( * classify_debug_level_ > 2 ) <nl> cprintf ( " Config % d , rating = % d \ n " , ConfigNum , rating ) ; <nl> if ( rating > BestMatch ) { <nl> if ( BestMatch > 0 ) { <nl> int IntegerMatcher : : FindBestMatch ( <nl> } <nl> <nl> / * Compute Certainty Rating * / <nl> - Result - > Rating = ( ( 65536 . 0 - BestMatch ) / 65536 . 0 * BlobLength + <nl> - local_matcher_multiplier_ * NormalizationFactor / 256 . 0 ) / <nl> - ( BlobLength + local_matcher_multiplier_ ) ; <nl> + Result - > Rating = ( 65536 . 0 - BestMatch ) / 65536 . 0 ; <nl> <nl> return BestMatch ; <nl> } <nl> <nl> + / / Applies the CN normalization factor to the given rating and returns <nl> + / / the modified rating . <nl> + float IntegerMatcher : : ApplyCNCorrection ( float rating , int blob_length , <nl> + int normalization_factor ) { <nl> + return ( rating * blob_length + <nl> + local_matcher_multiplier_ * normalization_factor / 256 . 0 ) / <nl> + ( blob_length + local_matcher_multiplier_ ) ; <nl> + } <nl> + <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> # ifndef GRAPHICS_DISABLED <nl> / / Print debug information about the best match for the current class . <nl> void IntegerMatcher : : DebugBestMatch ( <nl> - int BestMatch , INT_RESULT Result , uinT16 BlobLength , <nl> - uinT8 NormalizationFactor ) { <nl> - cprintf ( " Rating = % 5 . 1f % % Best Config = % 3d \ n " , <nl> - 100 . 0 * ( ( * Result ) . Rating ) , ( int ) ( ( * Result ) . Config ) ) ; <nl> - cprintf <nl> - ( " Matcher Error = % 5 . 1f % % Blob Length = % 3d Weight = % 4 . 1f % % \ n " , <nl> - 100 . 0 * ( 65536 . 0 - BestMatch ) / 65536 . 0 , ( int ) BlobLength , <nl> - 100 . 0 * BlobLength / ( BlobLength + local_matcher_multiplier_ ) ) ; <nl> - cprintf <nl> - ( " Char Norm Error = % 5 . 1f % % Norm Strength = % 3d Weight = % 4 . 1f % % \ n " , <nl> - 100 . 0 * NormalizationFactor / 256 . 0 , <nl> - local_matcher_multiplier_ , <nl> - 100 . 0 * local_matcher_multiplier_ / <nl> - ( BlobLength + local_matcher_multiplier_ ) ) ; <nl> + int BestMatch , INT_RESULT Result ) { <nl> + tprintf ( " Rating = % 5 . 1f % % Best Config = % 3d , Distance = % 5 . 1f \ n " , <nl> + 100 . 0 * Result - > Rating , Result - > Config , <nl> + 100 . 0 * ( 65536 . 0 - BestMatch ) / 65536 . 0 ) ; <nl> } <nl> # endif <nl> <nl> mmm a / classify / intmatcher . h <nl> ppp b / classify / intmatcher . h <nl> struct CP_RESULT_STRUCT { <nl> <nl> typedef CP_RESULT_STRUCT CLASS_PRUNER_RESULTS [ MAX_NUM_CLASSES ] ; <nl> <nl> - typedef uinT8 CLASS_NORMALIZATION_ARRAY [ MAX_NUM_CLASSES ] ; <nl> - <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Variables <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> class IntegerMatcher { <nl> void Match ( INT_CLASS ClassTemplate , <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> - uinT16 BlobLength , <nl> inT16 NumFeatures , <nl> - INT_FEATURE_ARRAY Features , <nl> - uinT8 NormalizationFactor , <nl> + const INT_FEATURE_STRUCT * Features , <nl> INT_RESULT Result , <nl> int AdaptFeatureThreshold , <nl> int Debug , <nl> bool SeparateDebugWindows ) ; <nl> <nl> + / / Applies the CN normalization factor to the given rating and returns <nl> + / / the modified rating . <nl> + float ApplyCNCorrection ( float rating , int blob_length , <nl> + int normalization_factor ) ; <nl> + <nl> int FindGoodProtos ( INT_CLASS ClassTemplate , <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> class IntegerMatcher { <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> int FeatureNum , <nl> - INT_FEATURE Feature , <nl> + const INT_FEATURE_STRUCT * Feature , <nl> ScratchEvidence * evidence , <nl> int Debug ) ; <nl> <nl> int FindBestMatch ( INT_CLASS ClassTemplate , <nl> const ScratchEvidence & tables , <nl> - uinT16 BlobLength , <nl> - uinT8 NormalizationFactor , <nl> INT_RESULT Result ) ; <nl> <nl> # ifndef GRAPHICS_DISABLED <nl> class IntegerMatcher { <nl> BIT_VECTOR ProtoMask , <nl> BIT_VECTOR ConfigMask , <nl> inT16 NumFeatures , <nl> - INT_FEATURE_ARRAY Features , <nl> + const INT_FEATURE_STRUCT * Features , <nl> int AdaptFeatureThreshold , <nl> int Debug , <nl> bool SeparateDebugWindows ) ; <nl> <nl> - void DebugBestMatch ( int BestMatch , <nl> - INT_RESULT Result , <nl> - uinT16 BlobLength , <nl> - uinT8 NormalizationFactor ) ; <nl> + void DebugBestMatch ( int BestMatch , INT_RESULT Result ) ; <nl> # endif <nl> <nl> <nl> mmm a / classify / intproto . cpp <nl> ppp b / classify / intproto . cpp <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> Include Files and Type Defines <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> - # include " helpers . h " <nl> - # include " intproto . h " <nl> - # include " picofeat . h " <nl> - # include " mfoutline . h " <nl> - # include " emalloc . h " <nl> - # include " const . h " <nl> - # include " ndminx . h " <nl> - # include " svmnode . h " <nl> - # include " globals . h " <nl> - # include " classify . h " <nl> - # include " genericvector . h " <nl> - <nl> - / / extern GetPicoFeatureLength ( ) ; <nl> <nl> # include < math . h > <nl> # include < stdio . h > <nl> <nl> # include < unistd . h > <nl> # endif <nl> <nl> + # include " classify . h " <nl> + # include " const . h " <nl> + # include " emalloc . h " <nl> + # include " fontinfo . h " <nl> + # include " genericvector . h " <nl> + # include " globals . h " <nl> + # include " helpers . h " <nl> + # include " intproto . h " <nl> + # include " mfoutline . h " <nl> + # include " ndminx . h " <nl> + # include " picofeat . h " <nl> + # include " shapetable . h " <nl> + # include " svmnode . h " <nl> + <nl> / / Include automatically generated configuration file if running autoconf . <nl> # ifdef HAVE_CONFIG_H <nl> # include " config_auto . h " <nl> # endif <nl> <nl> + using tesseract : : FontInfo ; <nl> + using tesseract : : FontSet ; <nl> + using tesseract : : FontSpacingInfo ; <nl> + <nl> / * match debug display constants * / <nl> # define PROTO_PRUNER_SCALE ( 4 . 0 ) <nl> <nl> FLOAT32 BucketStart ( int Bucket , FLOAT32 Offset , int NumBuckets ) ; <nl> FLOAT32 BucketEnd ( int Bucket , FLOAT32 Offset , int NumBuckets ) ; <nl> <nl> void DoFill ( FILL_SPEC * FillSpec , <nl> - CLASS_PRUNER Pruner , <nl> + CLASS_PRUNER_STRUCT * Pruner , <nl> register uinT32 ClassMask , <nl> register uinT32 ClassCount , <nl> register uinT32 WordIndex ) ; <nl> double_VAR ( classify_pp_side_pad , 2 . 5 , " Proto Pruner Side Pad " ) ; <nl> * / <nl> void AddIntClass ( INT_TEMPLATES Templates , CLASS_ID ClassId , INT_CLASS Class ) { <nl> int Pruner ; <nl> - uinT32 * Word ; <nl> <nl> assert ( LegalClassId ( ClassId ) ) ; <nl> if ( ClassId ! = Templates - > NumClasses ) { <nl> void AddIntClass ( INT_TEMPLATES Templates , CLASS_ID ClassId , INT_CLASS Class ) { <nl> <nl> if ( Templates - > NumClasses > MaxNumClassesIn ( Templates ) ) { <nl> Pruner = Templates - > NumClassPruners + + ; <nl> - Templates - > ClassPruner [ Pruner ] = <nl> - ( CLASS_PRUNER ) Emalloc ( sizeof ( CLASS_PRUNER_STRUCT ) ) ; <nl> - <nl> - for ( Word = reinterpret_cast < uinT32 * > ( Templates - > ClassPruner [ Pruner ] ) ; <nl> - Word < reinterpret_cast < uinT32 * > ( Templates - > ClassPruner [ Pruner ] ) + <nl> - WERDS_PER_CP ; <nl> - * Word + + = 0 ) ; <nl> + Templates - > ClassPruners [ Pruner ] = new CLASS_PRUNER_STRUCT ; <nl> + memset ( Templates - > ClassPruners [ Pruner ] , 0 , sizeof ( CLASS_PRUNER_STRUCT ) ) ; <nl> } <nl> } / * AddIntClass * / <nl> <nl> int AddIntProto ( INT_CLASS Class ) { <nl> <nl> ProtoSet = ( PROTO_SET ) Emalloc ( sizeof ( PROTO_SET_STRUCT ) ) ; <nl> Class - > ProtoSets [ ProtoSetId ] = ProtoSet ; <nl> - for ( Word = reinterpret_cast < uinT32 * > ( ProtoSet - > ProtoPruner ) ; <nl> - Word < reinterpret_cast < uinT32 * > ( ProtoSet - > ProtoPruner ) + WERDS_PER_PP ; <nl> - * Word + + = 0 ) ; <nl> + memset ( ProtoSet , 0 , sizeof ( * ProtoSet ) ) ; <nl> <nl> / * reallocate space for the proto lengths and install in class * / <nl> Class - > ProtoLengths = <nl> ( uinT8 * ) Erealloc ( Class - > ProtoLengths , <nl> MaxNumIntProtosIn ( Class ) * sizeof ( uinT8 ) ) ; <nl> + memset ( & Class - > ProtoLengths [ Index ] , 0 , <nl> + sizeof ( * Class - > ProtoLengths ) * ( MaxNumIntProtosIn ( Class ) - Index ) ) ; <nl> } <nl> <nl> / * initialize proto so its length is zero and it isn ' t in any configs * / <nl> void AddProtoToClassPruner ( PROTO Proto , CLASS_ID ClassId , <nl> * / <nl> # define MAX_LEVEL 2 <nl> { <nl> - CLASS_PRUNER Pruner ; <nl> + CLASS_PRUNER_STRUCT * Pruner ; <nl> uinT32 ClassMask ; <nl> uinT32 ClassCount ; <nl> uinT32 WordIndex ; <nl> INT_TEMPLATES Classify : : CreateIntTemplates ( CLASSES FloatProtos , <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> # ifndef GRAPHICS_DISABLED <nl> - void DisplayIntFeature ( INT_FEATURE Feature , FLOAT32 Evidence ) { <nl> + void DisplayIntFeature ( const INT_FEATURE_STRUCT * Feature , FLOAT32 Evidence ) { <nl> / * <nl> * * Parameters : <nl> * * Feature pico - feature to be displayed <nl> INT_CLASS NewIntClass ( int MaxNumProtos , int MaxNumConfigs ) { <nl> INT_CLASS Class ; <nl> PROTO_SET ProtoSet ; <nl> int i ; <nl> - register uinT32 * Word ; <nl> <nl> assert ( MaxNumConfigs < = MAX_NUM_CONFIGS ) ; <nl> <nl> INT_CLASS NewIntClass ( int MaxNumProtos , int MaxNumConfigs ) { <nl> for ( i = 0 ; i < Class - > NumProtoSets ; i + + ) { <nl> / * allocate space for a proto set , install in class , and initialize * / <nl> ProtoSet = ( PROTO_SET ) Emalloc ( sizeof ( PROTO_SET_STRUCT ) ) ; <nl> + memset ( ProtoSet , 0 , sizeof ( * ProtoSet ) ) ; <nl> Class - > ProtoSets [ i ] = ProtoSet ; <nl> - for ( Word = reinterpret_cast < uinT32 * > ( ProtoSet - > ProtoPruner ) ; <nl> - Word < reinterpret_cast < uinT32 * > ( ProtoSet - > ProtoPruner ) + WERDS_PER_PP ; <nl> - * Word + + = 0 ) ; <nl> <nl> / * allocate space for the proto lengths and install in class * / <nl> } <nl> if ( MaxNumIntProtosIn ( Class ) > 0 ) { <nl> Class - > ProtoLengths = <nl> ( uinT8 * ) Emalloc ( MaxNumIntProtosIn ( Class ) * sizeof ( uinT8 ) ) ; <nl> + memset ( Class - > ProtoLengths , 0 , <nl> + MaxNumIntProtosIn ( Class ) * sizeof ( * Class - > ProtoLengths ) ) ; <nl> + } else { <nl> + Class - > ProtoLengths = NULL ; <nl> } <nl> + memset ( Class - > ConfigLengths , 0 , sizeof ( Class - > ConfigLengths ) ) ; <nl> <nl> return ( Class ) ; <nl> <nl> void free_int_templates ( INT_TEMPLATES templates ) { <nl> for ( i = 0 ; i < templates - > NumClasses ; i + + ) <nl> free_int_class ( templates - > Class [ i ] ) ; <nl> for ( i = 0 ; i < templates - > NumClassPruners ; i + + ) <nl> - Efree ( templates - > ClassPruner [ i ] ) ; <nl> + delete templates - > ClassPruners [ i ] ; <nl> Efree ( templates ) ; <nl> } <nl> <nl> <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - / / Code to read / write Classify : : font * table structures . <nl> - namespace { <nl> - bool read_info ( FILE * f , FontInfo * fi , bool swap ) { <nl> - inT32 size ; <nl> - if ( fread ( & size , sizeof ( size ) , 1 , f ) ! = 1 ) return false ; <nl> - if ( swap ) <nl> - Reverse32 ( & size ) ; <nl> - char * font_name = new char [ size + 1 ] ; <nl> - fi - > name = font_name ; <nl> - if ( fread ( font_name , sizeof ( * font_name ) , size , f ) ! = size ) return false ; <nl> - font_name [ size ] = ' \ 0 ' ; <nl> - if ( fread ( & fi - > properties , sizeof ( fi - > properties ) , 1 , f ) ! = 1 ) return false ; <nl> - if ( swap ) <nl> - Reverse32 ( & fi - > properties ) ; <nl> - return true ; <nl> - } <nl> - <nl> - bool write_info ( FILE * f , const FontInfo & fi ) { <nl> - inT32 size = strlen ( fi . name ) ; <nl> - if ( fwrite ( & size , sizeof ( size ) , 1 , f ) ! = 1 ) return false ; <nl> - if ( fwrite ( fi . name , sizeof ( * fi . name ) , size , f ) ! = size ) return false ; <nl> - if ( fwrite ( & fi . properties , sizeof ( fi . properties ) , 1 , f ) ! = 1 ) return false ; <nl> - return true ; <nl> - } <nl> - <nl> - bool read_spacing_info ( FILE * f , FontInfo * fi , bool swap ) { <nl> - inT32 vec_size , kern_size ; <nl> - if ( fread ( & vec_size , sizeof ( vec_size ) , 1 , f ) ! = 1 ) return false ; <nl> - if ( swap ) Reverse32 ( & vec_size ) ; <nl> - ASSERT_HOST ( vec_size > = 0 ) ; <nl> - if ( vec_size = = 0 ) return true ; <nl> - fi - > init_spacing ( vec_size ) ; <nl> - for ( int i = 0 ; i < vec_size ; + + i ) { <nl> - FontSpacingInfo * fs = new FontSpacingInfo ( ) ; <nl> - if ( fread ( & fs - > x_gap_before , sizeof ( fs - > x_gap_before ) , 1 , f ) ! = 1 | | <nl> - fread ( & fs - > x_gap_after , sizeof ( fs - > x_gap_after ) , 1 , f ) ! = 1 | | <nl> - fread ( & kern_size , sizeof ( kern_size ) , 1 , f ) ! = 1 ) { <nl> - return false ; <nl> - } <nl> - if ( swap ) { <nl> - ReverseN ( & ( fs - > x_gap_before ) , sizeof ( fs - > x_gap_before ) ) ; <nl> - ReverseN ( & ( fs - > x_gap_after ) , sizeof ( fs - > x_gap_after ) ) ; <nl> - Reverse32 ( & kern_size ) ; <nl> - } <nl> - if ( kern_size < 0 ) { / / indication of a NULL entry in fi - > spacing_vec <nl> - delete fs ; <nl> - continue ; <nl> - } <nl> - if ( kern_size > 0 & & ( ! fs - > kerned_unichar_ids . DeSerialize ( swap , f ) | | <nl> - ! fs - > kerned_x_gaps . DeSerialize ( swap , f ) ) ) { <nl> - return false ; <nl> - } <nl> - fi - > add_spacing ( i , fs ) ; <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - bool write_spacing_info ( FILE * f , const FontInfo & fi ) { <nl> - inT32 vec_size = ( fi . spacing_vec = = NULL ) ? 0 : fi . spacing_vec - > size ( ) ; <nl> - if ( fwrite ( & vec_size , sizeof ( vec_size ) , 1 , f ) ! = 1 ) return false ; <nl> - inT16 x_gap_invalid = - 1 ; <nl> - for ( int i = 0 ; i < vec_size ; + + i ) { <nl> - FontSpacingInfo * fs = fi . spacing_vec - > get ( i ) ; <nl> - inT32 kern_size = ( fs = = NULL ) ? - 1 : fs - > kerned_x_gaps . size ( ) ; <nl> - if ( fs = = NULL ) { <nl> - if ( fwrite ( & ( x_gap_invalid ) , sizeof ( x_gap_invalid ) , 1 , f ) ! = 1 | | <nl> - fwrite ( & ( x_gap_invalid ) , sizeof ( x_gap_invalid ) , 1 , f ) ! = 1 | | <nl> - fwrite ( & kern_size , sizeof ( kern_size ) , 1 , f ) ! = 1 ) { <nl> - return false ; <nl> - } <nl> - } else { <nl> - if ( fwrite ( & ( fs - > x_gap_before ) , sizeof ( fs - > x_gap_before ) , 1 , f ) ! = 1 | | <nl> - fwrite ( & ( fs - > x_gap_after ) , sizeof ( fs - > x_gap_after ) , 1 , f ) ! = 1 | | <nl> - fwrite ( & kern_size , sizeof ( kern_size ) , 1 , f ) ! = 1 ) { <nl> - return false ; <nl> - } <nl> - } <nl> - if ( kern_size > 0 & & ( ! fs - > kerned_unichar_ids . Serialize ( f ) | | <nl> - ! fs - > kerned_x_gaps . Serialize ( f ) ) ) { <nl> - return false ; <nl> - } <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - bool read_set ( FILE * f , FontSet * fs , bool swap ) { <nl> - if ( fread ( & fs - > size , sizeof ( fs - > size ) , 1 , f ) ! = 1 ) return false ; <nl> - if ( swap ) <nl> - Reverse32 ( & fs - > size ) ; <nl> - fs - > configs = new int [ fs - > size ] ; <nl> - for ( int i = 0 ; i < fs - > size ; + + i ) { <nl> - if ( fread ( & fs - > configs [ i ] , sizeof ( fs - > configs [ i ] ) , 1 , f ) ! = 1 ) return false ; <nl> - if ( swap ) <nl> - Reverse32 ( & fs - > configs [ i ] ) ; <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - bool write_set ( FILE * f , const FontSet & fs ) { <nl> - if ( fwrite ( & fs . size , sizeof ( fs . size ) , 1 , f ) ! = 1 ) return false ; <nl> - for ( int i = 0 ; i < fs . size ; + + i ) { <nl> - if ( fwrite ( & fs . configs [ i ] , sizeof ( fs . configs [ i ] ) , 1 , f ) ! = 1 ) return false ; <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - } / / namespace . <nl> - <nl> namespace tesseract { <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> / * <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> int unicharset_size ; <nl> int version_id = 0 ; <nl> INT_TEMPLATES Templates ; <nl> - CLASS_PRUNER Pruner ; <nl> + CLASS_PRUNER_STRUCT * Pruner ; <nl> INT_CLASS Class ; <nl> uinT8 * Lengths ; <nl> PROTO_SET ProtoSet ; <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> CLASS_ID class_id , max_class_id ; <nl> inT16 * IndexFor = new inT16 [ MAX_NUM_CLASSES ] ; <nl> CLASS_ID * ClassIdFor = new CLASS_ID [ MAX_NUM_CLASSES ] ; <nl> - CLASS_PRUNER * TempClassPruner = new CLASS_PRUNER [ MAX_NUM_CLASS_PRUNERS ] ; <nl> + CLASS_PRUNER_STRUCT * * TempClassPruner = <nl> + new CLASS_PRUNER_STRUCT * [ MAX_NUM_CLASS_PRUNERS ] ; <nl> uinT32 SetBitsForMask = / / word with NUM_BITS_PER_CLASS <nl> ( 1 < < NUM_BITS_PER_CLASS ) - 1 ; / / set starting at bit 0 <nl> uinT32 Mask , NewMask , ClassBits ; <nl> - uinT32 * Word ; <nl> int MaxNumConfigs = MAX_NUM_CONFIGS ; <nl> int WerdsPerConfigVec = WERDS_PER_CONFIG_VEC ; <nl> <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> <nl> / * then read in the class pruners * / <nl> for ( i = 0 ; i < Templates - > NumClassPruners ; i + + ) { <nl> - Pruner = ( CLASS_PRUNER ) Emalloc ( sizeof ( CLASS_PRUNER_STRUCT ) ) ; <nl> + Pruner = new CLASS_PRUNER_STRUCT ; <nl> if ( ( nread = <nl> - fread ( ( char * ) Pruner , 1 , sizeof ( CLASS_PRUNER_STRUCT ) , <nl> + fread ( Pruner , 1 , sizeof ( CLASS_PRUNER_STRUCT ) , <nl> File ) ) ! = sizeof ( CLASS_PRUNER_STRUCT ) ) <nl> cprintf ( " Bad read of inttemp ! \ n " ) ; <nl> if ( swap ) { <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> for ( y = 0 ; y < NUM_CP_BUCKETS ; y + + ) { <nl> for ( z = 0 ; z < NUM_CP_BUCKETS ; z + + ) { <nl> for ( w = 0 ; w < WERDS_PER_CP_VECTOR ; w + + ) { <nl> - Reverse32 ( & Pruner [ x ] [ y ] [ z ] [ w ] ) ; <nl> + Reverse32 ( & Pruner - > p [ x ] [ y ] [ z ] [ w ] ) ; <nl> } <nl> } <nl> } <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> if ( version_id < 2 ) { <nl> TempClassPruner [ i ] = Pruner ; <nl> } else { <nl> - Templates - > ClassPruner [ i ] = Pruner ; <nl> + Templates - > ClassPruners [ i ] = Pruner ; <nl> } <nl> } <nl> <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> if ( ClassIdFor [ i ] > max_class_id ) <nl> max_class_id = ClassIdFor [ i ] ; <nl> for ( i = 0 ; i < = CPrunerIdFor ( max_class_id ) ; i + + ) { <nl> - Templates - > ClassPruner [ i ] = <nl> - ( CLASS_PRUNER ) Emalloc ( sizeof ( CLASS_PRUNER_STRUCT ) ) ; <nl> - for ( Word = ( uinT32 * ) ( Templates - > ClassPruner [ i ] ) ; <nl> - Word < ( uinT32 * ) ( Templates - > ClassPruner [ i ] ) + WERDS_PER_CP ; <nl> - * Word + + = 0 ) ; <nl> + Templates - > ClassPruners [ i ] = new CLASS_PRUNER_STRUCT ; <nl> + memset ( Templates - > ClassPruners [ i ] , 0 , sizeof ( CLASS_PRUNER_STRUCT ) ) ; <nl> } <nl> / / Convert class pruners from the old format ( indexed by class index ) <nl> / / to the new format ( indexed by class id ) . <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> for ( y = 0 ; y < NUM_CP_BUCKETS ; y + + ) <nl> for ( z = 0 ; z < NUM_CP_BUCKETS ; z + + ) <nl> for ( w = 0 ; w < WERDS_PER_CP_VECTOR ; w + + ) { <nl> - if ( TempClassPruner [ i ] [ x ] [ y ] [ z ] [ w ] = = 0 ) <nl> + if ( TempClassPruner [ i ] - > p [ x ] [ y ] [ z ] [ w ] = = 0 ) <nl> continue ; <nl> for ( b = 0 ; b < BITS_PER_WERD ; b + = NUM_BITS_PER_CLASS ) { <nl> bit_number = i * BITS_PER_CP_VECTOR + w * BITS_PER_WERD + b ; <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> class_id = ClassIdFor [ bit_number / NUM_BITS_PER_CLASS ] ; <nl> / / Single out NUM_BITS_PER_CLASS bits relating to class_id . <nl> Mask = SetBitsForMask < < b ; <nl> - ClassBits = TempClassPruner [ i ] [ x ] [ y ] [ z ] [ w ] & Mask ; <nl> + ClassBits = TempClassPruner [ i ] - > p [ x ] [ y ] [ z ] [ w ] & Mask ; <nl> / / Move these bits to the new position in which they should <nl> / / appear ( indexed corresponding to the class_id ) . <nl> new_i = CPrunerIdFor ( class_id ) ; <nl> INT_TEMPLATES Classify : : ReadIntTemplates ( FILE * File ) { <nl> / / Copy bits relating to class_id to the correct position <nl> / / in Templates - > ClassPruner . <nl> NewMask = SetBitsForMask < < new_b ; <nl> - Templates - > ClassPruner [ new_i ] [ x ] [ y ] [ z ] [ new_w ] & = ~ NewMask ; <nl> - Templates - > ClassPruner [ new_i ] [ x ] [ y ] [ z ] [ new_w ] | = ClassBits ; <nl> + Templates - > ClassPruners [ new_i ] - > p [ x ] [ y ] [ z ] [ new_w ] & = ~ NewMask ; <nl> + Templates - > ClassPruners [ new_i ] - > p [ x ] [ y ] [ z ] [ new_w ] | = ClassBits ; <nl> } <nl> } <nl> } <nl> for ( i = 0 ; i < Templates - > NumClassPruners ; i + + ) { <nl> - Efree ( TempClassPruner [ i ] ) ; <nl> + delete TempClassPruner [ i ] ; <nl> } <nl> } <nl> <nl> void Classify : : ShowMatchDisplay ( ) { <nl> * * History : Thu Mar 21 15 : 47 : 33 1991 , DSJ , Created . <nl> * / <nl> InitIntMatchWindowIfReqd ( ) ; <nl> - c_clear_window ( IntMatchWindow ) ; <nl> if ( ProtoDisplayWindow ) { <nl> ProtoDisplayWindow - > Clear ( ) ; <nl> } <nl> void Classify : : ShowMatchDisplay ( ) { <nl> ClearFeatureSpaceWindow ( <nl> static_cast < NORM_METHOD > ( static_cast < int > ( classify_norm_method ) ) , <nl> IntMatchWindow ) ; <nl> - <nl> IntMatchWindow - > ZoomToRectangle ( INT_MIN_X , INT_MIN_Y , <nl> INT_MAX_X , INT_MAX_Y ) ; <nl> if ( ProtoDisplayWindow ) { <nl> void Classify : : WriteIntTemplates ( FILE * File , INT_TEMPLATES Templates , <nl> <nl> / * then write out the class pruners * / <nl> for ( i = 0 ; i < Templates - > NumClassPruners ; i + + ) <nl> - fwrite ( Templates - > ClassPruner [ i ] , <nl> + fwrite ( Templates - > ClassPruners [ i ] , <nl> sizeof ( CLASS_PRUNER_STRUCT ) , 1 , File ) ; <nl> <nl> / * then write out each class * / <nl> FLOAT32 BucketEnd ( int Bucket , FLOAT32 Offset , int NumBuckets ) { <nl> <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> void DoFill ( FILL_SPEC * FillSpec , <nl> - CLASS_PRUNER Pruner , <nl> + CLASS_PRUNER_STRUCT * Pruner , <nl> register uinT32 ClassMask , <nl> register uinT32 ClassCount , <nl> register uinT32 WordIndex ) { <nl> void DoFill ( FILL_SPEC * FillSpec , <nl> for ( Y = FillSpec - > YStart ; Y < = FillSpec - > YEnd ; Y + + ) <nl> for ( Angle = FillSpec - > AngleStart ; <nl> TRUE ; CircularIncrement ( Angle , NUM_CP_BUCKETS ) ) { <nl> - OldWord = Pruner [ X ] [ Y ] [ Angle ] [ WordIndex ] ; <nl> + OldWord = Pruner - > p [ X ] [ Y ] [ Angle ] [ WordIndex ] ; <nl> if ( ClassCount > ( OldWord & ClassMask ) ) { <nl> OldWord & = ~ ClassMask ; <nl> OldWord | = ClassCount ; <nl> - Pruner [ X ] [ Y ] [ Angle ] [ WordIndex ] = OldWord ; <nl> + Pruner - > p [ X ] [ Y ] [ Angle ] [ WordIndex ] = OldWord ; <nl> } <nl> if ( Angle = = FillSpec - > AngleEnd ) <nl> break ; <nl> void FillPPLinearBits ( uinT32 ParamTable [ NUM_PP_BUCKETS ] [ WERDS_PER_PP_VECTOR ] , <nl> # ifndef GRAPHICS_DISABLED <nl> namespace tesseract { <nl> CLASS_ID Classify : : GetClassToDebug ( const char * Prompt , bool * adaptive_on , <nl> - bool * pretrained_on ) { <nl> + bool * pretrained_on , int * shape_id ) { <nl> / * <nl> * * Parameters : <nl> * * Prompt prompt to print while waiting for input from window <nl> CLASS_ID Classify : : GetClassToDebug ( const char * Prompt , bool * adaptive_on , <nl> tprintf ( " % s \ n " , Prompt ) ; <nl> SVEvent * ev ; <nl> SVEventType ev_type ; <nl> + int unichar_id = INVALID_UNICHAR_ID ; <nl> / / Wait until a click or popup event . <nl> do { <nl> ev = IntMatchWindow - > AwaitEvent ( SVET_ANY ) ; <nl> ev_type = ev - > type ; <nl> if ( ev_type = = SVET_POPUP ) { <nl> - if ( unicharset . contains_unichar ( ev - > parameter ) ) { <nl> - if ( ev - > command_id = = IDA_ADAPTIVE ) { <nl> - * adaptive_on = true ; <nl> - * pretrained_on = false ; <nl> - } else if ( ev - > command_id = = IDA_STATIC ) { <nl> + if ( ev - > command_id = = IDA_SHAPE_INDEX ) { <nl> + if ( shape_table_ ! = NULL ) { <nl> + * shape_id = atoi ( ev - > parameter ) ; <nl> * adaptive_on = false ; <nl> * pretrained_on = true ; <nl> + if ( * shape_id > = 0 & & * shape_id < shape_table_ - > NumShapes ( ) ) { <nl> + int font_id ; <nl> + shape_table_ - > GetFirstUnicharAndFont ( * shape_id , & unichar_id , <nl> + & font_id ) ; <nl> + tprintf ( " Shape % d , first unichar = % d , font = % d \ n " , <nl> + * shape_id , unichar_id , font_id ) ; <nl> + return unichar_id ; <nl> + } <nl> + tprintf ( " Shape index ' % s ' not found in shape table \ n " , ev - > parameter ) ; <nl> } else { <nl> - * adaptive_on = true ; <nl> - * pretrained_on = true ; <nl> + tprintf ( " No shape table loaded ! \ n " ) ; <nl> + } <nl> + } else { <nl> + if ( unicharset . contains_unichar ( ev - > parameter ) ) { <nl> + unichar_id = unicharset . unichar_to_id ( ev - > parameter ) ; <nl> + if ( ev - > command_id = = IDA_ADAPTIVE ) { <nl> + * adaptive_on = true ; <nl> + * pretrained_on = false ; <nl> + * shape_id = - 1 ; <nl> + } else if ( ev - > command_id = = IDA_STATIC ) { <nl> + * adaptive_on = false ; <nl> + * pretrained_on = true ; <nl> + } else { <nl> + * adaptive_on = true ; <nl> + * pretrained_on = true ; <nl> + } <nl> + if ( ev - > command_id = = IDA_ADAPTIVE | | shape_table_ = = NULL ) { <nl> + * shape_id = - 1 ; <nl> + return unichar_id ; <nl> + } <nl> + for ( int s = 0 ; s < shape_table_ - > NumShapes ( ) ; + + s ) { <nl> + if ( shape_table_ - > GetShape ( s ) . ContainsUnichar ( unichar_id ) ) { <nl> + tprintf ( " % s \ n " , shape_table_ - > DebugStr ( s ) . string ( ) ) ; <nl> + } <nl> + } <nl> + } else { <nl> + tprintf ( " Char class ' % s ' not found in unicharset " , <nl> + ev - > parameter ) ; <nl> } <nl> - return unicharset . unichar_to_id ( ev - > parameter ) ; <nl> } <nl> - tprintf ( " Char class ' % s ' not found in unicharset " , <nl> - ev - > parameter ) ; <nl> } <nl> delete ev ; <nl> } while ( ev_type ! = SVET_CLICK ) ; <nl> void RenderIntFeature ( ScrollView * window , const INT_FEATURE_STRUCT * Feature , <nl> / / using BinaryAnglePlusPi in intfx . cpp . <nl> Dx = ( Length / 2 . 0 ) * cos ( ( Feature - > Theta / 256 . 0 ) * 2 . 0 * PI - PI ) ; <nl> Dy = ( Length / 2 . 0 ) * sin ( ( Feature - > Theta / 256 . 0 ) * 2 . 0 * PI - PI ) ; <nl> - float x_offset = Dy / 4 . 0 ; <nl> - float y_offset = - Dx / 4 . 0 ; <nl> <nl> - window - > SetCursor ( X - Dx , Y - Dy ) ; <nl> - window - > DrawTo ( X + Dx , Y + Dy ) ; <nl> - / / Draw another copy of the feature offset perpendicualar to its direction . <nl> - X + = x_offset ; <nl> - Y + = y_offset ; <nl> - window - > SetCursor ( X - Dx , Y - Dy ) ; <nl> + window - > SetCursor ( X , Y ) ; <nl> window - > DrawTo ( X + Dx , Y + Dy ) ; <nl> } / * RenderIntFeature * / <nl> <nl> void InitIntMatchWindowIfReqd ( ) { <nl> " x " , " Class to debug " ) ; <nl> popup_menu - > AddChild ( " Debug Both " , IDA_BOTH , <nl> " x " , " Class to debug " ) ; <nl> + popup_menu - > AddChild ( " Debug Shape Index " , IDA_SHAPE_INDEX , <nl> + " 0 " , " Index to debug " ) ; <nl> popup_menu - > BuildMenu ( IntMatchWindow , false ) ; <nl> } <nl> } <nl> mmm a / classify / intproto . h <nl> ppp b / classify / intproto . h <nl> <nl> # include " matchdefs . h " <nl> # include " mfoutline . h " <nl> # include " protos . h " <nl> - # include " callcpp . h " <nl> # include " scrollview . h " <nl> # include " unicharset . h " <nl> <nl> <nl> * The position of the the bits recorded for each class in the <nl> * 4th dimension is determined by using CPrunerWordIndexFor ( c ) , <nl> * where c is the corresponding class id . * / <nl> - typedef uinT32 CLASS_PRUNER_STRUCT <nl> - [ NUM_CP_BUCKETS ] [ NUM_CP_BUCKETS ] [ NUM_CP_BUCKETS ] [ WERDS_PER_CP_VECTOR ] ; <nl> - <nl> - typedef <nl> - uinT32 ( * CLASS_PRUNER ) [ NUM_CP_BUCKETS ] [ NUM_CP_BUCKETS ] [ WERDS_PER_CP_VECTOR ] ; <nl> + struct CLASS_PRUNER_STRUCT { <nl> + uinT32 p [ NUM_CP_BUCKETS ] [ NUM_CP_BUCKETS ] [ NUM_CP_BUCKETS ] [ WERDS_PER_CP_VECTOR ] ; <nl> + } ; <nl> <nl> typedef struct <nl> { <nl> PROTO_SET_STRUCT , * PROTO_SET ; <nl> <nl> typedef uinT32 CONFIG_PRUNER [ NUM_PP_PARAMS ] [ NUM_PP_BUCKETS ] [ 4 ] ; <nl> <nl> - / / Struct for information about spacing between characters in a particular font . <nl> - struct FontSpacingInfo { <nl> - inT16 x_gap_before ; <nl> - inT16 x_gap_after ; <nl> - GenericVector < UNICHAR_ID > kerned_unichar_ids ; <nl> - GenericVector < inT16 > kerned_x_gaps ; <nl> - } ; <nl> - <nl> - / * <nl> - * font_properties contains properties about boldness , italicness , fixed pitch , <nl> - * serif , fraktur <nl> - * / <nl> - struct FontInfo { <nl> - FontInfo ( ) : name ( NULL ) , spacing_vec ( NULL ) { } <nl> - ~ FontInfo ( ) { } <nl> - / / Reserves unicharset_size spots in spacing_vec . <nl> - void init_spacing ( int unicharset_size ) { <nl> - spacing_vec = new GenericVector < FontSpacingInfo * > ( ) ; <nl> - spacing_vec - > init_to_size ( unicharset_size , NULL ) ; <nl> - } <nl> - / / Adds the given pointer to FontSpacingInfo to spacing_vec member <nl> - / / ( FontInfo class takes ownership of the pointer ) . <nl> - / / Note : init_spacing should be called before calling this function . <nl> - void add_spacing ( UNICHAR_ID uch_id , FontSpacingInfo * spacing_info ) { <nl> - ASSERT_HOST ( spacing_vec ! = NULL & & spacing_vec - > size ( ) > uch_id ) ; <nl> - ( * spacing_vec ) [ uch_id ] = spacing_info ; <nl> - } <nl> - <nl> - / / Returns the pointer to FontSpacingInfo for the given UNICHAR_ID . <nl> - const FontSpacingInfo * get_spacing ( UNICHAR_ID uch_id ) const { <nl> - return ( spacing_vec = = NULL | | spacing_vec - > size ( ) < = uch_id ) ? <nl> - NULL : ( * spacing_vec ) [ uch_id ] ; <nl> - } <nl> - <nl> - / / Fills spacing with the value of the x gap expected between the two given <nl> - / / UNICHAR_IDs . Returns true on success . <nl> - bool get_spacing ( UNICHAR_ID prev_uch_id , <nl> - UNICHAR_ID uch_id , <nl> - int * spacing ) const { <nl> - const FontSpacingInfo * prev_fsi = this - > get_spacing ( prev_uch_id ) ; <nl> - const FontSpacingInfo * fsi = this - > get_spacing ( uch_id ) ; <nl> - if ( prev_fsi = = NULL | | fsi = = NULL ) return false ; <nl> - int i = 0 ; <nl> - for ( ; i < prev_fsi - > kerned_unichar_ids . size ( ) ; + + i ) { <nl> - if ( prev_fsi - > kerned_unichar_ids [ i ] = = uch_id ) break ; <nl> - } <nl> - if ( i < prev_fsi - > kerned_unichar_ids . size ( ) ) { <nl> - * spacing = prev_fsi - > kerned_x_gaps [ i ] ; <nl> - } else { <nl> - * spacing = prev_fsi - > x_gap_after + fsi - > x_gap_before ; <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - bool is_italic ( ) const { return properties & 1 ; } <nl> - bool is_bold ( ) const { return ( properties & 2 ) ! = 0 ; } <nl> - bool is_fixed_pitch ( ) const { return ( properties & 4 ) ! = 0 ; } <nl> - bool is_serif ( ) const { return ( properties & 8 ) ! = 0 ; } <nl> - bool is_fraktur ( ) const { return ( properties & 16 ) ! = 0 ; } <nl> - <nl> - char * name ; <nl> - uinT32 properties ; <nl> - / / Horizontal spacing between characters ( indexed by UNICHAR_ID ) . <nl> - GenericVector < FontSpacingInfo * > * spacing_vec ; <nl> - } ; <nl> - <nl> - / / Every class ( character ) owns a FontSet that represents all the fonts that can <nl> - / / render this character . <nl> - / / Since almost all the characters from the same script share the same set of <nl> - / / fonts , the sets are shared over multiple classes ( see <nl> - / / Classify : : fontset_table_ ) . Thus , a class only store an id to a set . <nl> - / / Because some fonts cannot render just one character of a set , there are a <nl> - / / lot of FontSet that differ only by one font . Rather than storing directly <nl> - / / the FontInfo in the FontSet structure , it ' s better to share FontInfos among <nl> - / / FontSets ( Classify : : fontinfo_table_ ) . <nl> - struct FontSet { <nl> - int size ; <nl> - int * configs ; / / FontInfo ids <nl> - } ; <nl> - <nl> <nl> typedef struct <nl> { <nl> typedef struct <nl> int NumClasses ; <nl> int NumClassPruners ; <nl> INT_CLASS Class [ MAX_NUM_CLASSES ] ; <nl> - CLASS_PRUNER ClassPruner [ MAX_NUM_CLASS_PRUNERS ] ; <nl> + CLASS_PRUNER_STRUCT * ClassPruners [ MAX_NUM_CLASS_PRUNERS ] ; <nl> } <nl> <nl> <nl> typedef INT_FEATURE_STRUCT INT_FEATURE_ARRAY [ MAX_NUM_INT_FEATURES ] ; <nl> enum IntmatcherDebugAction { <nl> IDA_ADAPTIVE , <nl> IDA_STATIC , <nl> + IDA_SHAPE_INDEX , <nl> IDA_BOTH <nl> } ; <nl> <nl> enum IntmatcherDebugAction { <nl> # define ClassForClassId ( T , c ) ( ( T ) - > Class [ c ] ) <nl> # define ClassPrunersFor ( T ) ( ( T ) - > ClassPruner ) <nl> # define CPrunerIdFor ( c ) ( ( c ) / CLASSES_PER_CP ) <nl> - # define CPrunerFor ( T , c ) ( ( T ) - > ClassPruner [ CPrunerIdFor ( c ) ] ) <nl> + # define CPrunerFor ( T , c ) ( ( T ) - > ClassPruners [ CPrunerIdFor ( c ) ] ) <nl> # define CPrunerWordIndexFor ( c ) ( ( ( c ) % CLASSES_PER_CP ) / CLASSES_PER_CP_WERD ) <nl> # define CPrunerBitIndexFor ( c ) ( ( ( c ) % CLASSES_PER_CP ) % CLASSES_PER_CP_WERD ) <nl> # define CPrunerMaskFor ( L , c ) ( ( ( L ) + 1 ) < < CPrunerBitIndexFor ( c ) * NUM_BITS_PER_CLASS ) <nl> void UpdateMatchDisplay ( ) ; <nl> <nl> void ConvertConfig ( BIT_VECTOR Config , int ConfigId , INT_CLASS Class ) ; <nl> <nl> - void DisplayIntFeature ( INT_FEATURE Feature , FLOAT32 Evidence ) ; <nl> + void DisplayIntFeature ( const INT_FEATURE_STRUCT * Feature , FLOAT32 Evidence ) ; <nl> <nl> void DisplayIntProto ( INT_CLASS Class , PROTO_ID ProtoId , FLOAT32 Evidence ) ; <nl> <nl> new file mode 100644 <nl> index 000000000 . . bb272fde2 <nl> mmm / dev / null <nl> ppp b / classify / mastertrainer . cpp <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : mastertrainer . cpp <nl> + / / Description : Trainer to build the MasterClassifier . <nl> + / / Author : Ray Smith <nl> + / / Created : Wed Nov 03 18 : 10 : 01 PDT 2010 <nl> + / / <nl> + / / ( C ) Copyright 2010 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " mastertrainer . h " <nl> + # include < math . h > <nl> + # include < time . h > <nl> + # include " allheaders . h " <nl> + # include " boxread . h " <nl> + # include " classify . h " <nl> + # include " errorcounter . h " <nl> + # include " featdefs . h " <nl> + # include " sampleiterator . h " <nl> + # include " shapeclassifier . h " <nl> + # include " shapetable . h " <nl> + # include " svmnode . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + / / Constants controlling clustering . With a low kMinClusteredShapes and a high <nl> + / / kMaxUnicharsPerCluster , then kFontMergeDistance is the only limiting factor . <nl> + / / Min number of shapes in the output . <nl> + const int kMinClusteredShapes = 1 ; <nl> + / / Max number of unichars in any individual cluster . <nl> + const int kMaxUnicharsPerCluster = 2000 ; <nl> + / / Mean font distance below which to merge fonts and unichars . <nl> + const float kFontMergeDistance = 0 . 025 ; <nl> + <nl> + MasterTrainer : : MasterTrainer ( NormalizationMode norm_mode , <nl> + bool shape_analysis , <nl> + bool replicate_samples , <nl> + int debug_level ) <nl> + : norm_mode_ ( norm_mode ) , samples_ ( fontinfo_table_ ) , <nl> + junk_samples_ ( fontinfo_table_ ) , verify_samples_ ( fontinfo_table_ ) , <nl> + charsetsize_ ( 0 ) , <nl> + enable_shape_anaylsis_ ( shape_analysis ) , <nl> + enable_replication_ ( replicate_samples ) , <nl> + fragments_ ( NULL ) , prev_unichar_id_ ( - 1 ) , debug_level_ ( debug_level ) { <nl> + fontinfo_table_ . set_compare_callback ( <nl> + NewPermanentTessCallback ( CompareFontInfo ) ) ; <nl> + fontinfo_table_ . set_clear_callback ( <nl> + NewPermanentTessCallback ( FontInfoDeleteCallback ) ) ; <nl> + } <nl> + <nl> + MasterTrainer : : ~ MasterTrainer ( ) { <nl> + delete [ ] fragments_ ; <nl> + for ( int p = 0 ; p < page_images_ . size ( ) ; + + p ) <nl> + pixDestroy ( & page_images_ [ p ] ) ; <nl> + } <nl> + <nl> + / / WARNING ! Serialize / DeSerialize are only partial , providing <nl> + / / enough data to get the samples back and display them . <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool MasterTrainer : : Serialize ( FILE * fp ) const { <nl> + if ( fwrite ( & norm_mode_ , sizeof ( norm_mode_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( ! unicharset_ . save_to_file ( fp ) ) return false ; <nl> + if ( ! feature_space_ . Serialize ( fp ) ) return false ; <nl> + if ( ! samples_ . Serialize ( fp ) ) return false ; <nl> + if ( ! junk_samples_ . Serialize ( fp ) ) return false ; <nl> + if ( ! verify_samples_ . Serialize ( fp ) ) return false ; <nl> + if ( ! master_shapes_ . Serialize ( fp ) ) return false ; <nl> + if ( ! flat_shapes_ . Serialize ( fp ) ) return false ; <nl> + if ( ! fontinfo_table_ . write ( fp , NewPermanentTessCallback ( write_info ) ) ) <nl> + return false ; <nl> + if ( ! fontinfo_table_ . write ( fp , NewPermanentTessCallback ( write_spacing_info ) ) ) <nl> + return false ; <nl> + if ( ! xheights_ . Serialize ( fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool MasterTrainer : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( fread ( & norm_mode_ , sizeof ( norm_mode_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( swap ) { <nl> + ReverseN ( & norm_mode_ , sizeof ( norm_mode_ ) ) ; <nl> + } <nl> + if ( ! unicharset_ . load_from_file ( fp ) ) return false ; <nl> + charsetsize_ = unicharset_ . size ( ) ; <nl> + if ( ! feature_space_ . DeSerialize ( swap , fp ) ) return false ; <nl> + feature_map_ . Init ( feature_space_ ) ; <nl> + if ( ! samples_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( ! junk_samples_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( ! verify_samples_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( ! master_shapes_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( ! flat_shapes_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( ! fontinfo_table_ . read ( fp , NewPermanentTessCallback ( read_info ) , swap ) ) <nl> + return false ; <nl> + if ( ! fontinfo_table_ . read ( fp , NewPermanentTessCallback ( read_spacing_info ) , <nl> + swap ) ) <nl> + return false ; <nl> + if ( ! xheights_ . DeSerialize ( swap , fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Load an initial unicharset , or set one up if the file cannot be read . <nl> + void MasterTrainer : : LoadUnicharset ( const char * filename ) { <nl> + if ( ! unicharset_ . load_from_file ( filename ) ) { <nl> + tprintf ( " Failed to load unicharset from file % s \ n " <nl> + " Building unicharset for training from scratch . . . \ n " , <nl> + filename ) ; <nl> + unicharset_ . clear ( ) ; <nl> + / / Space character needed to represent NIL_LIST classification . <nl> + unicharset_ . unichar_insert ( " " ) ; <nl> + } <nl> + charsetsize_ = unicharset_ . size ( ) ; <nl> + delete [ ] fragments_ ; <nl> + fragments_ = new int [ charsetsize_ ] ; <nl> + memset ( fragments_ , 0 , sizeof ( * fragments_ ) * charsetsize_ ) ; <nl> + samples_ . LoadUnicharset ( filename ) ; <nl> + junk_samples_ . LoadUnicharset ( filename ) ; <nl> + verify_samples_ . LoadUnicharset ( filename ) ; <nl> + } <nl> + <nl> + / / Reads the samples and their features from the given . tr format file , <nl> + / / adding them to the trainer with the font_id from the content of the file . <nl> + / / See mftraining . cpp for a description of the file format . <nl> + / / If verification , then these are verification samples , not training . <nl> + void MasterTrainer : : ReadTrainingSamples ( FILE * fp , <nl> + const FEATURE_DEFS_STRUCT & feature_defs , <nl> + bool verification ) { <nl> + char buffer [ 2048 ] ; <nl> + int int_feature_type = ShortNameToFeatureType ( feature_defs , kIntFeatureType ) ; <nl> + int micro_feature_type = ShortNameToFeatureType ( feature_defs , <nl> + kMicroFeatureType ) ; <nl> + int cn_feature_type = ShortNameToFeatureType ( feature_defs , kCNFeatureType ) ; <nl> + int geo_feature_type = ShortNameToFeatureType ( feature_defs , kGeoFeatureType ) ; <nl> + <nl> + while ( fgets ( buffer , sizeof ( buffer ) , fp ) ! = NULL ) { <nl> + if ( buffer [ 0 ] = = ' \ n ' ) <nl> + continue ; <nl> + <nl> + char * space = strchr ( buffer , ' ' ) ; <nl> + if ( space = = NULL ) { <nl> + tprintf ( " Bad format in tr file , reading fontname , unichar \ n " ) ; <nl> + continue ; <nl> + } <nl> + * space + + = ' \ 0 ' ; <nl> + int font_id = GetFontInfoId ( buffer ) ; <nl> + int page_number ; <nl> + STRING unichar ; <nl> + TBOX bounding_box ; <nl> + if ( ! ParseBoxFileStr ( space , & page_number , & unichar , & bounding_box ) ) { <nl> + tprintf ( " Bad format in tr file , reading box coords \ n " ) ; <nl> + continue ; <nl> + } <nl> + CHAR_DESC char_desc = ReadCharDescription ( feature_defs , fp ) ; <nl> + TrainingSample * sample = new TrainingSample ; <nl> + sample - > set_font_id ( font_id ) ; <nl> + sample - > set_page_num ( page_number + page_images_ . size ( ) ) ; <nl> + sample - > set_bounding_box ( bounding_box ) ; <nl> + sample - > ExtractCharDesc ( int_feature_type , micro_feature_type , <nl> + cn_feature_type , geo_feature_type , char_desc ) ; <nl> + AddSample ( verification , unichar . string ( ) , sample ) ; <nl> + FreeCharDescription ( char_desc ) ; <nl> + } <nl> + charsetsize_ = unicharset_ . size ( ) ; <nl> + } <nl> + <nl> + / / Adds the given single sample to the trainer , setting the classid <nl> + / / appropriately from the given unichar_str . <nl> + void MasterTrainer : : AddSample ( bool verification , const char * unichar , <nl> + TrainingSample * sample ) { <nl> + if ( verification ) { <nl> + verify_samples_ . AddSample ( unichar , sample ) ; <nl> + prev_unichar_id_ = - 1 ; <nl> + } else if ( unicharset_ . contains_unichar ( unichar ) ) { <nl> + if ( prev_unichar_id_ > = 0 ) <nl> + fragments_ [ prev_unichar_id_ ] = - 1 ; <nl> + prev_unichar_id_ = samples_ . AddSample ( unichar , sample ) ; <nl> + if ( flat_shapes_ . FindShape ( prev_unichar_id_ , sample - > font_id ( ) ) < 0 ) <nl> + flat_shapes_ . AddShape ( prev_unichar_id_ , sample - > font_id ( ) ) ; <nl> + } else { <nl> + int junk_id = junk_samples_ . AddSample ( unichar , sample ) ; <nl> + if ( prev_unichar_id_ > = 0 ) { <nl> + CHAR_FRAGMENT * frag = CHAR_FRAGMENT : : parse_from_string ( unichar ) ; <nl> + if ( frag ! = NULL & & frag - > is_natural ( ) ) { <nl> + if ( fragments_ [ prev_unichar_id_ ] = = 0 ) <nl> + fragments_ [ prev_unichar_id_ ] = junk_id ; <nl> + else if ( fragments_ [ prev_unichar_id_ ] ! = junk_id ) <nl> + fragments_ [ prev_unichar_id_ ] = - 1 ; <nl> + } <nl> + delete frag ; <nl> + } <nl> + prev_unichar_id_ = - 1 ; <nl> + } <nl> + } <nl> + <nl> + / / Loads all pages from the given tif filename and append to page_images_ . <nl> + / / Must be called after ReadTrainingSamples , as the current number of images <nl> + / / is used as an offset for page numbers in the samples . <nl> + void MasterTrainer : : LoadPageImages ( const char * filename ) { <nl> + int page ; <nl> + Pix * pix ; <nl> + for ( page = 0 ; ( pix = pixReadTiff ( filename , page ) ) ! = NULL ; + + page ) { <nl> + page_images_ . push_back ( pix ) ; <nl> + } <nl> + tprintf ( " Loaded % d page images from % s \ n " , page , filename ) ; <nl> + } <nl> + <nl> + / / Cleans up the samples after initial load from the tr files , and prior to <nl> + / / saving the MasterTrainer : <nl> + / / Remaps fragmented chars if running shape anaylsis . <nl> + / / Sets up the samples appropriately for class / fontwise access . <nl> + / / Deletes outlier samples . <nl> + void MasterTrainer : : PostLoadCleanup ( ) { <nl> + if ( debug_level_ > 0 ) <nl> + tprintf ( " PostLoadCleanup . . . \ n " ) ; <nl> + if ( enable_shape_anaylsis_ ) <nl> + ReplaceFragmentedSamples ( ) ; <nl> + SampleIterator sample_it ; <nl> + sample_it . Init ( NULL , NULL , true , & verify_samples_ ) ; <nl> + sample_it . NormalizeSamples ( ) ; <nl> + verify_samples_ . OrganizeByFontAndClass ( ) ; <nl> + <nl> + samples_ . IndexFeatures ( feature_space_ ) ; <nl> + / / TODO ( rays ) DeleteOutliers is currently turned off to prove NOP - ness <nl> + / / against current training . <nl> + / / samples_ . DeleteOutliers ( feature_space_ , debug_level_ > 0 ) ; <nl> + samples_ . OrganizeByFontAndClass ( ) ; <nl> + if ( debug_level_ > 0 ) <nl> + tprintf ( " ComputeCanonicalSamples . . . \ n " ) ; <nl> + samples_ . ComputeCanonicalSamples ( feature_map_ , debug_level_ > 0 ) ; <nl> + } <nl> + <nl> + / / Gets the samples ready for training . Use after both <nl> + / / ReadTrainingSamples + PostLoadCleanup or DeSerialize . <nl> + / / Re - indexes the features and computes canonical and cloud features . <nl> + void MasterTrainer : : PreTrainingSetup ( ) { <nl> + if ( debug_level_ > 0 ) <nl> + tprintf ( " PreTrainingSetup . . . \ n " ) ; <nl> + samples_ . IndexFeatures ( feature_space_ ) ; <nl> + samples_ . ComputeCanonicalFeatures ( ) ; <nl> + if ( debug_level_ > 0 ) <nl> + tprintf ( " ComputeCloudFeatures . . . \ n " ) ; <nl> + samples_ . ComputeCloudFeatures ( feature_space_ . Size ( ) ) ; <nl> + } <nl> + <nl> + / / Sets up the master_shapes_ table , which tells which fonts should stay <nl> + / / together until they get to a leaf node classifier . <nl> + void MasterTrainer : : SetupMasterShapes ( ) { <nl> + tprintf ( " Building master shape table \ n " ) ; <nl> + int num_fonts = samples_ . NumFonts ( ) ; <nl> + <nl> + ShapeTable char_shapes_begin_fragment ( samples_ . unicharset ( ) ) ; <nl> + ShapeTable char_shapes_end_fragment ( samples_ . unicharset ( ) ) ; <nl> + ShapeTable char_shapes ( samples_ . unicharset ( ) ) ; <nl> + for ( int c = 0 ; c < samples_ . charsetsize ( ) ; + + c ) { <nl> + ShapeTable shapes ( samples_ . unicharset ( ) ) ; <nl> + for ( int f = 0 ; f < num_fonts ; + + f ) { <nl> + if ( samples_ . NumClassSamples ( f , c , true ) > 0 ) <nl> + shapes . AddShape ( c , f ) ; <nl> + } <nl> + ClusterShapes ( kMinClusteredShapes , 1 , kFontMergeDistance , & shapes ) ; <nl> + <nl> + const CHAR_FRAGMENT * fragment = samples_ . unicharset ( ) . get_fragment ( c ) ; <nl> + <nl> + if ( fragment = = NULL ) <nl> + char_shapes . AppendMasterShapes ( shapes ) ; <nl> + else if ( fragment - > is_beginning ( ) ) <nl> + char_shapes_begin_fragment . AppendMasterShapes ( shapes ) ; <nl> + else if ( fragment - > is_ending ( ) ) <nl> + char_shapes_end_fragment . AppendMasterShapes ( shapes ) ; <nl> + else <nl> + char_shapes . AppendMasterShapes ( shapes ) ; <nl> + } <nl> + ClusterShapes ( kMinClusteredShapes , kMaxUnicharsPerCluster , <nl> + kFontMergeDistance , & char_shapes_begin_fragment ) ; <nl> + char_shapes . AppendMasterShapes ( char_shapes_begin_fragment ) ; <nl> + ClusterShapes ( kMinClusteredShapes , kMaxUnicharsPerCluster , <nl> + kFontMergeDistance , & char_shapes_end_fragment ) ; <nl> + char_shapes . AppendMasterShapes ( char_shapes_end_fragment ) ; <nl> + ClusterShapes ( kMinClusteredShapes , kMaxUnicharsPerCluster , <nl> + kFontMergeDistance , & char_shapes ) ; <nl> + master_shapes_ . AppendMasterShapes ( char_shapes ) ; <nl> + tprintf ( " Master shape_table : % s \ n " , master_shapes_ . SummaryStr ( ) . string ( ) ) ; <nl> + } <nl> + <nl> + / / Adds the junk_samples_ to the main samples_ set . Junk samples are initially <nl> + / / fragments and n - grams ( all incorrectly segmented characters ) . <nl> + / / Various training functions may result in incorrectly segmented characters <nl> + / / being added to the unicharset of the main samples , perhaps because they <nl> + / / form a " radical " decomposition of some ( Indic ) grapheme , or because they <nl> + / / just look the same as a real character ( like rn / m ) <nl> + / / This function moves all the junk samples , to the main samples_ set , but <nl> + / / desirable junk , being any sample for which the unichar already exists in <nl> + / / the samples_ unicharset gets the unichar - ids re - indexed to match , but <nl> + / / anything else gets re - marked as unichar_id 0 ( space character ) to identify <nl> + / / it as junk to the error counter . <nl> + void MasterTrainer : : IncludeJunk ( ) { <nl> + / / Get ids of fragments in junk_samples_ that replace the dead chars . <nl> + const UNICHARSET & junk_set = junk_samples_ . unicharset ( ) ; <nl> + const UNICHARSET & sample_set = samples_ . unicharset ( ) ; <nl> + int num_junks = junk_samples_ . num_samples ( ) ; <nl> + tprintf ( " Moving % d junk samples to master sample set . \ n " , num_junks ) ; <nl> + for ( int s = 0 ; s < num_junks ; + + s ) { <nl> + TrainingSample * sample = junk_samples_ . mutable_sample ( s ) ; <nl> + int junk_id = sample - > class_id ( ) ; <nl> + const char * junk_utf8 = junk_set . id_to_unichar ( junk_id ) ; <nl> + int sample_id = sample_set . unichar_to_id ( junk_utf8 ) ; <nl> + if ( sample_id = = INVALID_UNICHAR_ID ) <nl> + sample_id = 0 ; <nl> + sample - > set_class_id ( sample_id ) ; <nl> + junk_samples_ . extract_sample ( s ) ; <nl> + samples_ . AddSample ( sample_id , sample ) ; <nl> + } <nl> + junk_samples_ . DeleteDeadSamples ( ) ; <nl> + samples_ . OrganizeByFontAndClass ( ) ; <nl> + } <nl> + <nl> + / / Replicates the samples and perturbs them if the enable_replication_ flag <nl> + / / is set . MUST be used after the last call to OrganizeByFontAndClass on <nl> + / / the training samples , ie after IncludeJunk if it is going to be used , as <nl> + / / OrganizeByFontAndClass will eat the replicated samples into the regular <nl> + / / samples . <nl> + void MasterTrainer : : ReplicateAndRandomizeSamplesIfRequired ( ) { <nl> + if ( enable_replication_ ) { <nl> + if ( debug_level_ > 0 ) <nl> + tprintf ( " ReplicateAndRandomize . . . \ n " ) ; <nl> + verify_samples_ . ReplicateAndRandomizeSamples ( ) ; <nl> + samples_ . ReplicateAndRandomizeSamples ( ) ; <nl> + samples_ . IndexFeatures ( feature_space_ ) ; <nl> + } <nl> + } <nl> + <nl> + / / Loads the basic font properties file into fontinfo_table_ . <nl> + / / Returns false on failure . <nl> + bool MasterTrainer : : LoadFontInfo ( const char * filename ) { <nl> + FILE * fp = fopen ( filename , " rb " ) ; <nl> + if ( fp = = NULL ) { <nl> + fprintf ( stderr , " Failed to load font_properties from % s \ n " , filename ) ; <nl> + return false ; <nl> + } <nl> + int italic , bold , fixed , serif , fraktur ; <nl> + while ( ! feof ( fp ) ) { <nl> + FontInfo fontinfo ; <nl> + char * font_name = new char [ 1024 ] ; <nl> + fontinfo . name = font_name ; <nl> + fontinfo . properties = 0 ; <nl> + fontinfo . universal_id = 0 ; <nl> + if ( fscanf ( fp , " % 1024s % i % i % i % i % i \ n " , font_name , <nl> + & italic , & bold , & fixed , & serif , & fraktur ) ! = 6 ) <nl> + continue ; <nl> + fontinfo . properties = <nl> + ( italic < < 0 ) + <nl> + ( bold < < 1 ) + <nl> + ( fixed < < 2 ) + <nl> + ( serif < < 3 ) + <nl> + ( fraktur < < 4 ) ; <nl> + if ( ! fontinfo_table_ . contains ( fontinfo ) ) { <nl> + fontinfo_table_ . push_back ( fontinfo ) ; <nl> + } <nl> + } <nl> + fclose ( fp ) ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Loads the xheight font properties file into xheights_ . <nl> + / / Returns false on failure . <nl> + bool MasterTrainer : : LoadXHeights ( const char * filename ) { <nl> + tprintf ( " fontinfo table is of size % d \ n " , fontinfo_table_ . size ( ) ) ; <nl> + xheights_ . init_to_size ( fontinfo_table_ . size ( ) , - 1 ) ; <nl> + if ( filename = = NULL ) return true ; <nl> + FILE * f = fopen ( filename , " rb " ) ; <nl> + if ( f = = NULL ) { <nl> + fprintf ( stderr , " Failed to load font xheights from % s \ n " , filename ) ; <nl> + return false ; <nl> + } <nl> + tprintf ( " Reading x - heights from % s . . . \ n " , filename ) ; <nl> + FontInfo fontinfo ; <nl> + fontinfo . properties = 0 ; / / Not used to lookup in the table . <nl> + fontinfo . universal_id = 0 ; <nl> + char buffer [ 1024 ] ; <nl> + int xht ; <nl> + int total_xheight = 0 ; <nl> + int xheight_count = 0 ; <nl> + while ( ! feof ( f ) ) { <nl> + if ( fscanf ( f , " % 1024s % d \ n " , buffer , & xht ) ! = 2 ) <nl> + continue ; <nl> + fontinfo . name = buffer ; <nl> + if ( ! fontinfo_table_ . contains ( fontinfo ) ) continue ; <nl> + int fontinfo_id = fontinfo_table_ . get_id ( fontinfo ) ; <nl> + xheights_ [ fontinfo_id ] = xht ; <nl> + total_xheight + = xht ; <nl> + + + xheight_count ; <nl> + } <nl> + if ( xheight_count = = 0 ) { <nl> + fprintf ( stderr , " No valid xheights in % s ! \ n " , filename ) ; <nl> + return false ; <nl> + } <nl> + int mean_xheight = DivRounded ( total_xheight , xheight_count ) ; <nl> + for ( int i = 0 ; i < fontinfo_table_ . size ( ) ; + + i ) { <nl> + if ( xheights_ [ i ] < 0 ) <nl> + xheights_ [ i ] = mean_xheight ; <nl> + } <nl> + return true ; <nl> + } / / LoadXHeights <nl> + <nl> + / / Reads spacing stats from filename and adds them to fontinfo_table . <nl> + bool MasterTrainer : : AddSpacingInfo ( const char * filename ) { <nl> + FILE * fontinfo_file = fopen ( filename , " rb " ) ; <nl> + if ( fontinfo_file = = NULL ) <nl> + return true ; / / We silently ignore missing files ! <nl> + / / Find the fontinfo_id . <nl> + int fontinfo_id = GetBestMatchingFontInfoId ( filename ) ; <nl> + if ( fontinfo_id < 0 ) { <nl> + tprintf ( " No font found matching fontinfo filename % s \ n " , filename ) ; <nl> + fclose ( fontinfo_file ) ; <nl> + return false ; <nl> + } <nl> + tprintf ( " Reading spacing from % s for font % d . . . \ n " , filename , fontinfo_id ) ; <nl> + / / TODO ( rays ) scale should probably be a double , but keep as an int for now <nl> + / / to duplicate current behavior . <nl> + int scale = kBlnXHeight / xheights_ [ fontinfo_id ] ; <nl> + int num_unichars ; <nl> + char uch [ UNICHAR_LEN ] ; <nl> + char kerned_uch [ UNICHAR_LEN ] ; <nl> + int x_gap , x_gap_before , x_gap_after , num_kerned ; <nl> + ASSERT_HOST ( fscanf ( fontinfo_file , " % d \ n " , & num_unichars ) = = 1 ) ; <nl> + FontInfo * fi = fontinfo_table_ . get_mutable ( fontinfo_id ) ; <nl> + fi - > init_spacing ( unicharset_ . size ( ) ) ; <nl> + FontSpacingInfo * spacing = NULL ; <nl> + for ( int l = 0 ; l < num_unichars ; + + l ) { <nl> + if ( fscanf ( fontinfo_file , " % s % d % d % d " , <nl> + uch , & x_gap_before , & x_gap_after , & num_kerned ) ! = 4 ) { <nl> + tprintf ( " Bad format of font spacing file % s \ n " , filename ) ; <nl> + fclose ( fontinfo_file ) ; <nl> + return false ; <nl> + } <nl> + bool valid = unicharset_ . contains_unichar ( uch ) ; <nl> + if ( valid ) { <nl> + spacing = new FontSpacingInfo ( ) ; <nl> + spacing - > x_gap_before = static_cast < inT16 > ( x_gap_before * scale ) ; <nl> + spacing - > x_gap_after = static_cast < inT16 > ( x_gap_after * scale ) ; <nl> + } <nl> + for ( int k = 0 ; k < num_kerned ; + + k ) { <nl> + if ( fscanf ( fontinfo_file , " % s % d " , kerned_uch , & x_gap ) ! = 2 ) { <nl> + tprintf ( " Bad format of font spacing file % s \ n " , filename ) ; <nl> + fclose ( fontinfo_file ) ; <nl> + return false ; <nl> + } <nl> + if ( ! valid | | ! unicharset_ . contains_unichar ( kerned_uch ) ) continue ; <nl> + spacing - > kerned_unichar_ids . push_back ( <nl> + unicharset_ . unichar_to_id ( kerned_uch ) ) ; <nl> + spacing - > kerned_x_gaps . push_back ( static_cast < inT16 > ( x_gap * scale ) ) ; <nl> + } <nl> + if ( valid ) fi - > add_spacing ( unicharset_ . unichar_to_id ( uch ) , spacing ) ; <nl> + } <nl> + fclose ( fontinfo_file ) ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Returns the font id corresponding to the given font name . <nl> + / / Returns - 1 if the font cannot be found . <nl> + int MasterTrainer : : GetFontInfoId ( const char * font_name ) { <nl> + FontInfo fontinfo ; <nl> + / / We are only borrowing the string , so it is OK to const cast it . <nl> + fontinfo . name = const_cast < char * > ( font_name ) ; <nl> + fontinfo . properties = 0 ; / / Not used to lookup in the table <nl> + fontinfo . universal_id = 0 ; <nl> + if ( ! fontinfo_table_ . contains ( fontinfo ) ) { <nl> + return - 1 ; <nl> + } else { <nl> + return fontinfo_table_ . get_id ( fontinfo ) ; <nl> + } <nl> + } <nl> + / / Returns the font_id of the closest matching font name to the given <nl> + / / filename . It is assumed that a substring of the filename will match <nl> + / / one of the fonts . If more than one is matched , the longest is returned . <nl> + int MasterTrainer : : GetBestMatchingFontInfoId ( const char * filename ) { <nl> + int fontinfo_id = - 1 ; <nl> + int best_len = 0 ; <nl> + for ( int f = 0 ; f < fontinfo_table_ . size ( ) ; + + f ) { <nl> + if ( strstr ( filename , fontinfo_table_ . get ( f ) . name ) ! = NULL ) { <nl> + int len = strlen ( fontinfo_table_ . get ( f ) . name ) ; <nl> + / / Use the longest matching length in case a substring of a font matched . <nl> + if ( len > best_len ) { <nl> + best_len = len ; <nl> + fontinfo_id = f ; <nl> + } <nl> + } <nl> + } <nl> + return fontinfo_id ; <nl> + } <nl> + <nl> + / / Sets up a flat shapetable with one shape per class / font combination . <nl> + void MasterTrainer : : SetupFlatShapeTable ( ShapeTable * shape_table ) { <nl> + / / To exactly mimic the results of the previous implementation , the shapes <nl> + / / must be clustered in order the fonts arrived , and reverse order of the <nl> + / / characters within each font . <nl> + / / Get a list of the fonts in the order they appeared . <nl> + GenericVector < int > active_fonts ; <nl> + int num_shapes = flat_shapes_ . NumShapes ( ) ; <nl> + for ( int s = 0 ; s < num_shapes ; + + s ) { <nl> + int font = flat_shapes_ . GetShape ( s ) [ 0 ] . font_ids [ 0 ] ; <nl> + int f = 0 ; <nl> + for ( f = 0 ; f < active_fonts . size ( ) ; + + f ) { <nl> + if ( active_fonts [ f ] = = font ) <nl> + break ; <nl> + } <nl> + if ( f = = active_fonts . size ( ) ) <nl> + active_fonts . push_back ( font ) ; <nl> + } <nl> + / / For each font in order , add all the shapes with that font in reverse order . <nl> + int num_fonts = active_fonts . size ( ) ; <nl> + for ( int f = 0 ; f < num_fonts ; + + f ) { <nl> + for ( int s = num_shapes - 1 ; s > = 0 ; - - s ) { <nl> + int font = flat_shapes_ . GetShape ( s ) [ 0 ] . font_ids [ 0 ] ; <nl> + if ( font = = active_fonts [ f ] ) { <nl> + shape_table - > AddShape ( flat_shapes_ . GetShape ( s ) ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Sets up a Clusterer for mftraining on a single shape_id . <nl> + / / Call FreeClusterer on the return value after use . <nl> + CLUSTERER * MasterTrainer : : SetupForClustering ( <nl> + const ShapeTable & shape_table , <nl> + const FEATURE_DEFS_STRUCT & feature_defs , <nl> + int shape_id , <nl> + int * num_samples ) { <nl> + <nl> + int desc_index = ShortNameToFeatureType ( feature_defs , kMicroFeatureType ) ; <nl> + int num_params = feature_defs . FeatureDesc [ desc_index ] - > NumParams ; <nl> + ASSERT_HOST ( num_params = = MFCount ) ; <nl> + CLUSTERER * clusterer = MakeClusterer ( <nl> + num_params , feature_defs . FeatureDesc [ desc_index ] - > ParamDesc ) ; <nl> + <nl> + / / We want to iterate over the samples of just the one shape . <nl> + IndexMapBiDi shape_map ; <nl> + shape_map . Init ( shape_table . NumShapes ( ) , false ) ; <nl> + shape_map . SetMap ( shape_id , true ) ; <nl> + shape_map . Setup ( ) ; <nl> + / / Reverse the order of the samples to match the previous behavior . <nl> + GenericVector < const TrainingSample * > sample_ptrs ; <nl> + SampleIterator it ; <nl> + it . Init ( & shape_map , & shape_table , false , & samples_ ) ; <nl> + for ( it . Begin ( ) ; ! it . AtEnd ( ) ; it . Next ( ) ) { <nl> + sample_ptrs . push_back ( & it . GetSample ( ) ) ; <nl> + } <nl> + int sample_id = 0 ; <nl> + for ( int i = sample_ptrs . size ( ) - 1 ; i > = 0 ; - - i ) { <nl> + const TrainingSample * sample = sample_ptrs [ i ] ; <nl> + int num_features = sample - > num_micro_features ( ) ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) <nl> + MakeSample ( clusterer , sample - > micro_features ( ) [ f ] , sample_id ) ; <nl> + + + sample_id ; <nl> + } <nl> + * num_samples = sample_id ; <nl> + return clusterer ; <nl> + } <nl> + <nl> + / / Writes the given float_classes ( produced by SetupForFloat2Int ) as inttemp <nl> + / / to the given inttemp_file , and the corresponding pffmtable . <nl> + / / The unicharset is the original encoding of graphemes , and shape_set should <nl> + / / match the size of the shape_table , and may possibly be totally fake . <nl> + void MasterTrainer : : WriteInttempAndPFFMTable ( const UNICHARSET & unicharset , <nl> + const UNICHARSET & shape_set , <nl> + const ShapeTable & shape_table , <nl> + CLASS_STRUCT * float_classes , <nl> + const char * inttemp_file , <nl> + const char * pffmtable_file ) { <nl> + tesseract : : Classify * classify = new tesseract : : Classify ( ) ; <nl> + / / Move the fontinfo table to classify . <nl> + classify - > get_fontinfo_table ( ) . move ( & fontinfo_table_ ) ; <nl> + INT_TEMPLATES int_templates = classify - > CreateIntTemplates ( float_classes , <nl> + shape_set ) ; <nl> + FILE * fp = fopen ( inttemp_file , " wb " ) ; <nl> + classify - > WriteIntTemplates ( fp , int_templates , shape_set ) ; <nl> + fclose ( fp ) ; <nl> + / / Now write pffmtable . This is complicated by the fact that the adaptive <nl> + / / classifier still wants one indexed by unichar - id , but the static <nl> + / / classifier needs one indexed by its shape class id . <nl> + / / We put the shapetable_cutoffs in a GenericVector , and compute the <nl> + / / unicharset cutoffs along the way . <nl> + GenericVector < uinT16 > shapetable_cutoffs ; <nl> + GenericVector < uinT16 > unichar_cutoffs ; <nl> + for ( int c = 0 ; c < unicharset . size ( ) ; + + c ) <nl> + unichar_cutoffs . push_back ( 0 ) ; <nl> + / * then write out each class * / <nl> + for ( int i = 0 ; i < int_templates - > NumClasses ; + + i ) { <nl> + INT_CLASS Class = ClassForClassId ( int_templates , i ) ; <nl> + / / Todo : Test with min instead of max <nl> + / / int MaxLength = LengthForConfigId ( Class , 0 ) ; <nl> + uinT16 max_length = 0 ; <nl> + for ( int config_id = 0 ; config_id < Class - > NumConfigs ; config_id + + ) { <nl> + / / Todo : Test with min instead of max <nl> + / / if ( LengthForConfigId ( Class , config_id ) < MaxLength ) <nl> + uinT16 length = Class - > ConfigLengths [ config_id ] ; <nl> + if ( length > max_length ) <nl> + max_length = Class - > ConfigLengths [ config_id ] ; <nl> + int shape_id = float_classes [ i ] . font_set . get ( config_id ) ; <nl> + const Shape & shape = shape_table . GetShape ( shape_id ) ; <nl> + for ( int c = 0 ; c < shape . size ( ) ; + + c ) { <nl> + int unichar_id = shape [ c ] . unichar_id ; <nl> + if ( length > unichar_cutoffs [ unichar_id ] ) <nl> + unichar_cutoffs [ unichar_id ] = length ; <nl> + } <nl> + } <nl> + shapetable_cutoffs . push_back ( max_length ) ; <nl> + } <nl> + fp = fopen ( pffmtable_file , " wb " ) ; <nl> + shapetable_cutoffs . Serialize ( fp ) ; <nl> + for ( int c = 0 ; c < unicharset . size ( ) ; + + c ) { <nl> + const char * unichar = unicharset . id_to_unichar ( c ) ; <nl> + if ( strcmp ( unichar , " " ) = = 0 ) { <nl> + unichar = " NULL " ; <nl> + } <nl> + fprintf ( fp , " % s % d \ n " , unichar , unichar_cutoffs [ c ] ) ; <nl> + } <nl> + fclose ( fp ) ; <nl> + free_int_templates ( int_templates ) ; <nl> + } <nl> + <nl> + / / Generate debug output relating to the canonical distance between the <nl> + / / two given UTF8 grapheme strings . <nl> + void MasterTrainer : : DebugCanonical ( const char * unichar_str1 , <nl> + const char * unichar_str2 ) { <nl> + int class_id1 = unicharset_ . unichar_to_id ( unichar_str1 ) ; <nl> + int class_id2 = unicharset_ . unichar_to_id ( unichar_str2 ) ; <nl> + if ( class_id2 = = INVALID_UNICHAR_ID ) <nl> + class_id2 = class_id1 ; <nl> + if ( class_id1 = = INVALID_UNICHAR_ID ) { <nl> + tprintf ( " No unicharset entry found for % s \ n " , unichar_str1 ) ; <nl> + return ; <nl> + } else { <nl> + tprintf ( " Font ambiguities for unichar % d = % s and % d = % s \ n " , <nl> + class_id1 , unichar_str1 , class_id2 , unichar_str2 ) ; <nl> + } <nl> + int num_fonts = samples_ . NumFonts ( ) ; <nl> + const IntFeatureMap & feature_map = feature_map_ ; <nl> + / / Iterate the fonts to get the similarity with other fonst of the same <nl> + / / class . <nl> + tprintf ( " " ) ; <nl> + for ( int f = 0 ; f < num_fonts ; + + f ) { <nl> + if ( samples_ . NumClassSamples ( f , class_id2 , false ) = = 0 ) <nl> + continue ; <nl> + tprintf ( " % 6d " , f ) ; <nl> + } <nl> + tprintf ( " \ n " ) ; <nl> + for ( int f1 = 0 ; f1 < num_fonts ; + + f1 ) { <nl> + / / Map the features of the canonical_sample . <nl> + if ( samples_ . NumClassSamples ( f1 , class_id1 , false ) = = 0 ) <nl> + continue ; <nl> + tprintf ( " % 4d " , f1 ) ; <nl> + for ( int f2 = 0 ; f2 < num_fonts ; + + f2 ) { <nl> + if ( samples_ . NumClassSamples ( f2 , class_id2 , false ) = = 0 ) <nl> + continue ; <nl> + float dist = samples_ . ClusterDistance ( f1 , class_id1 , f2 , class_id2 , <nl> + feature_map ) ; <nl> + tprintf ( " % 5 . 3f " , dist ) ; <nl> + } <nl> + tprintf ( " \ n " ) ; <nl> + } <nl> + / / Build a fake ShapeTable containing all the sample types . <nl> + ShapeTable shapes ( unicharset_ ) ; <nl> + for ( int f = 0 ; f < num_fonts ; + + f ) { <nl> + if ( samples_ . NumClassSamples ( f , class_id1 , true ) > 0 ) <nl> + shapes . AddShape ( class_id1 , f ) ; <nl> + if ( class_id1 ! = class_id2 & & <nl> + samples_ . NumClassSamples ( f , class_id2 , true ) > 0 ) <nl> + shapes . AddShape ( class_id2 , f ) ; <nl> + } <nl> + } <nl> + <nl> + / / Debugging for cloud / canonical features . <nl> + / / Displays a Features window containing : <nl> + / / If unichar_str2 is in the unicharset , and canonical_font is non - negative , <nl> + / / displays the canonical features of the char / font combination in red . <nl> + / / If unichar_str1 is in the unicharset , and cloud_font is non - negative , <nl> + / / displays the cloud feature of the char / font combination in green . <nl> + / / The canonical features are drawn first to show which ones have no <nl> + / / matches in the cloud features . <nl> + / / Until the features window is destroyed , each click in the features window <nl> + / / will display the samples that have that feature in a separate window . <nl> + void MasterTrainer : : DisplaySamples ( const char * unichar_str1 , int cloud_font , <nl> + const char * unichar_str2 , <nl> + int canonical_font ) { <nl> + const IntFeatureMap & feature_map = feature_map_ ; <nl> + const IntFeatureSpace & feature_space = feature_map . feature_space ( ) ; <nl> + ScrollView * f_window = CreateFeatureSpaceWindow ( " Features " , 100 , 500 ) ; <nl> + ClearFeatureSpaceWindow ( norm_mode_ = = NM_BASELINE ? baseline : character , <nl> + f_window ) ; <nl> + int class_id2 = samples_ . unicharset ( ) . unichar_to_id ( unichar_str2 ) ; <nl> + if ( class_id2 ! = INVALID_UNICHAR_ID & & canonical_font > = 0 ) { <nl> + const TrainingSample * sample = samples_ . GetCanonicalSample ( canonical_font , <nl> + class_id2 ) ; <nl> + for ( int f = 0 ; f < sample - > num_features ( ) ; + + f ) { <nl> + RenderIntFeature ( f_window , & sample - > features ( ) [ f ] , ScrollView : : RED ) ; <nl> + } <nl> + } <nl> + int class_id1 = samples_ . unicharset ( ) . unichar_to_id ( unichar_str1 ) ; <nl> + if ( class_id1 ! = INVALID_UNICHAR_ID & & cloud_font > = 0 ) { <nl> + const BitVector & cloud = samples_ . GetCloudFeatures ( cloud_font , class_id1 ) ; <nl> + for ( int f = 0 ; f < cloud . size ( ) ; + + f ) { <nl> + if ( cloud [ f ] ) { <nl> + INT_FEATURE_STRUCT feature = <nl> + feature_map . InverseIndexFeature ( f ) ; <nl> + RenderIntFeature ( f_window , & feature , ScrollView : : GREEN ) ; <nl> + } <nl> + } <nl> + } <nl> + f_window - > Update ( ) ; <nl> + ScrollView * s_window = CreateFeatureSpaceWindow ( " Samples " , 100 , 500 ) ; <nl> + SVEventType ev_type ; <nl> + do { <nl> + SVEvent * ev ; <nl> + / / Wait until a click or popup event . <nl> + ev = f_window - > AwaitEvent ( SVET_ANY ) ; <nl> + ev_type = ev - > type ; <nl> + if ( ev_type = = SVET_CLICK ) { <nl> + int feature_index = feature_space . XYToFeatureIndex ( ev - > x , ev - > y ) ; <nl> + if ( feature_index > = 0 ) { <nl> + / / Iterate samples and display those with the feature . <nl> + Shape shape ; <nl> + shape . AddToShape ( class_id1 , cloud_font ) ; <nl> + s_window - > Clear ( ) ; <nl> + samples_ . DisplaySamplesWithFeature ( feature_index , shape , <nl> + feature_space , ScrollView : : GREEN , <nl> + s_window ) ; <nl> + s_window - > Update ( ) ; <nl> + } <nl> + } <nl> + delete ev ; <nl> + } while ( ev_type ! = SVET_DESTROY ) ; <nl> + } <nl> + <nl> + / / Tests the given test_classifier on the internal samples . <nl> + / / See TestClassifier for details . <nl> + void MasterTrainer : : TestClassifierOnSamples ( int report_level , <nl> + bool replicate_samples , <nl> + ShapeClassifier * test_classifier , <nl> + STRING * report_string ) { <nl> + TestClassifier ( report_level , replicate_samples , & samples_ , <nl> + test_classifier , report_string ) ; <nl> + } <nl> + <nl> + / / Tests the given test_classifier on the given samples <nl> + / / report_levels : <nl> + / / 0 = no output . <nl> + / / 1 = bottom - line error rate . <nl> + / / 2 = bottom - line error rate + time . <nl> + / / 3 = font - level error rate + time . <nl> + / / 4 = list of all errors + short classifier debug output on 16 errors . <nl> + / / 5 = list of all errors + short classifier debug output on 25 errors . <nl> + / / If replicate_samples is true , then the test is run on an extended test <nl> + / / sample including replicated and systematically perturbed samples . <nl> + / / If report_string is non - NULL , a summary of the results for each font <nl> + / / is appended to the report_string . <nl> + double MasterTrainer : : TestClassifier ( int report_level , <nl> + bool replicate_samples , <nl> + TrainingSampleSet * samples , <nl> + ShapeClassifier * test_classifier , <nl> + STRING * report_string ) { <nl> + SampleIterator sample_it ; <nl> + sample_it . Init ( NULL , test_classifier - > GetShapeTable ( ) , replicate_samples , <nl> + samples ) ; <nl> + if ( report_level > 0 ) { <nl> + int num_samples = 0 ; <nl> + for ( sample_it . Begin ( ) ; ! sample_it . AtEnd ( ) ; sample_it . Next ( ) ) <nl> + + + num_samples ; <nl> + tprintf ( " Iterator has charset size of % d / % d , % d shapes , % d samples \ n " , <nl> + sample_it . SparseCharsetSize ( ) , sample_it . CompactCharsetSize ( ) , <nl> + test_classifier - > GetShapeTable ( ) - > NumShapes ( ) , num_samples ) ; <nl> + tprintf ( " Testing % sREPLICATED : \ n " , replicate_samples ? " " : " NON - " ) ; <nl> + } <nl> + double unichar_error = 0 . 0 ; <nl> + ErrorCounter : : ComputeErrorRate ( test_classifier , report_level , <nl> + CT_SHAPE_TOP_ERR , fontinfo_table_ , <nl> + page_images_ , & sample_it , & unichar_error , <nl> + NULL , report_string ) ; <nl> + return unichar_error ; <nl> + } <nl> + <nl> + / / Returns the average ( in some sense ) distance between the two given <nl> + / / shapes , which may contain multiple fonts and / or unichars . <nl> + float MasterTrainer : : ShapeDistance ( const ShapeTable & shapes , int s1 , int s2 ) { <nl> + const IntFeatureMap & feature_map = feature_map_ ; <nl> + const Shape & shape1 = shapes . GetShape ( s1 ) ; <nl> + const Shape & shape2 = shapes . GetShape ( s2 ) ; <nl> + int num_chars1 = shape1 . size ( ) ; <nl> + int num_chars2 = shape2 . size ( ) ; <nl> + float dist_sum = 0 . 0f ; <nl> + int dist_count = 0 ; <nl> + if ( num_chars1 > 1 | | num_chars2 > 1 ) { <nl> + / / In the multi - char case try to optimize the calculation by computing <nl> + / / distances between characters of matching font where possible . <nl> + for ( int c1 = 0 ; c1 < num_chars1 ; + + c1 ) { <nl> + for ( int c2 = 0 ; c2 < num_chars2 ; + + c2 ) { <nl> + dist_sum + = samples_ . UnicharDistance ( shape1 [ c1 ] , shape2 [ c2 ] , <nl> + true , feature_map ) ; <nl> + + + dist_count ; <nl> + } <nl> + } <nl> + } else { <nl> + / / In the single unichar case , there is little alternative , but to compute <nl> + / / the squared - order distance between pairs of fonts . <nl> + dist_sum = samples_ . UnicharDistance ( shape1 [ 0 ] , shape2 [ 0 ] , <nl> + false , feature_map ) ; <nl> + + + dist_count ; <nl> + } <nl> + return dist_sum / dist_count ; <nl> + } <nl> + <nl> + / / Replaces samples that are always fragmented with the corresponding <nl> + / / fragment samples . <nl> + void MasterTrainer : : ReplaceFragmentedSamples ( ) { <nl> + if ( fragments_ = = NULL ) return ; <nl> + / / Remove samples that are replaced by fragments . Each class that was <nl> + / / always naturally fragmented should be replaced by its fragments . <nl> + int num_samples = samples_ . num_samples ( ) ; <nl> + for ( int s = 0 ; s < num_samples ; + + s ) { <nl> + TrainingSample * sample = samples_ . mutable_sample ( s ) ; <nl> + if ( fragments_ [ sample - > class_id ( ) ] > 0 ) <nl> + samples_ . KillSample ( sample ) ; <nl> + } <nl> + samples_ . DeleteDeadSamples ( ) ; <nl> + <nl> + / / Get ids of fragments in junk_samples_ that replace the dead chars . <nl> + const UNICHARSET & frag_set = junk_samples_ . unicharset ( ) ; <nl> + # if 0 <nl> + / / TODO ( rays ) The original idea was to replace only graphemes that were <nl> + / / always naturally fragmented , but that left a lot of the Indic graphemes <nl> + / / out . Determine whether we can go back to that idea now that spacing <nl> + / / is fixed in the training images , or whether this code is obsolete . <nl> + bool * good_junk = new bool [ frag_set . size ( ) ] ; <nl> + memset ( good_junk , 0 , sizeof ( * good_junk ) * frag_set . size ( ) ) ; <nl> + for ( int dead_ch = 1 ; dead_ch < unicharset_ . size ( ) ; + + dead_ch ) { <nl> + int frag_ch = fragments_ [ dead_ch ] ; <nl> + if ( frag_ch < = 0 ) continue ; <nl> + const char * frag_utf8 = frag_set . id_to_unichar ( frag_ch ) ; <nl> + CHAR_FRAGMENT * frag = CHAR_FRAGMENT : : parse_from_string ( frag_utf8 ) ; <nl> + / / Mark the chars for all parts of the fragment as good in good_junk . <nl> + for ( int part = 0 ; part < frag - > get_total ( ) ; + + part ) { <nl> + frag - > set_pos ( part ) ; <nl> + int good_ch = frag_set . unichar_to_id ( frag - > to_string ( ) . string ( ) ) ; <nl> + if ( good_ch ! = INVALID_UNICHAR_ID ) <nl> + good_junk [ good_ch ] = true ; / / We want this one . <nl> + } <nl> + } <nl> + # endif <nl> + / / For now just use all the junk that was from natural fragments . <nl> + / / Get samples of fragments in junk_samples_ that replace the dead chars . <nl> + int num_junks = junk_samples_ . num_samples ( ) ; <nl> + for ( int s = 0 ; s < num_junks ; + + s ) { <nl> + TrainingSample * sample = junk_samples_ . mutable_sample ( s ) ; <nl> + int junk_id = sample - > class_id ( ) ; <nl> + const char * frag_utf8 = frag_set . id_to_unichar ( junk_id ) ; <nl> + CHAR_FRAGMENT * frag = CHAR_FRAGMENT : : parse_from_string ( frag_utf8 ) ; <nl> + if ( frag ! = NULL & & frag - > is_natural ( ) ) { <nl> + junk_samples_ . extract_sample ( s ) ; <nl> + samples_ . AddSample ( frag_set . id_to_unichar ( junk_id ) , sample ) ; <nl> + } <nl> + } <nl> + junk_samples_ . DeleteDeadSamples ( ) ; <nl> + junk_samples_ . OrganizeByFontAndClass ( ) ; <nl> + samples_ . OrganizeByFontAndClass ( ) ; <nl> + unicharset_ . clear ( ) ; <nl> + unicharset_ . AppendOtherUnicharset ( samples_ . unicharset ( ) ) ; <nl> + / / delete [ ] good_junk ; <nl> + / / Fragments_ no longer needed ? <nl> + delete [ ] fragments_ ; <nl> + fragments_ = NULL ; <nl> + } <nl> + <nl> + / / Runs a hierarchical agglomerative clustering to merge shapes in the given <nl> + / / shape_table , while satisfying the given constraints : <nl> + / / * End with at least min_shapes left in shape_table , <nl> + / / * No shape shall have more than max_shape_unichars in it , <nl> + / / * Don ' t merge shapes where the distance between them exceeds max_dist . <nl> + const float kInfiniteDist = 999 . 0f ; <nl> + void MasterTrainer : : ClusterShapes ( int min_shapes , int max_shape_unichars , <nl> + float max_dist , ShapeTable * shapes ) { <nl> + int num_shapes = shapes - > NumShapes ( ) ; <nl> + int max_merges = num_shapes - min_shapes ; <nl> + GenericVector < ShapeDist > * shape_dists = <nl> + new GenericVector < ShapeDist > [ num_shapes ] ; <nl> + float min_dist = kInfiniteDist ; <nl> + int min_s1 = 0 ; <nl> + int min_s2 = 0 ; <nl> + tprintf ( " Computing shape distances . . . " ) ; <nl> + for ( int s1 = 0 ; s1 < num_shapes ; + + s1 ) { <nl> + for ( int s2 = s1 + 1 ; s2 < num_shapes ; + + s2 ) { <nl> + ShapeDist dist ( s1 , s2 , ShapeDistance ( * shapes , s1 , s2 ) ) ; <nl> + shape_dists [ s1 ] . push_back ( dist ) ; <nl> + if ( dist . distance < min_dist ) { <nl> + min_dist = dist . distance ; <nl> + min_s1 = s1 ; <nl> + min_s2 = s2 ; <nl> + } <nl> + } <nl> + tprintf ( " % d " , s1 ) ; <nl> + } <nl> + tprintf ( " \ n " ) ; <nl> + int num_merged = 0 ; <nl> + while ( num_merged < max_merges & & min_dist < max_dist ) { <nl> + tprintf ( " Distance = % f : " , min_dist ) ; <nl> + int num_unichars = shapes - > MergedUnicharCount ( min_s1 , min_s2 ) ; <nl> + shape_dists [ min_s1 ] [ min_s2 - min_s1 - 1 ] . distance = kInfiniteDist ; <nl> + if ( num_unichars > max_shape_unichars ) { <nl> + tprintf ( " Merge of % d and % d with % d would exceed max of % d unichars \ n " , <nl> + min_s1 , min_s2 , num_unichars , max_shape_unichars ) ; <nl> + } else { <nl> + shapes - > MergeShapes ( min_s1 , min_s2 ) ; <nl> + shape_dists [ min_s2 ] . clear ( ) ; <nl> + + + num_merged ; <nl> + <nl> + for ( int s = 0 ; s < min_s1 ; + + s ) { <nl> + if ( ! shape_dists [ s ] . empty ( ) ) { <nl> + shape_dists [ s ] [ min_s1 - s - 1 ] . distance = <nl> + ShapeDistance ( * shapes , s , min_s1 ) ; <nl> + shape_dists [ s ] [ min_s2 - s - 1 ] . distance = kInfiniteDist ; <nl> + } <nl> + } <nl> + for ( int s2 = min_s1 + 1 ; s2 < num_shapes ; + + s2 ) { <nl> + if ( shape_dists [ min_s1 ] [ s2 - min_s1 - 1 ] . distance < kInfiniteDist ) <nl> + shape_dists [ min_s1 ] [ s2 - min_s1 - 1 ] . distance = <nl> + ShapeDistance ( * shapes , min_s1 , s2 ) ; <nl> + } <nl> + for ( int s = min_s1 + 1 ; s < min_s2 ; + + s ) { <nl> + if ( ! shape_dists [ s ] . empty ( ) ) { <nl> + shape_dists [ s ] [ min_s2 - s - 1 ] . distance = kInfiniteDist ; <nl> + } <nl> + } <nl> + } <nl> + min_dist = kInfiniteDist ; <nl> + for ( int s1 = 0 ; s1 < num_shapes ; + + s1 ) { <nl> + for ( int i = 0 ; i < shape_dists [ s1 ] . size ( ) ; + + i ) { <nl> + if ( shape_dists [ s1 ] [ i ] . distance < min_dist ) { <nl> + min_dist = shape_dists [ s1 ] [ i ] . distance ; <nl> + min_s1 = s1 ; <nl> + min_s2 = s1 + 1 + i ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + tprintf ( " Stopped with % d merged , min dist % f \ n " , num_merged , min_dist ) ; <nl> + delete [ ] shape_dists ; <nl> + if ( debug_level_ > 1 ) { <nl> + for ( int s1 = 0 ; s1 < num_shapes ; + + s1 ) { <nl> + if ( shapes - > MasterDestinationIndex ( s1 ) = = s1 ) { <nl> + tprintf ( " Master shape : % s \ n " , shapes - > DebugStr ( s1 ) . string ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + <nl> + } / / namespace tesseract . <nl> new file mode 100644 <nl> index 000000000 . . 90d396a9b <nl> mmm / dev / null <nl> ppp b / classify / mastertrainer . h <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : mastertrainer . h <nl> + / / Description : Trainer to build the MasterClassifier . <nl> + / / Author : Ray Smith <nl> + / / Created : Wed Nov 03 18 : 07 : 01 PDT 2010 <nl> + / / <nl> + / / ( C ) Copyright 2010 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_TRAINING_MASTERTRAINER_H__ <nl> + # define TESSERACT_TRAINING_MASTERTRAINER_H__ <nl> + <nl> + / * * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> + Include Files and Type Defines <nl> + mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> + # include " classify . h " <nl> + # include " cluster . h " <nl> + # include " intfx . h " <nl> + # include " elst . h " <nl> + # include " featdefs . h " <nl> + # include " fontinfo . h " <nl> + # include " indexmapbidi . h " <nl> + # include " intfeaturespace . h " <nl> + # include " intfeaturemap . h " <nl> + # include " intmatcher . h " <nl> + # include " params . h " <nl> + # include " shapetable . h " <nl> + # include " trainingsample . h " <nl> + # include " trainingsampleset . h " <nl> + # include " unicharset . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + class ShapeClassifier ; <nl> + <nl> + / / Simple struct to hold the distance between two shapes during clustering . <nl> + struct ShapeDist { <nl> + ShapeDist ( ) : shape1 ( 0 ) , shape2 ( 0 ) , distance ( 0 . 0f ) { } <nl> + ShapeDist ( int s1 , int s2 , float dist ) <nl> + : shape1 ( s1 ) , shape2 ( s2 ) , distance ( dist ) { } <nl> + <nl> + / / Sort operator to sort in ascending order of distance . <nl> + bool operator < ( const ShapeDist & other ) const { <nl> + return distance < other . distance ; <nl> + } <nl> + <nl> + int shape1 ; <nl> + int shape2 ; <nl> + float distance ; <nl> + } ; <nl> + <nl> + / / Class to encapsulate training processes that use the TrainingSampleSet . <nl> + / / Initially supports shape clustering and mftrainining . <nl> + / / Other important features of the MasterTrainer are conditioning the data <nl> + / / by outlier elimination , replication with perturbation , and serialization . <nl> + class MasterTrainer { <nl> + public : <nl> + MasterTrainer ( NormalizationMode norm_mode , bool shape_analysis , <nl> + bool replicate_samples , int debug_level ) ; <nl> + ~ MasterTrainer ( ) ; <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) const ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Loads an initial unicharset , or sets one up if the file cannot be read . <nl> + void LoadUnicharset ( const char * filename ) ; <nl> + <nl> + / / Sets the feature space definition . <nl> + void SetFeatureSpace ( const IntFeatureSpace & fs ) { <nl> + feature_space_ = fs ; <nl> + feature_map_ . Init ( fs ) ; <nl> + } <nl> + <nl> + / / Reads the samples and their features from the given file , <nl> + / / adding them to the trainer with the font_id from the content of the file . <nl> + / / If verification , then these are verification samples , not training . <nl> + void ReadTrainingSamples ( FILE * fp , <nl> + const FEATURE_DEFS_STRUCT & feature_defs , <nl> + bool verification ) ; <nl> + <nl> + / / Adds the given single sample to the trainer , setting the classid <nl> + / / appropriately from the given unichar_str . <nl> + void AddSample ( bool verification , const char * unichar_str , <nl> + TrainingSample * sample ) ; <nl> + <nl> + / / Loads all pages from the given tif filename and append to page_images_ . <nl> + / / Must be called after ReadTrainingSamples , as the current number of images <nl> + / / is used as an offset for page numbers in the samples . <nl> + void LoadPageImages ( const char * filename ) ; <nl> + <nl> + / / Cleans up the samples after initial load from the tr files , and prior to <nl> + / / saving the MasterTrainer : <nl> + / / Remaps fragmented chars if running shape anaylsis . <nl> + / / Sets up the samples appropriately for class / fontwise access . <nl> + / / Deletes outlier samples . <nl> + void PostLoadCleanup ( ) ; <nl> + <nl> + / / Gets the samples ready for training . Use after both <nl> + / / ReadTrainingSamples + PostLoadCleanup or DeSerialize . <nl> + / / Re - indexes the features and computes canonical and cloud features . <nl> + void PreTrainingSetup ( ) ; <nl> + <nl> + / / Sets up the master_shapes_ table , which tells which fonts should stay <nl> + / / together until they get to a leaf node classifier . <nl> + void SetupMasterShapes ( ) ; <nl> + <nl> + / / Adds the junk_samples_ to the main samples_ set . Junk samples are initially <nl> + / / fragments and n - grams ( all incorrectly segmented characters ) . <nl> + / / Various training functions may result in incorrectly segmented characters <nl> + / / being added to the unicharset of the main samples , perhaps because they <nl> + / / form a " radical " decomposition of some ( Indic ) grapheme , or because they <nl> + / / just look the same as a real character ( like rn / m ) <nl> + / / This function moves all the junk samples , to the main samples_ set , but <nl> + / / desirable junk , being any sample for which the unichar already exists in <nl> + / / the samples_ unicharset gets the unichar - ids re - indexed to match , but <nl> + / / anything else gets re - marked as unichar_id 0 ( space character ) to identify <nl> + / / it as junk to the error counter . <nl> + void IncludeJunk ( ) ; <nl> + <nl> + / / Replicates the samples and perturbs them if the enable_replication_ flag <nl> + / / is set . MUST be used after the last call to OrganizeByFontAndClass on <nl> + / / the training samples , ie after IncludeJunk if it is going to be used , as <nl> + / / OrganizeByFontAndClass will eat the replicated samples into the regular <nl> + / / samples . <nl> + void ReplicateAndRandomizeSamplesIfRequired ( ) ; <nl> + <nl> + / / Loads the basic font properties file into fontinfo_table_ . <nl> + / / Returns false on failure . <nl> + bool LoadFontInfo ( const char * filename ) ; <nl> + <nl> + / / Loads the xheight font properties file into xheights_ . <nl> + / / Returns false on failure . <nl> + bool LoadXHeights ( const char * filename ) ; <nl> + <nl> + / / Reads spacing stats from filename and adds them to fontinfo_table . <nl> + / / Returns false on failure . <nl> + bool AddSpacingInfo ( const char * filename ) ; <nl> + <nl> + / / Returns the font id corresponding to the given font name . <nl> + / / Returns - 1 if the font cannot be found . <nl> + int GetFontInfoId ( const char * font_name ) ; <nl> + / / Returns the font_id of the closest matching font name to the given <nl> + / / filename . It is assumed that a substring of the filename will match <nl> + / / one of the fonts . If more than one is matched , the longest is returned . <nl> + int GetBestMatchingFontInfoId ( const char * filename ) ; <nl> + <nl> + / / Sets up a flat shapetable with one shape per class / font combination . <nl> + void SetupFlatShapeTable ( ShapeTable * shape_table ) ; <nl> + <nl> + / / Sets up a Clusterer for mftraining on a single shape_id . <nl> + / / Call FreeClusterer on the return value after use . <nl> + CLUSTERER * SetupForClustering ( const ShapeTable & shape_table , <nl> + const FEATURE_DEFS_STRUCT & feature_defs , <nl> + int shape_id , int * num_samples ) ; <nl> + <nl> + / / Writes the given float_classes ( produced by SetupForFloat2Int ) as inttemp <nl> + / / to the given inttemp_file , and the corresponding pffmtable . <nl> + / / The unicharset is the original encoding of graphemes , and shape_set should <nl> + / / match the size of the shape_table , and may possibly be totally fake . <nl> + void WriteInttempAndPFFMTable ( const UNICHARSET & unicharset , <nl> + const UNICHARSET & shape_set , <nl> + const ShapeTable & shape_table , <nl> + CLASS_STRUCT * float_classes , <nl> + const char * inttemp_file , <nl> + const char * pffmtable_file ) ; <nl> + <nl> + const UNICHARSET & unicharset ( ) const { <nl> + return samples_ . unicharset ( ) ; <nl> + } <nl> + TrainingSampleSet * GetSamples ( ) { <nl> + return & samples_ ; <nl> + } <nl> + const ShapeTable & master_shapes ( ) const { <nl> + return master_shapes_ ; <nl> + } <nl> + <nl> + / / Generates debug output relating to the canonical distance between the <nl> + / / two given UTF8 grapheme strings . <nl> + void DebugCanonical ( const char * unichar_str1 , const char * unichar_str2 ) ; <nl> + / / Debugging for cloud / canonical features . <nl> + / / Displays a Features window containing : <nl> + / / If unichar_str2 is in the unicharset , and canonical_font is non - negative , <nl> + / / displays the canonical features of the char / font combination in red . <nl> + / / If unichar_str1 is in the unicharset , and cloud_font is non - negative , <nl> + / / displays the cloud feature of the char / font combination in green . <nl> + / / The canonical features are drawn first to show which ones have no <nl> + / / matches in the cloud features . <nl> + / / Until the features window is destroyed , each click in the features window <nl> + / / will display the samples that have that feature in a separate window . <nl> + void DisplaySamples ( const char * unichar_str1 , int cloud_font , <nl> + const char * unichar_str2 , int canonical_font ) ; <nl> + <nl> + / / Tests the given test_classifier on the internal samples . <nl> + / / See TestClassifier for details . <nl> + void TestClassifierOnSamples ( int report_level , <nl> + bool replicate_samples , <nl> + ShapeClassifier * test_classifier , <nl> + STRING * report_string ) ; <nl> + / / Tests the given test_classifier on the given samples <nl> + / / report_levels : <nl> + / / 0 = no output . <nl> + / / 1 = bottom - line error rate . <nl> + / / 2 = bottom - line error rate + time . <nl> + / / 3 = font - level error rate + time . <nl> + / / 4 = list of all errors + short classifier debug output on 16 errors . <nl> + / / 5 = list of all errors + short classifier debug output on 25 errors . <nl> + / / If replicate_samples is true , then the test is run on an extended test <nl> + / / sample including replicated and systematically perturbed samples . <nl> + / / If report_string is non - NULL , a summary of the results for each font <nl> + / / is appended to the report_string . <nl> + double TestClassifier ( int report_level , <nl> + bool replicate_samples , <nl> + TrainingSampleSet * samples , <nl> + ShapeClassifier * test_classifier , <nl> + STRING * report_string ) ; <nl> + <nl> + / / Returns the average ( in some sense ) distance between the two given <nl> + / / shapes , which may contain multiple fonts and / or unichars . <nl> + / / This function is public to facilitate testing . <nl> + float ShapeDistance ( const ShapeTable & shapes , int s1 , int s2 ) ; <nl> + <nl> + private : <nl> + / / Replaces samples that are always fragmented with the corresponding <nl> + / / fragment samples . <nl> + void ReplaceFragmentedSamples ( ) ; <nl> + <nl> + / / Runs a hierarchical agglomerative clustering to merge shapes in the given <nl> + / / shape_table , while satisfying the given constraints : <nl> + / / * End with at least min_shapes left in shape_table , <nl> + / / * No shape shall have more than max_shape_unichars in it , <nl> + / / * Don ' t merge shapes where the distance between them exceeds max_dist . <nl> + void ClusterShapes ( int min_shapes , int max_shape_unichars , <nl> + float max_dist , ShapeTable * shape_table ) ; <nl> + <nl> + private : <nl> + NormalizationMode norm_mode_ ; <nl> + / / Character set we are training for . <nl> + UNICHARSET unicharset_ ; <nl> + / / Original feature space . Subspace mapping is contained in feature_map_ . <nl> + IntFeatureSpace feature_space_ ; <nl> + TrainingSampleSet samples_ ; <nl> + TrainingSampleSet junk_samples_ ; <nl> + TrainingSampleSet verify_samples_ ; <nl> + / / Master shape table defines what fonts stay together until the leaves . <nl> + ShapeTable master_shapes_ ; <nl> + / / Flat shape table has each unichar / font id pair in a separate shape . <nl> + ShapeTable flat_shapes_ ; <nl> + / / Font metrics gathered from multiple files . <nl> + UnicityTable < FontInfo > fontinfo_table_ ; <nl> + / / Array of xheights indexed by font ids in fontinfo_table_ ; <nl> + GenericVector < int > xheights_ ; <nl> + <nl> + / / Non - serialized data initialized by other means or used temporarily <nl> + / / during loading of training samples . <nl> + / / Number of different class labels in unicharset_ . <nl> + int charsetsize_ ; <nl> + / / Flag to indicate that we are running shape analysis and need fragments <nl> + / / fixing . <nl> + bool enable_shape_anaylsis_ ; <nl> + / / Flag to indicate that sample replication is required . <nl> + bool enable_replication_ ; <nl> + / / Flag to indicate that junk should be included in samples_ . <nl> + bool include_junk_ ; <nl> + / / Array of classids of fragments that replace the correctly segmented chars . <nl> + int * fragments_ ; <nl> + / / Classid of previous correctly segmented sample that was added . <nl> + int prev_unichar_id_ ; <nl> + / / Debug output control . <nl> + int debug_level_ ; <nl> + / / Feature map used to construct reduced feature spaces for compact <nl> + / / classifiers . <nl> + IntFeatureMap feature_map_ ; <nl> + / / Vector of Pix pointers used for classifiers that need the image . <nl> + / / Indexed by page_num_ in the samples . <nl> + / / These images are owned by the trainer and need to be pixDestroyed . <nl> + GenericVector < Pix * > page_images_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + # endif <nl> mmm a / classify / mf . h <nl> ppp b / classify / mf . h <nl> <nl> <nl> typedef enum { <nl> MFXPosition , MFYPosition , <nl> - MFLength , MFDirection , MFBulge1 , MFBulge2 <nl> + MFLength , MFDirection , MFBulge1 , MFBulge2 , <nl> + MFCount / / For array sizes . <nl> } MF_PARAM_NAME ; <nl> + <nl> + typedef float MicroFeature [ MFCount ] ; <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Private Function Prototypes <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> mmm a / classify / mfoutline . cpp <nl> ppp b / classify / mfoutline . cpp <nl> MFOUTLINE ConvertOutline ( TESSLINE * outline ) { <nl> EdgePoint = NextPoint ; <nl> } while ( EdgePoint ! = StartPoint ) ; <nl> <nl> - MakeOutlineCircular ( MFOutline ) ; <nl> + if ( MFOutline ! = NULL ) <nl> + MakeOutlineCircular ( MFOutline ) ; <nl> return MFOutline ; <nl> } <nl> <nl> LIST ConvertOutlines ( TESSLINE * outline , <nl> <nl> while ( outline ! = NULL ) { <nl> mf_outline = ConvertOutline ( outline ) ; <nl> - mf_outlines = push ( mf_outlines , mf_outline ) ; <nl> + if ( mf_outline ! = NULL ) <nl> + mf_outlines = push ( mf_outlines , mf_outline ) ; <nl> outline = outline - > next ; <nl> } <nl> return mf_outlines ; <nl> void Classify : : NormalizeOutlines ( LIST Outlines , <nl> } / * NormalizeOutlines * / <nl> } / / namespace tesseract <nl> <nl> - / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> - void SmearExtremities ( MFOUTLINE Outline , FLOAT32 XScale , FLOAT32 YScale ) { <nl> - / * <nl> - * * Parameters : <nl> - * * Outline outline whose extremities are to be smeared <nl> - * * XScale factor used to normalize outline in x dir <nl> - * * YScale factor used to normalize outline in y dir <nl> - * * Globals : none <nl> - * * Operation : <nl> - * * This routine smears the extremities of the specified outline . <nl> - * * It does this by adding a random number between <nl> - * * - 0 . 5 and 0 . 5 pixels ( that is why X / YScale are needed ) to <nl> - * * the x and y position of the point . This is done so that <nl> - * * the discrete nature of the original scanned image does not <nl> - * * affect the statistical clustering used during training . <nl> - * * Return : none <nl> - * * Exceptions : none <nl> - * * History : 1 / 11 / 90 , DSJ , Created . <nl> - * / <nl> - MFEDGEPT * Current ; <nl> - MFOUTLINE EdgePoint ; <nl> - FLOAT32 MinXSmear ; <nl> - FLOAT32 MaxXSmear ; <nl> - FLOAT32 MinYSmear ; <nl> - FLOAT32 MaxYSmear ; <nl> - <nl> - if ( Outline ! = NIL_LIST ) { <nl> - MinXSmear = - 0 . 5 * XScale ; <nl> - MaxXSmear = 0 . 5 * XScale ; <nl> - MinYSmear = - 0 . 5 * YScale ; <nl> - MaxYSmear = 0 . 5 * YScale ; <nl> - EdgePoint = Outline ; <nl> - do { <nl> - Current = PointAt ( EdgePoint ) ; <nl> - if ( Current - > ExtremityMark ) { <nl> - Current - > Point . x + = <nl> - UniformRandomNumber ( MinXSmear , MaxXSmear ) ; <nl> - Current - > Point . y + = <nl> - UniformRandomNumber ( MinYSmear , MaxYSmear ) ; <nl> - } <nl> - <nl> - EdgePoint = NextPointAfter ( EdgePoint ) ; <nl> - } <nl> - while ( EdgePoint ! = Outline ) ; <nl> - } <nl> - } / * SmearExtremities * / <nl> - <nl> - <nl> / * * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Private Code <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> mmm a / classify / mfoutline . h <nl> ppp b / classify / mfoutline . h <nl> MFOUTLINE NextExtremity ( MFOUTLINE EdgePoint ) ; <nl> void NormalizeOutline ( MFOUTLINE Outline , <nl> FLOAT32 XOrigin ) ; <nl> <nl> - void SmearExtremities ( MFOUTLINE Outline , FLOAT32 XScale , FLOAT32 YScale ) ; <nl> - <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Private Function Prototypes <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> mmm a / classify / mfx . cpp <nl> ppp b / classify / mfx . cpp <nl> CHAR_FEATURES BlobMicroFeatures ( TBLOB * Blob , const DENORM & denorm ) { <nl> Outline = ( MFOUTLINE ) first_node ( RemainingOutlines ) ; <nl> FindDirectionChanges ( Outline , classify_min_slope , classify_max_slope ) ; <nl> MarkDirectionChanges ( Outline ) ; <nl> - SmearExtremities ( Outline , XScale , YScale ) ; <nl> MicroFeatures = ConvertToMicroFeatures ( Outline , MicroFeatures ) ; <nl> } <nl> FreeOutlines ( Outlines ) ; <nl> mmm a / classify / normmatch . cpp <nl> ppp b / classify / normmatch . cpp <nl> const double kWidthErrorWeighting = 0 . 125 ; <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> namespace tesseract { <nl> - FLOAT32 Classify : : ComputeNormMatch ( CLASS_ID ClassId , FEATURE Feature , <nl> + FLOAT32 Classify : : ComputeNormMatch ( CLASS_ID ClassId , <nl> + const FEATURE_STRUCT & feature , <nl> BOOL8 DebugMatch ) { <nl> / * <nl> * * Parameters : <nl> FLOAT32 Classify : : ComputeNormMatch ( CLASS_ID ClassId , FEATURE Feature , <nl> / * handle requests for classification as noise * / <nl> if ( ClassId = = NO_CLASS ) { <nl> / * kludge - clean up constants and make into control knobs later * / <nl> - Match = ( Feature - > Params [ CharNormLength ] * <nl> - Feature - > Params [ CharNormLength ] * 500 . 0 + <nl> - Feature - > Params [ CharNormRx ] * <nl> - Feature - > Params [ CharNormRx ] * 8000 . 0 + <nl> - Feature - > Params [ CharNormRy ] * <nl> - Feature - > Params [ CharNormRy ] * 8000 . 0 ) ; <nl> + Match = ( feature . Params [ CharNormLength ] * <nl> + feature . Params [ CharNormLength ] * 500 . 0 + <nl> + feature . Params [ CharNormRx ] * <nl> + feature . Params [ CharNormRx ] * 8000 . 0 + <nl> + feature . Params [ CharNormRy ] * <nl> + feature . Params [ CharNormRy ] * 8000 . 0 ) ; <nl> return ( 1 . 0 - NormEvidenceOf ( Match ) ) ; <nl> } <nl> <nl> FLOAT32 Classify : : ComputeNormMatch ( CLASS_ID ClassId , FEATURE Feature , <nl> Protos = NormProtos - > Protos [ ClassId ] ; <nl> <nl> if ( DebugMatch ) { <nl> - cprintf ( " \ nFeature = " ) ; <nl> - WriteFeature ( stdout , Feature ) ; <nl> + tprintf ( " \ nChar norm for class % s \ n " , unicharset . id_to_unichar ( ClassId ) ) ; <nl> } <nl> <nl> ProtoId = 0 ; <nl> iterate ( Protos ) { <nl> Proto = ( PROTOTYPE * ) first_node ( Protos ) ; <nl> - Delta = Feature - > Params [ CharNormY ] - Proto - > Mean [ CharNormY ] ; <nl> + Delta = feature . Params [ CharNormY ] - Proto - > Mean [ CharNormY ] ; <nl> Match = Delta * Delta * Proto - > Weight . Elliptical [ CharNormY ] ; <nl> - Delta = Feature - > Params [ CharNormRx ] - Proto - > Mean [ CharNormRx ] ; <nl> + if ( DebugMatch ) { <nl> + tprintf ( " YMiddle : Proto = % g , Delta = % g , Var = % g , Dist = % g \ n " , <nl> + Proto - > Mean [ CharNormY ] , Delta , <nl> + Proto - > Weight . Elliptical [ CharNormY ] , Match ) ; <nl> + } <nl> + Delta = feature . Params [ CharNormRx ] - Proto - > Mean [ CharNormRx ] ; <nl> Match + = Delta * Delta * Proto - > Weight . Elliptical [ CharNormRx ] ; <nl> + if ( DebugMatch ) { <nl> + tprintf ( " Height : Proto = % g , Delta = % g , Var = % g , Dist = % g \ n " , <nl> + Proto - > Mean [ CharNormRx ] , Delta , <nl> + Proto - > Weight . Elliptical [ CharNormRx ] , Match ) ; <nl> + } <nl> / / Ry is width ! See intfx . cpp . <nl> - Delta = Feature - > Params [ CharNormRy ] - Proto - > Mean [ CharNormRy ] ; <nl> + Delta = feature . Params [ CharNormRy ] - Proto - > Mean [ CharNormRy ] ; <nl> + if ( DebugMatch ) { <nl> + tprintf ( " Width : Proto = % g , Delta = % g , Var = % g \ n " , <nl> + Proto - > Mean [ CharNormRy ] , Delta , <nl> + Proto - > Weight . Elliptical [ CharNormRy ] ) ; <nl> + } <nl> Delta = Delta * Delta * Proto - > Weight . Elliptical [ CharNormRy ] ; <nl> Delta * = kWidthErrorWeighting ; <nl> Match + = Delta ; <nl> + if ( DebugMatch ) { <nl> + tprintf ( " Total Dist = % g , scaled = % g , sigmoid = % g , penalty = % g \ n " , <nl> + Match , Match / classify_norm_adj_midpoint , <nl> + NormEvidenceOf ( Match ) , 256 * ( 1 - NormEvidenceOf ( Match ) ) ) ; <nl> + } <nl> <nl> if ( Match < BestMatch ) <nl> BestMatch = Match ; <nl> <nl> - if ( DebugMatch ) { <nl> - cprintf ( " Proto % 1d = " , ProtoId ) ; <nl> - WriteNFloats ( stdout , NormProtos - > NumParams , Proto - > Mean ) ; <nl> - cprintf ( " var = " ) ; <nl> - WriteNFloats ( stdout , NormProtos - > NumParams , <nl> - Proto - > Variance . Elliptical ) ; <nl> - cprintf ( " match = " ) ; <nl> - PrintNormMatch ( stdout , NormProtos - > NumParams , Proto , Feature ) ; <nl> - } <nl> ProtoId + + ; <nl> } <nl> - return ( 1 . 0 - NormEvidenceOf ( BestMatch ) ) ; <nl> + return 1 . 0 - NormEvidenceOf ( BestMatch ) ; <nl> } / * ComputeNormMatch * / <nl> <nl> void Classify : : FreeNormProtos ( ) { <nl> NORM_PROTOS * Classify : : ReadNormProtos ( FILE * File , inT64 end_offset ) { <nl> * / <nl> NORM_PROTOS * NormProtos ; <nl> int i ; <nl> - char unichar [ UNICHAR_LEN + 1 ] ; <nl> + char unichar [ 2 * UNICHAR_LEN + 1 ] ; <nl> UNICHAR_ID unichar_id ; <nl> LIST Protos ; <nl> int NumProtos ; <nl> NORM_PROTOS * Classify : : ReadNormProtos ( FILE * File , inT64 end_offset ) { <nl> Protos = <nl> push_last ( Protos , ReadPrototype ( File , NormProtos - > NumParams ) ) ; <nl> NormProtos - > Protos [ unichar_id ] = Protos ; <nl> - } else <nl> - cprintf ( " Error : unichar % s in normproto file is not in unichar set . \ n " ) ; <nl> + } else { <nl> + cprintf ( " Error : unichar % s in normproto file is not in unichar set . \ n " , <nl> + unichar ) ; <nl> + for ( i = 0 ; i < NumProtos ; i + + ) <nl> + FreePrototype ( ReadPrototype ( File , NormProtos - > NumParams ) ) ; <nl> + } <nl> SkipNewline ( File ) ; <nl> } <nl> return ( NormProtos ) ; <nl> mmm a / classify / ocrfeatures . cpp <nl> ppp b / classify / ocrfeatures . cpp <nl> void WriteFeature ( FILE * File , FEATURE Feature ) { <nl> <nl> for ( i = 0 ; i < Feature - > Type - > NumParams ; i + + ) { <nl> # ifndef WIN32 <nl> - assert ( ! isnan ( Feature - > Params [ i ] ) ) ; <nl> + assert ( ! isnan ( Feature - > Params [ i ] ) ) ; <nl> # endif <nl> - fprintf ( File , " % 12g " , Feature - > Params [ i ] ) ; <nl> + fprintf ( File , " % g " , Feature - > Params [ i ] ) ; <nl> } <nl> - fprintf ( File , " \ n " ) ; <nl> - <nl> + fprintf ( File , " \ n " ) ; <nl> } / * WriteFeature * / <nl> <nl> <nl> mmm a / classify / ocrfeatures . h <nl> ppp b / classify / ocrfeatures . h <nl> const PARAM_DESC Name [ ] = { <nl> Macro for describing a new feature . The parameters of the macro <nl> are as follows : <nl> <nl> - DefineFeature ( Name , NumLinear , NumCircular , <nl> - MinFeatPerChar , MaxFeatPerChar , <nl> - LongName , ShortName , ParamName ) <nl> + DefineFeature ( Name , NumLinear , NumCircular , ShortName , ParamName ) <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * / <nl> - # define DefineFeature ( Name , NL , NC , Min , Max , LN , SN , PN ) \ <nl> + # define DefineFeature ( Name , NL , NC , SN , PN ) \ <nl> const FEATURE_DESC_STRUCT Name = { \ <nl> ( ( NL ) + ( NC ) ) , SN , PN } ; <nl> <nl> mmm a / classify / picofeat . cpp <nl> ppp b / classify / picofeat . cpp <nl> <nl> # include " mfoutline . h " <nl> # include " ocrfeatures . h " <nl> # include " params . h " <nl> + # include " trainingsample . h " <nl> <nl> # include < math . h > <nl> # include < stdio . h > <nl> void NormalizePicoX ( FEATURE_SET FeatureSet ) { <nl> Feature - > Params [ PicoFeatX ] - = Origin ; <nl> } <nl> } / * NormalizePicoX * / <nl> + <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> + FEATURE_SET ExtractIntCNFeatures ( TBLOB * blob , const DENORM & denorm ) { <nl> + / * <nl> + * * Parameters : <nl> + * * blob blob to extract features from <nl> + * * denorm normalization / denormalization parameters . <nl> + * * Return : Integer character - normalized features for blob . <nl> + * * Exceptions : none <nl> + * * History : 8 / 8 / 2011 , rays , Created . <nl> + * / <nl> + tesseract : : TrainingSample * sample = GetIntFeatures ( <nl> + tesseract : : NM_CHAR_ANISOTROPIC , blob , denorm ) ; <nl> + if ( sample = = NULL ) return NULL ; <nl> + <nl> + int num_features = sample - > num_features ( ) ; <nl> + const INT_FEATURE_STRUCT * features = sample - > features ( ) ; <nl> + FEATURE_SET feature_set = NewFeatureSet ( num_features ) ; <nl> + for ( int f = 0 ; f < num_features ; + + f ) { <nl> + FEATURE feature = NewFeature ( & IntFeatDesc ) ; <nl> + <nl> + feature - > Params [ IntX ] = features [ f ] . X ; <nl> + feature - > Params [ IntY ] = features [ f ] . Y ; <nl> + feature - > Params [ IntDir ] = features [ f ] . Theta ; <nl> + AddFeature ( feature_set , feature ) ; <nl> + } <nl> + delete sample ; <nl> + <nl> + return feature_set ; <nl> + } / * ExtractIntCNFeatures * / <nl> + <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * / <nl> + FEATURE_SET ExtractIntGeoFeatures ( TBLOB * blob , const DENORM & denorm ) { <nl> + / * <nl> + * * Parameters : <nl> + * * blob blob to extract features from <nl> + * * denorm normalization / denormalization parameters . <nl> + * * Return : Geometric ( top / bottom / width ) features for blob . <nl> + * * Exceptions : none <nl> + * * History : 8 / 8 / 2011 , rays , Created . <nl> + * / <nl> + tesseract : : TrainingSample * sample = GetIntFeatures ( <nl> + tesseract : : NM_CHAR_ANISOTROPIC , blob , denorm ) ; <nl> + if ( sample = = NULL ) return NULL ; <nl> + <nl> + FEATURE_SET feature_set = NewFeatureSet ( 1 ) ; <nl> + FEATURE feature = NewFeature ( & IntFeatDesc ) ; <nl> + <nl> + feature - > Params [ GeoBottom ] = sample - > geo_feature ( GeoBottom ) ; <nl> + feature - > Params [ GeoTop ] = sample - > geo_feature ( GeoTop ) ; <nl> + feature - > Params [ GeoWidth ] = sample - > geo_feature ( GeoWidth ) ; <nl> + AddFeature ( feature_set , feature ) ; <nl> + delete sample ; <nl> + <nl> + return feature_set ; <nl> + } / * ExtractIntGeoFeatures * / <nl> mmm a / classify / picofeat . h <nl> ppp b / classify / picofeat . h <nl> <nl> # include " ocrfeatures . h " <nl> # include " params . h " <nl> <nl> + / / Enum for the order / type of params in IntFeatDesc . <nl> + enum IntParams { <nl> + IntX , / / x - position ( 0 - 255 ) . <nl> + IntY , / / y - position ( 0 - 255 ) . <nl> + IntDir / / Direction ( 0 - 255 , circular ) . <nl> + } ; <nl> + <nl> + / / Enum for the order / type of params in GeoFeatDesc . <nl> + enum GeoParams { <nl> + GeoBottom , / / Bounding box bottom in baseline space ( 0 - 255 ) . <nl> + GeoTop , / / Bounding box top in baseline space ( 0 - 255 ) . <nl> + GeoWidth , / / Bounding box width in baseline space ( 0 - 255 ) . <nl> + <nl> + GeoCount / / Number of geo features . <nl> + } ; <nl> + <nl> typedef enum <nl> { PicoFeatY , PicoFeatDir , PicoFeatX } <nl> PICO_FEAT_PARAM_NAME ; <nl> extern double_VAR_H ( classify_pico_feature_length , 0 . 05 , " Pico Feature Length " ) ; <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> # define GetPicoFeatureLength ( ) ( PicoFeatureLength ) <nl> <nl> + FEATURE_SET ExtractIntCNFeatures ( TBLOB * Blob , const DENORM & denorm ) ; <nl> + FEATURE_SET ExtractIntGeoFeatures ( TBLOB * Blob , const DENORM & denorm ) ; <nl> + <nl> / * * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> Global Data Definitions and Declarations <nl> mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * * / <nl> mmm a / classify / protos . h <nl> ppp b / classify / protos . h <nl> typedef struct <nl> } PROTO_STRUCT ; <nl> typedef PROTO_STRUCT * PROTO ; <nl> <nl> - typedef struct <nl> - { <nl> + struct CLASS_STRUCT { <nl> + CLASS_STRUCT ( ) <nl> + : NumProtos ( 0 ) , MaxNumProtos ( 0 ) , Prototypes ( NULL ) , <nl> + NumConfigs ( 0 ) , MaxNumConfigs ( 0 ) , Configurations ( NULL ) { <nl> + } <nl> inT16 NumProtos ; <nl> inT16 MaxNumProtos ; <nl> PROTO Prototypes ; <nl> typedef struct <nl> inT16 MaxNumConfigs ; <nl> CONFIGS Configurations ; <nl> UnicityTableEqEq < int > font_set ; <nl> - } CLASS_STRUCT ; <nl> + } ; <nl> typedef CLASS_STRUCT * CLASS_TYPE ; <nl> typedef CLASS_STRUCT * CLASSES ; <nl> <nl> new file mode 100644 <nl> index 000000000 . . 5f06a288b <nl> mmm / dev / null <nl> ppp b / classify / sampleiterator . cpp <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " sampleiterator . h " <nl> + <nl> + # include " indexmapbidi . h " <nl> + # include " shapetable . h " <nl> + # include " trainingsample . h " <nl> + # include " trainingsampleset . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + / / = = = = = = = = = = = = = = = = = = SampleIterator Implementation = = = = = = = = = = = = = = = = = <nl> + <nl> + SampleIterator : : SampleIterator ( ) <nl> + : charset_map_ ( NULL ) , <nl> + shape_table_ ( NULL ) , <nl> + sample_set_ ( NULL ) , <nl> + randomize_ ( false ) , <nl> + owned_shape_table_ ( NULL ) { <nl> + num_shapes_ = 0 ; <nl> + Begin ( ) ; <nl> + } <nl> + <nl> + SampleIterator : : ~ SampleIterator ( ) { <nl> + Clear ( ) ; <nl> + } <nl> + <nl> + void SampleIterator : : Clear ( ) { <nl> + delete owned_shape_table_ ; <nl> + owned_shape_table_ = NULL ; <nl> + } <nl> + <nl> + / / See class comment for arguments . <nl> + void SampleIterator : : Init ( const IndexMapBiDi * charset_map , <nl> + const ShapeTable * shape_table , <nl> + bool randomize , <nl> + TrainingSampleSet * sample_set ) { <nl> + Clear ( ) ; <nl> + charset_map_ = charset_map ; <nl> + shape_table_ = shape_table ; <nl> + sample_set_ = sample_set ; <nl> + randomize_ = randomize ; <nl> + if ( shape_table_ = = NULL & & charset_map_ ! = NULL ) { <nl> + / / The caller wishes to iterate by class . The easiest way to do this <nl> + / / is to create a dummy shape_table_ that we will own . <nl> + int num_fonts = sample_set_ - > NumFonts ( ) ; <nl> + owned_shape_table_ = new ShapeTable ( sample_set_ - > unicharset ( ) ) ; <nl> + int charsetsize = sample_set_ - > unicharset ( ) . size ( ) ; <nl> + for ( int c = 0 ; c < charsetsize ; + + c ) { <nl> + / / We always add a shape for each character to keep the index in sync <nl> + / / with the unichar_id . <nl> + int shape_id = owned_shape_table_ - > AddShape ( c , 0 ) ; <nl> + for ( int f = 1 ; f < num_fonts ; + + f ) { <nl> + if ( sample_set_ - > NumClassSamples ( f , c , true ) > 0 ) { <nl> + owned_shape_table_ - > AddToShape ( shape_id , c , f ) ; <nl> + } <nl> + } <nl> + } <nl> + shape_table_ = owned_shape_table_ ; <nl> + } <nl> + if ( shape_table_ ! = NULL ) { <nl> + num_shapes_ = shape_table_ - > NumShapes ( ) ; <nl> + } else { <nl> + num_shapes_ = randomize ? sample_set_ - > num_samples ( ) <nl> + : sample_set_ - > num_raw_samples ( ) ; <nl> + } <nl> + Begin ( ) ; <nl> + } <nl> + <nl> + / / Iterator functions designed for use with a simple for loop : <nl> + / / for ( it . Begin ( ) ; ! it . AtEnd ( ) ; it . Next ( ) ) { <nl> + / / const TrainingSample & sample = it . GetSample ( ) ; <nl> + / / } <nl> + void SampleIterator : : Begin ( ) { <nl> + shape_index_ = - 1 ; <nl> + shape_char_index_ = 0 ; <nl> + num_shape_chars_ = 0 ; <nl> + shape_font_index_ = 0 ; <nl> + num_shape_fonts_ = 0 ; <nl> + sample_index_ = 0 ; <nl> + num_samples_ = 0 ; <nl> + / / Find the first indexable sample . <nl> + Next ( ) ; <nl> + } <nl> + <nl> + bool SampleIterator : : AtEnd ( ) const { <nl> + return shape_index_ > = num_shapes_ ; <nl> + } <nl> + <nl> + const TrainingSample & SampleIterator : : GetSample ( ) const { <nl> + if ( shape_table_ ! = NULL ) { <nl> + const UnicharAndFonts * shape_entry = GetShapeEntry ( ) ; <nl> + int char_id = shape_entry - > unichar_id ; <nl> + int font_id = shape_entry - > font_ids [ shape_font_index_ ] ; <nl> + return * sample_set_ - > GetSample ( font_id , char_id , sample_index_ ) ; <nl> + } else { <nl> + return * sample_set_ - > GetSample ( shape_index_ ) ; <nl> + } <nl> + } <nl> + <nl> + TrainingSample * SampleIterator : : MutableSample ( ) const { <nl> + if ( shape_table_ ! = NULL ) { <nl> + const UnicharAndFonts * shape_entry = GetShapeEntry ( ) ; <nl> + int char_id = shape_entry - > unichar_id ; <nl> + int font_id = shape_entry - > font_ids [ shape_font_index_ ] ; <nl> + return sample_set_ - > MutableSample ( font_id , char_id , sample_index_ ) ; <nl> + } else { <nl> + return sample_set_ - > mutable_sample ( shape_index_ ) ; <nl> + } <nl> + } <nl> + <nl> + / / Returns the total index ( from the original set of samples ) of the current <nl> + / / sample . <nl> + int SampleIterator : : GlobalSampleIndex ( ) const { <nl> + if ( shape_table_ ! = NULL ) { <nl> + const UnicharAndFonts * shape_entry = GetShapeEntry ( ) ; <nl> + int char_id = shape_entry - > unichar_id ; <nl> + int font_id = shape_entry - > font_ids [ shape_font_index_ ] ; <nl> + return sample_set_ - > GlobalSampleIndex ( font_id , char_id , sample_index_ ) ; <nl> + } else { <nl> + return shape_index_ ; <nl> + } <nl> + } <nl> + <nl> + / / Returns the index of the current sample in compact charset space , so <nl> + / / in a 2 - class problem between x and y , the returned indices will all be <nl> + / / 0 or 1 , and have nothing to do with the unichar_ids . <nl> + / / If the charset_map_ is NULL , then this is equal to GetSparseClassID ( ) . <nl> + int SampleIterator : : GetCompactClassID ( ) const { <nl> + return charset_map_ ! = NULL ? charset_map_ - > SparseToCompact ( shape_index_ ) <nl> + : GetSparseClassID ( ) ; <nl> + } <nl> + / / Returns the index of the current sample in sparse charset space , so <nl> + / / in a 2 - class problem between x and y , the returned indices will all be <nl> + / / x or y , where x and y may be unichar_ids ( no shape_table_ ) or shape_ids <nl> + / / with a shape_table_ . <nl> + int SampleIterator : : GetSparseClassID ( ) const { <nl> + return shape_table_ ! = NULL ? shape_index_ : GetSample ( ) . class_id ( ) ; <nl> + } <nl> + <nl> + / / Moves on to the next indexable sample . If the end is reached , leaves <nl> + / / the state such that AtEnd ( ) is true . <nl> + void SampleIterator : : Next ( ) { <nl> + if ( shape_table_ ! = NULL ) { <nl> + / / Next sample in this class / font combination . <nl> + + + sample_index_ ; <nl> + if ( sample_index_ < num_samples_ ) <nl> + return ; <nl> + / / Next font in this class in this shape . <nl> + sample_index_ = 0 ; <nl> + do { <nl> + + + shape_font_index_ ; <nl> + if ( shape_font_index_ > = num_shape_fonts_ ) { <nl> + / / Next unichar in this shape . <nl> + shape_font_index_ = 0 ; <nl> + + + shape_char_index_ ; <nl> + if ( shape_char_index_ > = num_shape_chars_ ) { <nl> + / / Find the next shape that is mapped in the charset_map_ . <nl> + shape_char_index_ = 0 ; <nl> + do { <nl> + + + shape_index_ ; <nl> + } while ( shape_index_ < num_shapes_ & & <nl> + charset_map_ ! = NULL & & <nl> + charset_map_ - > SparseToCompact ( shape_index_ ) < 0 ) ; <nl> + if ( shape_index_ > = num_shapes_ ) <nl> + return ; / / The end . <nl> + num_shape_chars_ = shape_table_ - > GetShape ( shape_index_ ) . size ( ) ; <nl> + } <nl> + } <nl> + const UnicharAndFonts * shape_entry = GetShapeEntry ( ) ; <nl> + num_shape_fonts_ = shape_entry - > font_ids . size ( ) ; <nl> + int char_id = shape_entry - > unichar_id ; <nl> + int font_id = shape_entry - > font_ids [ shape_font_index_ ] ; <nl> + num_samples_ = sample_set_ - > NumClassSamples ( font_id , char_id , randomize_ ) ; <nl> + } while ( num_samples_ = = 0 ) ; <nl> + } else { <nl> + / / We are just iterating over the samples . <nl> + + + shape_index_ ; <nl> + } <nl> + } <nl> + <nl> + / / Returns the size of the compact charset space . <nl> + int SampleIterator : : CompactCharsetSize ( ) const { <nl> + return charset_map_ ! = NULL ? charset_map_ - > CompactSize ( ) <nl> + : SparseCharsetSize ( ) ; <nl> + } <nl> + <nl> + / / Returns the size of the sparse charset space . <nl> + int SampleIterator : : SparseCharsetSize ( ) const { <nl> + return charset_map_ ! = NULL <nl> + ? charset_map_ - > SparseSize ( ) <nl> + : ( shape_table_ ! = NULL ? shape_table_ - > NumShapes ( ) <nl> + : sample_set_ - > charsetsize ( ) ) ; <nl> + } <nl> + <nl> + / / Apply the supplied feature_space / feature_map transform to all samples <nl> + / / accessed by this iterator . <nl> + void SampleIterator : : MapSampleFeatures ( const IntFeatureMap & feature_map ) { <nl> + for ( Begin ( ) ; ! AtEnd ( ) ; Next ( ) ) { <nl> + TrainingSample * sample = MutableSample ( ) ; <nl> + sample - > MapFeatures ( feature_map ) ; <nl> + } <nl> + } <nl> + <nl> + / / Adjust the weights of all the samples to be uniform in the given charset . <nl> + / / Returns the number of samples in the iterator . <nl> + int SampleIterator : : UniformSamples ( ) { <nl> + int num_good_samples = 0 ; <nl> + for ( Begin ( ) ; ! AtEnd ( ) ; Next ( ) ) { <nl> + TrainingSample * sample = MutableSample ( ) ; <nl> + sample - > set_weight ( 1 . 0 ) ; <nl> + + + num_good_samples ; <nl> + } <nl> + NormalizeSamples ( ) ; <nl> + return num_good_samples ; <nl> + } <nl> + <nl> + / / Normalize the weights of all the samples in the charset_map so they sum <nl> + / / to 1 . Returns the minimum assigned sample weight . <nl> + double SampleIterator : : NormalizeSamples ( ) { <nl> + double total_weight = 0 . 0 ; <nl> + int sample_count = 0 ; <nl> + for ( Begin ( ) ; ! AtEnd ( ) ; Next ( ) ) { <nl> + const TrainingSample & sample = GetSample ( ) ; <nl> + total_weight + = sample . weight ( ) ; <nl> + + + sample_count ; <nl> + } <nl> + / / Normalize samples . <nl> + double min_assigned_sample_weight = 1 . 0 ; <nl> + if ( total_weight > 0 . 0 ) { <nl> + for ( Begin ( ) ; ! AtEnd ( ) ; Next ( ) ) { <nl> + TrainingSample * sample = MutableSample ( ) ; <nl> + double weight = sample - > weight ( ) / total_weight ; <nl> + if ( weight < min_assigned_sample_weight ) <nl> + min_assigned_sample_weight = weight ; <nl> + sample - > set_weight ( weight ) ; <nl> + } <nl> + } <nl> + return min_assigned_sample_weight ; <nl> + } <nl> + <nl> + / / Helper returns the current UnicharAndFont shape_entry . <nl> + const UnicharAndFonts * SampleIterator : : GetShapeEntry ( ) const { <nl> + const Shape & shape = shape_table_ - > GetShape ( shape_index_ ) ; <nl> + return & shape [ shape_char_index_ ] ; <nl> + } <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> new file mode 100644 <nl> index 000000000 . . fd22d3163 <nl> mmm / dev / null <nl> ppp b / classify / sampleiterator . h <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + <nl> + # ifndef TESSERACT_CLASSIFY_SAMPLEITERATOR_H_ <nl> + # define TESSERACT_CLASSIFY_SAMPLEITERATOR_H_ <nl> + <nl> + namespace tesseract { <nl> + <nl> + class IndexMapBiDi ; <nl> + class IntFeatureMap ; <nl> + class ShapeTable ; <nl> + class TrainingSample ; <nl> + class TrainingSampleSet ; <nl> + class UnicharAndFonts ; <nl> + <nl> + / / Iterator class to encapsulate the complex iteration involved in getting <nl> + / / all samples of all shapes needed for a classification problem . <nl> + / / <nl> + / / = = = = = INPUTS TO Init FUNCTION = = = = = <nl> + / / The charset_map defines a subset of the sample_set classes ( with a NULL <nl> + / / shape_table , or the shape_table classes if not NULL . ) <nl> + / / <nl> + / / The shape_table ( if not NULL ) defines the mapping from shapes to <nl> + / / font_id / class_id pairs . Each shape is a list of unichar_id and font lists . <nl> + / / <nl> + / / The sample_set holds the samples and provides indexed access to samples <nl> + / / of font_id / class_id pairs . <nl> + / / <nl> + / / If randomize is true , the samples are perturbed slightly , but the <nl> + / / perturbation is guaranteed to be the same for multiple identical <nl> + / / iterations . <nl> + / / <nl> + / / = = = = = DIFFERENT COMBINATIONS OF INPUTS = = = = = <nl> + / / NULL shape_table : <nl> + / / Without a shape_table , everything works in UNICHAR_IDs . <nl> + / / <nl> + / / NULL shape_table , NULL charset_map : <nl> + / / Iterations simply run over the samples in the order the samples occur in the <nl> + / / input files . <nl> + / / GetCompactClassID and GetSparseClassID both return the sample UNICHAR_ID . <nl> + / / <nl> + / / NULL shape_table , non - NULL charset_map : <nl> + / / When shape_table is NULL , the charset_map indexes unichar_ids directly , <nl> + / / and an iteration returns all samples of all chars in the charset_map , which <nl> + / / is a subset of the full unicharset . <nl> + / / The iteration will be in groups of the same unichar_id , in the order <nl> + / / defined by the charset_map . <nl> + / / GetCompactClassID returns the charset_map index of a sample , and <nl> + / / GetSparseClassID returns the sample UNICHAR_ID . <nl> + / / <nl> + / / Non - NULL shape_table : <nl> + / / With a shape_table , samples are grouped according to the shape_table , so <nl> + / / multiple UNICHAR_IDs and fonts may be grouped together , and everything <nl> + / / works in shape_ids . <nl> + / / <nl> + / / Non - NULL shape_table , NULL charset_map . <nl> + / / Iterations simply run over the samples in the order of shape_id . <nl> + / / GetCompactClassID and GetSparseClassID both return the shape_id . <nl> + / / ( If you want the unichar_id or font_id , the sample still has them . ) <nl> + / / <nl> + / / Non - NULL shape_table , non - NULL charset_map . <nl> + / / When shape_table is not NULL , the charset_map indexes and subsets shapes in <nl> + / / the shape_table , and iterations will be in shape_table order , not <nl> + / / charset_map order . <nl> + / / GetCompactClassID returns the charset_map index of a shape , and <nl> + / / GetSparseClassID returns the shape_id . <nl> + / / <nl> + / / = = = = = What is SampleIterator good for ? = = = = = <nl> + / / Inside a classifier training module , the SampleIterator has abstracted away <nl> + / / all the different modes above . <nl> + / / Use the following iteration to train your classifier : <nl> + / / for ( it . Begin ( ) ; ! it . AtEnd ( ) ; it . Next ( ) ) { <nl> + / / const TrainingSample & sample = it . GetSample ( ) ; <nl> + / / int class_id = it . GetCompactClassID ( ) ; <nl> + / / Your classifier may or may not be dealing with a shape_table , and may be <nl> + / / dealing with some subset of the character / shape set . It doesn ' t need to <nl> + / / know and shouldn ' t care . It is just learning shapes with compact class ids <nl> + / / in the range [ 0 , it . CompactCharsetSize ( ) ) . <nl> + class SampleIterator { <nl> + public : <nl> + SampleIterator ( ) ; <nl> + ~ SampleIterator ( ) ; <nl> + <nl> + void Clear ( ) ; <nl> + <nl> + / / See class comment for arguments . <nl> + void Init ( const IndexMapBiDi * charset_map , <nl> + const ShapeTable * shape_table , <nl> + bool randomize , <nl> + TrainingSampleSet * sample_set ) ; <nl> + <nl> + / / Iterator functions designed for use with a simple for loop : <nl> + / / for ( it . Begin ( ) ; ! it . AtEnd ( ) ; it . Next ( ) ) { <nl> + / / const TrainingSample & sample = it . GetSample ( ) ; <nl> + / / int class_id = it . GetCompactClassID ( ) ; <nl> + / / . . . <nl> + / / } <nl> + void Begin ( ) ; <nl> + bool AtEnd ( ) const ; <nl> + const TrainingSample & GetSample ( ) const ; <nl> + TrainingSample * MutableSample ( ) const ; <nl> + / / Returns the total index ( from the original set of samples ) of the current <nl> + / / sample . <nl> + int GlobalSampleIndex ( ) const ; <nl> + / / Returns the index of the current sample in compact charset space , so <nl> + / / in a 2 - class problem between x and y , the returned indices will all be <nl> + / / 0 or 1 , and have nothing to do with the unichar_ids . <nl> + / / If the charset_map_ is NULL , then this is equal to GetSparseClassID ( ) . <nl> + int GetCompactClassID ( ) const ; <nl> + / / Returns the index of the current sample in sparse charset space , so <nl> + / / in a 2 - class problem between x and y , the returned indices will all be <nl> + / / x or y , where x and y may be unichar_ids ( no shape_table_ ) or shape_ids <nl> + / / with a shape_table_ . <nl> + int GetSparseClassID ( ) const ; <nl> + / / Moves on to the next indexable sample . If the end is reached , leaves <nl> + / / the state such that AtEnd ( ) is true . <nl> + void Next ( ) ; <nl> + <nl> + / / Returns the size of the compact charset space . <nl> + int CompactCharsetSize ( ) const ; <nl> + / / Returns the size of the sparse charset space . <nl> + int SparseCharsetSize ( ) const ; <nl> + <nl> + const IndexMapBiDi & charset_map ( ) const { <nl> + return * charset_map_ ; <nl> + } <nl> + const ShapeTable * shape_table ( ) const { <nl> + return shape_table_ ; <nl> + } <nl> + / / Sample set operations . <nl> + const TrainingSampleSet * sample_set ( ) const { <nl> + return sample_set_ ; <nl> + } <nl> + <nl> + / / A set of functions that do something to all the samples accessed by the <nl> + / / iterator , as it is currently setup . <nl> + <nl> + / / Apply the supplied feature_space / feature_map transform to all samples <nl> + / / accessed by this iterator . <nl> + void MapSampleFeatures ( const IntFeatureMap & feature_map ) ; <nl> + <nl> + / / Adjust the weights of all the samples to be uniform in the given charset . <nl> + / / Returns the number of samples in the iterator . <nl> + int UniformSamples ( ) ; <nl> + <nl> + / / Normalize the weights of all the samples defined by the iterator so they <nl> + / / sum to 1 . Returns the minimum assigned sample weight . <nl> + double NormalizeSamples ( ) ; <nl> + <nl> + private : <nl> + / / Helper returns the current UnicharAndFont shape_entry . <nl> + const UnicharAndFonts * GetShapeEntry ( ) const ; <nl> + <nl> + / / Map to subset the actual charset space . <nl> + const IndexMapBiDi * charset_map_ ; <nl> + / / Shape table to recombine character classes into shapes <nl> + const ShapeTable * shape_table_ ; <nl> + / / The samples to iterate over . <nl> + TrainingSampleSet * sample_set_ ; <nl> + / / Flag to control randomizing the sample features . <nl> + bool randomize_ ; <nl> + / / Shape table owned by this used to iterate character classes . <nl> + ShapeTable * owned_shape_table_ ; <nl> + <nl> + / / Top - level iteration . Shape index in sparse charset_map space . <nl> + int shape_index_ ; <nl> + int num_shapes_ ; <nl> + / / Index to the character class within a shape . <nl> + int shape_char_index_ ; <nl> + int num_shape_chars_ ; <nl> + / / Index to the font within a shape / class pair . <nl> + int shape_font_index_ ; <nl> + int num_shape_fonts_ ; <nl> + / / The lowest level iteration . sample_index_ / num_samples_ counts samples <nl> + / / in the current shape / class / font combination . <nl> + int sample_index_ ; <nl> + int num_samples_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + # endif / / TESSERACT_CLASSIFY_SAMPLEITERATOR_H_ <nl> new file mode 100644 <nl> index 000000000 . . 08808127f <nl> mmm / dev / null <nl> ppp b / classify / shapeclassifier . h <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : shapeclassifier . h <nl> + / / Description : Base interface class for classifiers that return a <nl> + / / shape index . <nl> + / / Author : Ray Smith <nl> + / / Created : Tue Sep 13 11 : 26 : 32 PDT 2011 <nl> + / / <nl> + / / ( C ) Copyright 2011 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_CLASSIFY_SHAPECLASSIFIER_H_ <nl> + # define TESSERACT_CLASSIFY_SHAPECLASSIFIER_H_ <nl> + <nl> + template < typename T > class GenericVector ; <nl> + struct Pix ; <nl> + <nl> + namespace tesseract { <nl> + <nl> + class ShapeTable ; <nl> + class TrainingSample ; <nl> + <nl> + / / Classifier result from a low - level classification is an index into some <nl> + / / ShapeTable and a rating . <nl> + struct ShapeRating { <nl> + ShapeRating ( ) : shape_id ( 0 ) , rating ( 0 . 0f ) , raw ( 0 . 0f ) , font ( 0 . 0f ) { } <nl> + ShapeRating ( int s , float r ) <nl> + : shape_id ( s ) , rating ( r ) , raw ( 1 . 0f ) , font ( 0 . 0f ) { } <nl> + <nl> + / / Sort function to sort ratings appropriately by descending rating . <nl> + static int SortDescendingRating ( const void * t1 , const void * t2 ) { <nl> + const ShapeRating * a = reinterpret_cast < const ShapeRating * > ( t1 ) ; <nl> + const ShapeRating * b = reinterpret_cast < const ShapeRating * > ( t2 ) ; <nl> + if ( a - > rating > b - > rating ) { <nl> + return - 1 ; <nl> + } else if ( a - > rating < b - > rating ) { <nl> + return 1 ; <nl> + } else { <nl> + return a - > shape_id - b - > shape_id ; <nl> + } <nl> + } <nl> + <nl> + / / Index into some shape table indicates the class of the answer . <nl> + int shape_id ; <nl> + / / Rating from classifier with 1 . 0 perfect and 0 . 0 impossible . <nl> + / / Call it a probability if you must . <nl> + float rating ; <nl> + / / Subsidiary rating that a classifier may use internally . <nl> + float raw ; <nl> + / / Subsidiary rating that a classifier may use internally . <nl> + float font ; <nl> + } ; <nl> + <nl> + / / Interface base class for classifiers that produce ShapeRating results . <nl> + class ShapeClassifier { <nl> + public : <nl> + virtual ~ ShapeClassifier ( ) { } <nl> + <nl> + / / Classifies the given [ training ] sample , writing to results . <nl> + / / If page_pix is not NULL , the overriding function may call <nl> + / / sample . GetSamplePix ( padding , page_pix ) to get an image of the sample <nl> + / / padded ( with real image data ) by the given padding to extract features <nl> + / / from the image of the character . Other members of TrainingSample : <nl> + / / features ( ) , micro_features ( ) , cn_feature ( ) , geo_feature ( ) may be used <nl> + / / to get the appropriate tesseract features . <nl> + / / If debug is non - zero , then various degrees of classifier dependent debug <nl> + / / information is provided . <nl> + / / If keep_this ( a shape index ) is > = 0 , then the results should always <nl> + / / contain keep_this , and ( if possible ) anything of intermediate confidence . <nl> + / / ( Used for answering " Why didn ' t it get that right ? " questions . ) <nl> + / / The return value is the number of classes saved in results . <nl> + / / NOTE that overriding functions MUST clear results unless the classifier <nl> + / / is working with a team of such classifiers . <nl> + virtual int ClassifySample ( const TrainingSample & sample , Pix * page_pix , <nl> + int debug , int keep_this , <nl> + GenericVector < ShapeRating > * results ) = 0 ; <nl> + <nl> + / / Provides access to the ShapeTable that this classifier works with . <nl> + virtual const ShapeTable * GetShapeTable ( ) const = 0 ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + # endif / / TESSERACT_CLASSIFY_SHAPECLASSIFIER_H_ <nl> new file mode 100644 <nl> index 000000000 . . 9d4565262 <nl> mmm / dev / null <nl> ppp b / classify / shapetable . cpp <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : shapetable . cpp <nl> + / / Description : Class to map a classifier shape index to unicharset <nl> + / / indices and font indices . <nl> + / / Author : Ray Smith <nl> + / / Created : Tue Nov 02 15 : 31 : 32 PDT 2010 <nl> + / / <nl> + / / ( C ) Copyright 2010 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " shapetable . h " <nl> + <nl> + # include " intfeaturespace . h " <nl> + # include " strngs . h " <nl> + # include " unicharset . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool UnicharAndFonts : : Serialize ( FILE * fp ) { <nl> + inT32 uni_id = unichar_id ; <nl> + if ( fwrite ( & uni_id , sizeof ( uni_id ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( ! font_ids . Serialize ( fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool UnicharAndFonts : : DeSerialize ( bool swap , FILE * fp ) { <nl> + inT32 uni_id ; <nl> + if ( fread ( & uni_id , sizeof ( uni_id ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( swap ) <nl> + ReverseN ( & uni_id , sizeof ( uni_id ) ) ; <nl> + unichar_id = uni_id ; <nl> + if ( ! font_ids . DeSerialize ( swap , fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Sort function to sort a pair of UnicharAndFonts by unichar_id . <nl> + int UnicharAndFonts : : SortByUnicharId ( const void * v1 , const void * v2 ) { <nl> + const UnicharAndFonts * p1 = reinterpret_cast < const UnicharAndFonts * > ( v1 ) ; <nl> + const UnicharAndFonts * p2 = reinterpret_cast < const UnicharAndFonts * > ( v2 ) ; <nl> + return p1 - > unichar_id - p2 - > unichar_id ; <nl> + } <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Shape : : Serialize ( FILE * fp ) { <nl> + if ( fwrite ( & unichars_sorted_ , sizeof ( unichars_sorted_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( ! unichars_ . SerializeClasses ( fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool Shape : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( fread ( & unichars_sorted_ , sizeof ( unichars_sorted_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( ! unichars_ . DeSerializeClasses ( swap , fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Adds a font_id for the given unichar_id . If the unichar_id is not <nl> + / / in the shape , it is added . <nl> + void Shape : : AddToShape ( int unichar_id , int font_id ) { <nl> + for ( int c = 0 ; c < unichars_ . size ( ) ; + + c ) { <nl> + if ( unichars_ [ c ] . unichar_id = = unichar_id ) { <nl> + / / Found the unichar in the shape table . <nl> + GenericVector < int > & font_list = unichars_ [ c ] . font_ids ; <nl> + for ( int f = 0 ; f < font_list . size ( ) ; + + f ) { <nl> + if ( font_list [ f ] = = font_id ) <nl> + return ; / / Font is already there . <nl> + } <nl> + font_list . push_back ( font_id ) ; <nl> + return ; <nl> + } <nl> + } <nl> + / / Unichar_id is not in shape , so add it to shape . <nl> + unichars_ . push_back ( UnicharAndFonts ( unichar_id , font_id ) ) ; <nl> + unichars_sorted_ = unichars_ . size ( ) < = 1 ; <nl> + } <nl> + <nl> + / / Adds everything in other to this . <nl> + void Shape : : AddShape ( const Shape & other ) { <nl> + for ( int c = 0 ; c < other . unichars_ . size ( ) ; + + c ) { <nl> + for ( int f = 0 ; f < other . unichars_ [ c ] . font_ids . size ( ) ; + + f ) { <nl> + AddToShape ( other . unichars_ [ c ] . unichar_id , <nl> + other . unichars_ [ c ] . font_ids [ f ] ) ; <nl> + } <nl> + } <nl> + unichars_sorted_ = unichars_ . size ( ) < = 1 ; <nl> + } <nl> + <nl> + / / Returns true if the shape contains the given unichar_id , font_id pair . <nl> + bool Shape : : ContainsUnicharAndFont ( int unichar_id , int font_id ) const { <nl> + for ( int c = 0 ; c < unichars_ . size ( ) ; + + c ) { <nl> + if ( unichars_ [ c ] . unichar_id = = unichar_id ) { <nl> + / / Found the unichar , so look for the font . <nl> + GenericVector < int > & font_list = unichars_ [ c ] . font_ids ; <nl> + for ( int f = 0 ; f < font_list . size ( ) ; + + f ) { <nl> + if ( font_list [ f ] = = font_id ) <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + / / Returns true if the shape contains the given unichar_id , ignoring font . <nl> + bool Shape : : ContainsUnichar ( int unichar_id ) const { <nl> + for ( int c = 0 ; c < unichars_ . size ( ) ; + + c ) { <nl> + if ( unichars_ [ c ] . unichar_id = = unichar_id ) { <nl> + return true ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + / / Returns true if the shape contains the given font , ignoring unichar_id . <nl> + bool Shape : : ContainsFont ( int font_id ) const { <nl> + for ( int c = 0 ; c < unichars_ . size ( ) ; + + c ) { <nl> + GenericVector < int > & font_list = unichars_ [ c ] . font_ids ; <nl> + for ( int f = 0 ; f < font_list . size ( ) ; + + f ) { <nl> + if ( font_list [ f ] = = font_id ) <nl> + return true ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + / / Returns true if this is a subset ( including equal ) of other . <nl> + bool Shape : : IsSubsetOf ( const Shape & other ) const { <nl> + for ( int c = 0 ; c < unichars_ . size ( ) ; + + c ) { <nl> + int unichar_id = unichars_ [ c ] . unichar_id ; <nl> + const GenericVector < int > & font_list = unichars_ [ c ] . font_ids ; <nl> + for ( int f = 0 ; f < font_list . size ( ) ; + + f ) { <nl> + if ( ! other . ContainsUnicharAndFont ( unichar_id , font_list [ f ] ) ) <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + / / Returns true if the lists of unichar ids are the same in this and other , <nl> + / / ignoring fonts . <nl> + / / NOT const , as it will sort the unichars on demand . <nl> + bool Shape : : IsEqualUnichars ( Shape * other ) { <nl> + if ( unichars_ . size ( ) ! = other - > unichars_ . size ( ) ) return false ; <nl> + if ( ! unichars_sorted_ ) SortUnichars ( ) ; <nl> + if ( ! other - > unichars_sorted_ ) other - > SortUnichars ( ) ; <nl> + for ( int c = 0 ; c < unichars_ . size ( ) ; + + c ) { <nl> + if ( unichars_ [ c ] . unichar_id ! = other - > unichars_ [ c ] . unichar_id ) <nl> + return false ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + / / Sorts the unichars_ vector by unichar . <nl> + void Shape : : SortUnichars ( ) { <nl> + unichars_ . sort ( UnicharAndFonts : : SortByUnicharId ) ; <nl> + unichars_sorted_ = true ; <nl> + } <nl> + <nl> + ShapeTable : : ShapeTable ( ) : unicharset_ ( NULL ) { <nl> + } <nl> + ShapeTable : : ShapeTable ( const UNICHARSET & unicharset ) <nl> + : unicharset_ ( & unicharset ) { <nl> + } <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool ShapeTable : : Serialize ( FILE * fp ) const { <nl> + if ( ! shape_table_ . Serialize ( fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool ShapeTable : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( ! shape_table_ . DeSerialize ( swap , fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Returns a string listing the classes / fonts in a shape . <nl> + STRING ShapeTable : : DebugStr ( int shape_id ) const { <nl> + if ( shape_id < 0 | | shape_id > = shape_table_ . size ( ) ) <nl> + return STRING ( " INVALID_UNICHAR_ID " ) ; <nl> + const Shape & shape = GetShape ( shape_id ) ; <nl> + STRING result ; <nl> + result . add_str_int ( " Shape " , shape_id ) ; <nl> + for ( int c = 0 ; c < shape . size ( ) ; + + c ) { <nl> + result . add_str_int ( " c_id = " , shape [ c ] . unichar_id ) ; <nl> + result + = " = " ; <nl> + result + = unicharset_ - > id_to_unichar ( shape [ c ] . unichar_id ) ; <nl> + result . add_str_int ( " , " , shape [ c ] . font_ids . size ( ) ) ; <nl> + result + = " fonts = " ; <nl> + for ( int f = 0 ; f < shape [ c ] . font_ids . size ( ) ; + + f ) { <nl> + result . add_str_int ( " " , shape [ c ] . font_ids [ f ] ) ; <nl> + } <nl> + } <nl> + return result ; <nl> + } <nl> + <nl> + / / Returns a debug string summarizing the table . <nl> + STRING ShapeTable : : SummaryStr ( ) const { <nl> + int max_unichars = 0 ; <nl> + int num_multi_shapes = 0 ; <nl> + int num_master_shapes = 0 ; <nl> + for ( int s = 0 ; s < shape_table_ . size ( ) ; + + s ) { <nl> + if ( MasterDestinationIndex ( s ) ! = s ) continue ; <nl> + + + num_master_shapes ; <nl> + int shape_size = GetShape ( s ) . size ( ) ; <nl> + if ( shape_size > 1 ) <nl> + + + num_multi_shapes ; <nl> + if ( shape_size > max_unichars ) <nl> + max_unichars = shape_size ; <nl> + } <nl> + STRING result ; <nl> + result . add_str_int ( " Number of shapes = " , num_master_shapes ) ; <nl> + result . add_str_int ( " max unichars = " , max_unichars ) ; <nl> + result . add_str_int ( " number with multiple unichars = " , num_multi_shapes ) ; <nl> + return result ; <nl> + } <nl> + <nl> + <nl> + / / Adds a new shape starting with the given unichar_id and font_id . <nl> + / / Returns the assigned index . <nl> + int ShapeTable : : AddShape ( int unichar_id , int font_id ) { <nl> + int index = shape_table_ . size ( ) ; <nl> + Shape * shape = new Shape ; <nl> + shape - > AddToShape ( unichar_id , font_id ) ; <nl> + shape_table_ . push_back ( shape ) ; <nl> + return index ; <nl> + } <nl> + <nl> + / / Adds a copy of the given shape . <nl> + / / Returns the assigned index . <nl> + int ShapeTable : : AddShape ( const Shape & other ) { <nl> + int index = shape_table_ . size ( ) ; <nl> + Shape * shape = new Shape ( other ) ; <nl> + shape_table_ . push_back ( shape ) ; <nl> + return index ; <nl> + } <nl> + <nl> + / / Removes the shape given by the shape index . <nl> + void ShapeTable : : DeleteShape ( int shape_id ) { <nl> + delete shape_table_ [ shape_id ] ; <nl> + shape_table_ [ shape_id ] = NULL ; <nl> + shape_table_ . remove ( shape_id ) ; <nl> + } <nl> + <nl> + / / Adds a font_id to the given existing shape index for the given <nl> + / / unichar_id . If the unichar_id is not in the shape , it is added . <nl> + void ShapeTable : : AddToShape ( int shape_id , int unichar_id , int font_id ) { <nl> + Shape & shape = * shape_table_ [ shape_id ] ; <nl> + shape . AddToShape ( unichar_id , font_id ) ; <nl> + } <nl> + <nl> + / / Adds the given shape to the existing shape with the given index . <nl> + void ShapeTable : : AddShapeToShape ( int shape_id , const Shape & other ) { <nl> + Shape & shape = * shape_table_ [ shape_id ] ; <nl> + shape . AddShape ( other ) ; <nl> + } <nl> + <nl> + / / Returns the id of the shape that contains the given unichar and font . <nl> + / / If not found , returns - 1 . <nl> + / / If font_id < 0 , the font_id is ignored and the first shape that matches <nl> + / / the unichar_id is returned . <nl> + int ShapeTable : : FindShape ( int unichar_id , int font_id ) const { <nl> + for ( int s = 0 ; s < shape_table_ . size ( ) ; + + s ) { <nl> + const Shape & shape = GetShape ( s ) ; <nl> + for ( int c = 0 ; c < shape . size ( ) ; + + c ) { <nl> + if ( shape [ c ] . unichar_id = = unichar_id ) { <nl> + if ( font_id < 0 ) <nl> + return s ; / / We don ' t care about the font . <nl> + for ( int f = 0 ; f < shape [ c ] . font_ids . size ( ) ; + + f ) { <nl> + if ( shape [ c ] . font_ids [ f ] = = font_id ) <nl> + return s ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + return - 1 ; <nl> + } <nl> + <nl> + / / Returns the first unichar_id and font_id in the given shape . <nl> + void ShapeTable : : GetFirstUnicharAndFont ( int shape_id , <nl> + int * unichar_id , int * font_id ) const { <nl> + const UnicharAndFonts & unichar_and_fonts = ( * shape_table_ [ shape_id ] ) [ 0 ] ; <nl> + * unichar_id = unichar_and_fonts . unichar_id ; <nl> + * font_id = unichar_and_fonts . font_ids [ 0 ] ; <nl> + } <nl> + <nl> + / / Expands all the classes / fonts in the shape individually to build <nl> + / / a ShapeTable . <nl> + int ShapeTable : : BuildFromShape ( const Shape & shape , <nl> + const ShapeTable & master_shapes ) { <nl> + int num_masters = 0 ; <nl> + for ( int u_ind = 0 ; u_ind < shape . size ( ) ; + + u_ind ) { <nl> + for ( int f_ind = 0 ; f_ind < shape [ u_ind ] . font_ids . size ( ) ; + + f_ind ) { <nl> + int c = shape [ u_ind ] . unichar_id ; <nl> + int f = shape [ u_ind ] . font_ids [ f_ind ] ; <nl> + if ( FindShape ( c , f ) < 0 ) { <nl> + int shape_id = AddShape ( c , f ) ; <nl> + int master_id = master_shapes . FindShape ( c , f ) ; <nl> + if ( master_id > = 0 & & shape . size ( ) > 1 ) { <nl> + const Shape & master = master_shapes . GetShape ( master_id ) ; <nl> + if ( master . IsSubsetOf ( shape ) & & ! shape . IsSubsetOf ( master ) ) { <nl> + / / Add everything else from the master shape . <nl> + shape_table_ [ shape_id ] - > AddShape ( master ) ; <nl> + + + num_masters ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + return num_masters ; <nl> + } <nl> + <nl> + / / Returns true if the shapes are already merged . <nl> + bool ShapeTable : : AlreadyMerged ( int shape_id1 , int shape_id2 ) { <nl> + return MasterDestinationIndex ( shape_id1 ) = = MasterDestinationIndex ( shape_id2 ) ; <nl> + } <nl> + <nl> + / / Returns true if any shape contains multiple unichars . <nl> + bool ShapeTable : : AnyMultipleUnichars ( ) { <nl> + int num_shapes = NumShapes ( ) ; <nl> + for ( int s1 = 0 ; s1 < num_shapes ; + + s1 ) { <nl> + if ( MasterDestinationIndex ( s1 ) ! = s1 ) continue ; <nl> + if ( GetShape ( s1 ) . size ( ) > 1 ) <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + / / Returns the maximum number of unichars over all shapes . <nl> + int ShapeTable : : MaxNumUnichars ( ) const { <nl> + int max_num_unichars = 0 ; <nl> + int num_shapes = NumShapes ( ) ; <nl> + for ( int s = 0 ; s < num_shapes ; + + s ) { <nl> + if ( GetShape ( s ) . size ( ) > max_num_unichars ) <nl> + max_num_unichars = GetShape ( s ) . size ( ) ; <nl> + } <nl> + return max_num_unichars ; <nl> + } <nl> + <nl> + <nl> + / / Merges shapes with a common unichar over the [ start , end ) interval . <nl> + / / Assumes single unichar per shape . <nl> + void ShapeTable : : ForceFontMerges ( int start , int end ) { <nl> + for ( int s1 = start ; s1 < end ; + + s1 ) { <nl> + if ( MasterDestinationIndex ( s1 ) = = s1 & & GetShape ( s1 ) . size ( ) = = 1 ) { <nl> + int unichar_id = GetShape ( s1 ) [ 0 ] . unichar_id ; <nl> + for ( int s2 = s1 + 1 ; s2 < end ; + + s2 ) { <nl> + if ( MasterDestinationIndex ( s2 ) = = s2 & & GetShape ( s2 ) . size ( ) = = 1 & & <nl> + unichar_id = = GetShape ( s2 ) [ 0 ] . unichar_id ) { <nl> + MergeShapes ( s1 , s2 ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + ShapeTable compacted ( * unicharset_ ) ; <nl> + compacted . AppendMasterShapes ( * this ) ; <nl> + * this = compacted ; <nl> + } <nl> + <nl> + / / Returns the number of unichars in the master shape . <nl> + int ShapeTable : : MasterUnicharCount ( int shape_id ) const { <nl> + int master_id = MasterDestinationIndex ( shape_id ) ; <nl> + return GetShape ( master_id ) . size ( ) ; <nl> + } <nl> + <nl> + / / Returns the sum of the font counts in the master shape . <nl> + int ShapeTable : : MasterFontCount ( int shape_id ) const { <nl> + int master_id = MasterDestinationIndex ( shape_id ) ; <nl> + const Shape & shape = GetShape ( master_id ) ; <nl> + int font_count = 0 ; <nl> + for ( int c = 0 ; c < shape . size ( ) ; + + c ) { <nl> + font_count + = shape [ c ] . font_ids . size ( ) ; <nl> + } <nl> + return font_count ; <nl> + } <nl> + <nl> + / / Returns the number of unichars that would result from merging the shapes . <nl> + int ShapeTable : : MergedUnicharCount ( int shape_id1 , int shape_id2 ) const { <nl> + / / Do it the easy way for now . <nl> + int master_id1 = MasterDestinationIndex ( shape_id1 ) ; <nl> + int master_id2 = MasterDestinationIndex ( shape_id2 ) ; <nl> + Shape combined_shape ( * shape_table_ [ master_id1 ] ) ; <nl> + combined_shape . AddShape ( * shape_table_ [ master_id2 ] ) ; <nl> + return combined_shape . size ( ) ; <nl> + } <nl> + <nl> + / / Merges two shape_ids , leaving shape_id2 marked as merged . <nl> + void ShapeTable : : MergeShapes ( int shape_id1 , int shape_id2 ) { <nl> + int master_id1 = MasterDestinationIndex ( shape_id1 ) ; <nl> + int master_id2 = MasterDestinationIndex ( shape_id2 ) ; <nl> + / / Point master_id2 ( and all merged shapes ) to master_id1 . <nl> + shape_table_ [ master_id2 ] - > set_destination_index ( master_id1 ) ; <nl> + / / Add all the shapes of master_id2 to master_id1 . <nl> + shape_table_ [ master_id1 ] - > AddShape ( * shape_table_ [ master_id2 ] ) ; <nl> + tprintf ( " Merged shape % d - > % d , % d - > % d , now with % d unichars : % s \ n " , <nl> + shape_id1 , master_id1 , shape_id2 , master_id2 , <nl> + shape_table_ [ master_id1 ] - > size ( ) , <nl> + DebugStr ( master_id1 ) . string ( ) ) ; <nl> + } <nl> + <nl> + / / Returns the destination of this shape , ( if merged ) , taking into account <nl> + / / the fact that the destination may itself have been merged . <nl> + int ShapeTable : : MasterDestinationIndex ( int shape_id ) const { <nl> + int dest_id = shape_table_ [ shape_id ] - > destination_index ( ) ; <nl> + if ( dest_id = = shape_id | | dest_id < 0 ) <nl> + return shape_id ; / / Is master already . <nl> + int master_id = shape_table_ [ dest_id ] - > destination_index ( ) ; <nl> + if ( master_id = = dest_id | | master_id < 0 ) <nl> + return dest_id ; / / Dest is the master and shape_id points to it . <nl> + master_id = MasterDestinationIndex ( master_id ) ; <nl> + return master_id ; <nl> + } <nl> + <nl> + / / Appends the master shapes from other to this . <nl> + void ShapeTable : : AppendMasterShapes ( const ShapeTable & other ) { <nl> + for ( int s = 0 ; s < other . shape_table_ . size ( ) ; + + s ) { <nl> + if ( other . shape_table_ [ s ] - > destination_index ( ) < 0 ) { <nl> + AddShape ( * other . shape_table_ [ s ] ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Returns the number of master shapes remaining after merging . <nl> + int ShapeTable : : NumMasterShapes ( ) const { <nl> + int num_shapes = 0 ; <nl> + for ( int s = 0 ; s < shape_table_ . size ( ) ; + + s ) { <nl> + if ( shape_table_ [ s ] - > destination_index ( ) < 0 ) <nl> + + + num_shapes ; <nl> + } <nl> + return num_shapes ; <nl> + } <nl> + <nl> + <nl> + } / / namespace tesseract <nl> + <nl> + <nl> new file mode 100644 <nl> index 000000000 . . 375f334eb <nl> mmm / dev / null <nl> ppp b / classify / shapetable . h <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : shapetable . h <nl> + / / Description : Class to map a classifier shape index to unicharset <nl> + / / indices and font indices . <nl> + / / Author : Ray Smith <nl> + / / Created : Thu Oct 28 17 : 46 : 32 PDT 2010 <nl> + / / <nl> + / / ( C ) Copyright 2010 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_CLASSIFY_SHAPETABLE_H_ <nl> + # define TESSERACT_CLASSIFY_SHAPETABLE_H_ <nl> + <nl> + # include " genericvector . h " <nl> + # include " intmatcher . h " <nl> + <nl> + class STRING ; <nl> + class UNICHARSET ; <nl> + <nl> + namespace tesseract { <nl> + <nl> + / / Simple struct to hold a set of fonts associated with a single unichar - id . <nl> + / / A vector of UnicharAndFonts makes a shape . <nl> + struct UnicharAndFonts { <nl> + UnicharAndFonts ( ) : unichar_id ( 0 ) { <nl> + } <nl> + UnicharAndFonts ( int uni_id , int font_id ) : unichar_id ( uni_id ) { <nl> + font_ids . push_back ( font_id ) ; <nl> + } <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Sort function to sort a pair of UnicharAndFonts by unichar_id . <nl> + static int SortByUnicharId ( const void * v1 , const void * v2 ) ; <nl> + <nl> + GenericVector < int > font_ids ; <nl> + int unichar_id ; <nl> + } ; <nl> + <nl> + / / A Shape is a collection of unichar - ids and a list of fonts associated with <nl> + / / each , organized as a vector of UnicharAndFonts . Conceptually a Shape is <nl> + / / a classifiable unit , and represents a group of characters or parts of <nl> + / / characters that have a similar or identical shape . Shapes / ShapeTables may <nl> + / / be organized hierarchically from identical shapes at the leaves to vaguely <nl> + / / similar shapes near the root . <nl> + class Shape { <nl> + public : <nl> + Shape ( ) : destination_index_ ( - 1 ) { } <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + int destination_index ( ) const { <nl> + return destination_index_ ; <nl> + } <nl> + void set_destination_index ( int index ) { <nl> + destination_index_ = index ; <nl> + } <nl> + int size ( ) const { <nl> + return unichars_ . size ( ) ; <nl> + } <nl> + / / Returns a UnicharAndFonts entry for the given index , which must be <nl> + / / in the range [ 0 , size ( ) ) . <nl> + const UnicharAndFonts & operator [ ] ( int index ) const { <nl> + return unichars_ [ index ] ; <nl> + } <nl> + / / Adds a font_id for the given unichar_id . If the unichar_id is not <nl> + / / in the shape , it is added . <nl> + void AddToShape ( int unichar_id , int font_id ) ; <nl> + / / Adds everything in other to this . <nl> + void AddShape ( const Shape & other ) ; <nl> + / / Returns true if the shape contains the given unichar_id , font_id pair . <nl> + bool ContainsUnicharAndFont ( int unichar_id , int font_id ) const ; <nl> + / / Returns true if the shape contains the given unichar_id , ignoring font . <nl> + bool ContainsUnichar ( int unichar_id ) const ; <nl> + / / Returns true if the shape contains the given font , ignoring unichar_id . <nl> + bool ContainsFont ( int font_id ) const ; <nl> + / / Returns true if this is a subset ( including equal ) of other . <nl> + bool IsSubsetOf ( const Shape & other ) const ; <nl> + / / Returns true if the lists of unichar ids are the same in this and other , <nl> + / / ignoring fonts . <nl> + / / NOT const , as it will sort the unichars on demand . <nl> + bool IsEqualUnichars ( Shape * other ) ; <nl> + <nl> + private : <nl> + / / Sorts the unichars_ vector by unichar . <nl> + void SortUnichars ( ) ; <nl> + <nl> + / / Flag indicates that the unichars are sorted , allowing faster set <nl> + / / operations with another shape . <nl> + bool unichars_sorted_ ; <nl> + / / If this Shape is part of a ShapeTable the destiation_index_ is the index <nl> + / / of some other shape in the ShapeTable with which this shape is merged . <nl> + int destination_index_ ; <nl> + / / Array of unichars , each with a set of fonts . Each unichar has at most <nl> + / / one entry in the vector . <nl> + GenericVector < UnicharAndFonts > unichars_ ; <nl> + } ; <nl> + <nl> + / / ShapeTable is a class to encapsulate the triple indirection that is <nl> + / / used here . <nl> + / / ShapeTable is a vector of shapes . <nl> + / / Each shape is a vector of UnicharAndFonts representing the set of unichars <nl> + / / that the shape represents . <nl> + / / Each UnicharAndFonts also lists the fonts of the unichar_id that were <nl> + / / mapped to the shape during training . <nl> + class ShapeTable { <nl> + public : <nl> + ShapeTable ( ) ; <nl> + / / The UNICHARSET reference supplied here , or in set_unicharset below must <nl> + / / exist for the entire life of the ShapeTable . It is used only by DebugStr . <nl> + explicit ShapeTable ( const UNICHARSET & unicharset ) ; <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) const ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Accessors . <nl> + int NumShapes ( ) const { <nl> + return shape_table_ . size ( ) ; <nl> + } <nl> + const UNICHARSET & unicharset ( ) const { <nl> + return * unicharset_ ; <nl> + } <nl> + / / Shapetable takes a pointer to the UNICHARSET , so it must persist for the <nl> + / / entire life of the ShapeTable . <nl> + void set_unicharset ( const UNICHARSET & unicharset ) { <nl> + unicharset_ = & unicharset ; <nl> + } <nl> + / / Returns a string listing the classes / fonts in a shape . <nl> + STRING DebugStr ( int shape_id ) const ; <nl> + / / Returns a debug string summarizing the table . <nl> + STRING SummaryStr ( ) const ; <nl> + <nl> + / / Adds a new shape starting with the given unichar_id and font_id . <nl> + / / Returns the assigned index . <nl> + int AddShape ( int unichar_id , int font_id ) ; <nl> + / / Adds a copy of the given shape . <nl> + / / Returns the assigned index . <nl> + int AddShape ( const Shape & other ) ; <nl> + / / Removes the shape given by the shape index . All indices above are changed ! <nl> + void DeleteShape ( int shape_id ) ; <nl> + / / Adds a font_id to the given existing shape index for the given <nl> + / / unichar_id . If the unichar_id is not in the shape , it is added . <nl> + void AddToShape ( int shape_id , int unichar_id , int font_id ) ; <nl> + / / Adds the given shape to the existing shape with the given index . <nl> + void AddShapeToShape ( int shape_id , const Shape & other ) ; <nl> + / / Returns the id of the shape that contains the given unichar and font . <nl> + / / If not found , returns - 1 . <nl> + / / If font_id < 0 , the font_id is ignored and the first shape that matches <nl> + / / the unichar_id is returned . <nl> + int FindShape ( int unichar_id , int font_id ) const ; <nl> + / / Returns the first unichar_id and font_id in the given shape . <nl> + void GetFirstUnicharAndFont ( int shape_id , <nl> + int * unichar_id , int * font_id ) const ; <nl> + <nl> + / / Accessors for the Shape with the given shape_id . <nl> + const Shape & GetShape ( int shape_id ) const { <nl> + return * shape_table_ [ shape_id ] ; <nl> + } <nl> + Shape * MutableShape ( int shape_id ) { <nl> + return shape_table_ [ shape_id ] ; <nl> + } <nl> + <nl> + / / Expands all the classes / fonts in the shape individually to build <nl> + / / a ShapeTable . <nl> + int BuildFromShape ( const Shape & shape , const ShapeTable & master_shapes ) ; <nl> + <nl> + / / Returns true if the shapes are already merged . <nl> + bool AlreadyMerged ( int shape_id1 , int shape_id2 ) ; <nl> + / / Returns true if any shape contains multiple unichars . <nl> + bool AnyMultipleUnichars ( ) ; <nl> + / / Returns the maximum number of unichars over all shapes . <nl> + int MaxNumUnichars ( ) const ; <nl> + / / Merges shapes with a common unichar over the [ start , end ) interval . <nl> + / / Assumes single unichar per shape . <nl> + void ForceFontMerges ( int start , int end ) ; <nl> + / / Returns the number of unichars in the master shape . <nl> + int MasterUnicharCount ( int shape_id ) const ; <nl> + / / Returns the sum of the font counts in the master shape . <nl> + int MasterFontCount ( int shape_id ) const ; <nl> + / / Returns the number of unichars that would result from merging the shapes . <nl> + int MergedUnicharCount ( int shape_id1 , int shape_id2 ) const ; <nl> + / / Merges two shape_ids , leaving shape_id2 marked as merged . <nl> + void MergeShapes ( int shape_id1 , int shape_id2 ) ; <nl> + / / Appends the master shapes from other to this . <nl> + / / Used to create a clean ShapeTable from a merged one , or to create a <nl> + / / copy of a ShapeTable . <nl> + void AppendMasterShapes ( const ShapeTable & other ) ; <nl> + / / Returns the number of master shapes remaining after merging . <nl> + int NumMasterShapes ( ) const ; <nl> + / / Returns the destination of this shape , ( if merged ) , taking into account <nl> + / / the fact that the destination may itself have been merged . <nl> + / / For a non - merged shape , returns the input shape_id . <nl> + int MasterDestinationIndex ( int shape_id ) const ; <nl> + <nl> + private : <nl> + / / Pointer to a provided unicharset used only by the Debugstr member . <nl> + const UNICHARSET * unicharset_ ; <nl> + / / Vector of pointers to the Shapes in this ShapeTable . <nl> + PointerVector < Shape > shape_table_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + # endif / / TESSERACT_CLASSIFY_SHAPETABLE_H_ <nl> mmm a / classify / speckle . cpp <nl> ppp b / classify / speckle . cpp <nl> void AddLargeSpeckleTo ( BLOB_CHOICE_LIST * Choices ) { <nl> if ( Choices - > length ( ) = = 0 ) { <nl> blob_choice = <nl> new BLOB_CHOICE ( 0 , speckle_small_certainty + speckle_large_penalty , <nl> - speckle_small_certainty , - 1 , - 1 , NULL ) ; <nl> + speckle_small_certainty , - 1 , - 1 , NULL , 0 , 0 , false ) ; <nl> temp_it . add_to_end ( blob_choice ) ; <nl> return ; <nl> } <nl> void AddLargeSpeckleTo ( BLOB_CHOICE_LIST * Choices ) { <nl> blob_choice = temp_it . data ( ) ; / / pick the worst choice <nl> temp_it . add_to_end ( <nl> new BLOB_CHOICE ( 0 , blob_choice - > rating ( ) + speckle_large_penalty , <nl> - blob_choice - > certainty ( ) , - 1 , - 1 , NULL ) ) ; <nl> + blob_choice - > certainty ( ) , - 1 , - 1 , NULL , 0 , 0 , false ) ) ; <nl> } / * AddLargeSpeckleTo * / <nl> <nl> <nl> void AddLargeSpeckleTo ( BLOB_CHOICE_LIST * Choices ) { <nl> * <nl> * @ return TRUE if Blob is speckle , FALSE otherwise . <nl> * / <nl> - BOOL8 LargeSpeckle ( TBLOB * Blob ) { <nl> - double speckle_size ; <nl> - TPOINT TopLeft ; <nl> - TPOINT BottomRight ; <nl> - <nl> - speckle_size = BASELINE_SCALE * speckle_large_max_size ; <nl> - blob_bounding_box ( Blob , & TopLeft , & BottomRight ) ; <nl> - <nl> - if ( TopLeft . y - BottomRight . y < speckle_size & & <nl> - BottomRight . x - TopLeft . x < speckle_size ) <nl> - return ( TRUE ) ; <nl> - else <nl> - return ( FALSE ) ; <nl> - <nl> + BOOL8 LargeSpeckle ( TBLOB * blob ) { <nl> + double speckle_size = BASELINE_SCALE * speckle_large_max_size ; <nl> + TBOX bbox = blob - > bounding_box ( ) ; <nl> + return ( bbox . width ( ) < speckle_size & & bbox . height ( ) < speckle_size ) ; <nl> } / * LargeSpeckle * / <nl> new file mode 100644 <nl> index 000000000 . . f7735d8a2 <nl> mmm / dev / null <nl> ppp b / classify / tessclassifier . cpp <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : tessclassifier . cpp <nl> + / / Description : Tesseract implementation of a ShapeClassifier . <nl> + / / Author : Ray Smith <nl> + / / Created : Tue Nov 22 14 : 16 : 25 PST 2011 <nl> + / / <nl> + / / ( C ) Copyright 2011 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " tessclassifier . h " <nl> + <nl> + # include " classify . h " <nl> + # include " trainingsample . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + / / Classifies the given [ training ] sample , writing to results . <nl> + / / See ShapeClassifier for a full description . <nl> + int TessClassifier : : ClassifySample ( const TrainingSample & sample , <nl> + Pix * page_pix , int debug , int keep_this , <nl> + GenericVector < ShapeRating > * results ) { <nl> + if ( debug ) { <nl> + classify_ - > matcher_debug_level . set_value ( debug ? 2 : 0 ) ; <nl> + classify_ - > matcher_debug_flags . set_value ( debug ? 25 : 0 ) ; <nl> + classify_ - > classify_debug_level . set_value ( debug ? 3 : 0 ) ; <nl> + } else { <nl> + classify_ - > classify_debug_level . set_value ( debug ? 2 : 0 ) ; <nl> + } <nl> + classify_ - > CharNormTrainingSample ( pruner_only_ , sample , results ) ; <nl> + return results - > size ( ) ; <nl> + } <nl> + <nl> + / / Provides access to the ShapeTable that this classifier works with . <nl> + const ShapeTable * TessClassifier : : GetShapeTable ( ) const { <nl> + return classify_ - > shape_table ( ) ; <nl> + } <nl> + <nl> + } / / namespace tesseract <nl> + <nl> + <nl> new file mode 100644 <nl> index 000000000 . . f2483b7a0 <nl> mmm / dev / null <nl> ppp b / classify / tessclassifier . h <nl> <nl> + / / Copyright 2011 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / File : tessclassifier . h <nl> + / / Description : Tesseract implementation of a ShapeClassifier . <nl> + / / Author : Ray Smith <nl> + / / Created : Tue Nov 22 14 : 10 : 45 PST 2011 <nl> + / / <nl> + / / ( C ) Copyright 2011 , Google Inc . <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef THIRD_PARTY_TESSERACT_CLASSIFY_TESSCLASSIFIER_H_ <nl> + # define THIRD_PARTY_TESSERACT_CLASSIFY_TESSCLASSIFIER_H_ <nl> + <nl> + # include " shapeclassifier . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + class Classify ; <nl> + class TrainingSample ; <nl> + <nl> + / / Tesseract implementation of a ShapeClassifier . <nl> + / / Due to limitations in the content of TrainingSample , this currently <nl> + / / only works for the static classifier and only works if the ShapeTable <nl> + / / in classify is not NULL . <nl> + class TessClassifier : public ShapeClassifier { <nl> + public : <nl> + TessClassifier ( bool pruner_only , tesseract : : Classify * classify ) <nl> + : pruner_only_ ( pruner_only ) , classify_ ( classify ) { } <nl> + virtual ~ TessClassifier ( ) { } <nl> + <nl> + / / Classifies the given [ training ] sample , writing to results . <nl> + / / See ShapeClassifier for a full description . <nl> + virtual int ClassifySample ( const TrainingSample & sample , Pix * page_pix , <nl> + int debug , int keep_this , <nl> + GenericVector < ShapeRating > * results ) ; <nl> + / / Provides access to the ShapeTable that this classifier works with . <nl> + virtual const ShapeTable * GetShapeTable ( ) const ; <nl> + <nl> + private : <nl> + / / Indicates that this classifier is to use just the ClassPruner , or the <nl> + / / full classifier if false . <nl> + bool pruner_only_ ; <nl> + / / Borrowed pointer to the actual Tesseract classifier . <nl> + tesseract : : Classify * classify_ ; <nl> + } ; <nl> + <nl> + <nl> + } / / namespace tesseract <nl> + <nl> + <nl> + <nl> + <nl> + <nl> + # endif / * THIRD_PARTY_TESSERACT_CLASSIFY_TESSCLASSIFIER_H_ * / <nl> new file mode 100644 <nl> index 000000000 . . d712d8c26 <nl> mmm / dev / null <nl> ppp b / classify / trainingsample . cpp <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " trainingsample . h " <nl> + <nl> + # include < math . h > <nl> + # include " allheaders . h " <nl> + # include " helpers . h " <nl> + # include " intfeaturemap . h " <nl> + # include " normfeat . h " <nl> + # include " shapetable . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + ELISTIZE ( TrainingSample ) <nl> + <nl> + / / Center of randomizing operations . <nl> + const int kRandomizingCenter = 128 ; <nl> + <nl> + / / Randomizing factors . <nl> + const int TrainingSample : : kYShiftValues [ kSampleYShiftSize ] = { <nl> + 6 , 3 , - 3 , - 6 , 0 <nl> + } ; <nl> + const double TrainingSample : : kScaleValues [ kSampleScaleSize ] = { <nl> + 1 . 0625 , 0 . 9375 , 1 . 0 <nl> + } ; <nl> + <nl> + TrainingSample : : ~ TrainingSample ( ) { <nl> + delete [ ] features_ ; <nl> + delete [ ] micro_features_ ; <nl> + } <nl> + <nl> + / / WARNING ! Serialize / DeSerialize do not save / restore the " cache " data <nl> + / / members , which is mostly the mapped features , and the weight . <nl> + / / It is assumed these can all be reconstructed from what is saved . <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool TrainingSample : : Serialize ( FILE * fp ) const { <nl> + if ( fwrite ( & class_id_ , sizeof ( class_id_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( fwrite ( & font_id_ , sizeof ( font_id_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( fwrite ( & page_num_ , sizeof ( page_num_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( ! bounding_box_ . Serialize ( fp ) ) return false ; <nl> + if ( fwrite ( & num_features_ , sizeof ( num_features_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( fwrite ( & num_micro_features_ , sizeof ( num_micro_features_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fwrite ( features_ , sizeof ( * features_ ) , num_features_ , fp ) ! = num_features_ ) <nl> + return false ; <nl> + if ( fwrite ( micro_features_ , sizeof ( * micro_features_ ) , num_micro_features_ , <nl> + fp ) ! = num_micro_features_ ) <nl> + return false ; <nl> + if ( fwrite ( cn_feature_ , sizeof ( * cn_feature_ ) , kNumCNParams , fp ) ! = <nl> + kNumCNParams ) return false ; <nl> + if ( fwrite ( geo_feature_ , sizeof ( * geo_feature_ ) , GeoCount , fp ) ! = GeoCount ) <nl> + return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Creates from the given file . Returns NULL in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + TrainingSample * TrainingSample : : DeSerializeCreate ( bool swap , FILE * fp ) { <nl> + TrainingSample * sample = new TrainingSample ; <nl> + if ( sample - > DeSerialize ( swap , fp ) ) return sample ; <nl> + delete sample ; <nl> + return NULL ; <nl> + } <nl> + <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool TrainingSample : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( fread ( & class_id_ , sizeof ( class_id_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( fread ( & font_id_ , sizeof ( font_id_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( fread ( & page_num_ , sizeof ( page_num_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( ! bounding_box_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( fread ( & num_features_ , sizeof ( num_features_ ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( fread ( & num_micro_features_ , sizeof ( num_micro_features_ ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( swap ) { <nl> + ReverseN ( & class_id_ , sizeof ( class_id_ ) ) ; <nl> + ReverseN ( & num_features_ , sizeof ( num_features_ ) ) ; <nl> + ReverseN ( & num_micro_features_ , sizeof ( num_micro_features_ ) ) ; <nl> + } <nl> + delete [ ] features_ ; <nl> + features_ = new INT_FEATURE_STRUCT [ num_features_ ] ; <nl> + if ( fread ( features_ , sizeof ( * features_ ) , num_features_ , fp ) ! = num_features_ ) <nl> + return false ; <nl> + delete [ ] micro_features_ ; <nl> + micro_features_ = new MicroFeature [ num_micro_features_ ] ; <nl> + if ( fread ( micro_features_ , sizeof ( * micro_features_ ) , num_micro_features_ , <nl> + fp ) ! = num_micro_features_ ) <nl> + return false ; <nl> + if ( fread ( cn_feature_ , sizeof ( * cn_feature_ ) , kNumCNParams , fp ) ! = <nl> + kNumCNParams ) return false ; <nl> + if ( fread ( geo_feature_ , sizeof ( * geo_feature_ ) , GeoCount , fp ) ! = GeoCount ) <nl> + return false ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Saves the given features into a TrainingSample . <nl> + TrainingSample * TrainingSample : : CopyFromFeatures ( <nl> + const INT_FX_RESULT_STRUCT & fx_info , const INT_FEATURE_STRUCT * features , <nl> + int num_features ) { <nl> + TrainingSample * sample = new TrainingSample ; <nl> + sample - > num_features_ = num_features ; <nl> + sample - > features_ = new INT_FEATURE_STRUCT [ num_features ] ; <nl> + memcpy ( sample - > features_ , features , num_features * sizeof ( features [ 0 ] ) ) ; <nl> + sample - > geo_feature_ [ GeoBottom ] = fx_info . YBottom ; <nl> + sample - > geo_feature_ [ GeoTop ] = fx_info . YTop ; <nl> + sample - > geo_feature_ [ GeoWidth ] = fx_info . Width ; <nl> + sample - > features_are_indexed_ = false ; <nl> + sample - > features_are_mapped_ = false ; <nl> + return sample ; <nl> + } <nl> + <nl> + / / Constructs and returns a copy randomized by the method given by <nl> + / / the randomizer index . If index is out of [ 0 , kSampleRandomSize ) then <nl> + / / an exact copy is returned . <nl> + TrainingSample * TrainingSample : : RandomizedCopy ( int index ) const { <nl> + TrainingSample * sample = Copy ( ) ; <nl> + if ( index > = 0 & & index < kSampleRandomSize ) { <nl> + + + index ; / / Remove the first combination . <nl> + int yshift = kYShiftValues [ index / kSampleScaleSize ] ; <nl> + double scaling = kScaleValues [ index % kSampleScaleSize ] ; <nl> + for ( int i = 0 ; i < num_features_ ; + + i ) { <nl> + double result = ( features_ [ i ] . X - kRandomizingCenter ) * scaling ; <nl> + result + = kRandomizingCenter ; <nl> + sample - > features_ [ i ] . X = ClipToRange ( static_cast < int > ( result + 0 . 5 ) , 0 , <nl> + MAX_UINT8 ) ; <nl> + result = ( features_ [ i ] . Y - kRandomizingCenter ) * scaling ; <nl> + result + = kRandomizingCenter + yshift ; <nl> + sample - > features_ [ i ] . Y = ClipToRange ( static_cast < int > ( result + 0 . 5 ) , 0 , <nl> + MAX_UINT8 ) ; <nl> + } <nl> + } <nl> + return sample ; <nl> + } <nl> + <nl> + / / Constructs and returns an exact copy . <nl> + TrainingSample * TrainingSample : : Copy ( ) const { <nl> + TrainingSample * sample = new TrainingSample ; <nl> + sample - > class_id_ = class_id_ ; <nl> + sample - > font_id_ = font_id_ ; <nl> + sample - > weight_ = weight_ ; <nl> + sample - > sample_index_ = sample_index_ ; <nl> + sample - > num_features_ = num_features_ ; <nl> + if ( num_features_ > 0 ) { <nl> + sample - > features_ = new INT_FEATURE_STRUCT [ num_features_ ] ; <nl> + memcpy ( sample - > features_ , features_ , num_features_ * sizeof ( features_ [ 0 ] ) ) ; <nl> + } <nl> + sample - > num_micro_features_ = num_micro_features_ ; <nl> + if ( num_micro_features_ > 0 ) { <nl> + sample - > micro_features_ = new MicroFeature [ num_micro_features_ ] ; <nl> + memcpy ( sample - > micro_features_ , micro_features_ , <nl> + num_micro_features_ * sizeof ( micro_features_ [ 0 ] ) ) ; <nl> + } <nl> + memcpy ( sample - > cn_feature_ , cn_feature_ , sizeof ( * cn_feature_ ) * kNumCNParams ) ; <nl> + memcpy ( sample - > geo_feature_ , geo_feature_ , sizeof ( * geo_feature_ ) * GeoCount ) ; <nl> + return sample ; <nl> + } <nl> + <nl> + / / Extracts the needed information from the CHAR_DESC_STRUCT . <nl> + void TrainingSample : : ExtractCharDesc ( int int_feature_type , <nl> + int micro_type , <nl> + int cn_type , <nl> + int geo_type , <nl> + CHAR_DESC_STRUCT * char_desc ) { <nl> + / / Extract the INT features . <nl> + if ( features_ ! = NULL ) delete [ ] features_ ; <nl> + FEATURE_SET_STRUCT * char_features = char_desc - > FeatureSets [ int_feature_type ] ; <nl> + if ( char_features = = NULL ) { <nl> + tprintf ( " Error : no features to train on of type % s \ n " , <nl> + kIntFeatureType ) ; <nl> + num_features_ = 0 ; <nl> + features_ = NULL ; <nl> + } else { <nl> + num_features_ = char_features - > NumFeatures ; <nl> + features_ = new INT_FEATURE_STRUCT [ num_features_ ] ; <nl> + for ( int f = 0 ; f < num_features_ ; + + f ) { <nl> + features_ [ f ] . X = <nl> + static_cast < uinT8 > ( char_features - > Features [ f ] - > Params [ IntX ] ) ; <nl> + features_ [ f ] . Y = <nl> + static_cast < uinT8 > ( char_features - > Features [ f ] - > Params [ IntY ] ) ; <nl> + features_ [ f ] . Theta = <nl> + static_cast < uinT8 > ( char_features - > Features [ f ] - > Params [ IntDir ] ) ; <nl> + features_ [ f ] . CP_misses = 0 ; <nl> + } <nl> + } <nl> + / / Extract the Micro features . <nl> + if ( micro_features_ ! = NULL ) delete [ ] micro_features_ ; <nl> + char_features = char_desc - > FeatureSets [ micro_type ] ; <nl> + if ( char_features = = NULL ) { <nl> + tprintf ( " Error : no features to train on of type % s \ n " , <nl> + kMicroFeatureType ) ; <nl> + num_micro_features_ = 0 ; <nl> + micro_features_ = NULL ; <nl> + } else { <nl> + num_micro_features_ = char_features - > NumFeatures ; <nl> + micro_features_ = new MicroFeature [ num_micro_features_ ] ; <nl> + for ( int f = 0 ; f < num_micro_features_ ; + + f ) { <nl> + for ( int d = 0 ; d < MFCount ; + + d ) { <nl> + micro_features_ [ f ] [ d ] = char_features - > Features [ f ] - > Params [ d ] ; <nl> + } <nl> + } <nl> + } <nl> + / / Extract the CN feature . <nl> + char_features = char_desc - > FeatureSets [ cn_type ] ; <nl> + if ( char_features = = NULL ) { <nl> + tprintf ( " Error : no CN feature to train on . \ n " ) ; <nl> + } else { <nl> + ASSERT_HOST ( char_features - > NumFeatures = = 1 ) ; <nl> + cn_feature_ [ CharNormY ] = char_features - > Features [ 0 ] - > Params [ CharNormY ] ; <nl> + cn_feature_ [ CharNormLength ] = <nl> + char_features - > Features [ 0 ] - > Params [ CharNormLength ] ; <nl> + cn_feature_ [ CharNormRx ] = char_features - > Features [ 0 ] - > Params [ CharNormRx ] ; <nl> + cn_feature_ [ CharNormRy ] = char_features - > Features [ 0 ] - > Params [ CharNormRy ] ; <nl> + } <nl> + / / Extract the Geo feature . <nl> + char_features = char_desc - > FeatureSets [ geo_type ] ; <nl> + if ( char_features = = NULL ) { <nl> + tprintf ( " Error : no Geo feature to train on . \ n " ) ; <nl> + } else { <nl> + ASSERT_HOST ( char_features - > NumFeatures = = 1 ) ; <nl> + geo_feature_ [ GeoBottom ] = char_features - > Features [ 0 ] - > Params [ GeoBottom ] ; <nl> + geo_feature_ [ GeoTop ] = char_features - > Features [ 0 ] - > Params [ GeoTop ] ; <nl> + geo_feature_ [ GeoWidth ] = char_features - > Features [ 0 ] - > Params [ GeoWidth ] ; <nl> + } <nl> + features_are_indexed_ = false ; <nl> + features_are_mapped_ = false ; <nl> + } <nl> + <nl> + / / Sets the mapped_features_ from the features_ using the provided <nl> + / / feature_space to the indexed versions of the features . <nl> + void TrainingSample : : IndexFeatures ( const IntFeatureSpace & feature_space ) { <nl> + GenericVector < int > indexed_features ; <nl> + feature_space . IndexAndSortFeatures ( features_ , num_features_ , <nl> + & mapped_features_ ) ; <nl> + features_are_indexed_ = true ; <nl> + features_are_mapped_ = false ; <nl> + } <nl> + <nl> + / / Sets the mapped_features_ from the features using the provided <nl> + / / feature_map . <nl> + void TrainingSample : : MapFeatures ( const IntFeatureMap & feature_map ) { <nl> + GenericVector < int > indexed_features ; <nl> + feature_map . feature_space ( ) . IndexAndSortFeatures ( features_ , num_features_ , <nl> + & indexed_features ) ; <nl> + feature_map . MapIndexedFeatures ( indexed_features , & mapped_features_ ) ; <nl> + features_are_indexed_ = false ; <nl> + features_are_mapped_ = true ; <nl> + } <nl> + <nl> + / / Returns a pix representing the sample . ( Int features only . ) <nl> + Pix * TrainingSample : : RenderToPix ( const UNICHARSET * unicharset ) const { <nl> + Pix * pix = pixCreate ( kIntFeatureExtent , kIntFeatureExtent , 1 ) ; <nl> + for ( int f = 0 ; f < num_features_ ; + + f ) { <nl> + int start_x = features_ [ f ] . X ; <nl> + int start_y = kIntFeatureExtent - features_ [ f ] . Y ; <nl> + double dx = cos ( ( features_ [ f ] . Theta / 256 . 0 ) * 2 . 0 * PI - PI ) ; <nl> + double dy = - sin ( ( features_ [ f ] . Theta / 256 . 0 ) * 2 . 0 * PI - PI ) ; <nl> + for ( int i = 0 ; i < = 5 ; + + i ) { <nl> + int x = static_cast < int > ( start_x + dx * i ) ; <nl> + int y = static_cast < int > ( start_y + dy * i ) ; <nl> + if ( x > = 0 & & x < 256 & & y > = 0 & & y < 256 ) <nl> + pixSetPixel ( pix , x , y , 1 ) ; <nl> + } <nl> + } <nl> + if ( unicharset ! = NULL ) <nl> + pixSetText ( pix , unicharset - > id_to_unichar ( class_id_ ) ) ; <nl> + return pix ; <nl> + } <nl> + <nl> + / / Displays the features in the given window with the given color . <nl> + void TrainingSample : : DisplayFeatures ( ScrollView : : Color color , <nl> + ScrollView * window ) const { <nl> + for ( int f = 0 ; f < num_features_ ; + + f ) { <nl> + RenderIntFeature ( window , & features_ [ f ] , color ) ; <nl> + } <nl> + } <nl> + <nl> + / / Returns a pix of the original sample image . The pix is padded all round <nl> + / / by padding wherever possible . <nl> + / / The returned Pix must be pixDestroyed after use . <nl> + / / If the input page_pix is NULL , NULL is returned . <nl> + Pix * TrainingSample : : GetSamplePix ( int padding , Pix * page_pix ) const { <nl> + if ( page_pix = = NULL ) <nl> + return NULL ; <nl> + int page_width = pixGetWidth ( page_pix ) ; <nl> + int page_height = pixGetHeight ( page_pix ) ; <nl> + TBOX padded_box = bounding_box ( ) ; <nl> + padded_box . pad ( padding , padding ) ; <nl> + / / Clip the padded_box to the limits of the page <nl> + TBOX page_box ( 0 , 0 , page_width , page_height ) ; <nl> + padded_box & = page_box ; <nl> + Box * box = boxCreate ( page_box . left ( ) , page_height - page_box . top ( ) , <nl> + page_box . width ( ) , page_box . height ( ) ) ; <nl> + Pix * sample_pix = pixClipRectangle ( page_pix , box , NULL ) ; <nl> + boxDestroy ( & box ) ; <nl> + return sample_pix ; <nl> + } <nl> + <nl> + } / / namespace tesseract <nl> new file mode 100644 <nl> index 000000000 . . 821bbed99 <nl> mmm / dev / null <nl> ppp b / classify / trainingsample . h <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_TRAINING_TRAININGSAMPLE_H__ <nl> + # define TESSERACT_TRAINING_TRAININGSAMPLE_H__ <nl> + <nl> + # include " elst . h " <nl> + # include " featdefs . h " <nl> + # include " intfx . h " <nl> + # include " intmatcher . h " <nl> + # include " matrix . h " <nl> + # include " mf . h " <nl> + # include " picofeat . h " <nl> + # include " shapetable . h " <nl> + # include " unicharset . h " <nl> + <nl> + struct Pix ; <nl> + <nl> + namespace tesseract { <nl> + <nl> + class IntFeatureMap ; <nl> + class IntFeatureSpace ; <nl> + class ShapeTable ; <nl> + <nl> + / / Number of elements of cn_feature_ . <nl> + static const int kNumCNParams = 4 ; <nl> + / / Number of ways to shift the features when randomizing . <nl> + static const int kSampleYShiftSize = 5 ; <nl> + / / Number of ways to scale the features when randomizing . <nl> + static const int kSampleScaleSize = 3 ; <nl> + / / Total number of different ways to manipulate the features when randomizing . <nl> + / / The first and last combinations are removed to avoid an excessive <nl> + / / top movement ( first ) and an identity transformation ( last ) . <nl> + / / WARNING : To avoid patterned duplication of samples , be sure to keep <nl> + / / kSampleRandomSize prime ! <nl> + / / Eg with current values ( kSampleYShiftSize = 5 and TkSampleScaleSize = 3 ) <nl> + / / kSampleRandomSize is 13 , which is prime . <nl> + static const int kSampleRandomSize = kSampleYShiftSize * kSampleScaleSize - 2 ; <nl> + / / ASSERT_IS_PRIME ( kSampleRandomSize ) ! ! <nl> + <nl> + class TrainingSample : public ELIST_LINK { <nl> + public : <nl> + TrainingSample ( ) <nl> + : class_id_ ( INVALID_UNICHAR_ID ) , font_id_ ( 0 ) , page_num_ ( 0 ) , <nl> + num_features_ ( 0 ) , num_micro_features_ ( 0 ) , <nl> + features_ ( NULL ) , micro_features_ ( NULL ) , weight_ ( 1 . 0 ) , <nl> + max_dist_ ( 0 . 0 ) , sample_index_ ( 0 ) , <nl> + features_are_indexed_ ( false ) , features_are_mapped_ ( false ) , <nl> + is_error_ ( false ) { <nl> + } <nl> + ~ TrainingSample ( ) ; <nl> + <nl> + / / Saves the given features into a TrainingSample . The features are copied , <nl> + / / so may be deleted afterwards . Delete the return value after use . <nl> + static TrainingSample * CopyFromFeatures ( const INT_FX_RESULT_STRUCT & fx_info , <nl> + const INT_FEATURE_STRUCT * features , <nl> + int num_features ) ; <nl> + / / Constructs and returns a copy " randomized " by the method given by <nl> + / / the randomizer index . If index is out of [ 0 , kSampleRandomSize ) then <nl> + / / an exact copy is returned . <nl> + TrainingSample * RandomizedCopy ( int index ) const ; <nl> + / / Constructs and returns an exact copy . <nl> + TrainingSample * Copy ( ) const ; <nl> + <nl> + / / WARNING ! Serialize / DeSerialize do not save / restore the " cache " data <nl> + / / members , which is mostly the mapped features , and the weight . <nl> + / / It is assumed these can all be reconstructed from what is saved . <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) const ; <nl> + / / Creates from the given file . Returns NULL in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + static TrainingSample * DeSerializeCreate ( bool swap , FILE * fp ) ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Extracts the needed information from the CHAR_DESC_STRUCT . <nl> + void ExtractCharDesc ( int feature_type , int micro_type , <nl> + int cn_type , int geo_type , <nl> + CHAR_DESC_STRUCT * char_desc ) ; <nl> + <nl> + / / Sets the mapped_features_ from the features_ using the provided <nl> + / / feature_space to the indexed versions of the features . <nl> + void IndexFeatures ( const IntFeatureSpace & feature_space ) ; <nl> + / / Sets the mapped_features_ from the features_ using the provided <nl> + / / feature_map . <nl> + void MapFeatures ( const IntFeatureMap & feature_map ) ; <nl> + <nl> + / / Returns a pix representing the sample . ( Int features only . ) <nl> + Pix * RenderToPix ( const UNICHARSET * unicharset ) const ; <nl> + / / Displays the features in the given window with the given color . <nl> + void DisplayFeatures ( ScrollView : : Color color , ScrollView * window ) const ; <nl> + <nl> + / / Returns a pix of the original sample image . The pix is padded all round <nl> + / / by padding wherever possible . <nl> + / / The returned Pix must be pixDestroyed after use . <nl> + / / If the input page_pix is NULL , NULL is returned . <nl> + Pix * GetSamplePix ( int padding , Pix * page_pix ) const ; <nl> + <nl> + / / Accessors . <nl> + UNICHAR_ID class_id ( ) const { <nl> + return class_id_ ; <nl> + } <nl> + void set_class_id ( int id ) { <nl> + class_id_ = id ; <nl> + } <nl> + int font_id ( ) const { <nl> + return font_id_ ; <nl> + } <nl> + void set_font_id ( int id ) { <nl> + font_id_ = id ; <nl> + } <nl> + int page_num ( ) const { <nl> + return page_num_ ; <nl> + } <nl> + void set_page_num ( int page ) { <nl> + page_num_ = page ; <nl> + } <nl> + const TBOX & bounding_box ( ) const { <nl> + return bounding_box_ ; <nl> + } <nl> + void set_bounding_box ( const TBOX & box ) { <nl> + bounding_box_ = box ; <nl> + } <nl> + int num_features ( ) const { <nl> + return num_features_ ; <nl> + } <nl> + const INT_FEATURE_STRUCT * features ( ) const { <nl> + return features_ ; <nl> + } <nl> + int num_micro_features ( ) const { <nl> + return num_micro_features_ ; <nl> + } <nl> + const MicroFeature * micro_features ( ) const { <nl> + return micro_features_ ; <nl> + } <nl> + float cn_feature ( int index ) const { <nl> + return cn_feature_ [ index ] ; <nl> + } <nl> + int geo_feature ( int index ) const { <nl> + return geo_feature_ [ index ] ; <nl> + } <nl> + double weight ( ) const { <nl> + return weight_ ; <nl> + } <nl> + void set_weight ( double value ) { <nl> + weight_ = value ; <nl> + } <nl> + double max_dist ( ) const { <nl> + return max_dist_ ; <nl> + } <nl> + void set_max_dist ( double value ) { <nl> + max_dist_ = value ; <nl> + } <nl> + int sample_index ( ) const { <nl> + return sample_index_ ; <nl> + } <nl> + void set_sample_index ( int value ) { <nl> + sample_index_ = value ; <nl> + } <nl> + bool features_are_mapped ( ) const { <nl> + return features_are_mapped_ ; <nl> + } <nl> + const GenericVector < int > & mapped_features ( ) const { <nl> + ASSERT_HOST ( features_are_mapped_ ) ; <nl> + return mapped_features_ ; <nl> + } <nl> + const GenericVector < int > & indexed_features ( ) const { <nl> + ASSERT_HOST ( features_are_indexed_ ) ; <nl> + return mapped_features_ ; <nl> + } <nl> + bool is_error ( ) const { <nl> + return is_error_ ; <nl> + } <nl> + void set_is_error ( bool value ) { <nl> + is_error_ = value ; <nl> + } <nl> + <nl> + private : <nl> + / / Unichar id that this sample represents . There obviously must be a <nl> + / / reference UNICHARSET somewhere . Usually in TrainingSampleSet . <nl> + UNICHAR_ID class_id_ ; <nl> + / / Font id in which this sample was printed . Refers to a fontinfo_table_ in <nl> + / / MasterTrainer . <nl> + int font_id_ ; <nl> + / / Number of page that the sample came from . <nl> + int page_num_ ; <nl> + / / Bounding box of sample in original image . <nl> + TBOX bounding_box_ ; <nl> + / / Number of INT_FEATURE_STRUCT in features_ array . <nl> + int num_features_ ; <nl> + / / Number of MicroFeature in micro_features_ array . <nl> + int num_micro_features_ ; <nl> + / / Array of features . <nl> + INT_FEATURE_STRUCT * features_ ; <nl> + / / Array of features . <nl> + MicroFeature * micro_features_ ; <nl> + / / The one and only CN feature . Indexed by NORM_PARAM_NAME enum . <nl> + float cn_feature_ [ kNumCNParams ] ; <nl> + / / The one and only geometric feature . ( Aims at replacing cn_feature_ ) . <nl> + / / Indexed by GeoParams enum in picofeat . h <nl> + int geo_feature_ [ GeoCount ] ; <nl> + <nl> + / / Non - serialized cache data . <nl> + / / Weight used for boosting training . <nl> + double weight_ ; <nl> + / / Maximum distance to other samples of same class / font used in computing <nl> + / / the canonical sample . <nl> + double max_dist_ ; <nl> + / / Global index of this sample . <nl> + int sample_index_ ; <nl> + / / Indexed / mapped features , as indicated by the bools below . <nl> + GenericVector < int > mapped_features_ ; <nl> + bool features_are_indexed_ ; <nl> + bool features_are_mapped_ ; <nl> + / / True if the last classification was an error by the current definition . <nl> + bool is_error_ ; <nl> + <nl> + / / Randomizing factors . <nl> + static const int kYShiftValues [ kSampleYShiftSize ] ; <nl> + static const double kScaleValues [ kSampleScaleSize ] ; <nl> + } ; <nl> + <nl> + ELISTIZEH ( TrainingSample ) <nl> + <nl> + } / / namespace tesseract <nl> + <nl> + # endif / / TESSERACT_TRAINING_TRAININGSAMPLE_H__ <nl> new file mode 100644 <nl> index 000000000 . . 2e7f77da4 <nl> mmm / dev / null <nl> ppp b / classify / trainingsampleset . cpp <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # include " trainingsampleset . h " <nl> + # include " allheaders . h " <nl> + # include " boxread . h " <nl> + # include " fontinfo . h " <nl> + # include " indexmapbidi . h " <nl> + # include " intfeaturedist . h " <nl> + # include " intfeaturemap . h " <nl> + # include " intfeaturespace . h " <nl> + # include " shapetable . h " <nl> + # include " trainingsample . h " <nl> + # include " unicity_table . h " <nl> + <nl> + namespace tesseract { <nl> + <nl> + const int kTestChar = - 1 ; / / 37 ; <nl> + / / Max number of distances to compute the squared way <nl> + const int kSquareLimit = 25 ; <nl> + / / Prime numbers for subsampling distances . <nl> + const int kPrime1 = 17 ; <nl> + const int kPrime2 = 13 ; <nl> + / / Min samples from which to start discarding outliers . <nl> + const int kMinOutlierSamples = 5 ; <nl> + <nl> + TrainingSampleSet : : FontClassInfo : : FontClassInfo ( ) <nl> + : num_raw_samples ( 0 ) , canonical_sample ( - 1 ) , canonical_dist ( 0 . 0f ) { <nl> + } <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool TrainingSampleSet : : FontClassInfo : : Serialize ( FILE * fp ) const { <nl> + if ( fwrite ( & num_raw_samples , sizeof ( num_raw_samples ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fwrite ( & canonical_sample , sizeof ( canonical_sample ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fwrite ( & canonical_dist , sizeof ( canonical_dist ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( ! samples . Serialize ( fp ) ) return false ; <nl> + return true ; <nl> + } <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool TrainingSampleSet : : FontClassInfo : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( fread ( & num_raw_samples , sizeof ( num_raw_samples ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fread ( & canonical_sample , sizeof ( canonical_sample ) , 1 , fp ) ! = 1 ) <nl> + return false ; <nl> + if ( fread ( & canonical_dist , sizeof ( canonical_dist ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( ! samples . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( swap ) { <nl> + ReverseN ( & num_raw_samples , sizeof ( num_raw_samples ) ) ; <nl> + ReverseN ( & canonical_sample , sizeof ( canonical_sample ) ) ; <nl> + ReverseN ( & canonical_dist , sizeof ( canonical_dist ) ) ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + TrainingSampleSet : : TrainingSampleSet ( const UnicityTable < FontInfo > & font_table ) <nl> + : num_raw_samples_ ( 0 ) , unicharset_size_ ( 0 ) , <nl> + font_class_array_ ( NULL ) , fontinfo_table_ ( font_table ) { <nl> + } <nl> + <nl> + TrainingSampleSet : : ~ TrainingSampleSet ( ) { <nl> + delete font_class_array_ ; <nl> + } <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool TrainingSampleSet : : Serialize ( FILE * fp ) const { <nl> + if ( ! samples_ . Serialize ( fp ) ) return false ; <nl> + if ( ! unicharset_ . save_to_file ( fp ) ) return false ; <nl> + if ( ! font_id_map_ . Serialize ( fp ) ) return false ; <nl> + inT8 not_null = font_class_array_ ! = NULL ; <nl> + if ( fwrite ( & not_null , sizeof ( not_null ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( not_null ) { <nl> + if ( ! font_class_array_ - > SerializeClasses ( fp ) ) return false ; <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool TrainingSampleSet : : DeSerialize ( bool swap , FILE * fp ) { <nl> + if ( ! samples_ . DeSerialize ( swap , fp ) ) return false ; <nl> + num_raw_samples_ = samples_ . size ( ) ; <nl> + if ( ! unicharset_ . load_from_file ( fp ) ) return false ; <nl> + if ( ! font_id_map_ . DeSerialize ( swap , fp ) ) return false ; <nl> + if ( font_class_array_ ! = NULL ) { <nl> + delete font_class_array_ ; <nl> + font_class_array_ = NULL ; <nl> + } <nl> + inT8 not_null ; <nl> + if ( fread ( & not_null , sizeof ( not_null ) , 1 , fp ) ! = 1 ) return false ; <nl> + if ( not_null ) { <nl> + FontClassInfo empty ; <nl> + font_class_array_ = new GENERIC_2D_ARRAY < FontClassInfo > ( 1 , 1 , empty ) ; <nl> + if ( ! font_class_array_ - > DeSerializeClasses ( swap , fp ) ) return false ; <nl> + } <nl> + unicharset_size_ = unicharset_ . size ( ) ; <nl> + return true ; <nl> + } <nl> + <nl> + / / Load an initial unicharset , or set one up if the file cannot be read . <nl> + void TrainingSampleSet : : LoadUnicharset ( const char * filename ) { <nl> + if ( ! unicharset_ . load_from_file ( filename ) ) { <nl> + tprintf ( " Failed to load unicharset from file % s \ n " <nl> + " Building unicharset for boosting from scratch . . . \ n " , <nl> + filename ) ; <nl> + unicharset_ . clear ( ) ; <nl> + / / Space character needed to represent NIL_LIST classification . <nl> + unicharset_ . unichar_insert ( " " ) ; <nl> + } <nl> + unicharset_size_ = unicharset_ . size ( ) ; <nl> + } <nl> + <nl> + / / Adds a character sample to this sample set . <nl> + / / If the unichar is not already in the local unicharset , it is added . <nl> + / / Returns the unichar_id of the added sample , from the local unicharset . <nl> + int TrainingSampleSet : : AddSample ( const char * unichar , TrainingSample * sample ) { <nl> + if ( ! unicharset_ . contains_unichar ( unichar ) ) { <nl> + unicharset_ . unichar_insert ( unichar ) ; <nl> + if ( unicharset_ . size ( ) > MAX_NUM_CLASSES ) { <nl> + tprintf ( " Error : Size of unicharset in TrainingSampleSet : : AddSample is " <nl> + " greater than MAX_NUM_CLASSES \ n " ) ; <nl> + return - 1 ; <nl> + } <nl> + } <nl> + UNICHAR_ID char_id = unicharset_ . unichar_to_id ( unichar ) ; <nl> + AddSample ( char_id , sample ) ; <nl> + return char_id ; <nl> + } <nl> + <nl> + / / Adds a character sample to this sample set with the given unichar_id , <nl> + / / which must correspond to the local unicharset ( in this ) . <nl> + void TrainingSampleSet : : AddSample ( int unichar_id , TrainingSample * sample ) { <nl> + sample - > set_class_id ( unichar_id ) ; <nl> + samples_ . push_back ( sample ) ; <nl> + num_raw_samples_ = samples_ . size ( ) ; <nl> + unicharset_size_ = unicharset_ . size ( ) ; <nl> + } <nl> + <nl> + / / Returns the number of samples for the given font , class pair . <nl> + / / If randomize is true , returns the number of samples accessible <nl> + / / with randomizing on . ( Increases the number of samples if small . ) <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + int TrainingSampleSet : : NumClassSamples ( int font_id , int class_id , <nl> + bool randomize ) const { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + if ( font_id < 0 | | class_id < 0 | | <nl> + font_id > = font_id_map_ . SparseSize ( ) | | class_id > = unicharset_size_ ) { <nl> + / / There are no samples because the font or class doesn ' t exist . <nl> + return 0 ; <nl> + } <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + if ( font_index < 0 ) <nl> + return 0 ; / / The font has no samples . <nl> + if ( randomize ) <nl> + return ( * font_class_array_ ) ( font_index , class_id ) . samples . size ( ) ; <nl> + else <nl> + return ( * font_class_array_ ) ( font_index , class_id ) . num_raw_samples ; <nl> + } <nl> + <nl> + / / Gets a sample by its index . <nl> + const TrainingSample * TrainingSampleSet : : GetSample ( int index ) const { <nl> + return samples_ [ index ] ; <nl> + } <nl> + <nl> + / / Gets a sample by its font , class , index . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + const TrainingSample * TrainingSampleSet : : GetSample ( int font_id , int class_id , <nl> + int index ) const { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + if ( font_index < 0 ) return NULL ; <nl> + int sample_index = ( * font_class_array_ ) ( font_index , class_id ) . samples [ index ] ; <nl> + return samples_ [ sample_index ] ; <nl> + } <nl> + <nl> + / / Get a sample by its font , class , index . Does not randomize . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + TrainingSample * TrainingSampleSet : : MutableSample ( int font_id , int class_id , <nl> + int index ) { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + if ( font_index < 0 ) return NULL ; <nl> + int sample_index = ( * font_class_array_ ) ( font_index , class_id ) . samples [ index ] ; <nl> + return samples_ [ sample_index ] ; <nl> + } <nl> + <nl> + / / Returns a string debug representation of the given sample : <nl> + / / font , unichar_str , bounding box , page . <nl> + STRING TrainingSampleSet : : SampleToString ( const TrainingSample & sample ) const { <nl> + STRING boxfile_str ; <nl> + MakeBoxFileStr ( unicharset_ . id_to_unichar ( sample . class_id ( ) ) , <nl> + sample . bounding_box ( ) , sample . page_num ( ) , & boxfile_str ) ; <nl> + return STRING ( fontinfo_table_ . get ( sample . font_id ( ) ) . name ) + " " + boxfile_str ; <nl> + } <nl> + <nl> + / / Gets the combined set of features used by all the samples of the given <nl> + / / font / class combination . <nl> + const BitVector & TrainingSampleSet : : GetCloudFeatures ( <nl> + int font_id , int class_id ) const { <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + ASSERT_HOST ( font_index > = 0 ) ; <nl> + return ( * font_class_array_ ) ( font_index , class_id ) . cloud_features ; <nl> + } <nl> + / / Gets the indexed features of the canonical sample of the given <nl> + / / font / class combination . <nl> + const GenericVector < int > & TrainingSampleSet : : GetCanonicalFeatures ( <nl> + int font_id , int class_id ) const { <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + ASSERT_HOST ( font_index > = 0 ) ; <nl> + return ( * font_class_array_ ) ( font_index , class_id ) . canonical_features ; <nl> + } <nl> + <nl> + / / Returns the distance between the given UniCharAndFonts pair . <nl> + / / If matched_fonts , only matching fonts , are considered , unless that yields <nl> + / / the empty set . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + float TrainingSampleSet : : UnicharDistance ( const UnicharAndFonts & uf1 , <nl> + const UnicharAndFonts & uf2 , <nl> + bool matched_fonts , <nl> + const IntFeatureMap & feature_map ) { <nl> + int num_fonts1 = uf1 . font_ids . size ( ) ; <nl> + int c1 = uf1 . unichar_id ; <nl> + int num_fonts2 = uf2 . font_ids . size ( ) ; <nl> + int c2 = uf2 . unichar_id ; <nl> + double dist_sum = 0 . 0 ; <nl> + int dist_count = 0 ; <nl> + bool debug = false ; <nl> + if ( matched_fonts ) { <nl> + / / Compute distances only where fonts match . <nl> + for ( int i = 0 ; i < num_fonts1 ; + + i ) { <nl> + int f1 = uf1 . font_ids [ i ] ; <nl> + for ( int j = 0 ; j < num_fonts2 ; + + j ) { <nl> + int f2 = uf2 . font_ids [ j ] ; <nl> + if ( f1 = = f2 ) { <nl> + dist_sum + = ClusterDistance ( f1 , c1 , f2 , c2 , feature_map ) ; <nl> + + + dist_count ; <nl> + } <nl> + } <nl> + } <nl> + } else if ( num_fonts1 * num_fonts2 < = kSquareLimit ) { <nl> + / / Small enough sets to compute all the distances . <nl> + for ( int i = 0 ; i < num_fonts1 ; + + i ) { <nl> + int f1 = uf1 . font_ids [ i ] ; <nl> + for ( int j = 0 ; j < num_fonts2 ; + + j ) { <nl> + int f2 = uf2 . font_ids [ j ] ; <nl> + dist_sum + = ClusterDistance ( f1 , c1 , f2 , c2 , feature_map ) ; <nl> + if ( debug ) { <nl> + tprintf ( " Cluster dist % d % d % d % d = % g \ n " , <nl> + f1 , c1 , f2 , c2 , <nl> + ClusterDistance ( f1 , c1 , f2 , c2 , feature_map ) ) ; <nl> + } <nl> + + + dist_count ; <nl> + } <nl> + } <nl> + } else { <nl> + / / Subsample distances , using the largest set once , and stepping through <nl> + / / the smaller set so as to ensure that all the pairs are different . <nl> + int increment = kPrime1 ! = num_fonts2 ? kPrime1 : kPrime2 ; <nl> + int index = 0 ; <nl> + int num_samples = MAX ( num_fonts1 , num_fonts2 ) ; <nl> + for ( int i = 0 ; i < num_samples ; + + i , index + = increment ) { <nl> + int f1 = uf1 . font_ids [ i % num_fonts1 ] ; <nl> + int f2 = uf2 . font_ids [ index % num_fonts2 ] ; <nl> + if ( debug ) { <nl> + tprintf ( " Cluster dist % d % d % d % d = % g \ n " , <nl> + f1 , c1 , f2 , c2 , ClusterDistance ( f1 , c1 , f2 , c2 , feature_map ) ) ; <nl> + } <nl> + dist_sum + = ClusterDistance ( f1 , c1 , f2 , c2 , feature_map ) ; <nl> + + + dist_count ; <nl> + } <nl> + } <nl> + if ( dist_count = = 0 ) { <nl> + if ( matched_fonts ) <nl> + return UnicharDistance ( uf1 , uf2 , false , feature_map ) ; <nl> + return 0 . 0f ; <nl> + } <nl> + return dist_sum / dist_count ; <nl> + } <nl> + <nl> + / / Returns the distance between the given pair of font / class pairs . <nl> + / / Finds in cache or computes and caches . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + float TrainingSampleSet : : ClusterDistance ( int font_id1 , int class_id1 , <nl> + int font_id2 , int class_id2 , <nl> + const IntFeatureMap & feature_map ) { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_index1 = font_id_map_ . SparseToCompact ( font_id1 ) ; <nl> + int font_index2 = font_id_map_ . SparseToCompact ( font_id2 ) ; <nl> + if ( font_index1 < 0 | | font_index2 < 0 ) <nl> + return 0 . 0f ; <nl> + FontClassInfo & fc_info = ( * font_class_array_ ) ( font_index1 , class_id1 ) ; <nl> + if ( font_id1 = = font_id2 ) { <nl> + / / Special case cache for speed . <nl> + if ( fc_info . unichar_distance_cache . size ( ) = = 0 ) <nl> + fc_info . unichar_distance_cache . init_to_size ( unicharset_size_ , - 1 . 0f ) ; <nl> + if ( fc_info . unichar_distance_cache [ class_id2 ] < 0 ) { <nl> + / / Distance has to be calculated . <nl> + float result = ComputeClusterDistance ( font_id1 , class_id1 , <nl> + font_id2 , class_id2 , <nl> + feature_map ) ; <nl> + fc_info . unichar_distance_cache [ class_id2 ] = result ; <nl> + / / Copy to the symmetric cache entry . <nl> + FontClassInfo & fc_info2 = ( * font_class_array_ ) ( font_index2 , class_id2 ) ; <nl> + if ( fc_info2 . unichar_distance_cache . size ( ) = = 0 ) <nl> + fc_info2 . unichar_distance_cache . init_to_size ( unicharset_size_ , - 1 . 0f ) ; <nl> + fc_info2 . unichar_distance_cache [ class_id1 ] = result ; <nl> + } <nl> + return fc_info . unichar_distance_cache [ class_id2 ] ; <nl> + } else if ( class_id1 = = class_id2 ) { <nl> + / / Another special - case cache for equal class - id . <nl> + if ( fc_info . font_distance_cache . size ( ) = = 0 ) <nl> + fc_info . font_distance_cache . init_to_size ( font_id_map_ . CompactSize ( ) , <nl> + - 1 . 0f ) ; <nl> + if ( fc_info . font_distance_cache [ font_index2 ] < 0 ) { <nl> + / / Distance has to be calculated . <nl> + float result = ComputeClusterDistance ( font_id1 , class_id1 , <nl> + font_id2 , class_id2 , <nl> + feature_map ) ; <nl> + fc_info . font_distance_cache [ font_index2 ] = result ; <nl> + / / Copy to the symmetric cache entry . <nl> + FontClassInfo & fc_info2 = ( * font_class_array_ ) ( font_index2 , class_id2 ) ; <nl> + if ( fc_info2 . font_distance_cache . size ( ) = = 0 ) <nl> + fc_info2 . font_distance_cache . init_to_size ( font_id_map_ . CompactSize ( ) , <nl> + - 1 . 0f ) ; <nl> + fc_info2 . font_distance_cache [ font_index1 ] = result ; <nl> + } <nl> + return fc_info . font_distance_cache [ font_index2 ] ; <nl> + } <nl> + / / Both font and class are different . Linear search for class_id2 / font_id2 <nl> + / / in what is a hopefully short list of distances . <nl> + int cache_index = 0 ; <nl> + while ( cache_index < fc_info . distance_cache . size ( ) & & <nl> + ( fc_info . distance_cache [ cache_index ] . unichar_id ! = class_id2 | | <nl> + fc_info . distance_cache [ cache_index ] . font_id ! = font_id2 ) ) <nl> + + + cache_index ; <nl> + if ( cache_index = = fc_info . distance_cache . size ( ) ) { <nl> + / / Distance has to be calculated . <nl> + float result = ComputeClusterDistance ( font_id1 , class_id1 , <nl> + font_id2 , class_id2 , <nl> + feature_map ) ; <nl> + FontClassDistance fc_dist = { class_id2 , font_id2 , result } ; <nl> + fc_info . distance_cache . push_back ( fc_dist ) ; <nl> + / / Copy to the symmetric cache entry . We know it isn ' t there already , as <nl> + / / we always copy to the symmetric entry . <nl> + FontClassInfo & fc_info2 = ( * font_class_array_ ) ( font_index2 , class_id2 ) ; <nl> + fc_dist . unichar_id = class_id1 ; <nl> + fc_dist . font_id = font_id1 ; <nl> + fc_info2 . distance_cache . push_back ( fc_dist ) ; <nl> + } <nl> + return fc_info . distance_cache [ cache_index ] . distance ; <nl> + } <nl> + <nl> + / / Computes the distance between the given pair of font / class pairs . <nl> + float TrainingSampleSet : : ComputeClusterDistance ( <nl> + int font_id1 , int class_id1 , int font_id2 , int class_id2 , <nl> + const IntFeatureMap & feature_map ) const { <nl> + int dist = ReliablySeparable ( font_id1 , class_id1 , font_id2 , class_id2 , <nl> + feature_map , false ) ; <nl> + dist + = ReliablySeparable ( font_id2 , class_id2 , font_id1 , class_id1 , <nl> + feature_map , false ) ; <nl> + int denominator = GetCanonicalFeatures ( font_id1 , class_id1 ) . size ( ) ; <nl> + denominator + = GetCanonicalFeatures ( font_id2 , class_id2 ) . size ( ) ; <nl> + return static_cast < float > ( dist ) / denominator ; <nl> + } <nl> + <nl> + / / Helper to add a feature and its near neighbors to the good_features . <nl> + / / levels indicates how many times to compute the offset features of what is <nl> + / / already there . This is done by iteration rather than recursion . <nl> + static void AddNearFeatures ( const IntFeatureMap & feature_map , int f , int levels , <nl> + GenericVector < int > * good_features ) { <nl> + int prev_num_features = 0 ; <nl> + good_features - > push_back ( f ) ; <nl> + int num_features = 1 ; <nl> + for ( int level = 0 ; level < levels ; + + level ) { <nl> + for ( int i = prev_num_features ; i < num_features ; + + i ) { <nl> + int feature = ( * good_features ) [ i ] ; <nl> + for ( int dir = - kNumOffsetMaps ; dir < = kNumOffsetMaps ; + + dir ) { <nl> + if ( dir = = 0 ) continue ; <nl> + int f1 = feature_map . OffsetFeature ( feature , dir ) ; <nl> + if ( f1 > = 0 ) { <nl> + good_features - > push_back ( f1 ) ; <nl> + } <nl> + } <nl> + } <nl> + prev_num_features = num_features ; <nl> + num_features = good_features - > size ( ) ; <nl> + } <nl> + } <nl> + <nl> + / / Returns the number of canonical features of font / class 2 for which <nl> + / / neither the feature nor any of its near neighbors occurs in the cloud <nl> + / / of font / class 1 . Each such feature is a reliable separation between <nl> + / / the classes , ASSUMING that the canonical sample is sufficiently <nl> + / / representative that every sample has a feature near that particular <nl> + / / feature . To check that this is so on the fly would be prohibitively <nl> + / / expensive , but it might be possible to pre - qualify the canonical features <nl> + / / to include only those for which this assumption is true . <nl> + / / ComputeCanonicalFeatures and ComputeCloudFeatures must have been called <nl> + / / first , or the results will be nonsense . <nl> + int TrainingSampleSet : : ReliablySeparable ( int font_id1 , int class_id1 , <nl> + int font_id2 , int class_id2 , <nl> + const IntFeatureMap & feature_map , <nl> + bool thorough ) const { <nl> + int result = 0 ; <nl> + const TrainingSample * sample2 = GetCanonicalSample ( font_id2 , class_id2 ) ; <nl> + if ( sample2 = = NULL ) <nl> + return 0 ; / / There are no canonical features . <nl> + const GenericVector < int > & canonical2 = GetCanonicalFeatures ( font_id2 , <nl> + class_id2 ) ; <nl> + const BitVector & cloud1 = GetCloudFeatures ( font_id1 , class_id1 ) ; <nl> + if ( cloud1 . size ( ) = = 0 ) <nl> + return canonical2 . size ( ) ; / / There are no cloud features . <nl> + <nl> + / / Find a canonical2 feature that is not in cloud1 . <nl> + for ( int f = 0 ; f < canonical2 . size ( ) ; + + f ) { <nl> + int feature = canonical2 [ f ] ; <nl> + if ( cloud1 [ feature ] ) <nl> + continue ; <nl> + / / Gather the near neighbours of f . <nl> + GenericVector < int > good_features ; <nl> + AddNearFeatures ( feature_map , feature , 1 , & good_features ) ; <nl> + / / Check that none of the good_features are in the cloud . <nl> + int i ; <nl> + for ( i = 0 ; i < good_features . size ( ) ; + + i ) { <nl> + int good_f = good_features [ i ] ; <nl> + if ( cloud1 [ good_f ] ) { <nl> + break ; <nl> + } <nl> + } <nl> + if ( i < good_features . size ( ) ) <nl> + continue ; / / Found one in the cloud . <nl> + + + result ; <nl> + } <nl> + return result ; <nl> + } <nl> + <nl> + / / Returns the total index of the requested sample . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + int TrainingSampleSet : : GlobalSampleIndex ( int font_id , int class_id , <nl> + int index ) const { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + if ( font_index < 0 ) return - 1 ; <nl> + return ( * font_class_array_ ) ( font_index , class_id ) . samples [ index ] ; <nl> + } <nl> + <nl> + / / Gets the canonical sample for the given font , class pair . <nl> + / / ComputeCanonicalSamples must have been called first . <nl> + const TrainingSample * TrainingSampleSet : : GetCanonicalSample ( <nl> + int font_id , int class_id ) const { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + if ( font_index < 0 ) return NULL ; <nl> + int sample_index = ( * font_class_array_ ) ( font_index , <nl> + class_id ) . canonical_sample ; <nl> + return sample_index > = 0 ? samples_ [ sample_index ] : NULL ; <nl> + } <nl> + <nl> + / / Gets the max distance for the given canonical sample . <nl> + / / ComputeCanonicalSamples must have been called first . <nl> + float TrainingSampleSet : : GetCanonicalDist ( int font_id , int class_id ) const { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + if ( font_index < 0 ) return 0 . 0f ; <nl> + if ( ( * font_class_array_ ) ( font_index , class_id ) . canonical_sample > = 0 ) <nl> + return ( * font_class_array_ ) ( font_index , class_id ) . canonical_dist ; <nl> + else <nl> + return 0 . 0f ; <nl> + } <nl> + <nl> + / / Generates indexed features for all samples with the supplied feature_space . <nl> + void TrainingSampleSet : : IndexFeatures ( const IntFeatureSpace & feature_space ) { <nl> + for ( int s = 0 ; s < samples_ . size ( ) ; + + s ) <nl> + samples_ [ s ] - > IndexFeatures ( feature_space ) ; <nl> + } <nl> + <nl> + / / Delete outlier samples with few features that are shared with others . <nl> + / / IndexFeatures must have been called already . <nl> + void TrainingSampleSet : : DeleteOutliers ( const IntFeatureSpace & feature_space , <nl> + bool debug ) { <nl> + if ( font_class_array_ = = NULL ) <nl> + OrganizeByFontAndClass ( ) ; <nl> + Pixa * pixa = NULL ; <nl> + if ( debug ) <nl> + pixa = pixaCreate ( 0 ) ; <nl> + GenericVector < int > feature_counts ; <nl> + int fs_size = feature_space . Size ( ) ; <nl> + int font_size = font_id_map_ . CompactSize ( ) ; <nl> + for ( int font_index = 0 ; font_index < font_size ; + + font_index ) { <nl> + for ( int c = 0 ; c < unicharset_size_ ; + + c ) { <nl> + / / Create a histogram of the features used by all samples of this <nl> + / / font / class combination . <nl> + feature_counts . init_to_size ( fs_size , 0 ) ; <nl> + FontClassInfo & fcinfo = ( * font_class_array_ ) ( font_index , c ) ; <nl> + int sample_count = fcinfo . samples . size ( ) ; <nl> + if ( sample_count < kMinOutlierSamples ) <nl> + continue ; <nl> + for ( int i = 0 ; i < sample_count ; + + i ) { <nl> + int s = fcinfo . samples [ i ] ; <nl> + const GenericVector < int > & features = samples_ [ s ] - > indexed_features ( ) ; <nl> + for ( int f = 0 ; f < features . size ( ) ; + + f ) { <nl> + + + feature_counts [ features [ f ] ] ; <nl> + } <nl> + } <nl> + for ( int i = 0 ; i < sample_count ; + + i ) { <nl> + int s = fcinfo . samples [ i ] ; <nl> + const TrainingSample & sample = * samples_ [ s ] ; <nl> + const GenericVector < int > & features = sample . indexed_features ( ) ; <nl> + / / A feature that has a histogram count of 1 is only used by this <nl> + / / sample , making it ' bad ' . All others are ' good ' . <nl> + int good_features = 0 ; <nl> + int bad_features = 0 ; <nl> + for ( int f = 0 ; f < features . size ( ) ; + + f ) { <nl> + if ( feature_counts [ features [ f ] ] > 1 ) <nl> + + + good_features ; <nl> + else <nl> + + + bad_features ; <nl> + } <nl> + / / If more than 1 / 3 features are bad , then this is an outlier . <nl> + if ( bad_features * 2 > good_features ) { <nl> + tprintf ( " Deleting outlier sample of % s , % d good , % d bad \ n " , <nl> + SampleToString ( sample ) . string ( ) , <nl> + good_features , bad_features ) ; <nl> + if ( debug ) { <nl> + pixaAddPix ( pixa , sample . RenderToPix ( & unicharset_ ) , L_INSERT ) ; <nl> + / / Add the previous sample as well , so it is easier to see in <nl> + / / the output what is wrong with this sample . <nl> + int t ; <nl> + if ( i = = 0 ) <nl> + t = fcinfo . samples [ 1 ] ; <nl> + else <nl> + t = fcinfo . samples [ i - 1 ] ; <nl> + const TrainingSample & csample = * samples_ [ t ] ; <nl> + pixaAddPix ( pixa , csample . RenderToPix ( & unicharset_ ) , L_INSERT ) ; <nl> + } <nl> + / / Mark the sample for deletion . <nl> + KillSample ( samples_ [ s ] ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + / / Truly delete all bad samples and renumber everything . <nl> + DeleteDeadSamples ( ) ; <nl> + if ( pixa ! = NULL ) { <nl> + Pix * pix = pixaDisplayTiledInRows ( pixa , 1 , 2600 , 1 . 0 , 0 , 10 , 10 ) ; <nl> + pixaDestroy ( & pixa ) ; <nl> + pixWrite ( " outliers . png " , pix , IFF_PNG ) ; <nl> + pixDestroy ( & pix ) ; <nl> + } <nl> + } <nl> + <nl> + / / Marks the given sample index for deletion . <nl> + / / Deletion is actually completed by DeleteDeadSamples . <nl> + void TrainingSampleSet : : KillSample ( TrainingSample * sample ) { <nl> + sample - > set_sample_index ( - 1 ) ; <nl> + } <nl> + <nl> + / / Deletes all samples with zero features marked by KillSample . <nl> + void TrainingSampleSet : : DeleteDeadSamples ( ) { <nl> + samples_ . compact ( <nl> + NewPermanentTessCallback ( this , & TrainingSampleSet : : DeleteableSample ) ) ; <nl> + num_raw_samples_ = samples_ . size ( ) ; <nl> + / / Samples must be re - organized now we have deleted a few . <nl> + } <nl> + <nl> + / / Callback function returns true if the given sample is to be deleted , due <nl> + / / to having a negative classid . <nl> + bool TrainingSampleSet : : DeleteableSample ( const TrainingSample * sample ) { <nl> + return sample = = NULL | | sample - > class_id ( ) < 0 ; <nl> + } <nl> + <nl> + static Pix * DebugSample ( const UNICHARSET & unicharset , <nl> + TrainingSample * sample ) { <nl> + tprintf ( " \ nOriginal features : \ n " ) ; <nl> + for ( int i = 0 ; i < sample - > num_features ( ) ; + + i ) { <nl> + sample - > features ( ) [ i ] . print ( ) ; <nl> + } <nl> + if ( sample - > features_are_mapped ( ) ) { <nl> + tprintf ( " \ nMapped features : \ n " ) ; <nl> + for ( int i = 0 ; i < sample - > mapped_features ( ) . size ( ) ; + + i ) { <nl> + tprintf ( " % d " , sample - > mapped_features ( ) [ i ] ) ; <nl> + } <nl> + tprintf ( " \ n " ) ; <nl> + } <nl> + return sample - > RenderToPix ( & unicharset ) ; <nl> + } <nl> + <nl> + / / Construct an array to access the samples by font , class pair . <nl> + void TrainingSampleSet : : OrganizeByFontAndClass ( ) { <nl> + / / Font indexes are sparse , so we used a map to compact them , so we can <nl> + / / have an efficient 2 - d array of fonts and character classes . <nl> + SetupFontIdMap ( ) ; <nl> + int compact_font_size = font_id_map_ . CompactSize ( ) ; <nl> + / / Get a 2 - d array of generic vectors . <nl> + if ( font_class_array_ ! = NULL ) <nl> + delete font_class_array_ ; <nl> + FontClassInfo empty ; <nl> + font_class_array_ = new GENERIC_2D_ARRAY < FontClassInfo > ( <nl> + compact_font_size , unicharset_size_ , empty ) ; <nl> + for ( int s = 0 ; s < samples_ . size ( ) ; + + s ) { <nl> + int font_id = samples_ [ s ] - > font_id ( ) ; <nl> + int class_id = samples_ [ s ] - > class_id ( ) ; <nl> + if ( font_id < 0 | | font_id > = font_id_map_ . SparseSize ( ) ) { <nl> + tprintf ( " Font id = % d / % d , class id = % d / % d on sample % d \ n " , <nl> + font_id , font_id_map_ . SparseSize ( ) , class_id , unicharset_size_ , <nl> + s ) ; <nl> + } <nl> + ASSERT_HOST ( font_id > = 0 & & font_id < font_id_map_ . SparseSize ( ) ) ; <nl> + ASSERT_HOST ( class_id > = 0 & & class_id < unicharset_size_ ) ; <nl> + int font_index = font_id_map_ . SparseToCompact ( font_id ) ; <nl> + ( * font_class_array_ ) ( font_index , class_id ) . samples . push_back ( s ) ; <nl> + } <nl> + / / Set the num_raw_samples member of the FontClassInfo , to set the boundary <nl> + / / between the raw samples and the replicated ones . <nl> + for ( int f = 0 ; f < compact_font_size ; + + f ) { <nl> + for ( int c = 0 ; c < unicharset_size_ ; + + c ) <nl> + ( * font_class_array_ ) ( f , c ) . num_raw_samples = <nl> + ( * font_class_array_ ) ( f , c ) . samples . size ( ) ; <nl> + } <nl> + / / This is the global number of samples and also marks the boundary between <nl> + / / real and replicated samples . <nl> + num_raw_samples_ = samples_ . size ( ) ; <nl> + } <nl> + <nl> + / / Constructs the font_id_map_ which maps real font_ids ( sparse ) to a compact <nl> + / / index for the font_class_array_ . <nl> + void TrainingSampleSet : : SetupFontIdMap ( ) { <nl> + / / Number of samples for each font_id . <nl> + GenericVector < int > font_counts ; <nl> + for ( int s = 0 ; s < samples_ . size ( ) ; + + s ) { <nl> + int font_id = samples_ [ s ] - > font_id ( ) ; <nl> + while ( font_id > = font_counts . size ( ) ) <nl> + font_counts . push_back ( 0 ) ; <nl> + + + font_counts [ font_id ] ; <nl> + } <nl> + font_id_map_ . Init ( font_counts . size ( ) , false ) ; <nl> + for ( int f = 0 ; f < font_counts . size ( ) ; + + f ) { <nl> + font_id_map_ . SetMap ( f , font_counts [ f ] > 0 ) ; <nl> + } <nl> + font_id_map_ . Setup ( ) ; <nl> + } <nl> + <nl> + <nl> + / / Finds the sample for each font , class pair that has least maximum <nl> + / / distance to all the other samples of the same font , class . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + void TrainingSampleSet : : ComputeCanonicalSamples ( const IntFeatureMap & map , <nl> + bool debug ) { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + IntFeatureDist f_table ; <nl> + if ( debug ) tprintf ( " feature table size % d \ n " , map . sparse_size ( ) ) ; <nl> + f_table . Init ( & map ) ; <nl> + int worst_s1 = 0 ; <nl> + int worst_s2 = 0 ; <nl> + double global_worst_dist = 0 . 0 ; <nl> + / / Compute distances independently for each font and char index . <nl> + int font_size = font_id_map_ . CompactSize ( ) ; <nl> + for ( int font_index = 0 ; font_index < font_size ; + + font_index ) { <nl> + int font_id = font_id_map_ . CompactToSparse ( font_index ) ; <nl> + for ( int c = 0 ; c < unicharset_size_ ; + + c ) { <nl> + int samples_found = 0 ; <nl> + FontClassInfo & fcinfo = ( * font_class_array_ ) ( font_index , c ) ; <nl> + if ( fcinfo . samples . size ( ) = = 0 | | <nl> + ( kTestChar > = 0 & & c ! = kTestChar ) ) { <nl> + fcinfo . canonical_sample = - 1 ; <nl> + fcinfo . canonical_dist = 0 . 0f ; <nl> + if ( debug ) tprintf ( " Skipping class % d \ n " , c ) ; <nl> + continue ; <nl> + } <nl> + / / The canonical sample will be the one with the min_max_dist , which <nl> + / / is the sample with the lowest maximum distance to all other samples . <nl> + double min_max_dist = 2 . 0 ; <nl> + / / We keep track of the farthest apart pair ( max_s1 , max_s2 ) which <nl> + / / are max_max_dist apart , so we can see how bad the variability is . <nl> + double max_max_dist = 0 . 0 ; <nl> + int max_s1 = 0 ; <nl> + int max_s2 = 0 ; <nl> + fcinfo . canonical_sample = fcinfo . samples [ 0 ] ; <nl> + fcinfo . canonical_dist = 0 . 0f ; <nl> + for ( int i = 0 ; i < fcinfo . samples . size ( ) ; + + i ) { <nl> + int s1 = fcinfo . samples [ i ] ; <nl> + const GenericVector < int > & features1 = samples_ [ s1 ] - > indexed_features ( ) ; <nl> + f_table . Set ( features1 , features1 . size ( ) , true ) ; <nl> + double max_dist = 0 . 0 ; <nl> + / / Run the full squared - order search for similar samples . It is still <nl> + / / reasonably fast because f_table . FeatureDistance is fast , but we <nl> + / / may have to reconsider if we start playing with too many samples <nl> + / / of a single char / font . <nl> + for ( int j = 0 ; j < fcinfo . samples . size ( ) ; + + j ) { <nl> + int s2 = fcinfo . samples [ j ] ; <nl> + if ( samples_ [ s2 ] - > class_id ( ) ! = c | | <nl> + samples_ [ s2 ] - > font_id ( ) ! = font_id | | <nl> + s2 = = s1 ) <nl> + continue ; <nl> + GenericVector < int > features2 = samples_ [ s2 ] - > indexed_features ( ) ; <nl> + double dist = f_table . FeatureDistance ( features2 ) ; <nl> + int height = samples_ [ s2 ] - > geo_feature ( GeoTop ) - <nl> + samples_ [ s2 ] - > geo_feature ( GeoBottom ) ; <nl> + if ( dist = = 1 . 0 & & height > 64 ) { <nl> + / / TODO ( rays ) rethink this when the polygonal approximation goes . <nl> + / / Currently it is possible for dots and other small characters <nl> + / / to be completely different , even within the same class . <nl> + f_table . DebugFeatureDistance ( features2 ) ; <nl> + } <nl> + if ( dist > max_dist ) { <nl> + max_dist = dist ; <nl> + if ( dist > max_max_dist ) { <nl> + max_s1 = s1 ; <nl> + max_s2 = s2 ; <nl> + } <nl> + } <nl> + } <nl> + / / Using Set ( . . . , false ) is far faster than re initializing , due to <nl> + / / the sparseness of the feature space . <nl> + f_table . Set ( features1 , features1 . size ( ) , false ) ; <nl> + samples_ [ s1 ] - > set_max_dist ( max_dist ) ; <nl> + + + samples_found ; <nl> + if ( max_dist < min_max_dist ) { <nl> + fcinfo . canonical_sample = s1 ; <nl> + fcinfo . canonical_dist = max_dist ; <nl> + } <nl> + UpdateRange ( max_dist , & min_max_dist , & max_max_dist ) ; <nl> + } <nl> + if ( max_max_dist > global_worst_dist ) { <nl> + / / Keep a record of the worst pair over all characters / fonts too . <nl> + global_worst_dist = max_max_dist ; <nl> + worst_s1 = max_s1 ; <nl> + worst_s2 = max_s2 ; <nl> + } <nl> + if ( debug ) { <nl> + tprintf ( " Found % d samples of class % d = % s , font % d , " <nl> + " dist range [ % g , % g ] , worst pair = % s , % s \ n " , <nl> + samples_found , c , unicharset_ . debug_str ( c ) . string ( ) , <nl> + font_index , min_max_dist , max_max_dist , <nl> + SampleToString ( * samples_ [ max_s1 ] ) . string ( ) , <nl> + SampleToString ( * samples_ [ max_s2 ] ) . string ( ) ) ; <nl> + } <nl> + } <nl> + } <nl> + if ( debug ) { <nl> + tprintf ( " Global worst dist = % g , between sample % d and % d \ n " , <nl> + global_worst_dist , worst_s1 , worst_s2 ) ; <nl> + Pix * pix1 = DebugSample ( unicharset_ , samples_ [ worst_s1 ] ) ; <nl> + Pix * pix2 = DebugSample ( unicharset_ , samples_ [ worst_s2 ] ) ; <nl> + pixOr ( pix1 , pix1 , pix2 ) ; <nl> + pixWrite ( " worstpair . png " , pix1 , IFF_PNG ) ; <nl> + pixDestroy ( & pix1 ) ; <nl> + pixDestroy ( & pix2 ) ; <nl> + } <nl> + } <nl> + <nl> + / / Replicates the samples to a minimum frequency defined by <nl> + / / 2 * kSampleRandomSize , or for larger counts duplicates all samples . <nl> + / / After replication , the replicated samples are perturbed slightly , but <nl> + / / in a predictable and repeatable way . <nl> + / / Use after OrganizeByFontAndClass ( ) . <nl> + void TrainingSampleSet : : ReplicateAndRandomizeSamples ( ) { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_size = font_id_map_ . CompactSize ( ) ; <nl> + for ( int font_index = 0 ; font_index < font_size ; + + font_index ) { <nl> + for ( int c = 0 ; c < unicharset_size_ ; + + c ) { <nl> + FontClassInfo & fcinfo = ( * font_class_array_ ) ( font_index , c ) ; <nl> + int sample_count = fcinfo . samples . size ( ) ; <nl> + int min_samples = 2 * MAX ( kSampleRandomSize , sample_count ) ; <nl> + if ( sample_count > 0 & & sample_count < min_samples ) { <nl> + int base_count = sample_count ; <nl> + for ( int base_index = 0 ; sample_count < min_samples ; + + sample_count ) { <nl> + int src_index = fcinfo . samples [ base_index + + ] ; <nl> + if ( base_index > = base_count ) base_index = 0 ; <nl> + TrainingSample * sample = samples_ [ src_index ] - > RandomizedCopy ( <nl> + sample_count % kSampleRandomSize ) ; <nl> + int sample_index = samples_ . size ( ) ; <nl> + sample - > set_sample_index ( sample_index ) ; <nl> + samples_ . push_back ( sample ) ; <nl> + fcinfo . samples . push_back ( sample_index ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Caches the indexed features of the canonical samples . <nl> + / / ComputeCanonicalSamples must have been already called . <nl> + / / TODO ( rays ) see note on ReliablySeparable and try restricting the <nl> + / / canonical features to those that truly represent all samples . <nl> + void TrainingSampleSet : : ComputeCanonicalFeatures ( ) { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_size = font_id_map_ . CompactSize ( ) ; <nl> + for ( int font_index = 0 ; font_index < font_size ; + + font_index ) { <nl> + int font_id = font_id_map_ . CompactToSparse ( font_index ) ; <nl> + for ( int c = 0 ; c < unicharset_size_ ; + + c ) { <nl> + int num_samples = NumClassSamples ( font_id , c , false ) ; <nl> + if ( num_samples = = 0 ) <nl> + continue ; <nl> + const TrainingSample * sample = GetCanonicalSample ( font_id , c ) ; <nl> + FontClassInfo & fcinfo = ( * font_class_array_ ) ( font_index , c ) ; <nl> + fcinfo . canonical_features = sample - > indexed_features ( ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Computes the combined set of features used by all the samples of each <nl> + / / font / class combination . Use after ReplicateAndRandomizeSamples . <nl> + void TrainingSampleSet : : ComputeCloudFeatures ( int feature_space_size ) { <nl> + ASSERT_HOST ( font_class_array_ ! = NULL ) ; <nl> + int font_size = font_id_map_ . CompactSize ( ) ; <nl> + for ( int font_index = 0 ; font_index < font_size ; + + font_index ) { <nl> + int font_id = font_id_map_ . CompactToSparse ( font_index ) ; <nl> + for ( int c = 0 ; c < unicharset_size_ ; + + c ) { <nl> + int num_samples = NumClassSamples ( font_id , c , false ) ; <nl> + if ( num_samples = = 0 ) <nl> + continue ; <nl> + FontClassInfo & fcinfo = ( * font_class_array_ ) ( font_index , c ) ; <nl> + fcinfo . cloud_features . Init ( feature_space_size ) ; <nl> + for ( int s = 0 ; s < num_samples ; + + s ) { <nl> + const TrainingSample * sample = GetSample ( font_id , c , s ) ; <nl> + const GenericVector < int > & sample_features = sample - > indexed_features ( ) ; <nl> + for ( int i = 0 ; i < sample_features . size ( ) ; + + i ) <nl> + fcinfo . cloud_features . SetBit ( sample_features [ i ] ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Adds all fonts of the given class to the shape . <nl> + void TrainingSampleSet : : AddAllFontsForClass ( int class_id , Shape * shape ) const { <nl> + for ( int f = 0 ; f < font_id_map_ . CompactSize ( ) ; + + f ) { <nl> + int font_id = font_id_map_ . CompactToSparse ( f ) ; <nl> + shape - > AddToShape ( class_id , font_id ) ; <nl> + } <nl> + } <nl> + <nl> + / / Display the samples with the given indexed feature that also match <nl> + / / the given shape . <nl> + void TrainingSampleSet : : DisplaySamplesWithFeature ( int f_index , <nl> + const Shape & shape , <nl> + const IntFeatureSpace & space , <nl> + ScrollView : : Color color , <nl> + ScrollView * window ) const { <nl> + for ( int s = 0 ; s < num_raw_samples ( ) ; + + s ) { <nl> + const TrainingSample * sample = GetSample ( s ) ; <nl> + if ( shape . ContainsUnichar ( sample - > class_id ( ) ) ) { <nl> + GenericVector < int > indexed_features ; <nl> + space . IndexAndSortFeatures ( sample - > features ( ) , sample - > num_features ( ) , <nl> + & indexed_features ) ; <nl> + for ( int f = 0 ; f < indexed_features . size ( ) ; + + f ) { <nl> + if ( indexed_features [ f ] = = f_index ) { <nl> + sample - > DisplayFeatures ( color , window ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + <nl> + } / / namespace tesseract . <nl> new file mode 100644 <nl> index 000000000 . . 4ff4e86e0 <nl> mmm / dev / null <nl> ppp b / classify / trainingsampleset . h <nl> <nl> + / / Copyright 2010 Google Inc . All Rights Reserved . <nl> + / / Author : rays @ google . com ( Ray Smith ) <nl> + / / <nl> + / / Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + / / you may not use this file except in compliance with the License . <nl> + / / You may obtain a copy of the License at <nl> + / / http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + / / Unless required by applicable law or agreed to in writing , software <nl> + / / distributed under the License is distributed on an " AS IS " BASIS , <nl> + / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + / / See the License for the specific language governing permissions and <nl> + / / limitations under the License . <nl> + / / <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + # ifndef TESSERACT_TRAINING_TRAININGSAMPLESET_H__ <nl> + # define TESSERACT_TRAINING_TRAININGSAMPLESET_H__ <nl> + <nl> + # include " bitvector . h " <nl> + # include " genericvector . h " <nl> + # include " indexmapbidi . h " <nl> + # include " matrix . h " <nl> + # include " shapetable . h " <nl> + # include " trainingsample . h " <nl> + <nl> + class UNICHARSET ; <nl> + template < typename T > class UnicityTable ; <nl> + <nl> + namespace tesseract { <nl> + <nl> + struct FontInfo ; <nl> + class IntFeatureMap ; <nl> + class IntFeatureSpace ; <nl> + class TrainingSample ; <nl> + class UnicharAndFonts ; <nl> + <nl> + / / Collection of TrainingSample used for training or testing a classifier . <nl> + / / Provides several useful methods to operate on the collection as a whole , <nl> + / / including outlier detection and deletion , providing access by font and <nl> + / / class , finding the canonical sample , finding the " cloud " features ( OR of <nl> + / / all features in all samples ) , replication of samples , caching of distance <nl> + / / metrics . <nl> + class TrainingSampleSet { <nl> + public : <nl> + explicit TrainingSampleSet ( const UnicityTable < FontInfo > & fontinfo_table ) ; <nl> + ~ TrainingSampleSet ( ) ; <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) const ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Accessors <nl> + int num_samples ( ) const { <nl> + return samples_ . size ( ) ; <nl> + } <nl> + int num_raw_samples ( ) const { <nl> + return num_raw_samples_ ; <nl> + } <nl> + int NumFonts ( ) const { <nl> + return font_id_map_ . SparseSize ( ) ; <nl> + } <nl> + const UNICHARSET & unicharset ( ) const { <nl> + return unicharset_ ; <nl> + } <nl> + int charsetsize ( ) const { <nl> + return unicharset_size_ ; <nl> + } <nl> + <nl> + / / Loads an initial unicharset , or sets one up if the file cannot be read . <nl> + void LoadUnicharset ( const char * filename ) ; <nl> + <nl> + / / Adds a character sample to this sample set . <nl> + / / If the unichar is not already in the local unicharset , it is added . <nl> + / / Returns the unichar_id of the added sample , from the local unicharset . <nl> + int AddSample ( const char * unichar , TrainingSample * sample ) ; <nl> + / / Adds a character sample to this sample set with the given unichar_id , <nl> + / / which must correspond to the local unicharset ( in this ) . <nl> + void AddSample ( int unichar_id , TrainingSample * sample ) ; <nl> + <nl> + / / Returns the number of samples for the given font , class pair . <nl> + / / If randomize is true , returns the number of samples accessible <nl> + / / with randomizing on . ( Increases the number of samples if small . ) <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + int NumClassSamples ( int font_id , int class_id , bool randomize ) const ; <nl> + <nl> + / / Gets a sample by its index . <nl> + const TrainingSample * GetSample ( int index ) const ; <nl> + <nl> + / / Gets a sample by its font , class , index . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + const TrainingSample * GetSample ( int font_id , int class_id , int index ) const ; <nl> + <nl> + / / Get a sample by its font , class , index . Does not randomize . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + TrainingSample * MutableSample ( int font_id , int class_id , int index ) ; <nl> + <nl> + / / Returns a string debug representation of the given sample : <nl> + / / font , unichar_str , bounding box , page . <nl> + STRING SampleToString ( const TrainingSample & sample ) const ; <nl> + <nl> + / / Gets the combined set of features used by all the samples of the given <nl> + / / font / class combination . <nl> + const BitVector & GetCloudFeatures ( int font_id , int class_id ) const ; <nl> + / / Gets the indexed features of the canonical sample of the given <nl> + / / font / class combination . <nl> + const GenericVector < int > & GetCanonicalFeatures ( int font_id , <nl> + int class_id ) const ; <nl> + <nl> + / / Returns the distance between the given UniCharAndFonts pair . <nl> + / / If matched_fonts , only matching fonts , are considered , unless that yields <nl> + / / the empty set . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + float UnicharDistance ( const UnicharAndFonts & uf1 , const UnicharAndFonts & uf2 , <nl> + bool matched_fonts , const IntFeatureMap & feature_map ) ; <nl> + <nl> + / / Returns the distance between the given pair of font / class pairs . <nl> + / / Finds in cache or computes and caches . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + float ClusterDistance ( int font_id1 , int class_id1 , <nl> + int font_id2 , int class_id2 , <nl> + const IntFeatureMap & feature_map ) ; <nl> + <nl> + / / Computes the distance between the given pair of font / class pairs . <nl> + float ComputeClusterDistance ( int font_id1 , int class_id1 , <nl> + int font_id2 , int class_id2 , <nl> + const IntFeatureMap & feature_map ) const ; <nl> + <nl> + / / Returns the number of canonical features of font / class 2 for which <nl> + / / neither the feature nor any of its near neighbors occurs in the cloud <nl> + / / of font / class 1 . Each such feature is a reliable separation between <nl> + / / the classes , ASSUMING that the canonical sample is sufficiently <nl> + / / representative that every sample has a feature near that particular <nl> + / / feature . To check that this is so on the fly would be prohibitively <nl> + / / expensive , but it might be possible to pre - qualify the canonical features <nl> + / / to include only those for which this assumption is true . <nl> + / / ComputeCanonicalFeatures and ComputeCloudFeatures must have been called <nl> + / / first , or the results will be nonsense . <nl> + int ReliablySeparable ( int font_id1 , int class_id1 , <nl> + int font_id2 , int class_id2 , <nl> + const IntFeatureMap & feature_map , <nl> + bool thorough ) const ; <nl> + <nl> + <nl> + / / Returns the total index of the requested sample . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + int GlobalSampleIndex ( int font_id , int class_id , int index ) const ; <nl> + <nl> + / / Gets the canonical sample for the given font , class pair . <nl> + / / ComputeCanonicalSamples must have been called first . <nl> + const TrainingSample * GetCanonicalSample ( int font_id , int class_id ) const ; <nl> + / / Gets the max distance for the given canonical sample . <nl> + / / ComputeCanonicalSamples must have been called first . <nl> + float GetCanonicalDist ( int font_id , int class_id ) const ; <nl> + <nl> + / / Returns a mutable pointer to the sample with the given index . <nl> + TrainingSample * mutable_sample ( int index ) { <nl> + return samples_ [ index ] ; <nl> + } <nl> + / / Gets ownership of the sample with the given index , removing it from this . <nl> + TrainingSample * extract_sample ( int index ) { <nl> + TrainingSample * sample = samples_ [ index ] ; <nl> + samples_ [ index ] = NULL ; <nl> + return sample ; <nl> + } <nl> + <nl> + / / Generates indexed features for all samples with the supplied feature_space . <nl> + void IndexFeatures ( const IntFeatureSpace & feature_space ) ; <nl> + <nl> + / / Delete outlier samples with few features that are shared with others . <nl> + / / IndexFeatures must have been called already . <nl> + void DeleteOutliers ( const IntFeatureSpace & feature_space , bool debug ) ; <nl> + <nl> + / / Marks the given sample for deletion . <nl> + / / Deletion is actually completed by DeleteDeadSamples . <nl> + void KillSample ( TrainingSample * sample ) ; <nl> + <nl> + / / Deletes all samples with a negative sample index marked by KillSample . <nl> + / / Must be called before OrganizeByFontAndClass , and OrganizeByFontAndClass <nl> + / / must be called after as the samples have been renumbered . <nl> + void DeleteDeadSamples ( ) ; <nl> + <nl> + / / Callback function returns true if the given sample is to be deleted , due <nl> + / / to having a negative classid . <nl> + bool DeleteableSample ( const TrainingSample * sample ) ; <nl> + <nl> + / / Construct an array to access the samples by font , class pair . <nl> + void OrganizeByFontAndClass ( ) ; <nl> + <nl> + / / Constructs the font_id_map_ which maps real font_ids ( sparse ) to a compact <nl> + / / index for the font_class_array_ . <nl> + void SetupFontIdMap ( ) ; <nl> + <nl> + / / Finds the sample for each font , class pair that has least maximum <nl> + / / distance to all the other samples of the same font , class . <nl> + / / OrganizeByFontAndClass must have been already called . <nl> + void ComputeCanonicalSamples ( const IntFeatureMap & map , bool debug ) ; <nl> + <nl> + / / Replicates the samples to a minimum frequency defined by <nl> + / / 2 * kSampleRandomSize , or for larger counts duplicates all samples . <nl> + / / After replication , the replicated samples are perturbed slightly , but <nl> + / / in a predictable and repeatable way . <nl> + / / Use after OrganizeByFontAndClass ( ) . <nl> + void ReplicateAndRandomizeSamples ( ) ; <nl> + <nl> + / / Caches the indexed features of the canonical samples . <nl> + / / ComputeCanonicalSamples must have been already called . <nl> + void ComputeCanonicalFeatures ( ) ; <nl> + / / Computes the combined set of features used by all the samples of each <nl> + / / font / class combination . Use after ReplicateAndRandomizeSamples . <nl> + void ComputeCloudFeatures ( int feature_space_size ) ; <nl> + <nl> + / / Adds all fonts of the given class to the shape . <nl> + void AddAllFontsForClass ( int class_id , Shape * shape ) const ; <nl> + <nl> + / / Display the samples with the given indexed feature that also match <nl> + / / the given shape . <nl> + void DisplaySamplesWithFeature ( int f_index , const Shape & shape , <nl> + const IntFeatureSpace & feature_space , <nl> + ScrollView : : Color color , <nl> + ScrollView * window ) const ; <nl> + <nl> + private : <nl> + / / Struct to store a triplet of unichar , font , distance in the distance cache . <nl> + struct FontClassDistance { <nl> + int unichar_id ; <nl> + int font_id ; / / Real font id . <nl> + float distance ; <nl> + } ; <nl> + / / Simple struct to store information related to each font / class combination . <nl> + struct FontClassInfo { <nl> + FontClassInfo ( ) ; <nl> + <nl> + / / Writes to the given file . Returns false in case of error . <nl> + bool Serialize ( FILE * fp ) const ; <nl> + / / Reads from the given file . Returns false in case of error . <nl> + / / If swap is true , assumes a big / little - endian swap is needed . <nl> + bool DeSerialize ( bool swap , FILE * fp ) ; <nl> + <nl> + / / Number of raw samples . <nl> + inT32 num_raw_samples ; <nl> + / / Index of the canonical sample . <nl> + inT32 canonical_sample ; <nl> + / / Max distance of the canonical sample from any other . <nl> + float canonical_dist ; <nl> + / / Sample indices for the samples , including replicated . <nl> + GenericVector < inT32 > samples ; <nl> + <nl> + / / Non - serialized cache data . <nl> + / / Indexed features of the canonical sample . <nl> + GenericVector < int > canonical_features ; <nl> + / / The mapped features of all the samples . <nl> + BitVector cloud_features ; <nl> + <nl> + / / Caches for ClusterDistance . <nl> + / / Caches for other fonts but matching this unichar . - 1 indicates not set . <nl> + / / Indexed by compact font index from font_id_map_ . <nl> + GenericVector < float > font_distance_cache ; <nl> + / / Caches for other unichars but matching this font . - 1 indicates not set . <nl> + GenericVector < float > unichar_distance_cache ; <nl> + / / Cache for the rest ( non matching font and unichar . ) <nl> + / / A cache of distances computed by ReliablySeparable . <nl> + GenericVector < FontClassDistance > distance_cache ; <nl> + } ; <nl> + <nl> + PointerVector < TrainingSample > samples_ ; <nl> + / / Number of samples before replication / randomization . <nl> + int num_raw_samples_ ; <nl> + / / Character set we are training for . <nl> + UNICHARSET unicharset_ ; <nl> + / / Character set size to which the 2 - d arrays below refer . <nl> + int unicharset_size_ ; <nl> + / / Map to allow the font_class_array_ below to be compact . <nl> + / / The sparse space is the real font_id , used in samples_ . <nl> + / / The compact space is an index to font_class_array_ <nl> + IndexMapBiDi font_id_map_ ; <nl> + / / A 2 - d array of FontClassInfo holding information related to each <nl> + / / ( font_id , class_id ) pair . <nl> + GENERIC_2D_ARRAY < FontClassInfo > * font_class_array_ ; <nl> + <nl> + / / Reference to the fontinfo_table_ in MasterTrainer . Provides names <nl> + / / for font_ids in the samples . Not serialized ! <nl> + const UnicityTable < FontInfo > & fontinfo_table_ ; <nl> + } ; <nl> + <nl> + } / / namespace tesseract . <nl> + <nl> + <nl> + # endif / / TRAININGSAMPLESETSET_H_ <nl>
Added simultaneous multi - language capability , Added support for ShapeTable in classifier and training , Refactored class pruner , Added new uniform classifier API , Added new training error counter
tesseract-ocr/tesseract
5bc5e2a0b427e1c92057708b44bb6b4094f12439
2012-02-02T02:57:42Z
mmm a / db / db . cpp <nl> ppp b / db / db . cpp <nl> namespace mongo { <nl> dbexit ( EXIT_UNCAUGHT ) ; <nl> } <nl> <nl> - / / any thread cleanup can happen here <nl> - <nl> - if ( currentClient . get ( ) ) <nl> - currentClient - > shutdown ( ) ; <nl> + / / thread ending . . . <nl> + { <nl> + Client * c = currentClient . get ( ) ; <nl> + if ( c ) c - > shutdown ( ) ; <nl> + } <nl> globalScriptEngine - > threadDone ( ) ; <nl> } <nl> <nl> namespace mongo { <nl> <nl> MessagingPort p ; <nl> if ( ! p . connect ( db ) ) { <nl> - out ( ) < < " msg couldn ' t connect " < < endl ; <nl> + log ( ) < < " msg couldn ' t connect " < < endl ; <nl> return ; <nl> } <nl> <nl>
cleaning
mongodb/mongo
36566550f047d0aebbf94e1e2263f36871794a99
2010-08-26T15:59:30Z
mmm a / android / service / doc / BaseLoaderCallback . rst <nl> ppp b / android / service / doc / BaseLoaderCallback . rst <nl> There is a very base code snippet implementing the async initialization with Bas <nl> super . onResume ( ) ; <nl> <nl> Log . i ( TAG , " Trying to load OpenCV library " ) ; <nl> - if ( ! OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mOpenCVCallBack ) ) <nl> + if ( ! OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mOpenCVCallBack ) ) <nl> { <nl> Log . e ( TAG , " Cannot connect to OpenCV Manager " ) ; <nl> } <nl> There is a very base code snippet implementing the async initialization with Bas <nl> Using in Service <nl> mmmmmmmmmmmmmmm - <nl> <nl> - Default BaseLoaderCallback implementation treat application context as Activity and calls Activity . finish ( ) method to exit in case of initialization failure . <nl> - To override this behavior you need to override finish ( ) method of BaseLoaderCallback class and implement your own finalization method . <nl> + Default BaseLoaderCallback implementation treat application context as Activity and calls Activity . finish ( ) method to exit in case of initialization failure . <nl> + To override this behavior you need to override finish ( ) method of BaseLoaderCallback class and implement your own finalization method . <nl> <nl> mmm a / android / service / doc / JavaHelper . rst <nl> ppp b / android / service / doc / JavaHelper . rst <nl> OpenCV version constants <nl> <nl> OpenCV Library version 2 . 4 . 2 <nl> <nl> + . . data : : OPENCV_VERSION_2_4_3 <nl> + <nl> + OpenCV Library version 2 . 4 . 3 <nl> + <nl> Other constatnts <nl> mmmmmmmmmmmmmmm - <nl> <nl> mmm a / android / service / doc / LoaderCallbackInterface . rst <nl> ppp b / android / service / doc / LoaderCallbackInterface . rst <nl> void onManagerConnected ( ) <nl> . . method : : void onManagerConnected ( int status ) <nl> <nl> Callback method that is called after OpenCV Library initialization . <nl> - <nl> + <nl> : param status : status of initialization ( see Initialization Status Constants ) . <nl> <nl> void onPackageInstall ( ) <nl> mmm a / android / service / engine / jni / BinderComponent / OpenCVEngine . cpp <nl> ppp b / android / service / engine / jni / BinderComponent / OpenCVEngine . cpp <nl> std : : set < std : : string > OpenCVEngine : : InitKnownOpenCVersions ( ) <nl> result . insert ( " 240 " ) ; <nl> result . insert ( " 241 " ) ; <nl> result . insert ( " 242 " ) ; <nl> + result . insert ( " 243 " ) ; <nl> <nl> return result ; <nl> } <nl> mmm a / modules / java / generator / src / java / android + OpenCVLoader . java <nl> ppp b / modules / java / generator / src / java / android + OpenCVLoader . java <nl> <nl> * / <nl> public static final String OPENCV_VERSION_2_4_2 = " 2 . 4 . 2 " ; <nl> <nl> + / * * <nl> + * OpenCV Library version 2 . 4 . 3 . <nl> + * / <nl> + public static final String OPENCV_VERSION_2_4_3 = " 2 . 4 . 3 " ; <nl> + <nl> / * * <nl> * Loads and initializes OpenCV library from current application package . Roughly , it ' s an analog of system . loadLibrary ( " opencv_java " ) . <nl> * @ return Returns true is initialization of OpenCV was successful . <nl> mmm a / samples / android / 15 - puzzle / src / org / opencv / samples / puzzle15 / Puzzle15Activity . java <nl> ppp b / samples / android / 15 - puzzle / src / org / opencv / samples / puzzle15 / Puzzle15Activity . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / color - blob - detection / src / org / opencv / samples / colorblobdetect / ColorBlobDetectionActivity . java <nl> ppp b / samples / android / color - blob - detection / src / org / opencv / samples / colorblobdetect / ColorBlobDetectionActivity . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / face - detection / src / org / opencv / samples / fd / FdActivity . java <nl> ppp b / samples / android / face - detection / src / org / opencv / samples / fd / FdActivity . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / image - manipulations / src / org / opencv / samples / imagemanipulations / ImageManipulationsActivity . java <nl> ppp b / samples / android / image - manipulations / src / org / opencv / samples / imagemanipulations / ImageManipulationsActivity . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / tutorial - 1 - addopencv / src / org / opencv / samples / tutorial1 / Sample1Java . java <nl> ppp b / samples / android / tutorial - 1 - addopencv / src / org / opencv / samples / tutorial1 / Sample1Java . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / tutorial - 2 - opencvcamera / src / org / opencv / samples / tutorial2 / Sample2NativeCamera . java <nl> ppp b / samples / android / tutorial - 2 - opencvcamera / src / org / opencv / samples / tutorial2 / Sample2NativeCamera . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / tutorial - 3 - native / src / org / opencv / samples / tutorial3 / Sample3Native . java <nl> ppp b / samples / android / tutorial - 3 - native / src / org / opencv / samples / tutorial3 / Sample3Native . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl> mmm a / samples / android / tutorial - 4 - mixed / src / org / opencv / samples / tutorial4 / Sample4Mixed . java <nl> ppp b / samples / android / tutorial - 4 - mixed / src / org / opencv / samples / tutorial4 / Sample4Mixed . java <nl> public void onPause ( ) <nl> public void onResume ( ) <nl> { <nl> super . onResume ( ) ; <nl> - OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_2 , this , mLoaderCallback ) ; <nl> + OpenCVLoader . initAsync ( OpenCVLoader . OPENCV_VERSION_2_4_3 , this , mLoaderCallback ) ; <nl> } <nl> <nl> public void onDestroy ( ) { <nl>
2 . 4 . 3 version support added to OpenCV Manager . Docs updated . Samples updated .
opencv/opencv
76bcf72ded5fe7101fab2be507941e683ed18890
2012-10-24T05:51:01Z
mmm a / modules / python / src2 / cv2 . cpp <nl> ppp b / modules / python / src2 / cv2 . cpp <nl> static int pyopencv_to ( const PyObject * o , Mat & m , const ArgInfo info , bool allow <nl> needcopy = true ; <nl> } <nl> <nl> + if ( ismultichannel & & _strides [ 1 ] ! = ( npy_intp ) elemsize * _sizes [ 2 ] ) <nl> + needcopy = true ; <nl> + <nl> if ( needcopy ) <nl> { <nl> if ( info . outputarg ) <nl> { <nl> - failmsg ( " output array % s is not row - contiguous ( step [ ndims - 1 ] ! = elemsize ) " , info . name ) ; <nl> + failmsg ( " Layout of the output array % s is compatible with cv : : Mat ( step [ ndims - 1 ] ! = elemsize or step [ 1 ] ! = elemsize * nchannels ) " , info . name ) ; <nl> return false ; <nl> } <nl> if ( needcast ) <nl>
fixed bugs ( kind of ) and
opencv/opencv
d652cc72f2ab09f5fbe1066ee2d0f1e5bdc568af
2012-10-19T16:47:57Z
mmm a / tensorflow / contrib / graph_editor / transform . py <nl> ppp b / tensorflow / contrib / graph_editor / transform . py <nl> def copy_op_handler ( info , op , copy_shape = True ) : <nl> control_inputs_ = [ ci for ci in control_inputs_ if ci is not None ] <nl> <nl> # Transform it if any : <nl> - original_op_ = info . transformer . transform_original_op_hanlder ( info , <nl> + original_op_ = info . transformer . transform_original_op_handler ( info , <nl> op . _original_op ) <nl> <nl> # Transform inputs : <nl> def __init__ ( self ) : <nl> in sgv . inputs . This handler defaults to a transform which keep the same <nl> input if the source and destination graphs are the same , otherwise <nl> use placeholders . <nl> - transform_original_op_hanlder : handle the transform of original_op . This <nl> + transform_original_op_handler : handle the transform of original_op . This <nl> handler defaults to transforming original_op only if they are in the <nl> subgraph , otherwise they are ignored . <nl> " " " <nl> def __init__ ( self ) : <nl> self . assign_collections_handler = assign_renamed_collections_handler <nl> self . transform_external_input_handler = replace_t_with_placeholder_handler <nl> self . transform_external_hidden_input_handler = keep_t_if_possible_handler <nl> - self . transform_original_op_hanlder = transform_op_if_inside_handler <nl> + self . transform_original_op_handler = transform_op_if_inside_handler <nl> <nl> # temporary per - call variable <nl> self . _info = None <nl> def __call__ ( self , <nl> information about the transform , including mapping between <nl> original and transformed tensors and operations . <nl> Raises : <nl> - ValueError : if the argumens are invalid . <nl> + ValueError : if the arguments are invalid . <nl> " " " <nl> sgv = subgraph . make_view ( sgv ) <nl> if not isinstance ( dst_graph , tf_ops . Graph ) : <nl> def graph_replace ( target_ts , replacement_ts , dst_scope = " " , <nl> " " " Create a new graph which compute the targets from the replaced Tensors . <nl> <nl> Args : <nl> - target_ts : a single tf . Tensor or an iterabble of tf . Tensor . <nl> + target_ts : a single tf . Tensor or an iterable of tf . Tensor . <nl> replacement_ts : dictionary mapping from original tensors to replaced tensors <nl> dst_scope : the destination scope . <nl> src_scope : the source scope . <nl>
Fix spelling in identifier name ( hanlder - > handler ) .
tensorflow/tensorflow
ac312069ab40ff49103fd1061706da7a0a9d3772
2016-09-29T05:34:07Z
mmm a / swoole_client_coro . cc <nl> ppp b / swoole_client_coro . cc <nl> static void swoole_client_coro_free_object ( zend_object * object ) <nl> client_coro * client = swoole_client_coro_fetch_object ( object ) ; <nl> if ( client - > sock ) <nl> { <nl> - delete client - > sock ; <nl> + php_swoole_client_coro_socket_free ( client - > sock ) ; <nl> } <nl> zend_object_std_dtor ( & client - > std ) ; <nl> } <nl> static PHP_METHOD ( swoole_client_coro , __construct ) <nl> RETURN_TRUE ; <nl> } <nl> <nl> - static PHP_METHOD ( swoole_client_coro , __destruct ) <nl> - { <nl> - SW_PREVENT_USER_DESTRUCT ( ) ; <nl> - <nl> - client_coro_close ( ZEND_THIS ) ; <nl> - } <nl> + static PHP_METHOD ( swoole_client_coro , __destruct ) { } <nl> <nl> static PHP_METHOD ( swoole_client_coro , set ) <nl> { <nl>
Use free_obj
swoole/swoole-src
e8720fea5a30602abd610eda93b44d807e8d8dfb
2019-11-20T08:20:07Z
mmm a / . travis . yml <nl> ppp b / . travis . yml <nl> <nl> <nl> os : linux <nl> language : cpp <nl> + compiler : gcc <nl> env : <nl> global : <nl> - MAKEJOBS = - j3 <nl> matrix : <nl> env : HOST = x86_64 - unknown - linux - gnu DEP_OPTS = " NO_WALLET = 1 " RUN_TESTS = true GOAL = " install " BITCOIN_CONFIG = " - - enable - glibc - back - compat - - enable - reduce - exports " <nl> - compiler : " : Cross - Mac " <nl> env : HOST = x86_64 - apple - darwin11 PACKAGES = " cmake libcap - dev libz - dev libbz2 - dev " BITCOIN_CONFIG = " - - enable - reduce - exports " OSX_SDK = 10 . 9 GOAL = " deploy " <nl> + exclude : <nl> + - compiler : gcc <nl> install : <nl> - if [ - n " $ PACKAGES " ] ; then travis_retry sudo apt - get update ; fi <nl> - if [ - n " $ PACKAGES " ] ; then travis_retry sudo apt - get install - - no - install - recommends - - no - upgrade - qq $ PACKAGES ; fi <nl>
travis : for travis generating an extra build
bitcoin/bitcoin
bfadae33741ff3a58ed47f939080a3122bc2307d
2015-09-02T01:45:23Z
mmm a / third - party <nl> ppp b / third - party <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit fe93c33d5ae85c0cb1c6e57981030ad2901487d4 <nl> + Subproject commit 5211c1aeaf5dd24ac41149c6b05e24f4a52da23f <nl>
Update HHVM third - party hash
facebook/hhvm
4cb97d212b09986c9b3ddc48f4fc804512eac34b
2015-11-21T05:20:30Z
mmm a / dbms / src / Server / Client . cpp <nl> ppp b / dbms / src / Server / Client . cpp <nl> class Client : public Poco : : Util : : Application <nl> while ( ws > 0 & & isWhitespaceASCII ( line [ ws - 1 ] ) ) <nl> - - ws ; <nl> <nl> - if ( ws = = 0 & & query . empty ( ) ) <nl> + if ( ws = = 0 & & line . empty ( ) ) <nl> continue ; <nl> <nl> bool ends_with_semicolon = line [ ws - 1 ] = = ' ; ' ; <nl>
Fixed bug [ # CLICKHOUSE - 3561 ]
ClickHouse/ClickHouse
468a280a9458762729a49a104942e54d20bf78ac
2018-02-05T20:33:17Z
mmm a / torch / csrc / cuda / Module . cpp <nl> ppp b / torch / csrc / cuda / Module . cpp <nl> static struct PyMethodDef _THCPModule_methods [ ] = { <nl> { " _cuda_lock_mutex " , ( PyCFunction ) THCPModule_cudaLockMutex , METH_NOARGS , NULL } , <nl> { " _cuda_unlock_mutex " , ( PyCFunction ) THCPModule_cudaUnlockMutex , METH_NOARGS , NULL } , <nl> { " _nccl_reduce " , ( PyCFunction ) THCPModule_nccl_reduce , METH_VARARGS , NULL } , <nl> + { " _nccl_all_reduce " , ( PyCFunction ) THCPModule_nccl_all_reduce , METH_VARARGS , NULL } , <nl> + { " _nccl_broadcast " , ( PyCFunction ) THCPModule_nccl_broadcast , METH_VARARGS , NULL } , <nl> + { " _nccl_all_gather " , ( PyCFunction ) THCPModule_nccl_all_gather , METH_VARARGS , NULL } , <nl> + { " _nccl_reduce_scatter " , ( PyCFunction ) THCPModule_nccl_reduce_scatter , METH_VARARGS , NULL } , <nl> { NULL } <nl> } ; <nl> <nl> mmm a / torch / csrc / cuda / nccl . cpp <nl> ppp b / torch / csrc / cuda / nccl . cpp <nl> static ncclComm_t * _get_communicator ( std : : vector < at : : Tensor > & inputs ) { <nl> } <nl> } <nl> <nl> - static void _check_inputs ( std : : vector < at : : Tensor > & inputs , std : : vector < at : : Tensor > & outputs , int size_multiplier ) { <nl> + static void _check_inputs ( std : : vector < at : : Tensor > & inputs , std : : vector < at : : Tensor > & outputs , int input_multiplier , int output_multiplier ) { <nl> / / len ( inputs ) = = len ( outputs ) <nl> size_t len = inputs . size ( ) ; <nl> <nl> static void _check_inputs ( std : : vector < at : : Tensor > & inputs , std : : vector < at : : Tenso <nl> throw std : : runtime_error ( " all inputs must have the same number of elements " ) ; <nl> } <nl> <nl> - / / outputs have to be of size * size_multiplier <nl> - if ( output . numel ( ) ! = ( numel * size_multiplier ) ) { <nl> + if ( output . numel ( ) * output_multiplier ! = numel * input_multiplier ) { <nl> throw std : : runtime_error ( " output must be of size input_size * size_multiplier " ) ; <nl> } <nl> } <nl> PyObject * THCPModule_nccl_reduce ( PyObject * self , PyObject * args ) { <nl> <nl> / / we can safely release GIL after this line , no python API used <nl> AutoNoGIL no_gil ; <nl> - _check_inputs ( inputs , outputs , 1 ) ; <nl> + _check_inputs ( inputs , outputs , 1 , 1 ) ; <nl> size_t len = inputs . size ( ) ; <nl> <nl> ncclDataType_t data_type = _get_data_type ( inputs [ 0 ] . type ( ) . ID ( ) ) ; <nl> PyObject * THCPModule_nccl_reduce ( PyObject * self , PyObject * args ) { <nl> Py_RETURN_NONE ; <nl> END_HANDLE_TH_ERRORS <nl> } <nl> + <nl> + PyObject * THCPModule_nccl_all_reduce ( PyObject * self , PyObject * args ) { <nl> + HANDLE_TH_ERRORS <nl> + PyObject * _inputs , * _outputs ; <nl> + int op ; <nl> + <nl> + if ( ! PyArg_ParseTuple ( args , " OOi " , & _inputs , & _outputs , & op ) ) { <nl> + THPUtils_invalidArguments ( args , NULL , " nccl_all_reduce " , 1 , <nl> + " ( sequence [ Tensor ] inputs , sequence [ Tensor ] " <nl> + " outputs , int op " ) ; <nl> + return NULL ; <nl> + } <nl> + <nl> + std : : vector < at : : Tensor > inputs = THPUtils_PySequence_to_TensorList ( _inputs ) ; <nl> + std : : vector < at : : Tensor > outputs = THPUtils_PySequence_to_TensorList ( _outputs ) ; <nl> + <nl> + / / we can safely release GIL after this line , no python API used <nl> + AutoNoGIL no_gil ; <nl> + _check_inputs ( inputs , outputs , 1 , 1 ) ; <nl> + size_t len = inputs . size ( ) ; <nl> + <nl> + ncclDataType_t data_type = _get_data_type ( inputs [ 0 ] . type ( ) . ID ( ) ) ; <nl> + <nl> + int64_t count = inputs [ 0 ] . numel ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( * ( THCCachingAllocator_getCudaFreeMutex ( ) ) ) ; <nl> + ncclComm_t * comm = _get_communicator ( inputs ) ; <nl> + AutoGPU gpu_guard ; <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupStart ( ) ) ; <nl> + # endif <nl> + for ( size_t i = 0 ; i < len ; i + + ) { <nl> + int device = inputs [ i ] . get_device ( ) ; <nl> + gpu_guard . setDevice ( device ) ; <nl> + CHECK ( ncclAllReduce ( inputs [ i ] . data_ptr ( ) , outputs [ i ] . data_ptr ( ) , <nl> + count , data_type , ( ncclRedOp_t ) op , comm [ i ] , NULL ) ) ; <nl> + } <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupEnd ( ) ) ; <nl> + # endif <nl> + <nl> + Py_RETURN_NONE ; <nl> + END_HANDLE_TH_ERRORS <nl> + } <nl> + <nl> + PyObject * THCPModule_nccl_broadcast ( PyObject * self , PyObject * args ) { <nl> + HANDLE_TH_ERRORS <nl> + PyObject * _inputs ; <nl> + int root ; <nl> + <nl> + if ( ! PyArg_ParseTuple ( args , " Oi " , & _inputs , & root ) ) { <nl> + THPUtils_invalidArguments ( args , NULL , " nccl_broadcast " , 1 , <nl> + " ( sequence [ Tensor ] inputs , int root " ) ; <nl> + return NULL ; <nl> + } <nl> + <nl> + std : : vector < at : : Tensor > inputs = THPUtils_PySequence_to_TensorList ( _inputs ) ; <nl> + <nl> + / / we can safely release GIL after this line , no python API used <nl> + AutoNoGIL no_gil ; <nl> + _check_inputs ( inputs , inputs , 1 , 1 ) ; <nl> + size_t len = inputs . size ( ) ; <nl> + <nl> + ncclDataType_t data_type = _get_data_type ( inputs [ 0 ] . type ( ) . ID ( ) ) ; <nl> + <nl> + int64_t count = inputs [ 0 ] . numel ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( * ( THCCachingAllocator_getCudaFreeMutex ( ) ) ) ; <nl> + ncclComm_t * comm = _get_communicator ( inputs ) ; <nl> + AutoGPU gpu_guard ; <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupStart ( ) ) ; <nl> + # endif <nl> + for ( size_t i = 0 ; i < len ; i + + ) { <nl> + int device = inputs [ i ] . get_device ( ) ; <nl> + gpu_guard . setDevice ( device ) ; <nl> + CHECK ( ncclBcast ( inputs [ i ] . data_ptr ( ) , count , data_type , root , comm [ i ] , NULL ) ) ; <nl> + } <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupEnd ( ) ) ; <nl> + # endif <nl> + <nl> + Py_RETURN_NONE ; <nl> + END_HANDLE_TH_ERRORS <nl> + } <nl> + <nl> + PyObject * THCPModule_nccl_all_gather ( PyObject * self , PyObject * args ) { <nl> + HANDLE_TH_ERRORS <nl> + PyObject * _inputs , * _outputs ; <nl> + <nl> + if ( ! PyArg_ParseTuple ( args , " OO " , & _inputs , & _outputs ) ) { <nl> + THPUtils_invalidArguments ( args , NULL , " nccl_all_gather " , 1 , <nl> + " ( sequence [ Tensor ] inputs , sequence [ Tensor ] outputs " ) ; <nl> + return NULL ; <nl> + } <nl> + <nl> + std : : vector < at : : Tensor > inputs = THPUtils_PySequence_to_TensorList ( _inputs ) ; <nl> + std : : vector < at : : Tensor > outputs = THPUtils_PySequence_to_TensorList ( _outputs ) ; <nl> + <nl> + / / we can safely release GIL after this line , no python API used <nl> + AutoNoGIL no_gil ; <nl> + size_t len = inputs . size ( ) ; <nl> + _check_inputs ( inputs , outputs , len , 1 ) ; <nl> + <nl> + ncclDataType_t data_type = _get_data_type ( inputs [ 0 ] . type ( ) . ID ( ) ) ; <nl> + <nl> + int64_t count = inputs [ 0 ] . numel ( ) ; <nl> + std : : lock_guard < std : : mutex > lock ( * ( THCCachingAllocator_getCudaFreeMutex ( ) ) ) ; <nl> + ncclComm_t * comm = _get_communicator ( inputs ) ; <nl> + AutoGPU gpu_guard ; <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupStart ( ) ) ; <nl> + # endif <nl> + for ( size_t i = 0 ; i < len ; i + + ) { <nl> + int device = inputs [ i ] . get_device ( ) ; <nl> + gpu_guard . setDevice ( device ) ; <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclAllGather ( inputs [ i ] . data_ptr ( ) , outputs [ i ] . data_ptr ( ) , <nl> + count , data_type , comm [ i ] , NULL ) ) ; <nl> + # else <nl> + CHECK ( ncclAllGather ( inputs [ i ] . data_ptr ( ) , count , data_type , <nl> + outputs [ i ] . data_ptr ( ) , comm [ i ] , NULL ) ) ; <nl> + # endif <nl> + } <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupEnd ( ) ) ; <nl> + # endif <nl> + <nl> + Py_RETURN_NONE ; <nl> + END_HANDLE_TH_ERRORS <nl> + } <nl> + <nl> + PyObject * THCPModule_nccl_reduce_scatter ( PyObject * self , PyObject * args ) { <nl> + HANDLE_TH_ERRORS <nl> + PyObject * _inputs , * _outputs ; <nl> + int op ; <nl> + <nl> + if ( ! PyArg_ParseTuple ( args , " OOi " , & _inputs , & _outputs , & op ) ) { <nl> + THPUtils_invalidArguments ( args , NULL , " nccl_reduce_scatter " , 1 , <nl> + " ( sequence [ Tensor ] inputs , sequence [ Tensor ] outputs , int op " ) ; <nl> + return NULL ; <nl> + } <nl> + <nl> + std : : vector < at : : Tensor > inputs = THPUtils_PySequence_to_TensorList ( _inputs ) ; <nl> + std : : vector < at : : Tensor > outputs = THPUtils_PySequence_to_TensorList ( _outputs ) ; <nl> + <nl> + / / we can safely release GIL after this line , no python API used <nl> + AutoNoGIL no_gil ; <nl> + size_t len = inputs . size ( ) ; <nl> + _check_inputs ( inputs , outputs , 1 , len ) ; <nl> + <nl> + ncclDataType_t data_type = _get_data_type ( inputs [ 0 ] . type ( ) . ID ( ) ) ; <nl> + <nl> + int64_t count = inputs [ 0 ] . numel ( ) / len ; <nl> + std : : lock_guard < std : : mutex > lock ( * ( THCCachingAllocator_getCudaFreeMutex ( ) ) ) ; <nl> + ncclComm_t * comm = _get_communicator ( inputs ) ; <nl> + AutoGPU gpu_guard ; <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupStart ( ) ) ; <nl> + # endif <nl> + for ( size_t i = 0 ; i < len ; i + + ) { <nl> + int device = inputs [ i ] . get_device ( ) ; <nl> + gpu_guard . setDevice ( device ) ; <nl> + CHECK ( ncclReduceScatter ( inputs [ i ] . data_ptr ( ) , outputs [ i ] . data_ptr ( ) , <nl> + count , data_type , ( ncclRedOp_t ) op , comm [ i ] , NULL ) ) ; <nl> + } <nl> + # if defined ( NCCL_MAJOR ) & & ( NCCL_MAJOR > = 2 ) <nl> + CHECK ( ncclGroupEnd ( ) ) ; <nl> + # endif <nl> + <nl> + Py_RETURN_NONE ; <nl> + END_HANDLE_TH_ERRORS <nl> + } <nl> mmm a / torch / csrc / cuda / nccl . h <nl> ppp b / torch / csrc / cuda / nccl . h <nl> <nl> # include < Python . h > <nl> <nl> PyObject * THCPModule_nccl_reduce ( PyObject * self , PyObject * args ) ; <nl> - <nl> + PyObject * THCPModule_nccl_all_reduce ( PyObject * self , PyObject * args ) ; <nl> + PyObject * THCPModule_nccl_broadcast ( PyObject * self , PyObject * args ) ; <nl> + PyObject * THCPModule_nccl_all_gather ( PyObject * self , PyObject * args ) ; <nl> + PyObject * THCPModule_nccl_reduce_scatter ( PyObject * self , PyObject * args ) ; <nl> <nl> # endif <nl> mmm a / torch / cuda / nccl . py <nl> ppp b / torch / cuda / nccl . py <nl> def cudaStream ( ) : <nl> def all_reduce ( inputs , outputs = None , op = SUM ) : <nl> if outputs is None : <nl> outputs = inputs <nl> - _check_inputs ( inputs , outputs ) <nl> - comm = communicator ( inputs , outputs ) <nl> - count = inputs [ 0 ] . numel ( ) <nl> - data_type = nccl_types [ inputs [ 0 ] . type ( ) ] <nl> - with torch . cuda . _free_mutex ( ) : <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupStart ( ) <nl> - for i in range ( len ( inputs ) ) : <nl> - with torch . cuda . device ( comm . devices [ i ] ) : <nl> - check_error ( lib . ncclAllReduce ( <nl> - ctypes . c_void_p ( inputs [ i ] . data_ptr ( ) ) , <nl> - ctypes . c_void_p ( outputs [ i ] . data_ptr ( ) ) , <nl> - count , data_type , op , comm [ i ] , cudaStream ( ) ) ) <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupEnd ( ) <nl> - <nl> + torch . _C . _nccl_all_reduce ( inputs , outputs , op ) <nl> <nl> def reduce ( inputs , outputs = None , root = 0 , op = SUM , streams = None ) : <nl> assert ( root > = 0 and root < len ( inputs ) ) <nl> def reduce ( inputs , outputs = None , root = 0 , op = SUM , streams = None ) : <nl> <nl> def broadcast ( inputs , root = 0 ) : <nl> assert ( root > = 0 and root < len ( inputs ) ) <nl> - _check_inputs ( inputs , inputs ) <nl> - comm = communicator ( inputs ) <nl> - count = inputs [ 0 ] . numel ( ) <nl> - data_type = nccl_types [ inputs [ 0 ] . type ( ) ] <nl> - with torch . cuda . _free_mutex ( ) : <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupStart ( ) <nl> - for i in range ( len ( inputs ) ) : <nl> - with torch . cuda . device ( comm . devices [ i ] ) : <nl> - check_error ( lib . ncclBcast ( <nl> - ctypes . c_void_p ( inputs [ i ] . data_ptr ( ) ) , count , <nl> - data_type , root , comm [ i ] , cudaStream ( ) ) ) <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupEnd ( ) <nl> - <nl> + torch . _C . _nccl_broadcast ( inputs , root ) <nl> <nl> def all_gather ( inputs , outputs ) : <nl> - _check_inputs ( inputs , outputs , len ( inputs ) ) <nl> - comm = communicator ( inputs , outputs ) <nl> - count = inputs [ 0 ] . numel ( ) <nl> - data_type = nccl_types [ inputs [ 0 ] . type ( ) ] <nl> - with torch . cuda . _free_mutex ( ) : <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupStart ( ) <nl> - for i in range ( len ( inputs ) ) : <nl> - with torch . cuda . device ( comm . devices [ i ] ) : <nl> - if nccl_2_0 is None : <nl> - check_error ( lib . ncclAllGather ( <nl> - ctypes . c_void_p ( inputs [ i ] . data_ptr ( ) ) , count , data_type , <nl> - ctypes . c_void_p ( outputs [ i ] . data_ptr ( ) ) , comm [ i ] , <nl> - cudaStream ( ) ) ) <nl> - else : <nl> - check_error ( lib . ncclAllGather ( <nl> - ctypes . c_void_p ( inputs [ i ] . data_ptr ( ) ) , <nl> - ctypes . c_void_p ( outputs [ i ] . data_ptr ( ) ) , count , <nl> - data_type , comm [ i ] , cudaStream ( ) ) ) <nl> - <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupEnd ( ) <nl> - <nl> + torch . _C . _nccl_all_gather ( inputs , outputs ) <nl> <nl> def reduce_scatter ( inputs , outputs , op = SUM ) : <nl> - _check_inputs ( inputs , outputs , 1 . 0 / len ( inputs ) ) <nl> - comm = communicator ( inputs , outputs ) <nl> - count = inputs [ 0 ] . numel ( ) / / len ( inputs ) <nl> - data_type = nccl_types [ inputs [ 0 ] . type ( ) ] <nl> - with torch . cuda . _free_mutex ( ) : <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupStart ( ) <nl> - for i in range ( len ( inputs ) ) : <nl> - with torch . cuda . device ( comm . devices [ i ] ) : <nl> - check_error ( lib . ncclReduceScatter ( <nl> - ctypes . c_void_p ( inputs [ i ] . data_ptr ( ) ) , <nl> - ctypes . c_void_p ( outputs [ i ] . data_ptr ( ) ) , count , data_type , <nl> - op , comm [ i ] , cudaStream ( ) ) ) <nl> - if nccl_2_0 is not None : <nl> - lib . ncclGroupEnd ( ) <nl> - <nl> + torch . _C . _nccl_reduce_scatter ( inputs , outputs , op ) <nl> <nl> def _check_inputs ( inputs , outputs = None , size_multiplier = 1 ) : <nl> devices = set ( ) <nl>
implement all_reduce , broadcast , all_gather , reduce_scatter
pytorch/pytorch
e9dccb315625514b2a3bbd7b11be4660104bb0dd
2017-10-10T02:24:18Z
mmm a / docs / SIL . rst <nl> ppp b / docs / SIL . rst <nl> open_existential_metatype <nl> Extracts the metatype from an existential metatype . The protocol conformances associated with this existential <nl> container are associated directly with the archetype ` ` @ opened P ` ` . <nl> <nl> + alloc_existential_box <nl> + ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` <nl> + : : <nl> + <nl> + sil - instruction : : = ' alloc_existential_box ' sil - type ' , ' sil - type <nl> + <nl> + % 1 = alloc_existential_box $ P , $ T <nl> + / / $ P must be a protocol or protocol composition type with boxed <nl> + / / representation <nl> + / / $ T must be an AST type that conforms to P <nl> + / / % 1 # 0 will be of type $ P <nl> + / / % 1 # 1 will be of type $ * T ' , where T ' is the most abstracted lowering of T <nl> + <nl> + Allocates a boxed existential container of type ` ` $ P ` ` with space to hold a <nl> + value of type ` ` $ T ' ` ` . The box is not fully initialized until a valid value <nl> + has been stored into the box . If the box must be deallocated before it is <nl> + fully initialized , ` ` dealloc_existential_box ` ` must be used . A fully <nl> + initialized box can be ` ` retain ` ` - ed and ` ` release ` ` - d like any <nl> + reference - counted type . The address ` ` % 0 # 1 ` ` is dependent on the lifetime of <nl> + the owner reference ` ` % 0 # 0 ` ` . <nl> + <nl> + open_existential_box <nl> + ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` <nl> + : : <nl> + <nl> + sil - instruction : : = ' open_existential_box ' sil - operand ' to ' sil - type <nl> + <nl> + % 1 = open_existential_box % 0 : $ P to $ * @ opened P <nl> + / / % 0 must be a value of boxed protocol or protocol composition type $ P <nl> + / / % @ opened P must be the address type of a unique archetype that refers to <nl> + / / / an opened existential type P <nl> + / / % 1 will be of type $ * @ opened P <nl> + <nl> + Projects the address of the value inside a boxed existential container , and <nl> + uses the enclosed type and protocol conformance metadata to bind the <nl> + opened archetype ` ` $ @ opened P ` ` . The result address is dependent on both <nl> + the owning box and the enclosing function ; in order to " open " a boxed <nl> + existential that has directly adopted a class reference , temporary scratch <nl> + space may need to have been allocated . <nl> + <nl> + dealloc_existential_box <nl> + ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` <nl> + : : <nl> + <nl> + sil - instruction : : = ' dealloc_existential_box ' sil - operand <nl> + <nl> + dealloc_existential_box % 0 : $ P <nl> + / / % 0 must be an uninitialized box of boxed existential container type $ P <nl> + <nl> + Deallocates a boxed existential container . The value inside the existential <nl> + buffer is not destroyed ; either the box must be uninitialized , or the value <nl> + must have been projected out and destroyed beforehand . <nl> + <nl> Blocks <nl> ~ ~ ~ ~ ~ ~ <nl> <nl>
SIL . rst : Pre - document instructions for boxed existential containers .
apple/swift
daf3ec67de578eae59d725b9c45b75a7611ff11e
2015-03-13T02:40:22Z
mmm a / tensorflow / contrib / coder / BUILD <nl> ppp b / tensorflow / contrib / coder / BUILD <nl> tf_gen_op_libs ( <nl> ] , <nl> ) <nl> <nl> + cc_library ( <nl> + name = " range_coder_ops_util " , <nl> + srcs = [ " kernels / range_coder_ops_util . cc " ] , <nl> + hdrs = [ " kernels / range_coder_ops_util . h " ] , <nl> + visibility = [ " / / visibility : public " ] , <nl> + deps = [ <nl> + " / / tensorflow / core : framework " , <nl> + " / / tensorflow / core : lib " , <nl> + ] , <nl> + ) <nl> + <nl> tf_kernel_library ( <nl> name = " range_coder_ops " , <nl> srcs = [ <nl> " kernels / range_coder_ops . cc " , <nl> - " kernels / range_coder_ops_util . cc " , <nl> - ] , <nl> - hdrs = [ <nl> - " kernels / range_coder_ops_util . h " , <nl> ] , <nl> visibility = [ " / / visibility : public " ] , <nl> deps = [ <nl> " : coder_ops_op_lib " , <nl> " : range_coder " , <nl> + " : range_coder_ops_util " , <nl> " / / tensorflow / core : framework " , <nl> " / / tensorflow / core : lib " , <nl> ] , <nl>
Add missing pmf_to_cdf_op . cc in the source list in cmake .
tensorflow/tensorflow
3f7c9265b59cae306d029dfac76e25badd20def8
2018-04-24T02:42:05Z
mmm a / hphp / runtime / vm / bytecode . cpp <nl> ppp b / hphp / runtime / vm / bytecode . cpp <nl> bool doFCall ( ActRec * ar , PC & pc ) { <nl> <nl> OPTBLD_INLINE void iopFCall ( PC & pc , intva_t numArgs ) { <nl> auto ar = arFromSp ( numArgs ) ; <nl> - if ( ar - > m_func - > isBuiltin ( ) ) { <nl> + if ( vmfp ( ) - > func ( ) - > isBuiltin ( ) ) { <nl> + ar - > setUseWeakTypes ( ) ; <nl> + } else if ( ar - > m_func - > isBuiltin ( ) ) { <nl> if ( ! builtinCallUsesStrictTypes ( vmfp ( ) - > unit ( ) ) ) { <nl> ar - > setUseWeakTypes ( ) ; <nl> } <nl> mmm a / hphp / runtime / vm / interp - helpers . h <nl> ppp b / hphp / runtime / vm / interp - helpers . h <nl> namespace HPHP { <nl> <nl> / / In PHP7 the caller specifies if parameter type - checking is strict in the <nl> / / callee . NB : HH files ignore this preference and always use strict checking , <nl> - / / except in systemlib . Calls originating in systemlib are always strict . <nl> + / / except in systemlib . Calls originating in systemlib are never strict . <nl> inline bool callUsesStrictTypes ( ActRec * caller ) { <nl> - if ( RuntimeOption : : EnableHipHopSyntax | | ! RuntimeOption : : PHP7_ScalarTypes ) { <nl> - return true ; <nl> - } <nl> if ( ! caller ) { <nl> + / / eg when being called from hhbbc <nl> return true ; <nl> } <nl> auto func = caller - > func ( ) ; <nl> - return func - > isBuiltin ( ) | | func - > unit ( ) - > useStrictTypes ( ) ; <nl> + if ( func - > isBuiltin ( ) ) { <nl> + return false ; <nl> + } <nl> + if ( RuntimeOption : : EnableHipHopSyntax | | ! RuntimeOption : : PHP7_ScalarTypes ) { <nl> + return true ; <nl> + } <nl> + return func - > unit ( ) - > useStrictTypes ( ) ; <nl> } <nl> <nl> inline bool builtinCallUsesStrictTypes ( const Unit * caller ) { <nl> mmm a / hphp / runtime / vm / jit / irlower - act - rec . cpp <nl> ppp b / hphp / runtime / vm / jit / irlower - act - rec . cpp <nl> void cgSpillFrame ( IRLS & env , const IRInstruction * inst ) { <nl> <nl> auto const caller = inst - > marker ( ) . func ( ) ; <nl> auto const baseFlags = <nl> - ! caller - > isBuiltin ( ) & & ! caller - > unit ( ) - > useStrictTypes ( ) <nl> + caller - > isBuiltin ( ) | | ! caller - > unit ( ) - > useStrictTypes ( ) <nl> ? ActRec : : Flags : : UseWeakTypes <nl> : ActRec : : Flags : : None ; <nl> auto const naaf = static_cast < int32_t > ( <nl> mmm a / hphp / runtime / vm / jit / simplify . cpp <nl> ppp b / hphp / runtime / vm / jit / simplify . cpp <nl> ALWAYS_INLINE bool isSimplifyOkay ( const IRInstruction * inst ) { <nl> auto f = inst - > marker ( ) . func ( ) ; <nl> <nl> return ! RuntimeOption : : PHP7_ScalarTypes | | <nl> - ( f & & ! f - > unit ( ) - > useStrictTypes ( ) & & ! f - > isBuiltin ( ) ) ; <nl> + ( f & & ! f - > unit ( ) - > useStrictTypes ( ) ) ; <nl> } <nl> <nl> } <nl> mmm a / hphp / test / hhcodegen_failing_tests_slow <nl> ppp b / hphp / test / hhcodegen_failing_tests_slow <nl> slow / php7_backported / scalar - types / scalar_strict_declaration_placement_002 . php <nl> slow / php7_backported / scalar - types / scalar_strict_declaration_placement_003 . php <nl> slow / php7_backported / scalar - types / scalar_strict_declaration_placement_004 . php <nl> slow / php7_backported / scalar - types / scalar_weak_reference . php <nl> + slow / php7_backported / scalar - types / weak_from_builtins . php <nl> slow / php7_backported / varSyntax / indirect - fcall . php <nl> slow / php7_backported / varSyntax / issetOnTemp . php <nl> slow / php7_backported / varSyntax / staticMember . php <nl> new file mode 100644 <nl> index 00000000000 . . 7d813735cdc <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / php7_backported / scalar - types / weak_from_builtins . php <nl> <nl> + < ? php <nl> + <nl> + declare ( strict_types = 1 ) ; <nl> + <nl> + function print_str ( string $ foo ) { var_dump ( $ foo ) ; } <nl> + <nl> + $ input = [ 1 , 2 , 3 ] ; <nl> + array_map ( ' print_str ' , $ input ) ; <nl> new file mode 100644 <nl> index 00000000000 . . 16f9aea28b9 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / php7_backported / scalar - types / weak_from_builtins . php . expect <nl> <nl> + string ( 1 ) " 1 " <nl> + string ( 1 ) " 2 " <nl> + string ( 1 ) " 3 " <nl> new file mode 100644 <nl> index 00000000000 . . 014cea0e9b0 <nl> mmm / dev / null <nl> ppp b / hphp / test / slow / php7_backported / scalar - types / weak_from_builtins . php . ini <nl> @ @ - 0 , 0 + 1 @ @ <nl> + hhvm . php7 . all = 1 <nl>
Calls from HHVM builtins must not be strict
facebook/hhvm
207bfbcab2720c4426d6cc6536704274ac950b23
2017-06-16T17:53:46Z
mmm a / src / arm64 / assembler - arm64 . cc <nl> ppp b / src / arm64 / assembler - arm64 . cc <nl> void CPURegList : : RemoveCalleeSaved ( ) { <nl> } <nl> } <nl> <nl> - void CPURegList : : Align ( ) { <nl> - / / Use padreg , if necessary , to maintain stack alignment . <nl> - if ( Count ( ) % 2 ! = 0 ) { <nl> - if ( IncludesAliasOf ( padreg ) ) { <nl> - Remove ( padreg ) ; <nl> - } else { <nl> - Combine ( padreg ) ; <nl> - } <nl> - } <nl> - <nl> - DCHECK_EQ ( Count ( ) % 2 , 0 ) ; <nl> - } <nl> <nl> CPURegList CPURegList : : GetCalleeSaved ( int size ) { <nl> return CPURegList ( CPURegister : : kRegister , size , 19 , 29 ) ; <nl> mmm a / src / arm64 / deoptimizer - arm64 . cc <nl> ppp b / src / arm64 / deoptimizer - arm64 . cc <nl> void CopyRegListToFrame ( MacroAssembler * masm , const Register & dst , <nl> masm - > Sub ( dst , dst , dst_offset ) ; <nl> } <nl> <nl> + / / TODO ( jgruber ) : There ' s a hack here to explicitly skip restoration of the <nl> + / / so - called ' arm64 platform register ' x18 . The register may be in use by the <nl> + / / OS , thus we should not clobber it . Instead of this hack , it would be nicer <nl> + / / not to add x18 to the list of saved registers in the first place . The <nl> + / / complication here is that we require ` reg_list . Count ( ) % 2 = = 0 ` in multiple <nl> + / / spots . <nl> void RestoreRegList ( MacroAssembler * masm , const CPURegList & reg_list , <nl> const Register & src_base , int src_offset ) { <nl> DCHECK_EQ ( reg_list . Count ( ) % 2 , 0 ) ; <nl> void RestoreRegList ( MacroAssembler * masm , const CPURegList & reg_list , <nl> Register src = temps . AcquireX ( ) ; <nl> masm - > Add ( src , src_base , src_offset ) ; <nl> <nl> - / / No need to restore padreg . <nl> - restore_list . Remove ( padreg ) ; <nl> + / / x18 is the platform register and is reserved for the use of platform ABIs . <nl> + restore_list . Remove ( x18 ) ; <nl> <nl> / / Restore every register in restore_list from src . <nl> while ( ! restore_list . IsEmpty ( ) ) { <nl> mmm a / src / arm64 / macro - assembler - arm64 . cc <nl> ppp b / src / arm64 / macro - assembler - arm64 . cc <nl> CPURegList TurboAssembler : : DefaultFPTmpList ( ) { <nl> <nl> int TurboAssembler : : RequiredStackSizeForCallerSaved ( SaveFPRegsMode fp_mode , <nl> Register exclusion ) const { <nl> + int bytes = 0 ; <nl> auto list = kCallerSaved ; <nl> - list . Remove ( exclusion ) ; <nl> - list . Align ( ) ; <nl> + / / We only allow one exclusion register , so if the list is of even length <nl> + / / before exclusions , it must still be afterwards , to maintain alignment . <nl> + / / Therefore , we can ignore the exclusion register in the computation . <nl> + / / However , we leave it in the argument list to mirror the prototype for <nl> + / / Push / PopCallerSaved ( ) . <nl> + <nl> + / / X18 is excluded from caller - saved register list on ARM64 which makes <nl> + / / caller - saved registers in odd number . padreg is used accordingly to <nl> + / / maintain the alignment . <nl> + DCHECK_EQ ( list . Count ( ) % 2 , 1 ) ; <nl> + if ( exclusion . Is ( no_reg ) ) { <nl> + bytes + = kXRegSizeInBits / 8 ; <nl> + } else { <nl> + bytes - = kXRegSizeInBits / 8 ; <nl> + } <nl> <nl> - int bytes = list . Count ( ) * kXRegSizeInBits / 8 ; <nl> + bytes + = list . Count ( ) * kXRegSizeInBits / 8 ; <nl> <nl> if ( fp_mode = = kSaveFPRegs ) { <nl> DCHECK_EQ ( kCallerSavedV . Count ( ) % 2 , 0 ) ; <nl> int TurboAssembler : : RequiredStackSizeForCallerSaved ( SaveFPRegsMode fp_mode , <nl> <nl> int TurboAssembler : : PushCallerSaved ( SaveFPRegsMode fp_mode , <nl> Register exclusion ) { <nl> + int bytes = 0 ; <nl> auto list = kCallerSaved ; <nl> - list . Remove ( exclusion ) ; <nl> - list . Align ( ) ; <nl> <nl> - PushCPURegList ( list ) ; <nl> + / / X18 is excluded from caller - saved register list on ARM64 , use padreg <nl> + / / accordingly to maintain alignment . <nl> + if ( ! exclusion . Is ( no_reg ) ) { <nl> + list . Remove ( exclusion ) ; <nl> + } else { <nl> + list . Combine ( padreg ) ; <nl> + } <nl> <nl> - int bytes = list . Count ( ) * kXRegSizeInBits / 8 ; <nl> + DCHECK_EQ ( list . Count ( ) % 2 , 0 ) ; <nl> + PushCPURegList ( list ) ; <nl> + bytes + = list . Count ( ) * kXRegSizeInBits / 8 ; <nl> <nl> if ( fp_mode = = kSaveFPRegs ) { <nl> DCHECK_EQ ( kCallerSavedV . Count ( ) % 2 , 0 ) ; <nl> int TurboAssembler : : PopCallerSaved ( SaveFPRegsMode fp_mode , Register exclusion ) { <nl> } <nl> <nl> auto list = kCallerSaved ; <nl> - list . Remove ( exclusion ) ; <nl> - list . Align ( ) ; <nl> <nl> + / / X18 is excluded from caller - saved register list on ARM64 , use padreg <nl> + / / accordingly to maintain alignment . <nl> + if ( ! exclusion . Is ( no_reg ) ) { <nl> + list . Remove ( exclusion ) ; <nl> + } else { <nl> + list . Combine ( padreg ) ; <nl> + } <nl> + <nl> + DCHECK_EQ ( list . Count ( ) % 2 , 0 ) ; <nl> PopCPURegList ( list ) ; <nl> bytes + = list . Count ( ) * kXRegSizeInBits / 8 ; <nl> <nl> void MacroAssembler : : Printf ( const char * format , <nl> TmpList ( ) - > set_list ( 0 ) ; <nl> FPTmpList ( ) - > set_list ( 0 ) ; <nl> <nl> + / / x18 is the platform register and is reserved for the use of platform ABIs . <nl> + / / It is not part of the kCallerSaved list , but we add it here anyway to <nl> + / / ensure ` reg_list . Count ( ) % 2 = = 0 ` which is required in multiple spots . <nl> CPURegList saved_registers = kCallerSaved ; <nl> - saved_registers . Align ( ) ; <nl> + saved_registers . Combine ( x18 . code ( ) ) ; <nl> <nl> / / Preserve all caller - saved registers as well as NZCV . <nl> / / PushCPURegList asserts that the size of each list is a multiple of 16 <nl> mmm a / src / arm64 / register - arm64 . h <nl> ppp b / src / arm64 / register - arm64 . h <nl> class V8_EXPORT_PRIVATE CPURegList { <nl> / / preparing registers for an AAPCS64 function call , for example . <nl> void RemoveCalleeSaved ( ) ; <nl> <nl> - / / Align the list to 16 bytes . <nl> - void Align ( ) ; <nl> - <nl> CPURegister PopLowestIndex ( ) ; <nl> CPURegister PopHighestIndex ( ) ; <nl> <nl>
Revert " [ arm64 ] Cleanup TODO around handling of x18 "
v8/v8
78dfde9d27266f28628a08104d10e75921f10e93
2019-04-25T06:49:33Z
mmm a / jstests / multiVersion / upgrade_cluster . js <nl> ppp b / jstests / multiVersion / upgrade_cluster . js <nl> TestData . skipCheckingUUIDsConsistentAcrossCluster = true ; <nl> var runTest = function ( isRSCluster ) { <nl> " use strict " ; <nl> <nl> + const kMinVersion = 5 ; <nl> + const kCurrentVerion = 6 ; <nl> + <nl> jsTest . log ( " Starting " + ( isRSCluster ? " ( replica set ) " : " " ) + " cluster " + " . . . " ) ; <nl> <nl> var testCRUDAndAgg = function ( db ) { <nl> TestData . skipCheckingUUIDsConsistentAcrossCluster = true ; <nl> <nl> / / check that config . version document gets initialized properly <nl> var version = st . s . getCollection ( ' config . version ' ) . findOne ( ) ; <nl> - assert . eq ( version . minCompatibleVersion , 5 ) ; <nl> - assert . eq ( version . currentVersion , 6 ) ; <nl> + assert . eq ( version . minCompatibleVersion , kMinVersion ) ; <nl> + assert . eq ( version . currentVersion , kCurrentVerion ) ; <nl> var clusterID = version . clusterId ; <nl> assert . neq ( null , clusterID ) ; <nl> assert . eq ( version . excluding , undefined ) ; <nl> TestData . skipCheckingUUIDsConsistentAcrossCluster = true ; <nl> / / upgrade the config servers first <nl> jsTest . log ( ' upgrading config servers ' ) ; <nl> st . upgradeCluster ( " latest " , { upgradeMongos : false , upgradeShards : false } ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Restart mongos to clear all cache and force it to do remote calls . <nl> st . restartMongoses ( ) ; <nl> <nl> testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> TestData . skipCheckingUUIDsConsistentAcrossCluster = true ; <nl> / / Then upgrade the shards . <nl> jsTest . log ( ' upgrading shard servers ' ) ; <nl> st . upgradeCluster ( " latest " , { upgradeMongos : false , upgradeConfigs : false } ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Restart mongos to clear all cache and force it to do remote calls . <nl> st . restartMongoses ( ) ; <nl> <nl> testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> TestData . skipCheckingUUIDsConsistentAcrossCluster = true ; <nl> / / Finally , upgrade mongos <nl> jsTest . log ( ' upgrading mongos servers ' ) ; <nl> st . upgradeCluster ( " latest " , { upgradeConfigs : false , upgradeShards : false } ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Restart mongos to clear all cache and force it to do remote calls . <nl> + st . restartMongoses ( ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Check that version document is unmodified . <nl> + version = st . s . getCollection ( ' config . version ' ) . findOne ( ) ; <nl> + assert . eq ( version . minCompatibleVersion , kMinVersion ) ; <nl> + assert . eq ( version . currentVersion , kCurrentVerion ) ; <nl> + assert . eq ( clusterID , version . clusterId ) ; <nl> + assert . eq ( version . excluding , undefined ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Downgrade back <nl> + <nl> + jsTest . log ( ' downgrading mongos servers ' ) ; <nl> + st . upgradeCluster ( " last - stable " , { upgradeConfigs : false , upgradeShards : false } ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Restart mongos to clear all cache and force it to do remote calls . <nl> + st . restartMongoses ( ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + jsTest . log ( ' downgrading shard servers ' ) ; <nl> + st . upgradeCluster ( " last - stable " , { upgradeMongos : false , upgradeConfigs : false } ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Restart mongos to clear all cache and force it to do remote calls . <nl> + st . restartMongoses ( ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + jsTest . log ( ' downgrading config servers ' ) ; <nl> + st . upgradeCluster ( " last - stable " , { upgradeMongos : false , upgradeShards : false } ) ; <nl> + <nl> + testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> + testCRUDAndAgg ( st . s . getDB ( ' sharded ' ) ) ; <nl> + <nl> + / / Restart mongos to clear all cache and force it to do remote calls . <nl> st . restartMongoses ( ) ; <nl> <nl> testCRUDAndAgg ( st . s . getDB ( ' unsharded ' ) ) ; <nl> TestData . skipCheckingUUIDsConsistentAcrossCluster = true ; <nl> <nl> / / Check that version document is unmodified . <nl> version = st . s . getCollection ( ' config . version ' ) . findOne ( ) ; <nl> - assert . eq ( version . minCompatibleVersion , 5 ) ; <nl> - assert . eq ( version . currentVersion , 6 ) ; <nl> + assert . eq ( version . minCompatibleVersion , kMinVersion ) ; <nl> + assert . eq ( version . currentVersion , kCurrentVerion ) ; <nl> assert . eq ( clusterID , version . clusterId ) ; <nl> assert . eq ( version . excluding , undefined ) ; <nl> <nl>
SERVER - 34167 Add generic downgrade cluster test to multiversion suite
mongodb/mongo
52a2344209ae4667a8b5256aca0985996934b249
2019-05-14T14:55:42Z
mmm a / dbms / src / Functions / IFunction . h <nl> ppp b / dbms / src / Functions / IFunction . h <nl> class IFunction <nl> bool is_positive = true ; / / / true if the function is nondecreasing , false , if notincreasing . If is_monotonic = false , then it does not matter . <nl> bool is_always_monotonic = false ; / / / Is true if function is monotonic on the whole input range I <nl> <nl> - Monotonicity ( bool is_monotonic_ = false , bool is_positive_ = true , bool is_always_monotonic_ = false ) <nl> + Monotonicity ( bool is_monotonic_ = false , bool is_positive_ = true , bool is_always_monotonic_ = false ) <nl> : is_monotonic ( is_monotonic_ ) , is_positive ( is_positive_ ) , is_always_monotonic ( is_always_monotonic_ ) { } <nl> } ; <nl> <nl>
Update IFunction . h
ClickHouse/ClickHouse
894d09f797df657220d8895b7d7ece611c84c4f2
2017-07-09T14:13:51Z
mmm a / modules / imgproc / src / smooth . cpp <nl> ppp b / modules / imgproc / src / smooth . cpp <nl> void cv : : GaussianBlur ( InputArray _src , OutputArray _dst , Size ksize , <nl> { <nl> Mat src = _src . getMat ( ) , dst = _dst . getMat ( ) ; <nl> IppiSize roi = { src . cols , src . rows } ; <nl> - int bufSize = 0 ; <nl> - if ( ippStsNoErr = = ippicviFilterGaussGetBufferSize_32f_C1R ( roi , ksize . width , & bufSize ) ) <nl> + int specSize = 0 , bufferSize = 0 ; <nl> + if ( ippStsNoErr = = ippicviFilterGaussianGetBufferSize ( roi , ( Ipp32u ) ksize . width , ipp32f , 1 , & specSize , & bufferSize ) ) <nl> { <nl> - AutoBuffer < uchar > buf ( bufSize + 128 ) ; <nl> - if ( ippicviFilterGaussBorder_32f_C1R ( ( const Ipp32f * ) src . data , ( int ) src . step , <nl> - ( Ipp32f * ) dst . data , ( int ) dst . step , <nl> - roi , ksize . width , ( Ipp32f ) sigma1 , <nl> - ( IppiBorderType ) borderType , 0 . 0 , <nl> - alignPtr ( & buf [ 0 ] , 32 ) ) > = 0 ) <nl> - return ; <nl> + IppFilterGaussianSpec * pSpec = ( IppFilterGaussianSpec * ) ippicvMalloc ( specSize ) ; <nl> + Ipp8u * pBuffer = ( Ipp8u * ) ippicvMalloc ( bufferSize ) ; <nl> + if ( ippStsNoErr = = ippicviFilterGaussianInit ( roi , ( Ipp32u ) ksize . width , ( Ipp32f ) sigma1 , ( IppiBorderType ) borderType , ipp32f , 1 , pSpec , pBuffer ) ) <nl> + { <nl> + IppStatus sts = ippicviFilterGaussianBorder_32f_C1R ( ( const Ipp32f * ) src . data , ( int ) src . step , <nl> + ( Ipp32f * ) dst . data , ( int ) dst . step , <nl> + roi , 0 . 0 , pSpec , pBuffer ) ; <nl> + ippicvFree ( pBuffer ) ; <nl> + ippicvFree ( pSpec ) ; <nl> + if ( ippStsNoErr = = sts ) <nl> + return ; <nl> + } <nl> } <nl> } <nl> # endif <nl>
Remove unused code
opencv/opencv
07e84c635a576a201fa3877bff47db5dd70c06e9
2014-04-07T10:26:45Z
mmm a / tensorflow / lite / python / BUILD <nl> ppp b / tensorflow / lite / python / BUILD <nl> py_library ( <nl> " : lite_constants " , <nl> " : op_hint " , <nl> " / / tensorflow / python : graph_util " , <nl> + " / / tensorflow / python : tf_optimizer " , <nl> " / / tensorflow / python / keras " , <nl> " / / tensorflow / python / saved_model : constants " , <nl> " / / tensorflow / python / saved_model : loader " , <nl> mmm a / tensorflow / lite / python / lite . py <nl> ppp b / tensorflow / lite / python / lite . py <nl> <nl> from tensorflow . lite . python . op_hint import convert_op_hints_to_stubs # pylint : disable = unused - import <nl> from tensorflow . lite . python . op_hint import OpHint # pylint : disable = unused - import <nl> from tensorflow . core . framework import graph_pb2 as _graph_pb2 <nl> + from tensorflow . core . protobuf import rewriter_config_pb2 as _rewriter_config_pb2 <nl> + from tensorflow . core . protobuf import config_pb2 as _config_pb2 <nl> + from tensorflow . core . protobuf import meta_graph_pb2 as _meta_graph_pb2 <nl> from tensorflow . python import keras as _keras <nl> from tensorflow . python . client import session as _session <nl> from tensorflow . python . framework import graph_util as _tf_graph_util <nl> from tensorflow . python . framework import ops as _ops <nl> from tensorflow . python . framework . errors_impl import NotFoundError as _NotFoundError <nl> from tensorflow . python . framework . importer import import_graph_def as _import_graph_def <nl> + from tensorflow . python . grappler import tf_optimizer as _tf_optimizer <nl> from tensorflow . python . lib . io import file_io as _file_io <nl> from tensorflow . python . saved_model import signature_constants as _signature_constants <nl> from tensorflow . python . saved_model import tag_constants as _tag_constants <nl> + from tensorflow . python . training . saver import export_meta_graph as _export_meta_graph <nl> from tensorflow . python . util import deprecation as _deprecation <nl> from tensorflow . python . util . tf_export import tf_export as _tf_export <nl> <nl> <nl> + def _run_graph_optimizations ( graph_def , output_arrays ) : <nl> + " " " Apply standard TensorFlow optimizations to the graph_def . <nl> + <nl> + Args : <nl> + graph_def : Frozen GraphDef to be optimized . <nl> + output_arrays : List of arrays that are considered outputs of the graph . <nl> + <nl> + Returns : <nl> + A new , optimized GraphDef . <nl> + " " " <nl> + meta_graph = _export_meta_graph ( graph_def = graph_def ) <nl> + <nl> + # We need to add a collection called ' train_op ' so that grappler <nl> + # knows what the outputs are . <nl> + fetch_collection = _meta_graph_pb2 . CollectionDef ( ) <nl> + for output in output_arrays : <nl> + fetch_collection . node_list . value . append ( output ) <nl> + meta_graph . collection_def [ " train_op " ] . CopyFrom ( fetch_collection ) <nl> + <nl> + config = _config_pb2 . ConfigProto ( ) <nl> + rewrite_options = config . graph_options . rewrite_options <nl> + rewrite_options . layout_optimizer = _rewriter_config_pb2 . RewriterConfig . ON <nl> + return _tf_optimizer . OptimizeGraph ( config , meta_graph ) <nl> + <nl> + <nl> @ _tf_export ( " lite . TFLiteConverter " ) <nl> class TFLiteConverter ( object ) : <nl> " " " Convert a TensorFlow model into ` output_format ` using TOCO . <nl> def convert ( self ) : <nl> " dump_graphviz_video " : self . dump_graphviz_video <nl> } <nl> <nl> + optimized_graph = None <nl> + if self . inference_type = = constants . QUANTIZED_UINT8 : <nl> + optimized_graph = self . _graph_def <nl> + else : <nl> + try : <nl> + optimized_graph = _run_graph_optimizations ( <nl> + self . _graph_def , [ t . name for t in self . _output_tensors ] ) <nl> + except Exception : <nl> + optimized_graph = self . _graph_def <nl> + <nl> # Converts model . <nl> if self . _has_valid_tensors ( ) : <nl> result = _toco_convert_impl ( <nl> - input_data = self . _graph_def , <nl> + input_data = optimized_graph , <nl> input_tensors = self . _input_tensors , <nl> output_tensors = self . _output_tensors , <nl> * * converter_kwargs ) <nl> else : <nl> result = _toco_convert_graph_def ( <nl> - input_data = self . _graph_def , <nl> + input_data = optimized_graph , <nl> input_arrays_with_shape = self . _input_arrays_with_shape , <nl> output_arrays = self . _output_arrays , <nl> * * converter_kwargs ) <nl>
Automated rollback of commit 6a6658f3e2bae16e2d0067fcb7d7cb0850272d1b
tensorflow/tensorflow
e564b38a13f69fb1e64e530ba9d7f52009ce164e
2018-12-21T18:44:47Z
mmm a / tensorflow / python / ops / session_ops . py <nl> ppp b / tensorflow / python / ops / session_ops . py <nl> def _get_handle_reader ( graph , handle , dtype ) : <nl> if result is None : <nl> # Create reader if we haven ' t done it . <nl> handle_device = TensorHandle . _get_device_name ( handle ) <nl> - with ops . device ( handle_device ) : <nl> + with graph . as_default ( ) , graph . device ( handle_device ) : <nl> holder = array_ops . placeholder ( dtypes . string ) <nl> _register_handle_feeder ( holder . graph , holder , dtype ) <nl> reader = gen_data_flow_ops . _get_session_tensor ( holder , dtype ) <nl> def _get_handle_mover ( graph , feeder , handle ) : <nl> if result is None : <nl> # Create mover if we haven ' t done it . <nl> holder , reader = _get_handle_reader ( graph , handle , dtype ) <nl> - with ops . device ( feeder . op . device ) : <nl> + with graph . as_default ( ) , graph . device ( feeder . op . device ) : <nl> mover = gen_data_flow_ops . _get_session_handle ( reader ) <nl> result = ( holder , mover ) <nl> graph . _handle_movers [ graph_key ] = result <nl> def _get_handle_deleter ( graph , handle ) : <nl> if result is None : <nl> # Create deleter if we haven ' t done it . <nl> handle_device = TensorHandle . _get_device_name ( handle ) <nl> - with ops . device ( handle_device ) : <nl> + with graph . as_default ( ) , graph . device ( handle_device ) : <nl> holder = array_ops . placeholder ( dtypes . string ) <nl> deleter = gen_data_flow_ops . _delete_session_tensor ( holder ) <nl> result = ( holder , deleter ) <nl>
Make sure we always add nodes to the session graph for persistent tensors .
tensorflow/tensorflow
779c8534b3de27303808ff28dc581acc38e3e59f
2016-05-26T02:32:29Z
mmm a / lib / ClangImporter / ClangDiagnosticConsumer . cpp <nl> ppp b / lib / ClangImporter / ClangDiagnosticConsumer . cpp <nl> SourceLoc ClangDiagnosticConsumer : : resolveSourceLocation ( <nl> return loc ; <nl> <nl> auto buffer = clangSrcMgr . getBuffer ( decomposedLoc . first ) ; <nl> + unsigned mirrorID ; <nl> <nl> - auto mirrorID = <nl> - swiftSrcMgr . getIDForBufferIdentifier ( buffer - > getBufferIdentifier ( ) ) ; <nl> - if ( ! mirrorID ) { <nl> + auto mirrorIter = mirroredBuffers . find ( buffer ) ; <nl> + if ( mirrorIter ! = mirroredBuffers . end ( ) ) { <nl> + mirrorID = mirrorIter - > second ; <nl> + } else { <nl> std : : unique_ptr < llvm : : MemoryBuffer > mirrorBuffer { <nl> llvm : : MemoryBuffer : : getMemBuffer ( buffer - > getBuffer ( ) , <nl> buffer - > getBufferIdentifier ( ) , <nl> / * nullTerminated = * / true ) <nl> } ; <nl> mirrorID = swiftSrcMgr . addNewSourceBuffer ( std : : move ( mirrorBuffer ) ) ; <nl> + mirroredBuffers [ buffer ] = mirrorID ; <nl> } <nl> - loc = swiftSrcMgr . getLocForOffset ( mirrorID . getValue ( ) , decomposedLoc . second ) ; <nl> + loc = swiftSrcMgr . getLocForOffset ( mirrorID , decomposedLoc . second ) ; <nl> <nl> auto presumedLoc = clangSrcMgr . getPresumedLoc ( clangLoc ) ; <nl> if ( ! presumedLoc . getFilename ( ) ) <nl> SourceLoc ClangDiagnosticConsumer : : resolveSourceLocation ( <nl> swiftSrcMgr . openVirtualFile ( startOfLine , presumedFile , <nl> presumedLoc . getLine ( ) - bufferLineNumber ) ; <nl> if ( isNewVirtualFile ) { <nl> - SourceLoc endOfLine = findEndOfLine ( swiftSrcMgr , loc , mirrorID . getValue ( ) ) ; <nl> + SourceLoc endOfLine = findEndOfLine ( swiftSrcMgr , loc , mirrorID ) ; <nl> swiftSrcMgr . closeVirtualFile ( endOfLine ) ; <nl> } <nl> <nl> mmm a / lib / ClangImporter / ClangDiagnosticConsumer . h <nl> ppp b / lib / ClangImporter / ClangDiagnosticConsumer . h <nl> class ClangDiagnosticConsumer : public clang : : TextDiagnosticPrinter { <nl> / / IntrusiveRefCntPtr to stay a ref - counting pointer . <nl> SmallVector < llvm : : IntrusiveRefCntPtr < const clang : : SourceManager > , 4 > <nl> sourceManagersWithDiagnostics ; <nl> + llvm : : DenseMap < const llvm : : MemoryBuffer * , unsigned > mirroredBuffers ; <nl> <nl> const clang : : IdentifierInfo * CurrentImport = nullptr ; <nl> SourceLoc DiagLoc ; <nl> new file mode 100644 <nl> index 000000000000 . . cec1fa6c46af <nl> mmm / dev / null <nl> ppp b / test / ClangModules / Inputs / custom - modules / ImportsMissingHeader . h <nl> @ @ - 0 , 0 + 1 @ @ <nl> + # import " this - header - does - not - exist . h " <nl> mmm a / test / ClangModules / Inputs / custom - modules / module . map <nl> ppp b / test / ClangModules / Inputs / custom - modules / module . map <nl> module HasSubmodule { <nl> } <nl> } <nl> <nl> + module ImportsMissingHeader { <nl> + header " ImportsMissingHeader . h " <nl> + export * <nl> + } <nl> + <nl> module IndirectFramework { <nl> link framework " Indirect " <nl> } <nl> new file mode 100644 <nl> index 000000000000 . . 1204193887b9 <nl> mmm / dev / null <nl> ppp b / test / ClangModules / Inputs / custom - modules / more - custom - modules / ImportsMissingHeaderIndirect . h <nl> @ @ - 0 , 0 + 1 @ @ <nl> + @ import ImportsMissingHeader ; <nl> new file mode 100644 <nl> index 000000000000 . . 61147751392b <nl> mmm / dev / null <nl> ppp b / test / ClangModules / Inputs / custom - modules / more - custom - modules / module . map <nl> <nl> + / / It is important that this test uses a second module . map file . <nl> + module ImportsMissingHeaderIndirect { <nl> + header " ImportsMissingHeaderIndirect . h " <nl> + export * <nl> + } <nl> mmm a / test / ClangModules / broken - modules . swift <nl> ppp b / test / ClangModules / broken - modules . swift <nl> <nl> / / RUN : rm - rf % t & & mkdir - p % t <nl> + <nl> + / / RUN : not % target - swift - frontend - parse % s - I % S / Inputs / custom - modules / - show - diagnostics - after - fatal - D MISSING_FROM_MODULE 2 > % t / err . txt <nl> + / / RUN : FileCheck - check - prefix CHECK - MODULE - MAP % s < % t / err . txt <nl> + <nl> / / RUN : not % target - swift - frontend - parse % s - I % S / Inputs / custom - modules / - show - diagnostics - after - fatal 2 > % t / err . txt <nl> - / / RUN : FileCheck % s < % t / err . txt <nl> + / / RUN : FileCheck - check - prefix CHECK - check - prefix CHECK - DIRECT % s < % t / err . txt <nl> <nl> + / / RUN : not % target - swift - frontend - parse % s - I % S / Inputs / custom - modules / - show - diagnostics - after - fatal - D INDIRECT 2 > % t / err . txt <nl> + / / RUN : FileCheck - check - prefix CHECK - check - prefix CHECK - INDIRECT % s < % t / err . txt <nl> + <nl> + # if MISSING_FROM_MODULE <nl> import MissingHeader <nl> - / / CHECK : { { . * } } / Inputs / custom - modules / module . map : { { [ 0 - 9 ] + : [ 0 - 9 ] + } } : error : header ' this - header - does - not - exist . h ' not found <nl> - / / CHECK : roken - modules . swift : [ [ @ LINE - 2 ] ] : 8 : error : could not build Objective - C module ' MissingHeader ' <nl> + / / CHECK - MODULE - MAP : { { . * } } / Inputs / custom - modules / module . map : { { [ 0 - 9 ] + : [ 0 - 9 ] + } } : error : header ' this - header - does - not - exist . h ' not found <nl> + / / CHECK - MODULE - MAP : broken - modules . swift : [ [ @ LINE - 2 ] ] : 8 : error : could not build Objective - C module ' MissingHeader ' <nl> + <nl> + # else <nl> + <nl> + # if INDIRECT <nl> + import ImportsMissingHeaderIndirect <nl> + # else <nl> + import ImportsMissingHeader <nl> + # endif <nl> + <nl> + / / CHECK - INDIRECT : { { . * } } / Inputs / custom - modules / more - custom - modules / ImportsMissingHeaderIndirect . h : 1 : 9 : note : while building module ' ImportsMissingHeader ' imported from { { . * } } / Inputs / custom - modules / more - custom - modules / ImportsMissingHeaderIndirect . h : 1 : <nl> + / / CHECK - INDIRECT - NEXT : @ import ImportsMissingHeader ; <nl> + <nl> + / / CHECK : < module - includes > : 1 : 9 : note : in file included from < module - includes > : 1 : <nl> + / / CHECK - NEXT : # import " { { . * } } ImportsMissingHeader . h " <nl> + <nl> + / / CHECK : { { . * } } / Inputs / custom - modules / ImportsMissingHeader . h : 1 : 9 : error : ' this - header - does - not - exist . h ' file not found <nl> + <nl> + / / CHECK - INDIRECT : < module - includes > : 1 : 9 : note : in file included from < module - includes > : 1 : <nl> + / / CHECK - INDIRECT - NEXT : # import " { { . * } } ImportsMissingHeaderIndirect . h " <nl> + <nl> + / / CHECK - INDIRECT : { { . * } } / Inputs / custom - modules / more - custom - modules / ImportsMissingHeaderIndirect . h : 1 : 9 : error : could not build module ' ImportsMissingHeader ' <nl> + / / CHECK - INDIRECT - NEXT : @ import ImportsMissingHeader ; <nl> + <nl> + <nl> + / / CHECK - DIRECT : broken - modules . swift : { { [ 0 - 9 ] + } } : 8 : error : could not build Objective - C module ' ImportsMissingHeader ' <nl> + / / CHECK - INDIRECT : broken - modules . swift : { { [ 0 - 9 ] + } } : 8 : error : could not build Objective - C module ' ImportsMissingHeaderIndirect ' <nl> + <nl> + # endif <nl> + <nl>
[ ClangImporter ] Don ' t assume all memory buffers have unique identifiers .
apple/swift
2cd2fe341865d86b800cf0f709d0f897f8cc37a5
2015-02-11T23:07:37Z
mmm a / tensorflow / contrib / tensor_forest / core / ops / count_extremely_random_stats_op . cc <nl> ppp b / tensorflow / contrib / tensor_forest / core / ops / count_extremely_random_stats_op . cc <nl> REGISTER_OP ( " CountExtremelyRandomStats " ) <nl> . Input ( " sparse_input_shape : int64 " ) <nl> . Input ( " input_spec : int32 " ) <nl> . Input ( " input_labels : float " ) <nl> + . Input ( " input_weights : float " ) <nl> . Input ( " tree : int32 " ) <nl> . Input ( " tree_thresholds : float " ) <nl> . Input ( " node_to_accumulator : int32 " ) <nl> REGISTER_OP ( " CountExtremelyRandomStats " ) <nl> if ( c - > RankKnown ( c - > input ( 3 ) ) & & c - > Rank ( c - > input ( 3 ) ) > 0 ) { <nl> num_points = c - > UnknownDim ( ) ; <nl> } <nl> - const Dimension * num_nodes = c - > Dim ( c - > input ( 6 ) , 0 ) ; <nl> + const Dimension * num_nodes = c - > Dim ( c - > input ( 7 ) , 0 ) ; <nl> <nl> / / Node sums <nl> c - > set_output ( 0 , c - > Matrix ( num_nodes , num_classes ) ) ; <nl> input_spec : A 1 - D tensor containing the type of each column in input_data , <nl> type , individual feature types start at index 1 . <nl> input_labels : The training batch ' s labels ; ` input_labels [ i ] ` is the class <nl> of the i - th input . <nl> + input_weights : = A 1 - D float tensor . If non - empty , ` input_weights [ i ] ` gives <nl> + the weight of the i - th input . <nl> tree : = A 2 - d int32 tensor . ` tree [ i ] [ 0 ] ` gives the index of the left child <nl> of the i - th node , ` tree [ i ] [ 0 ] + 1 ` gives the index of the right child of <nl> the i - th node , and ` tree [ i ] [ 1 ] ` gives the index of the feature used to <nl> class CountExtremelyRandomStats : public OpKernel { <nl> const Tensor & sparse_input_shape = context - > input ( 3 ) ; <nl> const Tensor & input_spec = context - > input ( 4 ) ; <nl> const Tensor & input_labels = context - > input ( 5 ) ; <nl> - const Tensor & tree_tensor = context - > input ( 6 ) ; <nl> - const Tensor & tree_thresholds = context - > input ( 7 ) ; <nl> - const Tensor & node_to_accumulator = context - > input ( 8 ) ; <nl> - const Tensor & candidate_split_features = context - > input ( 9 ) ; <nl> - const Tensor & candidate_split_thresholds = context - > input ( 10 ) ; <nl> - const Tensor & birth_epochs = context - > input ( 11 ) ; <nl> - const Tensor & current_epoch = context - > input ( 12 ) ; <nl> + const Tensor & input_weights = context - > input ( 6 ) ; <nl> + const Tensor & tree_tensor = context - > input ( 7 ) ; <nl> + const Tensor & tree_thresholds = context - > input ( 8 ) ; <nl> + const Tensor & node_to_accumulator = context - > input ( 9 ) ; <nl> + const Tensor & candidate_split_features = context - > input ( 10 ) ; <nl> + const Tensor & candidate_split_thresholds = context - > input ( 11 ) ; <nl> + const Tensor & birth_epochs = context - > input ( 12 ) ; <nl> + const Tensor & current_epoch = context - > input ( 13 ) ; <nl> <nl> bool sparse_input = ( sparse_input_indices . shape ( ) . dims ( ) = = 2 ) ; <nl> + bool have_weights = ( input_weights . shape ( ) . dim_size ( 0 ) > 0 ) ; <nl> <nl> / / Check inputs . <nl> if ( sparse_input ) { <nl> class CountExtremelyRandomStats : public OpKernel { <nl> " input_data and input_labels . " ) ) ; <nl> } <nl> <nl> + if ( have_weights ) { <nl> + OP_REQUIRES ( <nl> + context , <nl> + input_weights . shape ( ) . dim_size ( 0 ) = = input_labels . shape ( ) . dim_size ( 0 ) , <nl> + errors : : InvalidArgument ( <nl> + " Number of inputs should be the same in input_weights and " <nl> + " input_labels . " ) ) ; <nl> + } <nl> + <nl> OP_REQUIRES ( context , input_labels . shape ( ) . dims ( ) > = 1 , <nl> errors : : InvalidArgument ( <nl> " input_labels should be at least one - dimensional " ) ) ; <nl> class CountExtremelyRandomStats : public OpKernel { <nl> if ( ! CheckTensorBounds ( context , sparse_input_values ) ) return ; <nl> if ( ! CheckTensorBounds ( context , sparse_input_shape ) ) return ; <nl> if ( ! CheckTensorBounds ( context , input_labels ) ) return ; <nl> + if ( ! CheckTensorBounds ( context , input_weights ) ) return ; <nl> if ( ! CheckTensorBounds ( context , tree_tensor ) ) return ; <nl> if ( ! CheckTensorBounds ( context , tree_thresholds ) ) return ; <nl> if ( ! CheckTensorBounds ( context , node_to_accumulator ) ) return ; <nl> class CountExtremelyRandomStats : public OpKernel { <nl> <nl> const int32 num_nodes = static_cast < int32 > ( tree_tensor . shape ( ) . dim_size ( 0 ) ) ; <nl> if ( regression_ ) { <nl> - ProcessResultsRegression ( <nl> - context , input_labels , birth_epochs , epoch , std : : move ( results ) , <nl> - num_nodes ) ; <nl> + ProcessResultsRegression ( context , input_labels , input_weights , <nl> + birth_epochs , epoch , std : : move ( results ) , <nl> + num_nodes ) ; <nl> } else { <nl> - ProcessResultsClassification ( <nl> - context , input_labels , birth_epochs , epoch , std : : move ( results ) , <nl> - num_nodes ) ; <nl> + ProcessResultsClassification ( context , input_labels , input_weights , <nl> + birth_epochs , epoch , std : : move ( results ) , <nl> + num_nodes ) ; <nl> } <nl> } <nl> <nl> protected : <nl> - void ProcessResultsClassification ( <nl> - OpKernelContext * context , <nl> - const Tensor & input_labels , <nl> - const Tensor & birth_epochs , <nl> - int32 epoch , <nl> - std : : unique_ptr < InputDataResult [ ] > results , <nl> - int32 num_nodes ) { <nl> + void ProcessResultsClassification ( OpKernelContext * context , <nl> + const Tensor & input_labels , <nl> + const Tensor & input_weights , <nl> + const Tensor & birth_epochs , int32 epoch , <nl> + std : : unique_ptr < InputDataResult [ ] > results , <nl> + int32 num_nodes ) { <nl> const int32 num_data = static_cast < int32 > ( input_labels . shape ( ) . dim_size ( 0 ) ) ; <nl> const auto labels = input_labels . unaligned_flat < float > ( ) ; <nl> const auto start_epochs = birth_epochs . unaligned_flat < int32 > ( ) ; <nl> + const auto weights = input_weights . unaligned_flat < float > ( ) ; <nl> <nl> / / Unused outputs for classification . Still have to specify them or <nl> / / tensorflow complains . <nl> class CountExtremelyRandomStats : public OpKernel { <nl> <nl> for ( int32 i = 0 ; i < num_data ; + + i ) { <nl> out_leaves ( i ) = results [ i ] . node_indices . back ( ) ; <nl> + float w = 1 . 0 ; <nl> + if ( weights . size ( ) > 0 ) { <nl> + w = weights ( i ) ; <nl> + } <nl> <nl> const int32 label = internal : : SubtleMustCopy ( <nl> static_cast < int32 > ( labels ( i ) ) ) ; <nl> class CountExtremelyRandomStats : public OpKernel { <nl> if ( epoch > start_epochs ( node ) + 1 ) { <nl> continue ; <nl> } <nl> - + + out_node_sums ( node , column ) ; <nl> - + + out_node_sums ( node , 0 ) ; <nl> + out_node_sums ( node , column ) + = w ; <nl> + out_node_sums ( node , 0 ) + = w ; <nl> } <nl> <nl> if ( epoch > start_epochs ( out_leaves ( i ) ) + 1 ) { <nl> continue ; <nl> } <nl> if ( accumulator > = 0 & & results [ i ] . splits_initialized ) { <nl> - + + total_delta [ make_pair ( accumulator , column ) ] ; <nl> - + + total_delta [ make_pair ( accumulator , 0 ) ] ; <nl> + total_delta [ make_pair ( accumulator , column ) ] + = w ; <nl> + total_delta [ make_pair ( accumulator , 0 ) ] + = w ; <nl> for ( const int32 split : results [ i ] . split_adds ) { <nl> - + + split_delta [ make_tuple ( accumulator , split , column ) ] ; <nl> - + + split_delta [ make_tuple ( accumulator , split , 0 ) ] ; <nl> + split_delta [ make_tuple ( accumulator , split , column ) ] + = w ; <nl> + split_delta [ make_tuple ( accumulator , split , 0 ) ] + = w ; <nl> } <nl> } <nl> } <nl> class CountExtremelyRandomStats : public OpKernel { <nl> } <nl> } <nl> <nl> - void ProcessResultsRegression ( <nl> - OpKernelContext * context , <nl> - const Tensor & input_labels , <nl> - const Tensor & birth_epochs , <nl> - const int32 epoch , <nl> - std : : unique_ptr < InputDataResult [ ] > results , <nl> - int32 num_nodes ) { <nl> + void ProcessResultsRegression ( OpKernelContext * context , <nl> + const Tensor & input_labels , <nl> + const Tensor & input_weights , <nl> + const Tensor & birth_epochs , const int32 epoch , <nl> + std : : unique_ptr < InputDataResult [ ] > results , <nl> + int32 num_nodes ) { <nl> const int32 num_data = static_cast < int32 > ( input_labels . shape ( ) . dim_size ( 0 ) ) ; <nl> int32 num_outputs = 1 ; <nl> if ( input_labels . shape ( ) . dims ( ) > 1 ) { <nl> class CountExtremelyRandomStats : public OpKernel { <nl> } <nl> const auto labels = input_labels . unaligned_flat < float > ( ) ; <nl> const auto start_epochs = birth_epochs . unaligned_flat < int32 > ( ) ; <nl> + const auto weights = input_weights . unaligned_flat < float > ( ) ; <nl> <nl> / / node pcw delta <nl> Tensor * output_node_pcw_sums_delta = nullptr ; <nl> class CountExtremelyRandomStats : public OpKernel { <nl> <nl> for ( int32 i = 0 ; i < num_data ; + + i ) { <nl> const int32 accumulator = results [ i ] . leaf_accumulator ; <nl> + float w = 1 . 0 ; <nl> + if ( weights . size ( ) > 0 ) { <nl> + w = weights ( i ) ; <nl> + } <nl> + <nl> for ( const int32 node : results [ i ] . node_indices ) { <nl> if ( epoch > start_epochs ( node ) + 1 ) { <nl> continue ; <nl> } <nl> for ( int32 j = 0 ; j < num_outputs ; + + j ) { <nl> const float output = labels ( i * num_outputs + j ) ; <nl> - out_node_sums ( node , j + 1 ) + = output ; <nl> - out_node_squares ( node , j + 1 ) + = output * output ; <nl> - + + out_node_sums ( node , 0 ) ; <nl> - + + out_node_squares ( node , 0 ) ; <nl> + out_node_sums ( node , j + 1 ) + = w * output ; <nl> + out_node_squares ( node , j + 1 ) + = w * output * output ; <nl> + out_node_sums ( node , 0 ) + = w ; <nl> + out_node_squares ( node , 0 ) + = w ; <nl> } <nl> } <nl> out_leaves ( i ) = results [ i ] . node_indices . back ( ) ; <nl> mmm a / tensorflow / contrib / tensor_forest / core / ops / training_ops_test . cc <nl> ppp b / tensorflow / contrib / tensor_forest / core / ops / training_ops_test . cc <nl> TEST ( TrainingOpsTest , SampleInputs_ShapeFn ) { <nl> TEST ( TrainingOpsTest , CountExtremelyRandomStats_ShapeFn ) { <nl> ShapeInferenceTestOp op ( " CountExtremelyRandomStats " ) ; <nl> TF_ASSERT_OK ( NodeDefBuilder ( " test " , " CountExtremelyRandomStats " ) <nl> - . Input ( " a " , 0 , DT_FLOAT ) <nl> - . Input ( " b " , 1 , DT_INT64 ) <nl> - . Input ( " c " , 2 , DT_FLOAT ) <nl> - . Input ( " d " , 3 , DT_INT64 ) <nl> - . Input ( " e " , 4 , DT_INT32 ) <nl> - . Input ( " f " , 5 , DT_FLOAT ) <nl> - . Input ( " g " , 6 , DT_INT32 ) <nl> - . Input ( " h " , 7 , DT_FLOAT ) <nl> - . Input ( " i " , 8 , DT_INT32 ) <nl> - . Input ( " j " , 9 , DT_INT32 ) <nl> - . Input ( " k " , 10 , DT_FLOAT ) <nl> - . Input ( " l " , 11 , DT_INT32 ) <nl> - . Input ( " m " , 12 , DT_INT32 ) <nl> + . Input ( " input_data " , 0 , DT_FLOAT ) <nl> + . Input ( " sparse_input_indices " , 1 , DT_INT64 ) <nl> + . Input ( " sparse_input_values " , 2 , DT_FLOAT ) <nl> + . Input ( " sparse_input_shape " , 3 , DT_INT64 ) <nl> + . Input ( " input_spec " , 4 , DT_INT32 ) <nl> + . Input ( " input_labels " , 5 , DT_FLOAT ) <nl> + . Input ( " input_weights " , 6 , DT_FLOAT ) <nl> + . Input ( " tree " , 7 , DT_INT32 ) <nl> + . Input ( " tree_thresholds " , 8 , DT_FLOAT ) <nl> + . Input ( " node_to_accumulator " , 9 , DT_INT32 ) <nl> + . Input ( " candidate_split_features " , 10 , DT_INT32 ) <nl> + . Input ( " candidate_split_thresholds " , 11 , DT_FLOAT ) <nl> + . Input ( " birth_epochs " , 12 , DT_INT32 ) <nl> + . Input ( " current_epoch " , 13 , DT_INT32 ) <nl> . Attr ( " num_classes " , 10 ) <nl> . Attr ( " regression " , false ) <nl> . Finalize ( & op . node_def ) ) ; <nl> <nl> / / num_points = 2 , num_nodes = 4 , regression = false , num_classes = 10 <nl> / / num_nodes = 4 <nl> - INFER_OK ( op , " [ 2 , 3 ] ; ? ; ? ; ? ; ? ; ? ; [ 4 ] ; ? ; ? ; ? ; ? ; ? ; ? " , <nl> - " [ d6_0 , 10 ] ; [ d6_0 , 10 ] ; [ ? , 3 ] ; [ ? ] ; [ 0 ] ; [ ? , 2 ] ; [ ? ] ; [ 0 ] ; [ d0_0 ] " ) ; <nl> + INFER_OK ( op , " [ 2 , 3 ] ; ? ; ? ; ? ; ? ; ? ; ? ; [ 4 ] ; ? ; ? ; ? ; ? ; ? ; ? " , <nl> + " [ d7_0 , 10 ] ; [ d7_0 , 10 ] ; [ ? , 3 ] ; [ ? ] ; [ 0 ] ; [ ? , 2 ] ; [ ? ] ; [ 0 ] ; [ d0_0 ] " ) ; <nl> <nl> TF_ASSERT_OK ( NodeDefBuilder ( " test " , " CountExtremelyRandomStats " ) <nl> - . Input ( " a " , 0 , DT_FLOAT ) <nl> - . Input ( " b " , 1 , DT_INT64 ) <nl> - . Input ( " c " , 2 , DT_FLOAT ) <nl> - . Input ( " d " , 3 , DT_INT64 ) <nl> - . Input ( " e " , 4 , DT_INT32 ) <nl> - . Input ( " f " , 5 , DT_FLOAT ) <nl> - . Input ( " g " , 6 , DT_INT32 ) <nl> - . Input ( " h " , 7 , DT_FLOAT ) <nl> - . Input ( " i " , 8 , DT_INT32 ) <nl> - . Input ( " j " , 9 , DT_INT32 ) <nl> - . Input ( " k " , 10 , DT_FLOAT ) <nl> - . Input ( " l " , 11 , DT_INT32 ) <nl> - . Input ( " m " , 12 , DT_INT32 ) <nl> + . Input ( " input_data " , 0 , DT_FLOAT ) <nl> + . Input ( " sparse_input_indices " , 1 , DT_INT64 ) <nl> + . Input ( " sparse_input_values " , 2 , DT_FLOAT ) <nl> + . Input ( " sparse_input_shape " , 3 , DT_INT64 ) <nl> + . Input ( " input_spec " , 4 , DT_INT32 ) <nl> + . Input ( " input_labels " , 5 , DT_FLOAT ) <nl> + . Input ( " input_weights " , 6 , DT_FLOAT ) <nl> + . Input ( " tree " , 7 , DT_INT32 ) <nl> + . Input ( " tree_thresholds " , 8 , DT_FLOAT ) <nl> + . Input ( " node_to_accumulator " , 9 , DT_INT32 ) <nl> + . Input ( " candidate_split_features " , 10 , DT_INT32 ) <nl> + . Input ( " candidate_split_thresholds " , 11 , DT_FLOAT ) <nl> + . Input ( " birth_epochs " , 12 , DT_INT32 ) <nl> + . Input ( " current_epoch " , 13 , DT_INT32 ) <nl> . Attr ( " num_classes " , 10 ) <nl> . Attr ( " regression " , true ) <nl> . Finalize ( & op . node_def ) ) ; <nl> TEST ( TrainingOpsTest , CountExtremelyRandomStats_ShapeFn ) { <nl> / / num_points = 2 , num_nodes = 4 , regression = false , num_classes = 10 <nl> / / num_nodes = 4 <nl> INFER_OK ( <nl> - op , " [ 2 , 3 ] ; ? ; ? ; ? ; ? ; ? ; [ 4 ] ; ? ; ? ; ? ; ? ; ? ; ? " , <nl> - " [ d6_0 , 10 ] ; [ d6_0 , 10 ] ; [ ? , 2 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ ? , 1 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ d0_0 ] " ) ; <nl> + op , " [ 2 , 3 ] ; ? ; ? ; ? ; ? ; ? ; ? ; [ 4 ] ; ? ; ? ; ? ; ? ; ? ; ? " , <nl> + " [ d7_0 , 10 ] ; [ d7_0 , 10 ] ; [ ? , 2 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ ? , 1 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ d0_0 ] " ) ; <nl> <nl> / / Sparse shape known and > 1 , so num_points is unknown <nl> - INFER_OK ( op , " [ 2 , 3 ] ; ? ; ? ; [ 10 , 11 ] ; ? ; ? ; [ 4 ] ; ? ; ? ; ? ; ? ; ? ; ? " , <nl> - " [ d6_0 , 10 ] ; [ d6_0 , 10 ] ; [ ? , 2 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ ? , 1 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ ? ] " ) ; <nl> + INFER_OK ( op , " [ 2 , 3 ] ; ? ; ? ; [ 10 , 11 ] ; ? ; ? ; ? ; [ 4 ] ; ? ; ? ; ? ; ? ; ? ; ? " , <nl> + " [ d7_0 , 10 ] ; [ d7_0 , 10 ] ; [ ? , 2 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ ? , 1 ] ; [ ? , 10 ] ; [ ? , 10 ] ; [ ? ] " ) ; <nl> } <nl> <nl> TEST ( TrainingOpsTest , TreePredictions_ShapeFn ) { <nl> mmm a / tensorflow / contrib / tensor_forest / python / kernel_tests / count_extremely_random_stats_op_test . py <nl> ppp b / tensorflow / contrib / tensor_forest / python / kernel_tests / count_extremely_random_stats_op_test . py <nl> def setUp ( self ) : <nl> def testSimple ( self ) : <nl> with self . test_session ( ) : <nl> ( pcw_node_sums , _ , pcw_splits_indices , pcw_splits_sums , _ , <nl> - pcw_totals_indices , pcw_totals_sums , _ , leaves ) = ( <nl> - self . ops . count_extremely_random_stats ( <nl> - self . input_data , [ ] , [ ] , [ ] , self . data_spec , self . input_labels , <nl> - self . tree , self . tree_thresholds , self . node_map , <nl> - self . split_features , self . split_thresholds , self . epochs , <nl> - self . current_epoch , <nl> - num_classes = 5 , regression = False ) ) <nl> + pcw_totals_indices , pcw_totals_sums , _ , <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( <nl> [ [ 4 . , 1 . , 1 . , 1 . , 1 . ] , [ 2 . , 1 . , 1 . , 0 . , 0 . ] , [ 2 . , 0 . , 0 . , 1 . , 1 . ] ] , <nl> def testSimple ( self ) : <nl> self . assertAllEqual ( [ 1 . , 2 . , 1 . ] , pcw_totals_sums . eval ( ) ) <nl> self . assertAllEqual ( [ 1 , 1 , 2 , 2 ] , leaves . eval ( ) ) <nl> <nl> + def testSimpleWeighted ( self ) : <nl> + with self . test_session ( ) : <nl> + input_weights = [ 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ] <nl> + ( pcw_node_sums , _ , pcw_splits_indices , pcw_splits_sums , _ , <nl> + pcw_totals_indices , pcw_totals_sums , _ , <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , <nl> + input_weights , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> + <nl> + self . assertAllEqual ( <nl> + [ [ 10 . , 1 . , 2 . , 3 . , 4 . ] , [ 3 . , 1 . , 2 . , 0 . , 0 . ] , [ 7 . , 0 . , 0 . , 3 . , 4 . ] ] , <nl> + pcw_node_sums . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] ] , pcw_splits_indices . eval ( ) ) <nl> + self . assertAllEqual ( [ 1 . , 1 . ] , pcw_splits_sums . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 0 , 2 ] , [ 0 , 0 ] , [ 0 , 1 ] ] , pcw_totals_indices . eval ( ) ) <nl> + self . assertAllEqual ( [ 2 . , 3 . , 1 . ] , pcw_totals_sums . eval ( ) ) <nl> + self . assertAllEqual ( [ 1 , 1 , 2 , 2 ] , leaves . eval ( ) ) <nl> + <nl> def testMissingLabel ( self ) : <nl> labels = [ 0 , 1 , - 1 , 3 ] <nl> with self . test_session ( ) : <nl> ( pcw_node_sums , _ , pcw_splits_indices , pcw_splits_sums , _ , <nl> pcw_totals_indices , pcw_totals_sums , _ , <nl> - leaves ) = ( self . ops . count_extremely_random_stats ( self . input_data , [ ] , [ ] , <nl> - [ ] , <nl> - self . data_spec , <nl> - labels , <nl> - self . tree , <nl> - self . tree_thresholds , <nl> - self . node_map , <nl> - self . split_features , <nl> - self . split_thresholds , <nl> - self . epochs , <nl> - self . current_epoch , <nl> - num_classes = 5 , <nl> - regression = False ) ) <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( <nl> [ [ 3 . , 1 . , 1 . , 0 . , 1 . ] , [ 2 . , 1 . , 1 . , 0 . , 0 . ] , [ 1 . , 0 . , 0 . , 0 . , 1 . ] ] , <nl> def testSparseInput ( self ) : <nl> - 0 . 5 , 2 . 0 ] <nl> with self . test_session ( ) : <nl> ( pcw_node_sums , _ , pcw_splits_indices , pcw_splits_sums , _ , <nl> - pcw_totals_indices , pcw_totals_sums , _ , leaves ) = ( <nl> - self . ops . count_extremely_random_stats ( <nl> - [ ] , sparse_indices , sparse_values , sparse_shape , self . data_spec , <nl> - self . input_labels , self . tree , <nl> - self . tree_thresholds , self . node_map , <nl> - self . split_features , self . split_thresholds , self . epochs , <nl> - self . current_epoch , <nl> - num_classes = 5 , regression = False ) ) <nl> + pcw_totals_indices , pcw_totals_sums , _ , <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + [ ] , <nl> + sparse_indices , <nl> + sparse_values , <nl> + sparse_shape , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( <nl> [ [ 4 . , 1 . , 1 . , 1 . , 1 . ] , <nl> def testSparseInput ( self ) : <nl> def testFutureEpoch ( self ) : <nl> current_epoch = [ 3 ] <nl> with self . test_session ( ) : <nl> - ( pcw_node_sums , _ , _ , pcw_splits_sums , _ , <nl> - _ , pcw_totals_sums , _ , leaves ) = ( <nl> - self . ops . count_extremely_random_stats ( <nl> - self . input_data , [ ] , [ ] , [ ] , self . data_spec , self . input_labels , <nl> - self . tree , self . tree_thresholds , self . node_map , <nl> - self . split_features , self . split_thresholds , self . epochs , <nl> - current_epoch , num_classes = 5 , regression = False ) ) <nl> + ( pcw_node_sums , _ , _ , pcw_splits_sums , _ , _ , pcw_totals_sums , _ , <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( <nl> [ [ 0 . , 0 . , 0 . , 0 . , 0 . ] , [ 0 . , 0 . , 0 . , 0 . , 0 . ] , [ 0 . , 0 . , 0 . , 0 . , 0 . ] ] , <nl> def testThreaded ( self ) : <nl> with self . test_session ( <nl> config = tf . ConfigProto ( intra_op_parallelism_threads = 2 ) ) : <nl> ( pcw_node_sums , _ , pcw_splits_indices , pcw_splits_sums , _ , <nl> - pcw_totals_indices , pcw_totals_sums , _ , leaves ) = ( <nl> - self . ops . count_extremely_random_stats ( <nl> - self . input_data , [ ] , [ ] , [ ] , self . data_spec , self . input_labels , <nl> - self . tree , self . tree_thresholds , self . node_map , <nl> - self . split_features , <nl> - self . split_thresholds , self . epochs , self . current_epoch , <nl> - num_classes = 5 , regression = False ) ) <nl> + pcw_totals_indices , pcw_totals_sums , _ , <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( [ [ 4 . , 1 . , 1 . , 1 . , 1 . ] , [ 2 . , 1 . , 1 . , 0 . , 0 . ] , <nl> [ 2 . , 0 . , 0 . , 1 . , 1 . ] ] , <nl> def testThreaded ( self ) : <nl> def testNoAccumulators ( self ) : <nl> with self . test_session ( ) : <nl> ( pcw_node_sums , _ , pcw_splits_indices , pcw_splits_sums , _ , <nl> - pcw_totals_indices , pcw_totals_sums , _ , leaves ) = ( <nl> - self . ops . count_extremely_random_stats ( <nl> - self . input_data , [ ] , [ ] , [ ] , self . data_spec , self . input_labels , <nl> - self . tree , self . tree_thresholds , [ - 1 ] * 3 , <nl> - self . split_features , self . split_thresholds , self . epochs , <nl> - self . current_epoch , num_classes = 5 , regression = False ) ) <nl> + pcw_totals_indices , pcw_totals_sums , _ , <nl> + leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , [ - 1 ] * 3 , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( [ [ 4 . , 1 . , 1 . , 1 . , 1 . ] , [ 2 . , 1 . , 1 . , 0 . , 0 . ] , <nl> [ 2 . , 0 . , 0 . , 1 . , 1 . ] ] , <nl> def testBadInput ( self ) : <nl> ' tree , tree_thresholds , node_to_accumulator , and birth_epoch . ' ) : <nl> pcw_node , _ , _ , _ , _ , _ , _ , _ , _ = ( <nl> self . ops . count_extremely_random_stats ( <nl> - self . input_data , [ ] , [ ] , [ ] , self . data_spec , self . input_labels , <nl> - self . tree , self . tree_thresholds , self . node_map , <nl> - self . split_features , self . split_thresholds , self . epochs , <nl> - self . current_epoch , num_classes = 5 , regression = False ) ) <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 5 , <nl> + regression = False ) ) <nl> <nl> self . assertAllEqual ( [ ] , pcw_node . eval ( ) ) <nl> <nl> def setUp ( self ) : <nl> def testSimple ( self ) : <nl> with self . test_session ( ) : <nl> ( pcw_node_sums , pcw_node_squares , pcw_splits_indices , pcw_splits_sums , <nl> - pcw_splits_squares , pcw_totals_indices , <nl> - pcw_totals_sums , pcw_totals_squares , leaves ) = ( <nl> - self . ops . count_extremely_random_stats ( <nl> - self . input_data , [ ] , [ ] , [ ] , self . data_spec , self . input_labels , <nl> - self . tree , self . tree_thresholds , self . node_map , <nl> - self . split_features , self . split_thresholds , self . epochs , <nl> - self . current_epoch , num_classes = 2 , regression = True ) ) <nl> + pcw_splits_squares , pcw_totals_indices , pcw_totals_sums , <nl> + pcw_totals_squares , leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , [ ] , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 2 , <nl> + regression = True ) ) <nl> <nl> self . assertAllEqual ( <nl> [ [ 4 . , 14 . ] , [ 2 . , 9 . ] , [ 2 . , 5 . ] ] , pcw_node_sums . eval ( ) ) <nl> def testSimple ( self ) : <nl> self . assertAllEqual ( [ [ 2 . , 45 . ] ] , pcw_totals_squares . eval ( ) ) <nl> self . assertAllEqual ( [ 1 , 1 , 2 , 2 ] , leaves . eval ( ) ) <nl> <nl> + def testSimpleWeighted ( self ) : <nl> + with self . test_session ( ) : <nl> + input_weights = [ 1 . 0 , 2 . 0 , 3 . 0 , 4 . 0 ] <nl> + ( pcw_node_sums , pcw_node_squares , pcw_splits_indices , pcw_splits_sums , <nl> + pcw_splits_squares , pcw_totals_indices , pcw_totals_sums , <nl> + pcw_totals_squares , leaves ) = ( self . ops . count_extremely_random_stats ( <nl> + self . input_data , [ ] , [ ] , [ ] , <nl> + self . data_spec , <nl> + self . input_labels , <nl> + input_weights , <nl> + self . tree , <nl> + self . tree_thresholds , <nl> + self . node_map , <nl> + self . split_features , <nl> + self . split_thresholds , <nl> + self . epochs , <nl> + self . current_epoch , <nl> + num_classes = 2 , <nl> + regression = True ) ) <nl> + <nl> + self . assertAllEqual ( [ [ 10 . , 33 . ] , [ 3 . , 15 . ] , [ 7 . , 18 . ] ] , <nl> + pcw_node_sums . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 10 . , 129 . ] , [ 3 . , 81 . ] , [ 7 . , 48 . ] ] , <nl> + pcw_node_squares . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 0 , 0 ] ] , pcw_splits_indices . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 1 . , 3 . ] ] , pcw_splits_sums . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 1 . , 9 . ] ] , pcw_splits_squares . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 0 ] ] , pcw_totals_indices . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 2 . , 9 . ] ] , pcw_totals_sums . eval ( ) ) <nl> + self . assertAllEqual ( [ [ 2 . , 45 . ] ] , pcw_totals_squares . eval ( ) ) <nl> + self . assertAllEqual ( [ 1 , 1 , 2 , 2 ] , leaves . eval ( ) ) <nl> + <nl> <nl> if __name__ = = ' __main__ ' : <nl> googletest . main ( ) <nl> mmm a / tensorflow / contrib / tensor_forest / python / ops / training_ops . py <nl> ppp b / tensorflow / contrib / tensor_forest / python / ops / training_ops . py <nl> def _CountExtremelyRandomStatsShape ( op ) : <nl> sparse_shape = op . inputs [ 3 ] . get_shape ( ) <nl> if sparse_shape . ndims > 0 : <nl> num_points = None <nl> - num_nodes = op . inputs [ 6 ] . get_shape ( ) [ 0 ] . value <nl> + num_nodes = op . inputs [ 7 ] . get_shape ( ) [ 0 ] . value <nl> num_classes = op . get_attr ( ' num_classes ' ) <nl> # The output of TraverseTree is [ leaf_node_index ( x ) for x in input_data ] . <nl> return [ tensor_shape . TensorShape ( [ num_nodes , num_classes ] ) , # node sums <nl> mmm a / tensorflow / contrib / tensor_forest / python / tensor_forest . py <nl> ppp b / tensorflow / contrib / tensor_forest / python / tensor_forest . py <nl> def _variance ( self , sums , squares ) : <nl> <nl> return math_ops . reduce_sum ( e_x2 - math_ops . square ( e_x ) , 1 ) <nl> <nl> - def training_graph ( self , input_data , input_labels , random_seed , <nl> - data_spec , epoch = None ) : <nl> + def training_graph ( self , <nl> + input_data , <nl> + input_labels , <nl> + random_seed , <nl> + data_spec , <nl> + epoch = None , <nl> + input_weights = None ) : <nl> <nl> " " " Constructs a TF graph for training a random tree . <nl> <nl> def training_graph ( self , input_data , input_labels , random_seed , <nl> data_spec : A list of tf . dtype values specifying the original types of <nl> each column . <nl> epoch : A tensor or placeholder for the epoch the training data comes from . <nl> + input_weights : A float tensor or placeholder holding per - input weights , <nl> + or None if all inputs are to be weighted equally . <nl> <nl> Returns : <nl> The last op in the random tree training graph . <nl> " " " <nl> epoch = [ 0 ] if epoch is None else epoch <nl> <nl> + if input_weights is None : <nl> + input_weights = [ ] <nl> + <nl> sparse_indices = [ ] <nl> sparse_values = [ ] <nl> sparse_shape = [ ] <nl> def training_graph ( self , input_data , input_labels , random_seed , <nl> input_data = [ ] <nl> <nl> # Count extremely random stats . <nl> - ( node_sums , node_squares , splits_indices , splits_sums , <nl> - splits_squares , totals_indices , totals_sums , <nl> - totals_squares , input_leaves ) = ( <nl> - self . training_ops . count_extremely_random_stats ( <nl> - input_data , sparse_indices , sparse_values , sparse_shape , <nl> - data_spec , input_labels , self . variables . tree , <nl> - self . variables . tree_thresholds , <nl> - self . variables . node_to_accumulator_map , <nl> - self . variables . candidate_split_features , <nl> - self . variables . candidate_split_thresholds , <nl> - self . variables . start_epoch , epoch , <nl> - num_classes = self . params . num_output_columns , <nl> - regression = self . params . regression ) ) <nl> + ( node_sums , node_squares , splits_indices , splits_sums , splits_squares , <nl> + totals_indices , totals_sums , totals_squares , <nl> + input_leaves ) = ( self . training_ops . count_extremely_random_stats ( <nl> + input_data , <nl> + sparse_indices , <nl> + sparse_values , <nl> + sparse_shape , <nl> + data_spec , <nl> + input_labels , <nl> + input_weights , <nl> + self . variables . tree , <nl> + self . variables . tree_thresholds , <nl> + self . variables . node_to_accumulator_map , <nl> + self . variables . candidate_split_features , <nl> + self . variables . candidate_split_thresholds , <nl> + self . variables . start_epoch , <nl> + epoch , <nl> + num_classes = self . params . num_output_columns , <nl> + regression = self . params . regression ) ) <nl> node_update_ops = [ ] <nl> node_update_ops . append ( <nl> state_ops . assign_add ( self . variables . node_sums , node_sums ) ) <nl>
Add support for weighted inputs to CountExtremelyRandomStats .
tensorflow/tensorflow
e01f7d1312fcfeeb26d6d53e0e6e423a46682919
2016-08-12T20:18:44Z
mmm a / addons / xbmc . addon / addon . xml <nl> ppp b / addons / xbmc . addon / addon . xml <nl> <nl> < ? xml version = " 1 . 0 " encoding = " UTF - 8 " ? > <nl> - < addon id = " xbmc . addon " version = " 12 . 9 . 9 " provider - name = " Team XBMC " > <nl> + < addon id = " xbmc . addon " version = " 12 . 9 . 10 " provider - name = " Team XBMC " > <nl> < backwards - compatibility abi = " 12 . 0 " / > <nl> < requires > <nl> < import addon = " xbmc . core " version = " 0 . 1 . 0 " / > <nl> mmm a / configure . in <nl> ppp b / configure . in <nl> <nl> # Process this file with autoconf to produce a configure script . <nl> <nl> AC_PREREQ ( 2 . 59 ) <nl> - AC_INIT ( [ xbmc ] , [ 12 . 9 . 9 ] , [ http : / / trac . xbmc . org ] ) <nl> + AC_INIT ( [ xbmc ] , [ 12 . 9 . 10 ] , [ http : / / trac . xbmc . org ] ) <nl> AC_CONFIG_HEADERS ( [ xbmc / config . h ] ) <nl> AH_TOP ( [ # pragma once ] ) <nl> m4_include ( [ m4 / ax_prog_cc_for_build . m4 ] ) <nl> mmm a / tools / android / packaging / xbmc / AndroidManifest . xml <nl> ppp b / tools / android / packaging / xbmc / AndroidManifest . xml <nl> <nl> < ! - - BEGIN_INCLUDE ( manifest ) - - > <nl> < manifest xmlns : android = " http : / / schemas . android . com / apk / res / android " <nl> package = " org . xbmc . xbmc " <nl> - android : versionCode = " 15 " <nl> - android : versionName = " 13 . 0 - ALPHA9 " > <nl> + android : versionCode = " 16 " <nl> + android : versionName = " 13 . 0 - ALPHA10 " > <nl> <nl> < ! - - This is the platform API where NativeActivity was introduced . - - > <nl> < uses - sdk android : minSdkVersion = " 14 " / > <nl> mmm a / tools / darwin / packaging / xbmc - atv2 / mkdeb - xbmc - atv2 . sh <nl> ppp b / tools / darwin / packaging / xbmc - atv2 / mkdeb - xbmc - atv2 . sh <nl> fi <nl> PACKAGE = org . xbmc . xbmc - atv2 <nl> <nl> VERSION = 13 . 0 <nl> - REVISION = 0 ~ alpha9 <nl> + REVISION = 0 ~ alpha10 <nl> ARCHIVE = $ { PACKAGE } _ $ { VERSION } - $ { REVISION } _iphoneos - arm . deb <nl> <nl> echo Creating $ PACKAGE package version $ VERSION revision $ REVISION <nl> mmm a / tools / darwin / packaging / xbmc - ios / mkdeb - xbmc - ios . sh <nl> ppp b / tools / darwin / packaging / xbmc - ios / mkdeb - xbmc - ios . sh <nl> fi <nl> PACKAGE = org . xbmc . xbmc - ios <nl> <nl> VERSION = 13 . 0 <nl> - REVISION = 0 ~ alpha9 <nl> + REVISION = 0 ~ alpha10 <nl> ARCHIVE = $ { PACKAGE } _ $ { VERSION } - $ { REVISION } _iphoneos - arm . deb <nl> <nl> echo Creating $ PACKAGE package version $ VERSION revision $ REVISION <nl> mmm a / tools / darwin / packaging / xbmc - osx / mkdmg - xbmc - osx . sh <nl> ppp b / tools / darwin / packaging / xbmc - osx / mkdmg - xbmc - osx . sh <nl> ARCHITECTURE = ` file $ XBMC / Contents / MacOS / XBMC | awk ' { print $ NF } ' ` <nl> PACKAGE = org . xbmc . xbmc - osx <nl> <nl> VERSION = 13 . 0 <nl> - REVISION = 0 ~ alpha9 <nl> + REVISION = 0 ~ alpha10 <nl> ARCHIVE = $ { PACKAGE } _ $ { VERSION } - $ { REVISION } _macosx - intel - $ { ARCHITECTURE } <nl> <nl> echo Creating $ PACKAGE package version $ VERSION revision $ REVISION <nl> mmm a / xbmc / GUIInfoManager . h <nl> ppp b / xbmc / GUIInfoManager . h <nl> namespace INFO <nl> <nl> # define VERSION_MAJOR 13 <nl> # define VERSION_MINOR 0 <nl> - # define VERSION_TAG " - ALPHA9 " <nl> + # define VERSION_TAG " - ALPHA10 " <nl> <nl> # define LISTITEM_START 35000 <nl> # define LISTITEM_THUMB ( LISTITEM_START ) <nl> mmm a / xbmc / osx / Info . plist <nl> ppp b / xbmc / osx / Info . plist <nl> <nl> < key > CFBundleExecutable < / key > <nl> < string > XBMC < / string > <nl> < key > CFBundleGetInfoString < / key > <nl> - < string > 13 . 0 . alpha9 < / string > <nl> + < string > 13 . 0 . alpha10 < / string > <nl> < key > CFBundleIconFile < / key > <nl> < string > xbmc . icns < / string > <nl> < key > CFBundleIdentifier < / key > <nl> <nl> < key > CFBundlePackageType < / key > <nl> < string > APPL < / string > <nl> < key > CFBundleShortVersionString < / key > <nl> - < string > 13 . 0 . alpha9 < / string > <nl> + < string > 13 . 0 . alpha10 < / string > <nl> < key > CFBundleVersion < / key > <nl> < string > r # # # # < / string > <nl> < key > CFBundleSignature < / key > <nl> mmm a / xbmc / win32 / XBMC_PC . rc <nl> ppp b / xbmc / win32 / XBMC_PC . rc <nl> BEGIN <nl> BEGIN <nl> VALUE " CompanyName " , " Team XBMC " <nl> VALUE " FileDescription " , " XBMC " <nl> - VALUE " FileVersion " , " 13 . 0 - ALPHA9 " <nl> + VALUE " FileVersion " , " 13 . 0 - ALPHA10 " <nl> VALUE " InternalName " , " XBMC . exe " <nl> VALUE " LegalCopyright " , " Copyright ( c ) Team XBMC . All rights reserved . " <nl> VALUE " OriginalFilename " , " XBMC . exe " <nl> VALUE " ProductName " , " XBMC for Windows " <nl> - VALUE " ProductVersion " , " 13 . 0 - ALPHA9 " <nl> + VALUE " ProductVersion " , " 13 . 0 - ALPHA10 " <nl> END <nl> END <nl> BLOCK " VarFileInfo " <nl>
[ release ] version bump to 13 . 0 alpha10 as we start new merge window
xbmc/xbmc
345ca4d85e937455013dcd1f2f91a5df1eb5e56a
2013-10-23T13:26:38Z
mmm a / js / server / tests / aql - optimizer - indexes . js <nl> ppp b / js / server / tests / aql - optimizer - indexes . js <nl> function optimizerIndexesTestSuite ( ) { <nl> assertTrue ( results . stats . scannedIndex > 0 ) ; <nl> } , <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief test index usage <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + testUseIndexJoin : function ( ) { <nl> + var query = " FOR i IN " + c . name ( ) + " FILTER i . value = = 8 FOR j IN " + c . name ( ) + " FILTER i . value = = j . value RETURN i . value " ; <nl> + <nl> + var plan = AQL_EXPLAIN ( query ) . plan ; <nl> + var indexes = 0 ; <nl> + var nodeTypes = plan . nodes . map ( function ( node ) { <nl> + if ( node . type = = = " IndexRangeNode " ) { <nl> + + + indexes ; <nl> + } <nl> + return node . type ; <nl> + } ) ; <nl> + assertEqual ( 2 , indexes ) ; <nl> + <nl> + var results = AQL_EXECUTE ( query ) ; <nl> + assertEqual ( [ 8 ] , results . json , query ) ; <nl> + assertEqual ( 0 , results . stats . scannedFull ) ; <nl> + assertTrue ( results . stats . scannedIndex > 0 ) ; <nl> + } , <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief test index usage <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + testUseIndexJoinJoin : function ( ) { <nl> + var query = " FOR i IN " + c . name ( ) + " FILTER i . value = = 8 FOR j IN " + c . name ( ) + " FILTER i . _key = = j . _key RETURN i . value " ; <nl> + <nl> + var plan = AQL_EXPLAIN ( query ) . plan ; <nl> + var indexes = 0 ; <nl> + var nodeTypes = plan . nodes . map ( function ( node ) { <nl> + if ( node . type = = = " IndexRangeNode " ) { <nl> + + + indexes ; <nl> + } <nl> + return node . type ; <nl> + } ) ; <nl> + assertEqual ( 2 , indexes ) ; <nl> + <nl> + var results = AQL_EXECUTE ( query ) ; <nl> + assertEqual ( [ 8 ] , results . json , query ) ; <nl> + assertEqual ( 0 , results . stats . scannedFull ) ; <nl> + assertTrue ( results . stats . scannedIndex > 0 ) ; <nl> + } , <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / / @ brief test index usage <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + testUseIndexJoinJoinJoin : function ( ) { <nl> + var query = " FOR i IN " + c . name ( ) + " FILTER i . value = = 8 FOR j IN " + c . name ( ) + " FILTER i . value = = j . value FOR k IN " + c . name ( ) + " FILTER j . value = = k . value RETURN i . value " ; <nl> + <nl> + var plan = AQL_EXPLAIN ( query ) . plan ; <nl> + var indexes = 0 ; <nl> + var nodeTypes = plan . nodes . map ( function ( node ) { <nl> + if ( node . type = = = " IndexRangeNode " ) { <nl> + + + indexes ; <nl> + } <nl> + return node . type ; <nl> + } ) ; <nl> + assertEqual ( 3 , indexes ) ; <nl> + <nl> + var results = AQL_EXECUTE ( query ) ; <nl> + assertEqual ( [ 8 ] , results . json , query ) ; <nl> + assertEqual ( 0 , results . stats . scannedFull ) ; <nl> + assertTrue ( results . stats . scannedIndex > 0 ) ; <nl> + } , <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / / @ brief test index usage <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl>
added tests
arangodb/arangodb
e7c7f774e096e96e69d890907cda521500c8a4f4
2014-11-26T19:24:28Z
mmm a / tensorflow / core / framework / load_library . cc <nl> ppp b / tensorflow / core / framework / load_library . cc <nl> Status LoadLibrary ( const char * library_filename , void * * result , <nl> std : : unordered_set < string > seen_op_names ; <nl> { <nl> mutex_lock lock ( mu ) ; <nl> - OpRegistry : : Global ( ) - > ProcessRegistrations ( ) ; <nl> + Status s = OpRegistry : : Global ( ) - > ProcessRegistrations ( ) ; <nl> + if ( ! s . ok ( ) ) { <nl> + return s ; <nl> + } <nl> TF_RETURN_IF_ERROR ( OpRegistry : : Global ( ) - > SetWatcher ( <nl> [ & op_list , & seen_op_names ] ( const Status & s , <nl> const OpDef & opdef ) - > Status { <nl> Status LoadLibrary ( const char * library_filename , void * * result , <nl> return Status : : OK ( ) ; <nl> } <nl> } <nl> - * op_list . add_op ( ) = opdef ; <nl> - seen_op_names . insert ( opdef . name ( ) ) ; <nl> + if ( s . ok ( ) ) { <nl> + * op_list . add_op ( ) = opdef ; <nl> + seen_op_names . insert ( opdef . name ( ) ) ; <nl> + } <nl> return s ; <nl> } ) ) ; <nl> OpRegistry : : Global ( ) - > DeferRegistrations ( ) ; <nl> - Status s = env - > LoadLibrary ( library_filename , & lib ) ; <nl> + s = env - > LoadLibrary ( library_filename , & lib ) ; <nl> + if ( s . ok ( ) ) { <nl> + s = OpRegistry : : Global ( ) - > ProcessRegistrations ( ) ; <nl> + } <nl> if ( ! s . ok ( ) ) { <nl> OpRegistry : : Global ( ) - > ClearDeferredRegistrations ( ) ; <nl> TF_RETURN_IF_ERROR ( OpRegistry : : Global ( ) - > SetWatcher ( nullptr ) ) ; <nl> return s ; <nl> } <nl> - OpRegistry : : Global ( ) - > ProcessRegistrations ( ) ; <nl> TF_RETURN_IF_ERROR ( OpRegistry : : Global ( ) - > SetWatcher ( nullptr ) ) ; <nl> } <nl> string str ; <nl> mmm a / tensorflow / core / framework / op . cc <nl> ppp b / tensorflow / core / framework / op . cc <nl> Status OpRegistry : : LookUp ( const string & op_type_name , <nl> bool first_call = false ; <nl> { / / Scope for lock . <nl> mutex_lock lock ( mu_ ) ; <nl> - first_call = CallDeferred ( ) ; <nl> + first_call = MustCallDeferred ( ) ; <nl> res = gtl : : FindWithDefault ( registry_ , op_type_name , nullptr ) ; <nl> / / Note : Can ' t hold mu_ while calling Export ( ) below . <nl> } <nl> Status OpRegistry : : LookUp ( const string & op_type_name , <nl> <nl> void OpRegistry : : GetRegisteredOps ( std : : vector < OpDef > * op_defs ) { <nl> mutex_lock lock ( mu_ ) ; <nl> - CallDeferred ( ) ; <nl> + MustCallDeferred ( ) ; <nl> for ( const auto & p : registry_ ) { <nl> op_defs - > push_back ( p . second - > op_def ) ; <nl> } <nl> Status OpRegistry : : SetWatcher ( const Watcher & watcher ) { <nl> <nl> void OpRegistry : : Export ( bool include_internal , OpList * ops ) const { <nl> mutex_lock lock ( mu_ ) ; <nl> - CallDeferred ( ) ; <nl> + MustCallDeferred ( ) ; <nl> <nl> std : : vector < std : : pair < string , const OpRegistrationData * > > sorted ( <nl> registry_ . begin ( ) , registry_ . end ( ) ) ; <nl> void OpRegistry : : ClearDeferredRegistrations ( ) { <nl> deferred_ . clear ( ) ; <nl> } <nl> <nl> - void OpRegistry : : ProcessRegistrations ( ) const { <nl> + Status OpRegistry : : ProcessRegistrations ( ) const { <nl> mutex_lock lock ( mu_ ) ; <nl> - CallDeferred ( ) ; <nl> + return CallDeferred ( ) ; <nl> } <nl> <nl> string OpRegistry : : DebugString ( bool include_internal ) const { <nl> string OpRegistry : : DebugString ( bool include_internal ) const { <nl> return ret ; <nl> } <nl> <nl> - bool OpRegistry : : CallDeferred ( ) const { <nl> + bool OpRegistry : : MustCallDeferred ( ) const { <nl> if ( initialized_ ) return false ; <nl> initialized_ = true ; <nl> for ( int i = 0 ; i < deferred_ . size ( ) ; + + i ) { <nl> bool OpRegistry : : CallDeferred ( ) const { <nl> return true ; <nl> } <nl> <nl> + Status OpRegistry : : CallDeferred ( ) const { <nl> + if ( initialized_ ) return Status : : OK ( ) ; <nl> + initialized_ = true ; <nl> + for ( int i = 0 ; i < deferred_ . size ( ) ; + + i ) { <nl> + Status s = RegisterAlreadyLocked ( deferred_ [ i ] ) ; <nl> + if ( ! s . ok ( ) ) { <nl> + return s ; <nl> + } <nl> + } <nl> + deferred_ . clear ( ) ; <nl> + return Status : : OK ( ) ; <nl> + } <nl> + <nl> Status OpRegistry : : RegisterAlreadyLocked ( <nl> OpRegistrationDataFactory op_data_factory ) const { <nl> std : : unique_ptr < OpRegistrationData > op_reg_data ( new OpRegistrationData ) ; <nl> mmm a / tensorflow / core / framework / op . h <nl> ppp b / tensorflow / core / framework / op . h <nl> class OpRegistry : public OpRegistryInterface { <nl> <nl> / / Process the current list of deferred registrations . Note that calls to <nl> / / Export , LookUp and DebugString would also implicitly process the deferred <nl> - / / registrations . <nl> - void ProcessRegistrations ( ) const ; <nl> + / / registrations . Returns the status of the first failed op registration or <nl> + / / Status : : OK ( ) otherwise . <nl> + Status ProcessRegistrations ( ) const ; <nl> <nl> / / Defer the registrations until a later call to a function that processes <nl> / / deferred registrations are made . Normally , registrations that happen after <nl> class OpRegistry : public OpRegistryInterface { <nl> private : <nl> / / Ensures that all the functions in deferred_ get called , their OpDef ' s <nl> / / registered , and returns with deferred_ empty . Returns true the first <nl> - / / time it is called . <nl> - bool CallDeferred ( ) const EXCLUSIVE_LOCKS_REQUIRED ( mu_ ) ; <nl> + / / time it is called . Prints a fatal log if any op registration fails . <nl> + bool MustCallDeferred ( ) const EXCLUSIVE_LOCKS_REQUIRED ( mu_ ) ; <nl> + <nl> + / / Calls the functions in deferred_ and registers their OpDef ' s <nl> + / / It returns the Status of the first failed op registration or Status : : OK ( ) <nl> + / / otherwise . <nl> + Status CallDeferred ( ) const EXCLUSIVE_LOCKS_REQUIRED ( mu_ ) ; <nl> <nl> / / Add ' def ' to the registry with additional data ' data ' . On failure , or if <nl> / / there is already an OpDef with that name registered , returns a non - okay <nl> mmm a / tensorflow / core / framework / op_registration_test . cc <nl> ppp b / tensorflow / core / framework / op_registration_test . cc <nl> TEST ( OpRegistrationTest , TestBasic ) { <nl> TEST ( OpRegistrationTest , TestDuplicate ) { <nl> std : : unique_ptr < OpRegistry > registry ( new OpRegistry ) ; <nl> Register ( " Foo " , registry . get ( ) ) ; <nl> - registry - > ProcessRegistrations ( ) ; <nl> + Status s = registry - > ProcessRegistrations ( ) ; <nl> + EXPECT_TRUE ( s . ok ( ) ) ; <nl> <nl> registry - > SetWatcher ( [ ] ( const Status & s , const OpDef & op_def ) - > Status { <nl> EXPECT_TRUE ( errors : : IsAlreadyExists ( s ) ) ; <nl> return Status : : OK ( ) ; <nl> } ) ; <nl> Register ( " Foo " , registry . get ( ) ) ; <nl> - registry - > ProcessRegistrations ( ) ; <nl> + s = registry - > ProcessRegistrations ( ) ; <nl> + EXPECT_TRUE ( s . ok ( ) ) ; <nl> } <nl> <nl> } / / namespace tensorflow <nl> mmm a / tensorflow / user_ops / BUILD <nl> ppp b / tensorflow / user_ops / BUILD <nl> py_tests ( <nl> data = [ " : duplicate_op . so " ] , <nl> ) <nl> <nl> + tf_custom_op_library ( <nl> + name = " invalid_op . so " , <nl> + srcs = [ " invalid_op . cc " ] , <nl> + ) <nl> + <nl> + py_tests ( <nl> + name = " invalid_op_test " , <nl> + size = " small " , <nl> + srcs = [ " invalid_op_test . py " ] , <nl> + data = [ " : invalid_op . so " ] , <nl> + ) <nl> + <nl> filegroup ( <nl> name = " all_files " , <nl> srcs = glob ( <nl> new file mode 100644 <nl> index 0000000000000 . . 51431660f20d3 <nl> mmm / dev / null <nl> ppp b / tensorflow / user_ops / invalid_op . cc <nl> <nl> + / * Copyright 2016 The TensorFlow Authors . All Rights Reserved . <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . <nl> + = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> + <nl> + # include " tensorflow / core / framework / op . h " <nl> + # include " tensorflow / core / framework / op_kernel . h " <nl> + <nl> + namespace tensorflow { <nl> + <nl> + REGISTER_OP ( " Invalid " ) <nl> + . Attr ( " invalid attr : int32 " ) / / invalid since the name has a space . <nl> + . Doc ( R " doc ( <nl> + An op to test that invalid ops do not successfully generate invalid python code . <nl> + ) doc " ) ; <nl> + <nl> + } / / namespace tensorflow <nl> new file mode 100644 <nl> index 0000000000000 . . c90a00ce58bb4 <nl> mmm / dev / null <nl> ppp b / tensorflow / user_ops / invalid_op_test . py <nl> <nl> + # Copyright 2016 The TensorFlow Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> + " " " Tests for custom user ops . " " " <nl> + from __future__ import absolute_import <nl> + from __future__ import division <nl> + from __future__ import print_function <nl> + <nl> + import os . path <nl> + <nl> + import tensorflow as tf <nl> + <nl> + <nl> + class InvalidOpTest ( tf . test . TestCase ) : <nl> + <nl> + def testBasic ( self ) : <nl> + library_filename = os . path . join ( tf . resource_loader . get_data_files_path ( ) , <nl> + ' invalid_op . so ' ) <nl> + with self . assertRaises ( tf . errors . InvalidArgumentError ) : <nl> + tf . load_op_library ( library_filename ) <nl> + <nl> + <nl> + if __name__ = = ' __main__ ' : <nl> + tf . test . main ( ) <nl>
When an invalid op is registered , ensure that tf . load_op_library returns
tensorflow/tensorflow
e40bbecdfd1116468d162cf2ef8d4bb8f879c5e9
2016-07-11T19:35:07Z
mmm a / editor / plugins / canvas_item_editor_plugin . cpp <nl> ppp b / editor / plugins / canvas_item_editor_plugin . cpp <nl> void CanvasItemEditor : : _find_canvas_items_at_pos ( const Point2 & p_pos , Node * p_no <nl> <nl> if ( canvas_item & & canvas_item - > is_visible_in_tree ( ) ) { <nl> Transform2D xform = ( p_parent_xform * p_canvas_xform * canvas_item - > get_transform ( ) ) . affine_inverse ( ) ; <nl> - const real_t local_grab_distance = xform . basis_xform ( Vector2 ( grab_distance , 0 ) ) . length ( ) ; <nl> + const real_t local_grab_distance = xform . basis_xform ( Vector2 ( grab_distance , 0 ) ) . length ( ) / zoom ; <nl> if ( canvas_item - > _edit_is_selected_on_click ( xform . xform ( p_pos ) , local_grab_distance ) ) { <nl> Node2D * node = Object : : cast_to < Node2D > ( canvas_item ) ; <nl> <nl>
Merge pull request from groud / fix_2D_selection
godotengine/godot
6e65c73f71c2c28e0b186e632427cea399492f22
2019-01-24T22:38:30Z
mmm a / test / common_methods_invocations . py <nl> ppp b / test / common_methods_invocations . py <nl> def method_tests ( ) : <nl> ( ' index_select ' , ( ) , ( 0 , torch . tensor ( [ 0 ] , dtype = torch . int64 ) ) , ' scalar_mixed_dim ' , [ 0 ] ) , <nl> ( ' index_select ' , ( ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) ) , ' scalar_dim ' , [ 0 ] ) , <nl> ( ' index_add ' , ( S , S ) , ( 0 , index_variable ( 2 , S ) , ( 2 , S ) ) , ' dim ' , [ 0 ] ) , <nl> - ( ' index_add ' , ( ) , ( 0 , torch . tensor ( [ 0 ] , dtype = torch . int64 ) , torch . tensor ( [ 2 . ] ) ) , ' scalar_input_dim ' , [ 0 ] ) , <nl> - ( ' index_add ' , ( ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) , torch . tensor ( 2 . ) ) , ' scalar_all_dim ' , [ 0 ] ) , <nl> + ( ' index_add ' , ( ) , ( 0 , torch . tensor ( [ 0 ] , dtype = torch . int64 ) , ( 1 , ) ) , ' scalar_input_dim ' , [ 0 ] ) , <nl> + ( ' index_add ' , ( ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) , ( ) ) , ' scalar_all_dim ' , [ 0 ] ) , <nl> ( ' index_copy ' , ( S , S ) , ( 0 , index_perm_variable ( 2 , S ) , ( 2 , S ) ) , ' dim ' , [ 0 ] ) , <nl> - ( ' index_copy ' , ( ) , ( 0 , torch . tensor ( [ 0 ] , dtype = torch . int64 ) , torch . tensor ( [ 2 . ] ) ) , ' scalar_input_dim ' , [ 0 ] ) , <nl> - ( ' index_copy ' , ( ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) , torch . tensor ( 2 . ) ) , ' scalar_all_dim ' , [ 0 ] ) , <nl> + ( ' index_copy ' , ( ) , ( 0 , torch . tensor ( [ 0 ] , dtype = torch . int64 ) , ( 1 , ) ) , ' scalar_input_dim ' , [ 0 ] ) , <nl> + ( ' index_copy ' , ( ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) , ( ) ) , ' scalar_all_dim ' , [ 0 ] ) , <nl> ( ' index_fill ' , ( S , S ) , ( 0 , index_variable ( 2 , S ) , 2 ) , ' dim ' , [ 0 ] ) , <nl> - # FIXME : we should compute the derivative w . r . t torch . tensor ( 2 ) <nl> - ( ' index_fill ' , ( S , S ) , ( 0 , index_variable ( 2 , S ) , non_differentiable ( torch . tensor ( 2 ) ) ) , <nl> - ' variable_dim ' , [ 0 ] ) , <nl> + ( ' index_fill ' , ( S , S ) , ( 0 , index_variable ( 2 , S ) , ( ) ) , ' variable_dim ' , [ 0 ] ) , <nl> ( ' index_fill ' , ( S , S ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) , 2 ) , ' scalar_index_dim ' , [ 0 ] ) , <nl> ( ' index_fill ' , ( ) , ( 0 , torch . tensor ( [ 0 ] , dtype = torch . int64 ) , 2 ) , ' scalar_input_dim ' , [ 0 ] ) , <nl> ( ' index_fill ' , ( ) , ( 0 , torch . tensor ( 0 , dtype = torch . int64 ) , 2 ) , ' scalar_both_dim ' , [ 0 ] ) , <nl> def method_tests ( ) : <nl> ' batched_broadcast_b ' , NO_ARGS , [ skipIfNoLapack ] ) , <nl> ( ' fill_ ' , ( S , S , S ) , ( 1 , ) , ' number ' ) , <nl> ( ' fill_ ' , ( ) , ( 1 , ) , ' number_scalar ' ) , <nl> - # FIXME : we should compute the derivative w . r . t torch . tensor ( 1 ) <nl> - ( ' fill_ ' , ( S , S , S ) , ( non_differentiable ( torch . tensor ( 1 ) ) , ) , ' variable ' ) , <nl> + ( ' fill_ ' , ( S , S , S ) , ( ( ) , ) , ' variable ' ) , <nl> ( ' eq_ ' , ( S , S , S ) , ( ( S , S , S ) , ) ) , <nl> ( ' eq_ ' , ( S , S , S ) , ( ( 1 , ) , ) , ' broadcast_rhs ' ) , <nl> ( ' eq_ ' , ( ) , ( ( ) , ) , ' scalar ' ) , <nl>
Clean up autograd method tests
pytorch/pytorch
8c9df48fd433ee51d3305d2f500b962baa480aee
2019-02-10T21:49:12Z
mmm a / src / GUI . cpp <nl> ppp b / src / GUI . cpp <nl> void GUI : : readParamsOnSocket ( ) { <nl> processParams ( QString : : fromUtf8 ( params . data ( ) ) . split ( QString : : fromUtf8 ( " \ n " ) ) ) ; <nl> qDebug ( " Received parameters from another instance " ) ; <nl> } <nl> - delete clientConnection ; <nl> } <nl> } <nl> <nl>
- I thought there was a memory leak here but it crashes when I delete it so . .
qbittorrent/qBittorrent
366d5108c4d479f345f62f3325f5e048b8329174
2007-08-26T16:30:52Z
mmm a / buildscripts / clang_format . py <nl> ppp b / buildscripts / clang_format . py <nl> def __init__ ( self , path , cache_dir ) : <nl> CLANG_FORMAT_PROGNAME , <nl> ] ) ) <nl> <nl> - for ospath in os . environ [ " PATH " ] . split ( os . pathsep ) : <nl> + directories_to_check = os . environ [ " PATH " ] . split ( os . pathsep ) <nl> + <nl> + # If Windows , try to grab it from Program Files <nl> + # Check both native Program Files and WOW64 version <nl> + if sys . platform = = " win32 " : <nl> + programfiles = [ <nl> + os . environ [ " ProgramFiles " ] , <nl> + os . environ [ " ProgramFiles ( x86 ) " ] , <nl> + ] <nl> + <nl> + directories_to_check + = [ os . path . join ( p , " LLVM \ \ bin \ \ " ) for p in programfiles ] <nl> + <nl> + for ospath in directories_to_check : <nl> for program in programs : <nl> self . path = os . path . join ( ospath , program ) <nl> if os . path . exists ( self . path ) and self . _validate_version ( ) : <nl>
SERVER - 45594 clang_format . py should probe Program Files for clang - format . exe
mongodb/mongo
e5b1e4b391e3ff3f52f6db451874b23f2c3741e8
2020-01-16T21:37:46Z
mmm a / etc / evergreen . yml <nl> ppp b / etc / evergreen . yml <nl> buildvariants : <nl> - name : concurrency_replication_causal_consistency <nl> distros : <nl> - rhel62 - large <nl> - - name : concurrency_sharded_replication <nl> - - name : concurrency_sharded_replication_with_balancer <nl> - - name : concurrency_sharded_clusterwide_ops_add_remove_shards <nl> - name : concurrency_simultaneous <nl> - name : concurrency_simultaneous_replication <nl> distros : <nl> buildvariants : <nl> - name : replica_sets <nl> - name : . replica_sets . common <nl> - name : rollback_fuzzer_gen <nl> - - name : . sharding . common ! . multiversion ! . csrs <nl> - - name : . sharding . jscore ! . wo_snapshot ! . multi_stmt <nl> - name : . updatefuzzer <nl> <nl> - name : enterprise - rhel - 71 - ppc64le - inmem <nl>
SERVER - 45502 The FCV 4 . 4 migration protocol does not work on shards with storage engines that do not support document - level locking
mongodb/mongo
b5ca171828cf00dd7aab93360e2b7b30cf73f770
2020-01-15T18:18:36Z
mmm a / src / data - flow . cc <nl> ppp b / src / data - flow . cc <nl> Variable * AssignedVariablesAnalyzer : : FindSmiLoopVariable ( ForStatement * stmt ) { <nl> <nl> / / We only deal with local variables . <nl> Variable * loop_var = init - > target ( ) - > AsVariableProxy ( ) - > AsVariable ( ) ; <nl> - if ( ! loop_var - > IsStackAllocated ( ) ) return NULL ; <nl> + if ( loop_var = = NULL | | ! loop_var - > IsStackAllocated ( ) ) return NULL ; <nl> <nl> / / The initial value has to be a smi . <nl> Literal * init_lit = init - > value ( ) - > AsLiteral ( ) ; <nl>
Fix a bug in smi loop analysis .
v8/v8
463ab046fa7ca63e2ff150583d6d54c363ac179e
2010-03-11T10:37:29Z
mmm a / src / dbg / _scriptapi_misc . h <nl> ppp b / src / dbg / _scriptapi_misc . h <nl> namespace Script <nl> { <nl> namespace Misc <nl> { <nl> + / / / < summary > <nl> + / / / Evaluates an expression and returns the result . Analagous to using the Command field in x64dbg . <nl> + / / / <nl> + / / / Expressions can consist of memory locations , registers , flags , API names , labels , symbols , variables etc . <nl> + / / / <nl> + / / / Example : bool success = ParseExpression ( " [ esp + 8 ] " , & val ) <nl> + / / / < / summary > <nl> + / / / < param name = " expression " > The expression to evaluate . < / param > <nl> + / / / < param name = " value " > The result of the expression . < / param > <nl> + / / / < returns > True on success , False on failure . < / returns > <nl> SCRIPT_EXPORT bool ParseExpression ( const char * expression , duint * value ) ; <nl> + <nl> + / / / < summary > <nl> + / / / Returns the address of a function in the debuggee ' s memory space . <nl> + / / / <nl> + / / / Example : duint addr = RemoteGetProcAddress ( " kernel32 . dll " , " GetProcAddress " ) <nl> + / / / < / summary > <nl> + / / / < param name = " module " > The name of the module . < / param > <nl> + / / / < param name = " api " > The name of the function . < / param > <nl> + / / / < returns > The address of the function in the debuggee . < / returns > <nl> SCRIPT_EXPORT duint RemoteGetProcAddress ( const char * module , const char * api ) ; <nl> + <nl> + / / / < summary > <nl> + / / / Returns the address for a label created in the disassembly window . <nl> + / / / <nl> + / / / Example : duint addr = ResolveLabel ( " sneaky_crypto " ) <nl> + / / / < / summary > <nl> + / / / < param name = " label " > The name of the label to resolve . < / param > <nl> + / / / < returns > The memory address for the label . < / returns > <nl> SCRIPT_EXPORT duint ResolveLabel ( const char * label ) ; <nl> + <nl> + / / / < summary > <nl> + / / / Allocates the requested number of bytes from x64dbg ' s default process heap . <nl> + / / / <nl> + / / / Note : this allocation is in the debugger , not the debuggee . <nl> + / / / <nl> + / / / Memory allocated using this function should be Free ' d after use . <nl> + / / / <nl> + / / / Example : void * addr = Alloc ( 0x100000 ) <nl> + / / / < / summary > <nl> + / / / < param name = " size " > Number of bytes to allocate . < / param > <nl> + / / / < returns > A pointer to the newly allocated memory . < / returns > <nl> SCRIPT_EXPORT void * Alloc ( duint size ) ; <nl> + <nl> + / / / < summary > <nl> + / / / Frees memory previously allocated by Alloc . <nl> + / / / <nl> + / / / Example : Free ( addr ) <nl> + / / / < / summary > <nl> + / / / < param name = " ptr " > Pointer returned by Alloc . < / param > <nl> + / / / < returns > Nothing . < / returns > <nl> SCRIPT_EXPORT void Free ( void * ptr ) ; <nl> } ; / / Misc <nl> } ; / / Script <nl>
Tripleslash for scriptapi_misc functions
x64dbg/x64dbg
7627fce15c2f49e0e07b432c3ffc813d6bb21def
2017-09-11T13:00:30Z
mmm a / src / translations / sqlb_ru . ts <nl> ppp b / src / translations / sqlb_ru . ts <nl> If any of the other settings were altered for this database file you need to pro <nl> < context > <nl> < name > DBBrowserDB < / name > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 167 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 171 " / > <nl> < source > Please specify the database name under which you want to access the attached database < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 398 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 406 " / > <nl> < source > Do you want to save the changes made to the database file % 1 ? < / source > <nl> < translation > Сохранить сделанные изменения в файле базы данных % 1 ? < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 455 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 464 " / > <nl> < source > Exporting database to SQL file . . . < / source > <nl> < translation > Экспорт базы данных в файл SQL . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 456 " / > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 634 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 465 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 652 " / > <nl> < source > Cancel < / source > <nl> < translation > Отменить < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 633 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 651 " / > <nl> < source > Executing SQL . . . < / source > <nl> < translation > Выполнить код SQL . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 654 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 673 " / > <nl> < source > Action cancelled . < / source > <nl> < translation > Действие отменено . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 665 " / > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 673 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 692 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 700 " / > <nl> < source > Error in statement # % 1 : % 2 . <nl> Aborting execution . < / source > <nl> < translation > Ошибка в операторе # % 1 : % 2 . Прерывание выполнения . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 938 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 966 " / > <nl> < source > renameColumn : cannot find table % 1 . < / source > <nl> < translation > переименованиеСтолбца : невозможно найти таблицу % 1 . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 949 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 977 " / > <nl> < source > renameColumn : cannot find column % 1 . < / source > <nl> < translation > переименованиеСтолбца : невозможно найти столбец % 1 . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 957 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 985 " / > <nl> < source > renameColumn : creating savepoint failed . DB says : % 1 < / source > <nl> < translation > переименованиеСтолбца : ошибка создания точки сохранения . БД говорит : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 997 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1030 " / > <nl> < source > renameColumn : creating new table failed . DB says : % 1 < / source > <nl> < translation > переименованиеСтолбца : ошибка создания новой таблицы . БД говорит : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1007 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1040 " / > <nl> < source > renameColumn : copying data to new table failed . DB says : <nl> % 1 < / source > <nl> < translation > переименованиеСтолбца : ошибка копирования данных в новую таблицу . БД говорит : <nl> % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1030 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1063 " / > <nl> < source > renameColumn : deleting old table failed . DB says : % 1 < / source > <nl> < translation > переименованиеСтолбца : ошибка удаления старой таблицы . БД говорит : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1050 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1083 " / > <nl> < source > Restoring some of the objects associated with this table failed . This is most likely because some column names changed . Here & apos ; s the SQL statement which you might want to fix and execute manually : <nl> <nl> < / source > <nl> < translation > Ошибка восстановления некоторых объектов , ассоциированных с этой таблицей . Наиболее вероятная причина этого - изменение имён некоторых столбцов таблицы . Вот SQL оператор , который нужно исправить и выполнить вручную : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1059 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1092 " / > <nl> < source > renameColumn : releasing savepoint failed . DB says : % 1 < / source > <nl> < translation > переименованиеСтолбца : ошибока освобождения точки сохранения . БД говорит : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1074 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1107 " / > <nl> < source > Error renaming table & apos ; % 1 & apos ; to & apos ; % 2 & apos ; . Message from database engine : <nl> % 3 < / source > <nl> < translation > Ошибка переименования программы & apos ; % 1 & apos ; в & apos ; % 2 & apos ; . Сообщение от движка БД : <nl> % 3 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1121 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1153 " / > <nl> < source > . . . & lt ; string can not be logged , contains binary data & gt ; . . . < / source > <nl> < translation > . . . & lt ; строка не может быть залогирована , содержит двоичные данные & gt ; . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1161 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1193 " / > <nl> < source > unknown object type % 1 < / source > <nl> < translation > неизвестный тип объекта % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1165 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1197 " / > <nl> < source > could not get list of db objects : % 1 , % 2 < / source > <nl> < translation > невозможно получить список объекто БД : % 1 , % 2 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1195 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1227 " / > <nl> < source > could not get types < / source > <nl> < translation > невозможно получить типы < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1218 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1252 " / > <nl> < source > didn & apos ; t receive any output from pragma % 1 < / source > <nl> < translation > не принято ни одного выхода из прагмы % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1222 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1256 " / > <nl> < source > could not execute pragma command : % 1 , % 2 < / source > <nl> < translation > невозможно выполнить комманду - прагму : % 1 , % 2 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1237 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1271 " / > <nl> < source > Error setting pragma % 1 to % 2 : % 3 < / source > <nl> < translation > Ошибка установки прагмы % 1 в % 2 : % 3 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitedb . cpp " line = " 1276 " / > <nl> + < location filename = " . . / sqlitedb . cpp " line = " 1310 " / > <nl> < source > File not found . < / source > <nl> < translation > Файл не найден . < / translation > <nl> < / message > <nl> Aborting execution . < / source > <nl> < translation > Схема < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / DbStructureModel . cpp " line = " 143 " / > <nl> + < location filename = " . . / DbStructureModel . cpp " line = " 148 " / > <nl> + < source > Browsables ( % 1 ) < / source > <nl> + < translation > Просматриваемые ( % 1 ) < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / DbStructureModel . cpp " line = " 153 " / > <nl> + < source > All < / source > <nl> + < translation > Все < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / DbStructureModel . cpp " line = " 157 " / > <nl> < source > Tables ( % 1 ) < / source > <nl> < translation > Таблицы ( % 1 ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / DbStructureModel . cpp " line = " 147 " / > <nl> + < location filename = " . . / DbStructureModel . cpp " line = " 162 " / > <nl> < source > Indices ( % 1 ) < / source > <nl> < translation > Индексы ( % 1 ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / DbStructureModel . cpp " line = " 151 " / > <nl> + < location filename = " . . / DbStructureModel . cpp " line = " 167 " / > <nl> < source > Views ( % 1 ) < / source > <nl> < translation > Представления ( % 1 ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / DbStructureModel . cpp " line = " 155 " / > <nl> + < location filename = " . . / DbStructureModel . cpp " line = " 172 " / > <nl> < source > Triggers ( % 1 ) < / source > <nl> < translation > Триггеры ( % 1 ) < / translation > <nl> < / message > <nl> Aborting execution . < / source > <nl> < / message > <nl> < message > <nl> < location filename = " . . / EditDialog . ui " line = " 52 " / > <nl> - < location filename = " . . / EditDialog . cpp " line = " 290 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 269 " / > <nl> < source > Image < / source > <nl> < translation > Изображение < / translation > <nl> < / message > <nl> Aborting execution . < / source > <nl> < translation > Размер данных в таблице < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 260 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 239 " / > <nl> < source > Choose a file < / source > <nl> < translation > Выбрать файл < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 262 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 241 " / > <nl> < source > Text files ( * . txt ) ; ; Image files ( % 1 ) ; ; All files ( * ) < / source > <nl> < translation > Текстовые файлы ( * . txt ) ; ; Файлы изображений ( % 1 ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 297 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 276 " / > <nl> < source > Choose a filename to export data < / source > <nl> < translation > Выбрать имя файла для экспорта данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 292 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 271 " / > <nl> < source > Text files ( * . txt ) ; ; All files ( * ) < / source > <nl> < translation > Текстовые файлы ( * . txt ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 191 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 188 " / > <nl> < source > Image data can & apos ; t be viewed with the text editor < / source > <nl> < translation > Изображение не может быть отображено в текстовом редакторе < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 219 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 216 " / > <nl> < source > Binary data can & apos ; t be viewed with the text editor < / source > <nl> < translation > Бинарные данные не могут быть отображены в текстовом редакторе < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 460 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 483 " / > <nl> < source > Type of data currently in cell : % 1 Image < / source > <nl> < translation > Тип данных в ячейке : % 1 Изображение < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 466 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 489 " / > <nl> < source > % 1x % 2 pixel ( s ) < / source > <nl> < translation > % 1x % 2 пикселей < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 480 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 503 " / > <nl> < source > Type of data currently in cell : NULL < / source > <nl> < translation > Тип данных в ячейке : NULL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 486 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 406 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 509 " / > <nl> < source > Type of data currently in cell : Text / Numeric < / source > <nl> < translation > Тип данных в ячейке : Текст / Числовое < / translation > <nl> < / message > <nl> < message numerus = " yes " > <nl> - < location filename = " . . / EditDialog . cpp " line = " 487 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 407 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 510 " / > <nl> < source > % n char ( s ) < / source > <nl> < translation > <nl> < numerusform > % n символ < / numerusform > <nl> Aborting execution . < / source > <nl> < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditDialog . cpp " line = " 492 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 515 " / > <nl> < source > Type of data currently in cell : Binary < / source > <nl> < translation > Тип данных в ячейке : Двоичные данные < / translation > <nl> < / message > <nl> < message numerus = " yes " > <nl> - < location filename = " . . / EditDialog . cpp " line = " 481 " / > <nl> - < location filename = " . . / EditDialog . cpp " line = " 493 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 504 " / > <nl> + < location filename = " . . / EditDialog . cpp " line = " 516 " / > <nl> < source > % n byte ( s ) < / source > <nl> < translation > <nl> < numerusform > % n байт < / numerusform > <nl> Aborting execution . < / source > <nl> < translation > Внешний ключ < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 138 " / > <nl> + < location filename = " . . / EditTableDialog . ui " line = " 294 " / > <nl> + < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; span style = & quot ; font - weight : 600 ; color : # ff0000 ; & quot ; & gt ; Warning : & lt ; / span & gt ; There is something with this table definition that our parser doesn & apos ; t fully understand . Modifying and saving this table might result it in problems . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> + < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; span style = & quot ; font - weight : 600 ; color : # ff0000 ; & quot ; & gt ; Внимание : & lt ; / span & gt ; Определение данной таблицы наш парсер не смог понять . Eё модификация и сохранение может привести к последующим проблемам . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 146 " / > <nl> < source > Error creating table . Message from database engine : <nl> % 1 < / source > <nl> < translation > Ошибка создания таблицы . Сообщение от движка базы данных : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 222 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 229 " / > <nl> < source > There already is a field with that name . Please rename it first or choose a different name for this field . < / source > <nl> < translation > Поле с таким именем уже существует . Пожалуйста переименуйте его , либо выберите другое имя для данного поля . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 242 " / > <nl> < source > This column is referenced in a foreign key in table % 1 , column % 2 and thus its name cannot be changed . < / source > <nl> - < translation > На данную колонку ссылкается внешний ключ в таблице % 1 , поле % 2 поэтому ее имя не может быть изменено . < / translation > <nl> + < translation type = " obsolete " > На данную колонку ссылкается внешний ключ в таблице % 1 , поле % 2 поэтому ее имя не может быть изменено . < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 252 " / > <nl> + < source > This column is referenced in a foreign key in table % 1 and thus its name cannot be changed . < / source > <nl> + < translation > На данную колонку ссылкается внешний ключ в таблице % 1 , поэтому ее имя не может быть изменено . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 298 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 318 " / > <nl> < source > There is at least one row with this field set to NULL . This makes it impossible to set this flag . Please change the table data first . < / source > <nl> < translation > Существует по крайней мере одна строка , где это поле установлено в NULL . Установить этот флаг нельзя . Сначала измените данные таблицы . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 325 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 345 " / > <nl> < source > There is at least one row with a non - integer value in this field . This makes it impossible to set the AI flag . Please change the table data first . < / source > <nl> < translation > Существует по крайней мере одна строка , где это поле содержит нечисловое значение . Установить флаг АИ нельзя . Сначала измените данные таблицы . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 369 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 389 " / > <nl> < source > Column & apos ; % 1 & apos ; has no unique data . <nl> < / source > <nl> < translation > Столбец & apos ; % 1 & quot ; содержит не уникальные данные . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 370 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 390 " / > <nl> < source > This makes it impossible to set this flag . Please change the table data first . < / source > <nl> < translation > Невозможно . Для начала , измените данные таблицы . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 507 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 530 " / > <nl> < source > Are you sure you want to delete the field & apos ; % 1 & apos ; ? <nl> All data currently stored in this field will be lost . < / source > <nl> < translation > Удалить поле & apos ; % 1 & apos ; ? <nl> Все данные , которые в настоящий момент сохранены в этом поле , будут потеряны . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / EditTableDialog . cpp " line = " 620 " / > <nl> + < location filename = " . . / EditTableDialog . cpp " line = " 643 " / > <nl> < source > Please add a field which meets the following criteria before setting the without rowid flag : <nl> - Primary key flag set <nl> - Auto increment disabled < / source > <nl> All data currently stored in this field will be lost . < / source > <nl> < translation > Экспортировать данные в формате CSV < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 22 " / > <nl> < source > & amp ; Table ( s ) < / source > <nl> - < translation > & amp ; Таблицы < / translation > <nl> + < translation type = " obsolete " > & amp ; Таблицы < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 48 " / > <nl> < source > & amp ; Column names in first line < / source > <nl> - < translation > & amp ; Имена столбцов в первой строке < / translation > <nl> + < translation type = " obsolete " > & amp ; Имена столбцов в первой строке < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 68 " / > <nl> < source > Field & amp ; separator < / source > <nl> + < translation type = " obsolete " > & amp ; Разделитель полей < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 22 " / > <nl> + < source > Tab & amp ; le ( s ) < / source > <nl> + < translation > & amp ; Таблицы < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 57 " / > <nl> + < source > Colu & amp ; mn names in first line < / source > <nl> + < translation > & amp ; Имена столбцов в первой строке < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 77 " / > <nl> + < source > Fie & amp ; ld separator < / source > <nl> < translation > & amp ; Разделитель полей < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 93 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 102 " / > <nl> < source > , < / source > <nl> < translation > , < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 98 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 107 " / > <nl> < source > ; < / source > <nl> < translation > ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 103 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 112 " / > <nl> < source > Tab < / source > <nl> < translation > Табуляция < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 108 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 117 " / > <nl> < source > | < / source > <nl> < translation > | < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 113 " / > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 183 " / > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 245 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 122 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 192 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 254 " / > <nl> < source > Other < / source > <nl> < translation > Другой < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 143 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 152 " / > <nl> < source > & amp ; Quote character < / source > <nl> < translation > & amp ; Символ кавычки < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 168 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 177 " / > <nl> < source > & quot ; < / source > <nl> < translation > & quot ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 173 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 182 " / > <nl> < source > & apos ; < / source > <nl> < translation > & apos ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 213 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 222 " / > <nl> < source > New line characters < / source > <nl> < translation > Разделитель строк < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 235 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 244 " / > <nl> < source > Windows : CR + LF ( \ r \ n ) < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . ui " line = " 240 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 249 " / > <nl> < source > Unix : LF ( \ n ) < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 154 " / > <nl> + < location filename = " . . / ExportDataDialog . ui " line = " 288 " / > <nl> + < source > Pretty print < / source > <nl> + < translation > Красивый вывод < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 167 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 234 " / > <nl> < source > Could not open output file : % 1 < / source > <nl> < translation > Не удалось открыть выходной файл : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 168 " / > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 196 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 263 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 289 " / > <nl> < source > Choose a filename to export data < / source > <nl> < translation > Выберите имя файла для экспорта данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 169 " / > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 197 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 249 " / > <nl> < source > Text files ( * . csv * . txt ) < / source > <nl> < translation > Текстовые файлы ( * . csv * . txt ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 186 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 253 " / > <nl> + < source > Text files ( * . json * . js * . txt ) < / source > <nl> + < translation > Текстовые файлы ( * . json * . js * . txt ) < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 279 " / > <nl> < source > Please select at least 1 table . < / source > <nl> < translation > Пожалуйста , выберите хотя бы одну таблицу . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 212 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 303 " / > <nl> < source > Choose a directory < / source > <nl> < translation > Выберать каталог < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / ExportDataDialog . cpp " line = " 245 " / > <nl> + < location filename = " . . / ExportDataDialog . cpp " line = " 335 " / > <nl> < source > Export completed . < / source > <nl> < translation > Экспорт завершён . < / translation > <nl> < / message > <nl> All data currently stored in this field will be lost . < / source > <nl> < context > <nl> < name > ExtendedTableWidget < / name > <nl> < message > <nl> - < location filename = " . . / ExtendedTableWidget . cpp " line = " 135 " / > <nl> + < location filename = " . . / ExtendedTableWidget . cpp " line = " 234 " / > <nl> < source > The content of clipboard is bigger than the range selected . <nl> Do you want to insert it anyway ? < / source > <nl> < translation > Содержимое буфера обмена больше чем выбранный диапазон . <nl> Do you want to insert it anyway ? < / source > <nl> < / message > <nl> < message > <nl> < location filename = " . . / MainWindow . ui " line = " 35 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 788 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 791 " / > <nl> < source > toolBar1 < / source > <nl> < translation > панельИнструментов1 < / translation > <nl> < / message > <nl> Do you want to insert it anyway ? < / source > <nl> < / message > <nl> < message > <nl> < location filename = " . . / MainWindow . ui " line = " 125 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1640 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1702 " / > <nl> < source > F5 < / source > <nl> < translation > F5 < / translation > <nl> < / message > <nl> Do you want to insert it anyway ? < / source > <nl> < translation > Это представление базы данных . Сделайте двойной щелчок по любой записи , чтобы отредактировать её содержимое . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 214 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 217 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Scroll to the beginning & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Прокрутить к началу & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 217 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 220 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Clicking this button navigates to the beginning in the table view above . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Нажатие этой кнопки переводит к началу в таблице выше . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 220 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 223 " / > <nl> < source > | & lt ; < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 230 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 233 " / > <nl> < source > Scroll 100 records upwards < / source > <nl> < translation > Прокрутить на 100 записей вверх < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 233 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 236 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Clicking this button navigates 100 records upwards in the table view above . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Нажатие этой кнопки к перемещению на 100 записей вверх в табличном представлении выше & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 236 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 239 " / > <nl> < source > & lt ; < / source > <nl> < translation > & lt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 243 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 246 " / > <nl> < source > 0 - 0 of 0 < / source > <nl> < translation > 0 - 0 из 0 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 253 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 256 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Scroll 100 records downwards & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Прокрутить на 100 записей вниз & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 256 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 259 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Clicking this button navigates 100 records downwards in the table view above . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Нажатие этой кнопки к перемещению на 100 записей вниз в табличном представлении выше & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 259 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 262 " / > <nl> < source > & gt ; < / source > <nl> < translation > & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 269 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 272 " / > <nl> < source > Scroll to the end < / source > <nl> < translation > Прокрутить к концу < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 272 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 275 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & amp ; lt ; html & amp ; gt ; & amp ; lt ; head / & amp ; gt ; & amp ; lt ; body & amp ; gt ; & amp ; lt ; p & amp ; gt ; Clicking this button navigates up to the end in the table view above . & amp ; lt ; / p & amp ; gt ; & amp ; lt ; / body & amp ; gt ; & amp ; lt ; / html & amp ; gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & amp ; lt ; html & amp ; gt ; & amp ; lt ; head / & amp ; gt ; & amp ; lt ; body & amp ; gt ; & amp ; lt ; p & amp ; gt ; Нажатие этой кнопки перемещает в конец таблицы выше . & amp ; lt ; / p & amp ; gt ; & amp ; lt ; / body & amp ; gt ; & amp ; lt ; / html & amp ; gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 275 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 278 " / > <nl> < source > & gt ; | < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 295 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 298 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Click here to jump to the specified record & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Нажмите здесь , чтобы перейти к указанной записи & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 298 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 301 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; This button is used to navigate to the record number specified in the Go to area . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Эта кнопка используется , чтобы переместиться к записи , номер которой указан в области Перейти к & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 301 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 304 " / > <nl> < source > Go to : < / source > <nl> < translation > Перейти к : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 308 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 311 " / > <nl> < source > Enter record number to browse < / source > <nl> < translation > Введите номер записи для просмотра < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 311 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 314 " / > <nl> < source > Type a record number in this area and click the Go to : button to display the record in the database view < / source > <nl> < translation > Напечатайте номер записи в этой области и нажмите кнопку Перейти к : , чтобы отобразить запись в представлении базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 314 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 317 " / > <nl> < source > 1 < / source > <nl> < translation > 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 348 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 351 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_auto_vacuum & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Auto Vacuum & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_auto_vacuum & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Auto Vacuum & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 365 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1125 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1169 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 368 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1139 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1183 " / > <nl> < source > None < / source > <nl> < translation > Нет < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 370 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 687 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 373 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 690 " / > <nl> < source > Full < / source > <nl> < translatorcomment > Полный , целый < / translatorcomment > <nl> < translation > Full < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 375 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 378 " / > <nl> < source > Incremental < / source > <nl> < translation > Incremental < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 383 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 386 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_automatic_index & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Automatic Index & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_automatic_index & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Automatic Index & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 403 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 406 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_checkpoint_fullfsync & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Checkpoint Full FSYNC & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_checkpoint_fullfsync & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Checkpoint Full FSYNC & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 423 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 426 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_foreign_keys & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Foreign Keys & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_foreign_keys & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Foreign Keys & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 443 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 446 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_fullfsync & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Full FSYNC & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_fullfsync & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Full FSYNC & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 463 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 466 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_ignore_check_constraints & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Ignore Check Constraints & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_ignore_check_constraints & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Ignore Check Constraints & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 483 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 486 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_journal_mode & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Journal Mode & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_journal_mode & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Journal Mode & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 497 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 500 " / > <nl> < source > Delete < / source > <nl> < translation > Delete < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 502 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 505 " / > <nl> < source > Truncate < / source > <nl> < translation > Truncate < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 507 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 510 " / > <nl> < source > Persist < / source > <nl> < translation > Persist < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 512 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 719 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 515 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 722 " / > <nl> < source > Memory < / source > <nl> < translation > Memory < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 517 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 520 " / > <nl> < source > WAL < / source > <nl> < translation > WAL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 522 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 677 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 525 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 680 " / > <nl> < source > Off < / source > <nl> < translation > Off < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 530 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 533 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_journal_size_limit & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Journal Size Limit & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_journal_size_limit & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Journal Size Limit & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 553 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 556 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_locking_mode & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Locking Mode & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_locking_mode & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Locking Mode & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 567 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 682 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 570 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 685 " / > <nl> < source > Normal < / source > <nl> < translation > Normal < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 572 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 575 " / > <nl> < source > Exclusive < / source > <nl> < translation > Exclusive < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 580 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 583 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_max_page_count & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Max Page Count & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_max_page_count & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Max Page Count & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 600 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 603 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_page_size & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Page Size & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_page_size & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Page Size & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 623 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 626 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_recursive_triggers & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Recursive Triggers & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_recursive_triggers & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Recursive Triggers & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 643 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 646 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_secure_delete & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Secure Delete & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_secure_delete & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Secure Delete & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 663 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 666 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_synchronous & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Synchronous & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_synchronous & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Synchronous & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 695 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 698 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_temp_store & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Temp Store & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_temp_store & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; Temp Store & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 709 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 712 " / > <nl> < source > Default < / source > <nl> < translation > Default < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 714 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 717 " / > <nl> < source > File < / source > <nl> < translation > File < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 727 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 730 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_schema_version & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; User Version & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_schema_version & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; User Version & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 747 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 750 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_wal_autocheckpoint & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; WAL Auto Checkpoint & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; & lt ; a href = & quot ; http : / / www . sqlite . org / pragma . html # pragma_wal_autocheckpoint & quot ; & gt ; & lt ; span style = & quot ; text - decoration : underline ; color : # 0000ff ; & quot ; & gt ; WAL Auto Checkpoint & lt ; / span & gt ; & lt ; / a & gt ; & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 828 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 831 " / > <nl> < source > & amp ; File < / source > <nl> < translation > & amp ; Файл < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 832 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 835 " / > <nl> < source > & amp ; Import < / source > <nl> < translation > & amp ; Импорт < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 839 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 842 " / > <nl> < source > & amp ; Export < / source > <nl> < translation > & amp ; Экспорт < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 865 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 850 " / > <nl> + < source > Remote < / source > <nl> + < translation > Удаленный сервер < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 878 " / > <nl> < source > & amp ; Edit < / source > <nl> < translation > & amp ; Редактирование < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 875 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 888 " / > <nl> < source > & amp ; View < / source > <nl> < translation > & amp ; Вид < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 883 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 896 " / > <nl> < source > & amp ; Help < / source > <nl> < translation > & amp ; Справка < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 899 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 913 " / > <nl> < source > DB Toolbar < / source > <nl> < translation > Панель инструментов БД < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1670 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 932 " / > <nl> + < source > Edit Database & amp ; Cell < / source > <nl> + < translation > Редактирование & amp ; ячейки БД < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1319 " / > <nl> + < source > DB Sche & amp ; ma < / source > <nl> + < translation > Схе & amp ; ма БД < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1732 " / > <nl> < source > & amp ; Load extension < / source > <nl> < translation > Загрузить & amp ; расширение < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1732 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1747 " / > <nl> + < source > Execute current line [ Shift + F5 ] < / source > <nl> + < translation > Выполнить текущую строку [ Shift + F5 ] < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1750 " / > <nl> + < source > Shift + F5 < / source > <nl> + < translation > Shift + F5 < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1806 " / > <nl> < source > Sa & amp ; ve Project < / source > <nl> < translation > & amp ; Сохранить проект < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1747 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1824 " / > <nl> < source > Open & amp ; Project < / source > <nl> < translation > Открыть & amp ; проект < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1820 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1906 " / > <nl> < source > Edit display format < / source > <nl> < translation > Формат отображения < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1823 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1909 " / > <nl> < source > Edit the display format of the data in this column < / source > <nl> < translation > Редактирование формата отображения для данных из этой колонки < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1831 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1917 " / > <nl> < source > Show rowid column < / source > <nl> < translation > Отображать колонку rowid < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1834 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1920 " / > <nl> < source > Toggle the visibility of the rowid column < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1839 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2527 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1925 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2604 " / > <nl> < source > Set encoding < / source > <nl> < translation > Кодировка < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1842 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1928 " / > <nl> < source > Change the encoding of the text in the table cells < / source > <nl> < translation > Изменение кодировки текста в данной таблице < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1847 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1933 " / > <nl> < source > Set encoding for all tables < / source > <nl> < translation > Установить кодировку для всех таблиц < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1850 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1936 " / > <nl> < source > Change the default encoding assumed for all tables in the database < / source > <nl> < translation > Изменить кодировку по умолчанию для всех таблиц в базе данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1855 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1858 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1941 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1944 " / > <nl> < source > Duplicate record < / source > <nl> < translation > Дубликат записи < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1761 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1953 " / > <nl> + < source > SQLCipher & amp ; FAQ . . . < / source > <nl> + < translation > < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1956 " / > <nl> + < source > Opens the SQLCipher FAQ in a browser window < / source > <nl> + < translation > Открыть SQLCiphier FAQ в браузере < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1961 " / > <nl> + < source > Table ( s ) to JSON . . . < / source > <nl> + < translation > Таблицы в файл JSON . . . < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1964 " / > <nl> + < source > Export one or more table ( s ) to a JSON file < / source > <nl> + < translation > Экспортировать таблицы в JSON файл < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1972 " / > <nl> + < source > Open from Remote < / source > <nl> + < translation > Загрузить из облака < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1977 " / > <nl> + < source > Save to Remote < / source > <nl> + < translation > Сохранить в облако < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / MainWindow . ui " line = " 1841 " / > <nl> < source > & amp ; Attach Database < / source > <nl> < translation > & amp ; Прикрепить базу данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1779 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1782 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1865 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1868 " / > <nl> < source > Save SQL file as < / source > <nl> < translation > Сохранить файл SQL как < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1803 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1889 " / > <nl> < source > & amp ; Browse Table < / source > <nl> < translation > Пр & amp ; осмотр данных < / translation > <nl> < / message > <nl> Do you want to insert it anyway ? < / source > <nl> < translation > Очистить все фильтры < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 965 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 979 " / > <nl> < source > User < / source > <nl> < translation > Пользователем < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 970 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 984 " / > <nl> < source > Application < / source > <nl> < translation > Приложением < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 997 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1011 " / > <nl> < source > & amp ; Clear < / source > <nl> < translation > О & amp ; чистить < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1067 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1081 " / > <nl> < source > Columns < / source > <nl> < translation > Столбцы < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1072 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1086 " / > <nl> < source > X < / source > <nl> < translation > X < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1077 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1091 " / > <nl> < source > Y < / source > <nl> < translation > Y < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1082 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1096 " / > <nl> < source > _ < / source > <nl> < translation > _ < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1114 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1128 " / > <nl> < source > Line type : < / source > <nl> < translation > Линия : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1130 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1144 " / > <nl> < source > Line < / source > <nl> < translation > Обычная < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1135 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1149 " / > <nl> < source > StepLeft < / source > <nl> < translation > Ступенчатая , слева < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1140 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1154 " / > <nl> < source > StepRight < / source > <nl> < translation > Ступенчатая , справа < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1145 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1159 " / > <nl> < source > StepCenter < / source > <nl> < translation > Ступенчатая , по центру < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1150 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1164 " / > <nl> < source > Impulse < / source > <nl> < translation > Импульс < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1158 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1172 " / > <nl> < source > Point shape : < / source > <nl> < translation > Отрисовка точек : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1174 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1188 " / > <nl> < source > Cross < / source > <nl> < translation > Крест < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1179 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1193 " / > <nl> < source > Plus < / source > <nl> < translation > Плюс < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1184 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1198 " / > <nl> < source > Circle < / source > <nl> < translation > Круг < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1189 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1203 " / > <nl> < source > Disc < / source > <nl> < translation > Диск < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1194 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1208 " / > <nl> < source > Square < / source > <nl> < translation > Квадрат < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1199 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1213 " / > <nl> < source > Diamond < / source > <nl> < translation > Ромб < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1204 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1218 " / > <nl> < source > Star < / source > <nl> < translation > Звезда < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1209 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1223 " / > <nl> < source > Triangle < / source > <nl> < translation > Треугольник < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1214 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1228 " / > <nl> < source > TriangleInverted < / source > <nl> < translation > Треугольник перевернутый < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1219 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1233 " / > <nl> < source > CrossSquare < / source > <nl> < translation > Крест в квадрате < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1224 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1238 " / > <nl> < source > PlusSquare < / source > <nl> < translation > Плюс в квадрате < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1229 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1243 " / > <nl> < source > CrossCircle < / source > <nl> < translation > Крест в круге < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1234 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1248 " / > <nl> < source > PlusCircle < / source > <nl> < translation > Плюс в круге < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1239 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1253 " / > <nl> < source > Peace < / source > <nl> < translation > Мир < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1260 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1274 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Save current plot . . . & lt ; / p & gt ; & lt ; p & gt ; File format chosen by extension ( png , jpg , pdf , bmp ) & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Сохранить текущий график . . . & lt ; / p & gt ; & lt ; p & gt ; Формат файла выбирается расширением ( png , jpg , pdf , bmp ) & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1263 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1277 " / > <nl> < source > Save current plot . . . < / source > <nl> < translation > Сохранить текущий график . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1289 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1303 " / > <nl> < source > Load all data . This has only an effect if not all data has been fetched from the table yet due to the partial fetch mechanism . < / source > <nl> < translation > Загружать все данные . Имеет эффект лишь если не все данные подгружены . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1305 " / > <nl> < source > DB Schema < / source > <nl> - < translation > Схема БД < / translation > <nl> + < translation type = " obsolete " > Схема БД < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1334 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1348 " / > <nl> < source > & amp ; New Database . . . < / source > <nl> < translation > & amp ; Новая база данных . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1337 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1340 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1351 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1354 " / > <nl> < source > Create a new database file < / source > <nl> < translation > Создать новый файл базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1343 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1357 " / > <nl> < source > This option is used to create a new database file . < / source > <nl> < translation > Эта опция используется , чтобы создать новый файл базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1346 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1360 " / > <nl> < source > Ctrl + N < / source > <nl> < translation > Ctrl + N < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1355 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1372 " / > <nl> < source > & amp ; Open Database . . . < / source > <nl> < translation > & amp ; Открыть базу данных . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1358 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1361 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1375 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1378 " / > <nl> < source > Open an existing database file < / source > <nl> < translation > Открыть существующий файл базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1364 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1381 " / > <nl> < source > This option is used to open an existing database file . < / source > <nl> < translation > Эта опция используется , чтобы открыть существующий файл базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1367 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1384 " / > <nl> < source > Ctrl + O < / source > <nl> < translation > Ctrl + O < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1375 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1395 " / > <nl> < source > & amp ; Close Database < / source > <nl> < translation > & amp ; Закрыть базу данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1378 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1398 " / > <nl> < source > Ctrl + W < / source > <nl> < translation > Ctrl + W < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1393 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1416 " / > <nl> < source > Revert database to last saved state < / source > <nl> < translation > Вернуть базу данных в последнее сохранённое состояние < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1396 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1419 " / > <nl> < source > This option is used to revert the current database file to its last saved state . All changes made since the last save operation are lost . < / source > <nl> < translation > Эта опция используется , чтобы вернуть текущий файл базы данных в его последнее сохранённое состояние . Все изменения , сделаные с последней операции сохранения теряются . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1411 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1437 " / > <nl> < source > Write changes to the database file < / source > <nl> < translation > Записать изменения в файл базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1414 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1440 " / > <nl> < source > This option is used to save changes to the database file . < / source > <nl> < translation > Эта опция используется , чтобы сохранить изменения в файле базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1417 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1443 " / > <nl> < source > Ctrl + S < / source > <nl> < translation > Ctrl + S < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1428 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1457 " / > <nl> < source > Compact the database file , removing space wasted by deleted records < / source > <nl> < translation > Уплотнить базу данных , удаляя пространство , занимаемое удалёнными записями < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1431 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1434 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1460 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1463 " / > <nl> < source > Compact the database file , removing space wasted by deleted records . < / source > <nl> < translation > Уплотнить базу данных , удаляя пространство , занимаемое удалёнными записями . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1439 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1471 " / > <nl> < source > E & amp ; xit < / source > <nl> < translation > & amp ; Выход < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1442 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1474 " / > <nl> < source > Ctrl + Q < / source > <nl> < translation > Ctrl + Q < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1453 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1485 " / > <nl> < source > Import data from an . sql dump text file into a new or existing database . < / source > <nl> < translation > Импортировать данные из текстового файла sql в новую или существующую базу данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1456 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1488 " / > <nl> < source > This option lets you import data from an . sql dump text file into a new or existing database . SQL dump files can be created on most database engines , including MySQL and PostgreSQL . < / source > <nl> < translation > Эта опция позволяет импортировать данные из текстового файла sql в новую или существующую базу данных . Файл SQL может быть создан на большинстве движков баз данных , включая MySQL и PostgreSQL . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1464 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1499 " / > <nl> < source > Open a wizard that lets you import data from a comma separated text file into a database table . < / source > <nl> < translation > Открыть мастер , который позволяет импортировать данные из файла CSV в таблицу базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1467 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1502 " / > <nl> < source > Open a wizard that lets you import data from a comma separated text file into a database table . CSV files can be created on most database and spreadsheet applications . < / source > <nl> < translation > Открыть мастер , который позволяет импортировать данные из файла CSV в таблицу базы данных . Файлы CSV могут быть созданы в большинстве приложений баз данных и электронных таблиц . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1475 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1513 " / > <nl> < source > Export a database to a . sql dump text file . < / source > <nl> < translation > Экспортировать базу данных в текстовый файл . sql . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1478 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1516 " / > <nl> < source > This option lets you export a database to a . sql dump text file . SQL dump files contain all data necessary to recreate the database on most database engines , including MySQL and PostgreSQL . < / source > <nl> < translation > Эта опция позволяет экспортировать базу данных в текстовый файл . sql . Файлы SQL содержат все данные , необходимые для создания базы данных в большистве движков баз данных , включая MySQL и PostgreSQL . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1486 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1527 " / > <nl> < source > Export a database table as a comma separated text file . < / source > <nl> < translation > Экспортировать таблицу базы данных как CSV текстовый файл . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1489 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1530 " / > <nl> < source > Export a database table as a comma separated text file , ready to be imported into other database or spreadsheet applications . < / source > <nl> < translation > Экспортировать таблицу базы данных как CSV текстовый файл , готовый для импортирования в другие базы данных или приложения электронных таблиц . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1504 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1548 " / > <nl> < source > Open the Create Table wizard , where it is possible to define the name and fields for a new table in the database < / source > <nl> < translation > Открыть мастер создания таблиц , где возможно определить имя и поля для новой таблиы в базе данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1522 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1569 " / > <nl> < source > Open the Delete Table wizard , where you can select a database table to be dropped . < / source > <nl> < translation > Открыть мастер удаления таблицы , где можно выбрать таблицу базы данных для удаления . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1537 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1587 " / > <nl> < source > Open the Modify Table wizard , where it is possible to rename an existing table . It is also possible to add or delete fields form a table , as well as modify field names and types . < / source > <nl> < translation > Открыть мастер изменения таблицы , где возможно переименовать существующую таблиц . Можно добавить или удалить поля таблицы , так же изменять имена полей и типы . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1552 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1605 " / > <nl> < source > Open the Create Index wizard , where it is possible to define a new index on an existing database table . < / source > <nl> < translation > Открыть мастер создания интекса , в котором можно определить новый индекс для существующей таблиц базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1561 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1617 " / > <nl> < source > & amp ; Preferences . . . < / source > <nl> < translation > & amp ; Настройки . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1564 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1567 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1620 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1623 " / > <nl> < source > Open the preferences window . < / source > <nl> < translation > Открыть окно настроек . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1582 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1638 " / > <nl> < source > & amp ; DB Toolbar < / source > <nl> < translation > & amp ; Панель инструментов БД < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1585 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1641 " / > <nl> < source > Shows or hides the Database toolbar . < / source > <nl> < translation > Показать или скрыть панель инструментов База данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1600 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1659 " / > <nl> < source > Shift + F1 < / source > <nl> < translation > Shift + F1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1605 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1667 " / > <nl> < source > & amp ; About . . . < / source > <nl> < translation > О & amp ; программе . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1613 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1675 " / > <nl> < source > & amp ; Recently opened < / source > <nl> < translation > & amp ; Недавно открываемые < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1622 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1684 " / > <nl> < source > Open & amp ; tab < / source > <nl> < translation > Открыть & amp ; вкладку < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1588 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1625 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1644 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1687 " / > <nl> < source > Ctrl + T < / source > <nl> < translation > Ctrl + T < / translation > <nl> < / message > <nl> Do you want to insert it anyway ? < / source > <nl> < translation > Данные < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 324 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 327 " / > <nl> < source > Edit Pragmas < / source > <nl> < translation > Прагмы < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 782 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 785 " / > <nl> < source > Execute SQL < / source > <nl> < translation > SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 918 " / > <nl> < source > Edit Database Cell < / source > <nl> - < translation > Редактирование ячейки БД < / translation > <nl> + < translation type = " obsolete " > Редактирование ячейки БД < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 930 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 944 " / > <nl> < source > SQL & amp ; Log < / source > <nl> < translation > & amp ; Журнал SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 948 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 962 " / > <nl> < source > Show S & amp ; QL submitted by < / source > <nl> < translation > По & amp ; казывать SQL , выполненный < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1040 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1054 " / > <nl> < source > & amp ; Plot < / source > <nl> < translation > & amp ; График < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1390 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1413 " / > <nl> < source > & amp ; Revert Changes < / source > <nl> < translation > & amp ; Отменить изменения < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1408 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1434 " / > <nl> < source > & amp ; Write Changes < / source > <nl> < translation > & amp ; Записать изменения < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1425 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1454 " / > <nl> < source > Compact & amp ; Database < / source > <nl> < translation > & amp ; Уплотнить базу данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1450 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1482 " / > <nl> < source > & amp ; Database from SQL file . . . < / source > <nl> < translation > & amp ; База данных из файла SQL . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1461 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1496 " / > <nl> < source > & amp ; Table from CSV file . . . < / source > <nl> < translation > & amp ; Таблицы из файла CSV . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1472 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1510 " / > <nl> < source > & amp ; Database to SQL file . . . < / source > <nl> < translation > Базу & amp ; данных в файл SQL . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1483 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1524 " / > <nl> < source > & amp ; Table ( s ) as CSV file . . . < / source > <nl> < translation > & amp ; Таблицы в файл CSV . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1501 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1545 " / > <nl> < source > & amp ; Create Table . . . < / source > <nl> < translation > & amp ; Создать таблицу . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1516 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1563 " / > <nl> < source > & amp ; Delete Table . . . < / source > <nl> < translation > & amp ; Удалить таблицу . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1534 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1584 " / > <nl> < source > & amp ; Modify Table . . . < / source > <nl> < translation > & amp ; Изменить таблицу . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1549 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1602 " / > <nl> < source > Create & amp ; Index . . . < / source > <nl> < translation > Создать и & amp ; ндекс . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1597 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1656 " / > <nl> < source > W & amp ; hat & apos ; s This ? < / source > <nl> < translation > Что & amp ; это такое ? < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1634 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1696 " / > <nl> < source > & amp ; Execute SQL < / source > <nl> < translation > В & amp ; ыполнить код SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1637 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1699 " / > <nl> < source > Execute SQL [ F5 , Ctrl + Return ] < / source > <nl> < translation > Выполнить код SQL [ F5 , Ctrl + Return ] < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1649 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1711 " / > <nl> < source > Open SQL file < / source > <nl> < translation > Открыть файл SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1658 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1791 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1794 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1720 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1877 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1880 " / > <nl> < source > Save SQL file < / source > <nl> < translation > Сохранить файл SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1679 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1744 " / > <nl> < source > Execute current line < / source > <nl> < translation > Выполнить текущую строку < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1682 " / > <nl> < source > Execute current line [ Ctrl + E ] < / source > <nl> - < translation > Выполнить текущую строку [ Ctrl + E ] < / translation > <nl> + < translation type = " obsolete " > Выполнить текущую строку [ Ctrl + E ] < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1685 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 178 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 185 " / > <nl> < source > Ctrl + E < / source > <nl> < translation > Ctrl + E < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1693 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1758 " / > <nl> < source > Export as CSV file < / source > <nl> < translation > Экспортировать в файл CSV < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1696 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1761 " / > <nl> < source > Export table as comma separated values file < / source > <nl> < translation > Экспортировать таблицу как CSV файл < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1705 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1770 " / > <nl> < source > & amp ; Wiki . . . < / source > <nl> < translation > В & amp ; ики . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1714 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1782 " / > <nl> < source > Bug & amp ; report . . . < / source > <nl> < translation > & amp ; Отчёт об ошибке . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1723 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1794 " / > <nl> < source > Web & amp ; site . . . < / source > <nl> < translation > & amp ; Веб - сайт . . . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1735 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1738 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1809 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1812 " / > <nl> < source > Save the current session to a file < / source > <nl> < translation > Сохранить текущее состояние в файл < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1750 " / > <nl> - < location filename = " . . / MainWindow . ui " line = " 1753 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1827 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1830 " / > <nl> < source > Load a working session from a file < / source > <nl> < translation > Загрузить рабочее состояние из файла < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1770 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1853 " / > <nl> < source > & amp ; Set Encryption < / source > <nl> < translation > Ши & amp ; фрование < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1812 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1898 " / > <nl> < source > Copy Create statement < / source > <nl> < translation > Копировать CREATE выражение < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1815 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1901 " / > <nl> < source > Copy the CREATE statement of the item to the clipboard < / source > <nl> < translation > Копировать CREATE выражение элемента в буффер обмена < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 113 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 120 " / > <nl> < source > Ctrl + Return < / source > <nl> < translation > Ctrl + Return < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 157 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 164 " / > <nl> < source > Ctrl + L < / source > <nl> < translation > Ctrl + L < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 164 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 171 " / > <nl> < source > Ctrl + P < / source > <nl> < translation > Ctrl + P < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 164 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 171 " / > <nl> < source > Ctrl + D < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 170 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 177 " / > <nl> < source > Ctrl + I < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 184 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 196 " / > <nl> < source > Encrypted < / source > <nl> < translation > Зашифровано < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 191 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 203 " / > <nl> < source > Read only < / source > <nl> < translation > Только для чтения < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 192 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 204 " / > <nl> < source > Database file is read only . Editing the database is disabled . < / source > <nl> < translation > База данных только для чтения . Редактирование запрещено . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 198 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 210 " / > <nl> < source > Database encoding < / source > <nl> < translation > Кодировка базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 185 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 197 " / > <nl> < source > Database is encrypted using SQLCipher < / source > <nl> < translation > База данных зашифрована с использованием SQLCipher < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 258 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2273 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 270 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2350 " / > <nl> < source > Choose a database file < / source > <nl> < translation > Выбрать файл базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 305 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1145 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1980 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2190 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 317 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1170 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2042 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2267 " / > <nl> < source > Choose a filename to save under < / source > <nl> < translation > Выбрать имя , под которым сохранить данные < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 582 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 567 " / > <nl> < source > Error adding record : <nl> < / source > <nl> < translation > Ошибка добавления записи : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 599 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 584 " / > <nl> < source > Error deleting record : <nl> % 1 < / source > <nl> < translation > Ошибка удаления записи : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 608 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 593 " / > <nl> < source > Please select a record first < / source > <nl> < translation > Сначала выберите запись < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 705 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 689 " / > <nl> < source > % 1 - % 2 of % 3 < / source > <nl> < translation > % 1 - % 2 из % 3 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 717 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 732 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 701 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 715 " / > <nl> < source > There is no database opened . Please open or create a new database file . < / source > <nl> < translation > Нет открытой базы данных . Откройте или создайте файл новой базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 761 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 736 " / > <nl> < source > Are you sure you want to delete the % 1 & apos ; % 2 & apos ; ? <nl> All data associated with the % 1 will be lost . < / source > <nl> < translation > Хотите удалить % 1 & apos ; % 2 & apos ; ? <nl> Все данные , связанные с % 1 , будут потеряны . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 768 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 743 " / > <nl> < source > Error : could not delete the % 1 . Message from database engine : <nl> % 2 < / source > <nl> < translation > Ошибка : невозмножно удалить % 1 . Сообщение из движка базы данных : % 2 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 781 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 755 " / > <nl> < source > There is no database opened . < / source > <nl> < translation > Нет открытой базы данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1689 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1751 " / > <nl> < source > A new DB Browser for SQLite version is available ( % 1 . % 2 . % 3 ) . & lt ; br / & gt ; & lt ; br / & gt ; Please download at & lt ; a href = & apos ; % 4 & apos ; & gt ; % 4 & lt ; / a & gt ; . < / source > <nl> < translation > Вышла новая версия Обозревателя для SQLite ( % 1 . % 2 . % 3 ) . & lt ; br / & gt ; & lt ; br / & gt ; Она доступна для скачивания по адресу & lt ; a href = & apos ; % 4 & apos ; & gt ; % 4 & lt ; / a & gt ; . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2051 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2191 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2128 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2268 " / > <nl> < source > DB Browser for SQLite project file ( * . sqbpro ) < / source > <nl> < translation > Файл проекта Обозревателя для SQLite ( * . sqbpro ) < / translation > <nl> < / message > <nl> All data associated with the % 1 will be lost . < / source > <nl> < translation > Ошибка выполнения запроса : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 967 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 963 " / > <nl> < source > % 1 rows returned in % 2ms from : % 3 < / source > <nl> < translation > % 1 строки возвращены за % 2мс из : % 3 < / translation > <nl> < / message > <nl> All data associated with the % 1 will be lost . < / source > <nl> < translation > Запрос успешно выполнен : % 1 ( заняло % 2мс % 3 ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1054 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1064 " / > <nl> < source > Choose a text file < / source > <nl> < translation > Выбрать текстовый файл < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1055 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1065 " / > <nl> < source > Text files ( * . csv * . txt ) ; ; All files ( * ) < / source > <nl> < translation > Текстовые файлы ( * . csv * . txt ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1064 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1073 " / > <nl> < source > Import completed < / source > <nl> < translation > Импорт завершён < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1103 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1129 " / > <nl> < source > Are you sure you want to undo all changes made to the database file & apos ; % 1 & apos ; since the last save ? < / source > <nl> < translation > Отменить все изменения , сделанные в файле базы данных & apos ; % 1 & apos ; после последнего сохранения ? < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1128 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1153 " / > <nl> < source > Choose a file to import < / source > <nl> < translation > Выберать файл для импорта < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1129 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1509 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1555 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1154 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1567 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1613 " / > <nl> < source > Text files ( * . sql * . txt ) ; ; All files ( * ) < / source > <nl> < translation > Текстовые файлы ( * . sql * . txt ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1139 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1164 " / > <nl> < source > Do you want to create a new database file to hold the imported data ? <nl> If you answer no we will attempt to import the data in the SQL file to the current database . < / source > <nl> < translation > Создать новый файл базы данных , чтобы сохранить импортированные данные ? <nl> Если ответить Нет , будет выполнена попытка импортировать данные файла SQL в текущую базу данных . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1149 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1174 " / > <nl> < source > File % 1 already exists . Please choose a different name . < / source > <nl> < translation > Файл % 1 уже существует . Выберите другое имя . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1164 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1189 " / > <nl> < source > Error importing data : % 1 < / source > <nl> < translation > Ошибка импортирования данных : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1166 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1191 " / > <nl> < source > Import completed . < / source > <nl> < translation > Импорт завершён . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1220 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1245 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1246 " / > <nl> < source > Delete View < / source > <nl> < translation > Удалить представление < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1222 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1248 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1249 " / > <nl> < source > Delete Trigger < / source > <nl> < translation > Удалить триггер < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1224 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1251 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1252 " / > <nl> < source > Delete Index < / source > <nl> < translation > Удалить индекс < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2523 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2600 " / > <nl> < source > Please choose a new encoding for this table . < / source > <nl> < translation > Пожалуйста выбирите новую кодировку для данной таблицы . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2525 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2602 " / > <nl> < source > Please choose a new encoding for all tables . < / source > <nl> < translation > Пожалуйста выбирите новую кодировку для всех таблиц . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2528 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2605 " / > <nl> < source > % 1 <nl> Leave the field empty for using the database encoding . < / source > <nl> < translation > % 1 <nl> Оставьте это поле пустым если хотите чтобы использовалась кодировка по умолчанию . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2539 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2616 " / > <nl> < source > This encoding is either not valid or not supported . < / source > <nl> < translation > Неверная кодировка либо она не поддерживается . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . ui " line = " 1519 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1226 " / > <nl> + < location filename = " . . / MainWindow . ui " line = " 1566 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1254 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1255 " / > <nl> < source > Delete Table < / source > <nl> < translation > Удалить таблицу < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1272 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1302 " / > <nl> < source > & amp ; % 1 % 2 < / source > <nl> < translation > & amp ; % 1 % 2 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1437 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1495 " / > <nl> < source > Setting PRAGMA values will commit your current transaction . <nl> Are you sure ? < / source > <nl> < translation > Установка значений PRAGMA завершит текущую транзакцию . Установить значения ? < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1508 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1566 " / > <nl> < source > Select SQL file to open < / source > <nl> < translation > Выбрать файл SQL для октрытия < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1554 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1612 " / > <nl> < source > Select file name < / source > <nl> < translation > Выбрать имя файла < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1569 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1627 " / > <nl> < source > Select extension file < / source > <nl> < translation > Выбрать расширение файла < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1570 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1628 " / > <nl> < source > Extensions ( * . so * . dll ) ; ; All files ( * ) < / source > <nl> < translation > Расширения ( * . so * . dll ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1576 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1634 " / > <nl> < source > Extension successfully loaded . < / source > <nl> < translation > Расширение успешно загружено . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1578 " / > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1590 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1636 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1648 " / > <nl> < source > Error loading extension : % 1 < / source > <nl> < translation > Ошибка загрузки расширения : % 1 < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1685 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1747 " / > <nl> < source > Don & apos ; t show again < / source > <nl> < translation > Не показывать снова < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1688 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 1750 " / > <nl> < source > New version available . < / source > <nl> < translation > Доступна новая версия . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1959 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2021 " / > <nl> < source > Choose a axis color < / source > <nl> < translation > Выбрать цвет осей < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 1981 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2043 " / > <nl> < source > PNG ( * . png ) ; ; JPG ( * . jpg ) ; ; PDF ( * . pdf ) ; ; BMP ( * . bmp ) ; ; All Files ( * ) < / source > <nl> < translation > PNG ( * . png ) ; ; JPG ( * . jpg ) ; ; PDF ( * . pdf ) ; ; BMP ( * . bmp ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 2050 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 2127 " / > <nl> < source > Choose a file to open < / source > <nl> < translation > Выбрать файл для открытия < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / MainWindow . cpp " line = " 293 " / > <nl> + < location filename = " . . / MainWindow . cpp " line = " 305 " / > <nl> < source > Invalid file format . < / source > <nl> < translation > Ошибочный формат файла . < / translation > <nl> < / message > <nl> Are you sure ? < / source > <nl> < translation > Настройки < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 146 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 206 " / > <nl> < source > & amp ; Database < / source > <nl> < translation > & amp ; База данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 161 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 221 " / > <nl> < source > Database & amp ; encoding < / source > <nl> < translation > & amp ; Кодировка базы данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 185 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 245 " / > <nl> < source > Open databases with foreign keys enabled . < / source > <nl> < translation > Открывать базы данных с включенными внешними ключами . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 188 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 248 " / > <nl> < source > & amp ; Foreign keys < / source > <nl> < translation > & amp ; Внешние ключи < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 138 " / > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 198 " / > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 838 " / > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 858 " / > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 875 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 132 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 163 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 258 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 930 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 950 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 967 " / > <nl> < source > enabled < / source > <nl> < translation > включены < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 86 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 42 " / > <nl> < source > Default & amp ; location < / source > <nl> < translation > & amp ; Расположение <nl> по умолчанию < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 75 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 94 " / > <nl> < source > . . . < / source > <nl> < translation > . . . < / translation > <nl> < / message > <nl> Are you sure ? < / source > <nl> < translation > & amp ; Общие < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 36 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 55 " / > <nl> < source > Remember last location < / source > <nl> < translation > Запоминать последнюю директорию < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 41 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 60 " / > <nl> < source > Always use this location < / source > <nl> < translation > Всегда открывать указанную < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 46 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 65 " / > <nl> < source > Remember last location for session only < / source > <nl> < translation > Запоминать последнюю директорию только для сессий < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 96 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 105 " / > <nl> < source > Lan & amp ; guage < / source > <nl> < translation > & amp ; Язык < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 128 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 122 " / > <nl> < source > Automatic & amp ; updates < / source > <nl> < translation > & amp ; Следить за обновлениями < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 302 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 362 " / > <nl> < source > Data & amp ; Browser < / source > <nl> < translation > Обозреватель & amp ; данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 345 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 437 " / > <nl> < source > NULL fields < / source > <nl> < translation > NULL поля < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 364 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 456 " / > <nl> < source > & amp ; Text < / source > <nl> < translation > & amp ; Текст < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 205 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 265 " / > <nl> < source > Remove line breaks in schema & amp ; view < / source > <nl> < translation > Удалить переводы строки в & amp ; схеме данных < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 218 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 115 " / > <nl> + < source > Show remote options < / source > <nl> + < translation > Опции & quot ; облака & quot ; < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 186 " / > <nl> + < source > Remote server < / source > <nl> + < translation > Сервер < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 194 " / > <nl> + < source > dbhub . io < / source > <nl> + < translation > < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 278 " / > <nl> < source > Prefetch block si & amp ; ze < / source > <nl> < translation > Размер блока & amp ; упреждающей выборки < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 238 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 298 " / > <nl> < source > Advanced < / source > <nl> < translation > Дополнительно < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 268 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 328 " / > <nl> < source > SQL to execute after opening database < / source > <nl> < translation > SQL , который нужно выполнить после открытия БД < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 294 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 354 " / > <nl> < source > Default field type < / source > <nl> < translation > Тип данных по умолчанию < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 310 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 370 " / > <nl> < source > Font < / source > <nl> < translation > Шрифт < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 316 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 376 " / > <nl> < source > & amp ; Font < / source > <nl> < translation > & amp ; Шрифт < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 329 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 389 " / > <nl> < source > Font si & amp ; ze : < / source > <nl> < translation > Ра & amp ; змер шрифта : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 380 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 405 " / > <nl> + < source > Content < / source > <nl> + < translation > Содержимое < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 411 " / > <nl> + < source > Symbol limit in cell < / source > <nl> + < translation > Количество символов в ячейке < / translation > <nl> + < / message > <nl> + < message > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 472 " / > <nl> < source > Field colors < / source > <nl> < translation > Цветовое оформление полей < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 386 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 478 " / > <nl> < source > NULL < / source > <nl> < translation > < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 396 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 488 " / > <nl> < source > Regular < / source > <nl> < translation > Обычные < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 429 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 521 " / > <nl> < source > Text < / source > <nl> < translation > Текст < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 439 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 531 " / > <nl> < source > Binary < / source > <nl> < translation > Двоичные данные < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 465 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 557 " / > <nl> < source > Background < / source > <nl> < translation > Фон < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 542 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 634 " / > <nl> < source > Filters < / source > <nl> < translation > Фильтры < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 555 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 647 " / > <nl> < source > Escape character < / source > <nl> < translation > Символ экранирования < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 565 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 657 " / > <nl> < source > Delay time ( & amp ; ms ) < / source > <nl> < translation > Время задержки ( & amp ; мс ) < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 575 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 667 " / > <nl> < source > Set the waiting time before a new filter value is applied . Can be set to 0 for disabling waiting . < / source > <nl> < translation > Время задержки перед применением нового фильтра . Нулевое значение отключает ожидание . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 591 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 683 " / > <nl> < source > & amp ; SQL < / source > <nl> < translation > Р & amp ; едактор SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 604 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 696 " / > <nl> < source > Settings name < / source > <nl> < translation > Имя настроек < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 609 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 701 " / > <nl> < source > Context < / source > <nl> < translation > Контекст < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 614 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 706 " / > <nl> < source > Colour < / source > <nl> < translation > Цвет < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 619 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 711 " / > <nl> < source > Bold < / source > <nl> < translation > Жирный < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 624 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 716 " / > <nl> < source > Italic < / source > <nl> < translation > Курсив < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 629 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 721 " / > <nl> < source > Underline < / source > <nl> < translation > Подчёркивание < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 637 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 729 " / > <nl> < source > Keyword < / source > <nl> < translation > Ключевое слово < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 654 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 746 " / > <nl> < source > function < / source > <nl> < translation > функция < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 657 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 749 " / > <nl> < source > Function < / source > <nl> < translation > Функция < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 665 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 757 " / > <nl> < source > Table < / source > <nl> < translation > Таблица < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 685 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 777 " / > <nl> < source > Comment < / source > <nl> < translation > Комментарий < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 705 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 797 " / > <nl> < source > Identifier < / source > <nl> < translation > Идентификатор < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 725 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 817 " / > <nl> < source > String < / source > <nl> < translation > Строка < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 742 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 834 " / > <nl> < source > currentline < / source > <nl> < translation > текущаястрока < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 745 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 837 " / > <nl> < source > Current line < / source > <nl> < translation > Текущая строка < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 755 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 847 " / > <nl> < source > SQL & amp ; editor font size < / source > <nl> < translation > Размер шрифта в & amp ; редакторе SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 772 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 864 " / > <nl> < source > SQL & amp ; log font size < / source > <nl> < translation > Размер шрифта в & amp ; журнале SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 789 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 881 " / > <nl> < source > Tab size < / source > <nl> < translation > Размер табуляции < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 812 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 904 " / > <nl> < source > SQL editor & amp ; font < / source > <nl> < translation > & amp ; Шрифт в редакторе SQL < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 825 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 917 " / > <nl> < source > Error indicators < / source > <nl> < translation > Индикаторы ошибок < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 835 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 927 " / > <nl> < source > Enabling error indicators highlights the SQL code lines that caused errors during the last execution < / source > <nl> < translation > Подсветка в SQL коде строк , выполнение которых привело к ошибкам < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 845 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 937 " / > <nl> < source > Hori & amp ; zontal tiling < / source > <nl> < translation > Гори & amp ; зонтальное распределение < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 855 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 947 " / > <nl> < source > If enabled the SQL code editor and the result table view are shown side by side instead of one over the other . < / source > <nl> < translation > Если данная опция включена , то SQL редактор и результат запроса будут расположены рядом по горизонтали . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 865 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 957 " / > <nl> < source > Code co & amp ; mpletion < / source > <nl> < translation > Авто & amp ; дополнение кода < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 885 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 977 " / > <nl> < source > & amp ; Extensions < / source > <nl> < translation > Р & amp ; асширения < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 891 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 983 " / > <nl> < source > Select extensions to load for every database : < / source > <nl> < translation > Выберите расширения , чтобы загружать их для каждой базы данных : < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 912 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 1004 " / > <nl> < source > Add extension < / source > <nl> < translation > Добавить расширение < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 923 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 1015 " / > <nl> < source > Remove extension < / source > <nl> < translation > Удалить расширение < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 951 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 1043 " / > <nl> < source > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; While supporting the REGEXP operator SQLite doesn & apos ; t implement any regular expression & lt ; br / & gt ; algorithm but calls back the running application . DB Browser for SQLite implements this & lt ; br / & gt ; algorithm for you to let you use REGEXP out of the box . However , as there are multiple possible & lt ; br / & gt ; implementations of this and you might want to use another one , you & apos ; re free to disable the & lt ; br / & gt ; application & apos ; s implementation and load your own by using an extension . Requires restart of the application . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / source > <nl> < translation > & lt ; html & gt ; & lt ; head / & gt ; & lt ; body & gt ; & lt ; p & gt ; Обозреватель для SQLite позволяет использовать оператор REGEXP & apos ; из коробки & apos ; . Но тем & lt ; br / & gt ; не менее , возможны несколько различных вариантов реализаций данного оператора и вы свободны & lt ; br / & gt ; в выборе какую именно использовать . Можно отключить нашу реализацию и использовать другую - & lt ; br / & gt ; путем загрузки соответсвующего расширения . В этом случае требуется перезагрузка приложения . & lt ; / p & gt ; & lt ; / body & gt ; & lt ; / html & gt ; < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . ui " line = " 954 " / > <nl> + < location filename = " . . / PreferencesDialog . ui " line = " 1046 " / > <nl> < source > Disable Regular Expression extension < / source > <nl> < translation > Отключить расширение Регулярных Выражений < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . cpp " line = " 50 " / > <nl> + < location filename = " . . / PreferencesDialog . cpp " line = " 49 " / > <nl> < source > Choose a directory < / source > <nl> < translation > Выберать каталог < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . cpp " line = " 169 " / > <nl> + < location filename = " . . / PreferencesDialog . cpp " line = " 183 " / > <nl> < source > The language will change after you restart the application . < / source > <nl> < translation > Язык будет применен после перезапуска приложения . < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . cpp " line = " 453 " / > <nl> + < location filename = " . . / PreferencesDialog . cpp " line = " 248 " / > <nl> < source > Select extension file < / source > <nl> < translation > Выберать файл расширения < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / PreferencesDialog . cpp " line = " 454 " / > <nl> + < location filename = " . . / PreferencesDialog . cpp " line = " 249 " / > <nl> < source > Extensions ( * . so * . dll ) ; ; All files ( * ) < / source > <nl> < translation > Расширения ( * . so * . dll ) ; ; Все файлы ( * ) < / translation > <nl> < / message > <nl> Create a backup ! < / source > <nl> < context > <nl> < name > SqliteTableModel < / name > <nl> < message > <nl> - < location filename = " . . / sqlitetablemodel . cpp " line = " 249 " / > <nl> + < location filename = " . . / sqlitetablemodel . cpp " line = " 260 " / > <nl> < source > References % 1 ( % 2 ) <nl> Hold Ctrl + Shift and click to jump there < / source > <nl> < translation > Ссылается на % 1 ( % 2 ) <nl> Нажмите Ctrl + Shift и клик чтобы переместиться туда < / translation > <nl> < / message > <nl> < message > <nl> - < location filename = " . . / sqlitetablemodel . cpp " line = " 299 " / > <nl> + < location filename = " . . / sqlitetablemodel . cpp " line = " 313 " / > <nl> < source > Error changing data : <nl> % 1 < / source > <nl> < translation > Ошибка изменения данных : <nl>
UPDATE Russian translation ( )
sqlitebrowser/sqlitebrowser
d1f93d96f98354f8f16bdef1c53bc680e3ef096b
2016-10-01T21:14:33Z
mmm a / arangod / CMakeLists . txt <nl> ppp b / arangod / CMakeLists . txt <nl> SET ( ARANGOD_SOURCES <nl> MMFiles / MMFilesCompactorThread . cpp <nl> MMFiles / MMFilesDatafile . cpp <nl> MMFiles / MMFilesDatafileStatistics . cpp <nl> + MMFiles / MMFilesDitch . cpp <nl> MMFiles / MMFilesDocumentOperation . cpp <nl> MMFiles / MMFilesEdgeIndex . cpp <nl> MMFiles / MMFilesEngine . cpp <nl> SET ( ARANGOD_SOURCES <nl> V8Server / v8 - vocindex . cpp <nl> VocBase / AuthInfo . cpp <nl> VocBase / DatafileStatisticsContainer . cpp <nl> - VocBase / Ditch . cpp <nl> VocBase / EdgeCollectionInfo . cpp <nl> VocBase / Graphs . cpp <nl> VocBase / KeyGenerator . cpp <nl> mmm a / arangod / MMFiles / MMFilesCleanupThread . cpp <nl> ppp b / arangod / MMFiles / MMFilesCleanupThread . cpp <nl> <nl> # include " Basics / files . h " <nl> # include " Logger / Logger . h " <nl> # include " MMFiles / MMFilesCollection . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " StorageEngine / EngineSelectorFeature . h " <nl> # include " StorageEngine / StorageEngine . h " <nl> # include " Utils / CursorRepository . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " MMFiles / MMFilesLogfileManager . h " <nl> <nl> void MMFilesCleanupThread : : cleanupCollection ( arangodb : : LogicalCollection * collec <nl> / / loop until done <nl> <nl> while ( true ) { <nl> - auto mmfiles = toMMFilesCollection ( collection ) ; <nl> + auto mmfiles = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) ; <nl> auto ditches = mmfiles - > ditches ( ) ; <nl> <nl> TRI_ASSERT ( ditches ! = nullptr ) ; <nl> mmm a / arangod / MMFiles / MMFilesCollection . h <nl> ppp b / arangod / MMFiles / MMFilesCollection . h <nl> <nl> # include " Basics / ReadWriteLock . h " <nl> # include " Indexes / IndexLookupContext . h " <nl> # include " MMFiles / MMFilesDatafileStatistics . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " MMFiles / MMFilesRevisionsCache . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / KeyGenerator . h " <nl> # include " VocBase / ManagedDocumentResult . h " <nl> # include " VocBase / PhysicalCollection . h " <nl> class MMFilesPrimaryIndex ; <nl> class MMFilesWalMarker ; <nl> <nl> class MMFilesCollection final : public PhysicalCollection { <nl> - friend class MMFilesCompactorThread ; <nl> - friend class MMFilesEngine ; <nl> + friend class MMFilesCompactorThread ; <nl> + friend class MMFilesEngine ; <nl> <nl> public : <nl> + static inline MMFilesCollection * toMMFilesCollection ( <nl> + PhysicalCollection * physical ) { <nl> + auto rv = static_cast < MMFilesCollection * > ( physical ) ; <nl> + TRI_ASSERT ( rv ! = nullptr ) ; <nl> + return rv ; <nl> + } <nl> + <nl> + static inline MMFilesCollection * toMMFilesCollection ( <nl> + LogicalCollection * logical ) { <nl> + auto phys = logical - > getPhysical ( ) ; <nl> + TRI_ASSERT ( phys ! = nullptr ) ; <nl> + return toMMFilesCollection ( phys ) ; <nl> + } <nl> + <nl> / / / @ brief state during opening of a collection <nl> struct OpenIteratorState { <nl> LogicalCollection * _collection ; <nl> class MMFilesCollection final : public PhysicalCollection { <nl> <nl> std : : unique_ptr < IndexIterator > getAllIterator ( transaction : : Methods * trx , ManagedDocumentResult * mdr , bool reverse ) override ; <nl> std : : unique_ptr < IndexIterator > getAnyIterator ( transaction : : Methods * trx , ManagedDocumentResult * mdr ) override ; <nl> - void invokeOnAllElements ( std : : function < bool ( DocumentIdentifierToken const & ) > callback ) ; <nl> + void invokeOnAllElements ( std : : function < bool ( DocumentIdentifierToken const & ) > callback ) override ; <nl> <nl> / / / @ brief Restores an index from VelocyPack . <nl> int restoreIndex ( transaction : : Methods * , velocypack : : Slice const & , <nl> class MMFilesCollection final : public PhysicalCollection { <nl> TRI_voc_tick_t _maxTick ; <nl> } ; <nl> <nl> - inline MMFilesCollection * toMMFilesCollection ( PhysicalCollection * physical ) { <nl> - auto rv = dynamic_cast < MMFilesCollection * > ( physical ) ; <nl> - TRI_ASSERT ( rv ! = nullptr ) ; <nl> - return rv ; <nl> - } <nl> - <nl> - inline MMFilesCollection * toMMFilesCollection ( LogicalCollection * logical ) { <nl> - auto phys = logical - > getPhysical ( ) ; <nl> - TRI_ASSERT ( phys ) ; <nl> - return toMMFilesCollection ( phys ) ; <nl> - } <nl> - <nl> } <nl> <nl> # endif <nl> mmm a / arangod / MMFiles / MMFilesCollectorCache . h <nl> ppp b / arangod / MMFiles / MMFilesCollectorCache . h <nl> <nl> # define ARANGOD_MMFILES_COLLECTOR_CACHE_H 1 <nl> <nl> # include " Basics / Common . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " VocBase / DatafileStatisticsContainer . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / voc - types . h " <nl> <nl> struct MMFilesDatafile ; <nl> mmm a / arangod / MMFiles / MMFilesCollectorThread . h <nl> ppp b / arangod / MMFiles / MMFilesCollectorThread . h <nl> <nl> # include " Basics / Thread . h " <nl> # include " MMFiles / MMFilesCollectorCache . h " <nl> # include " MMFiles / MMFilesDatafile . h " <nl> - # include " VocBase / Ditch . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " VocBase / voc - types . h " <nl> <nl> namespace arangodb { <nl> mmm a / arangod / MMFiles / MMFilesCompactionLocker . h <nl> ppp b / arangod / MMFiles / MMFilesCompactionLocker . h <nl> <nl> / / / @ author Jan Steemann <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - # ifndef ARANGOD_VOCBASE_COMPACTION_LOCKER_H <nl> - # define ARANGOD_VOCBASE_COMPACTION_LOCKER_H 1 <nl> + # ifndef ARANGOD_MMFILES_MMFILES_COMPACTION_LOCKER_H <nl> + # define ARANGOD_MMFILES_MMFILES_COMPACTION_LOCKER_H 1 <nl> <nl> # include " Basics / Common . h " <nl> # include " MMFiles / MMFilesCollection . h " <nl> mmm a / arangod / MMFiles / MMFilesCompactorThread . cpp <nl> ppp b / arangod / MMFiles / MMFilesCompactorThread . cpp <nl> void MMFilesCompactorThread : : compactDatafiles ( LogicalCollection * collection , <nl> removeDatafile ( collection , compaction . _datafile ) ; <nl> <nl> / / add a deletion ditch to the collection <nl> - auto b = toMMFilesCollection ( collection ) - > ditches ( ) - > createDropDatafileDitch ( <nl> - compaction . _datafile , collection , DropDatafileCallback , __FILE__ , <nl> - __LINE__ ) ; <nl> - <nl> + auto b = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > createDropDatafileDitch ( compaction . _datafile , collection , <nl> + DropDatafileCallback , __FILE__ , <nl> + __LINE__ ) ; <nl> + <nl> if ( b = = nullptr ) { <nl> LOG_TOPIC ( ERR , Logger : : COMPACTOR ) < < " out of memory when creating datafile - drop ditch " ; <nl> } <nl> void MMFilesCompactorThread : : compactDatafiles ( LogicalCollection * collection , <nl> <nl> if ( i = = 0 ) { <nl> / / add a rename marker <nl> - auto b = toMMFilesCollection ( collection ) - > ditches ( ) - > createRenameDatafileDitch ( <nl> - compaction . _datafile , context - > _compactor , context - > _collection , RenameDatafileCallback , __FILE__ , <nl> - __LINE__ ) ; <nl> + auto b = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > createRenameDatafileDitch ( <nl> + compaction . _datafile , context - > _compactor , <nl> + context - > _collection , RenameDatafileCallback , __FILE__ , <nl> + __LINE__ ) ; <nl> <nl> if ( b = = nullptr ) { <nl> LOG_TOPIC ( ERR , Logger : : COMPACTOR ) < < " out of memory when creating datafile - rename ditch " ; <nl> void MMFilesCompactorThread : : compactDatafiles ( LogicalCollection * collection , <nl> removeDatafile ( collection , compaction . _datafile ) ; <nl> <nl> / / add a drop datafile marker <nl> - auto b = toMMFilesCollection ( collection ) - > ditches ( ) - > createDropDatafileDitch ( <nl> - compaction . _datafile , collection , DropDatafileCallback , __FILE__ , <nl> - __LINE__ ) ; <nl> + auto b = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > createDropDatafileDitch ( compaction . _datafile , collection , <nl> + DropDatafileCallback , __FILE__ , <nl> + __LINE__ ) ; <nl> <nl> if ( b = = nullptr ) { <nl> LOG_TOPIC ( ERR , Logger : : COMPACTOR ) < < " out of memory when creating datafile - drop ditch " ; <nl> void MMFilesCompactorThread : : run ( ) { <nl> try { <nl> double const now = TRI_microtime ( ) ; <nl> if ( physical - > lastCompactionStamp ( ) + compactionCollectionInterval ( ) < = now ) { <nl> - auto ce = toMMFilesCollection ( collection ) - > ditches ( ) - > createCompactionDitch ( __FILE__ , <nl> - __LINE__ ) ; <nl> + auto ce = arangodb : : MMFilesCollection : : toMMFilesCollection ( <nl> + collection ) <nl> + - > ditches ( ) <nl> + - > createCompactionDitch ( __FILE__ , __LINE__ ) ; <nl> <nl> if ( ce = = nullptr ) { <nl> / / out of memory <nl> void MMFilesCompactorThread : : run ( ) { <nl> / / in case an error occurs , we must still free this ditch <nl> } <nl> <nl> - toMMFilesCollection ( collection ) - > ditches ( ) - > freeDitch ( ce ) ; <nl> + arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > freeDitch ( ce ) ; <nl> } <nl> } <nl> } catch ( . . . ) { <nl> similarity index 99 % <nl> rename from arangod / VocBase / Ditch . cpp <nl> rename to arangod / MMFiles / MMFilesDitch . cpp <nl> mmm a / arangod / VocBase / Ditch . cpp <nl> ppp b / arangod / MMFiles / MMFilesDitch . cpp <nl> <nl> / / / @ author Dr . Frank Celler <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - # include " Ditch . h " <nl> + # include " MMFilesDitch . h " <nl> # include " Basics / MutexLocker . h " <nl> # include " Logger / Logger . h " <nl> # include " MMFiles / MMFilesDatafile . h " <nl> similarity index 99 % <nl> rename from arangod / VocBase / Ditch . h <nl> rename to arangod / MMFiles / MMFilesDitch . h <nl> mmm a / arangod / VocBase / Ditch . h <nl> ppp b / arangod / MMFiles / MMFilesDitch . h <nl> <nl> / / / @ author Dr . Frank Celler <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - # ifndef ARANGOD_VOC_BASE_DITCH_H <nl> - # define ARANGOD_VOC_BASE_DITCH_H 1 <nl> + # ifndef ARANGOD_MMFILES_MMFILES_DITCH_H <nl> + # define ARANGOD_MMFILES_MMFILES_DITCH_H 1 <nl> <nl> # include " Basics / Common . h " <nl> # include " Basics / Mutex . h " <nl> mmm a / arangod / MMFiles / MMFilesEngine . cpp <nl> ppp b / arangod / MMFiles / MMFilesEngine . cpp <nl> char * MMFilesEngine : : nextFreeMarkerPosition ( <nl> <nl> / / we only need the ditches when we are outside the recovery <nl> / / the compactor will not run during recovery <nl> - auto ditch = <nl> - toMMFilesCollection ( collection ) - > ditches ( ) - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> + auto ditch = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> <nl> if ( ditch = = nullptr ) { <nl> THROW_ARANGO_EXCEPTION ( TRI_ERROR_OUT_OF_MEMORY ) ; <nl> mmm a / arangod / Replication / InitialSyncer . cpp <nl> ppp b / arangod / Replication / InitialSyncer . cpp <nl> <nl> # include " StorageEngine / StorageEngine . h " <nl> # include " Utils / CollectionGuard . h " <nl> # include " MMFiles / MMFilesCollection . h " / / TODO - - Remove - - ditches <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " MMFiles / MMFilesDatafileHelper . h " <nl> # include " MMFiles / MMFilesIndexElement . h " <nl> # include " MMFiles / MMFilesPrimaryIndex . h " <nl> # include " Utils / OperationOptions . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / ManagedDocumentResult . h " <nl> # include " VocBase / PhysicalCollection . h " <nl> int InitialSyncer : : handleSyncKeys ( arangodb : : LogicalCollection * col , <nl> errorMsg = std : : string ( " unable to start transaction : " ) + TRI_errno_string ( res ) ; <nl> return res ; <nl> } <nl> - <nl> - ditch = toMMFilesCollection ( col ) - > ditches ( ) - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> + <nl> + ditch = arangodb : : MMFilesCollection : : toMMFilesCollection ( col ) <nl> + - > ditches ( ) <nl> + - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> <nl> if ( ditch = = nullptr ) { <nl> return TRI_ERROR_OUT_OF_MEMORY ; <nl> int InitialSyncer : : handleSyncKeys ( arangodb : : LogicalCollection * col , <nl> <nl> TRI_ASSERT ( ditch ! = nullptr ) ; <nl> <nl> - TRI_DEFER ( toMMFilesCollection ( col ) - > ditches ( ) - > freeDitch ( ditch ) ) ; <nl> + TRI_DEFER ( arangodb : : MMFilesCollection : : toMMFilesCollection ( col ) <nl> + - > ditches ( ) <nl> + - > freeDitch ( ditch ) ) ; <nl> <nl> { <nl> SingleCollectionTransaction trx ( StandaloneTransactionContext : : Create ( _vocbase ) , col - > cid ( ) , AccessMode : : Type : : READ ) ; <nl> mmm a / arangod / Transaction / Methods . cpp <nl> ppp b / arangod / Transaction / Methods . cpp <nl> <nl> # include " Cluster / ServerState . h " <nl> # include " Indexes / Index . h " <nl> # include " Logger / Logger . h " <nl> - # include " MMFiles / MMFilesCollection . h " / / TODO - - remove - - ditches <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " MMFiles / MMFilesLogfileManager . h " / / TODO - - remove - - waitForTick <nl> # include " StorageEngine / EngineSelectorFeature . h " <nl> # include " StorageEngine / StorageEngine . h " <nl> <nl> # include " Utils / OperationOptions . h " <nl> # include " Utils / SingleCollectionTransaction . h " <nl> # include " Utils / TransactionContext . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / ManagedDocumentResult . h " <nl> # include " VocBase / ticks . h " <nl> mmm a / arangod / Utils / CollectionExport . cpp <nl> ppp b / arangod / Utils / CollectionExport . cpp <nl> <nl> <nl> # include " CollectionExport . h " <nl> # include " Basics / WriteLocker . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " StorageEngine / EngineSelectorFeature . h " <nl> # include " StorageEngine / StorageEngine . h " <nl> # include " Utils / CollectionGuard . h " <nl> # include " Utils / SingleCollectionTransaction . h " <nl> # include " Utils / StandaloneTransactionContext . h " <nl> # include " Transaction / Hints . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / PhysicalCollection . h " <nl> # include " VocBase / vocbase . h " <nl> void CollectionExport : : run ( uint64_t maxWaitTime , size_t limit ) { <nl> / / try to acquire the exclusive lock on the compaction <nl> engine - > preventCompaction ( _collection - > vocbase ( ) , [ this ] ( TRI_vocbase_t * vocbase ) { <nl> / / create a ditch under the compaction lock <nl> - _ditch = toMMFilesCollection ( _collection ) - > ditches ( ) - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> + _ditch = arangodb : : MMFilesCollection : : toMMFilesCollection ( _collection ) <nl> + - > ditches ( ) <nl> + - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> } ) ; <nl> <nl> / / now we either have a ditch or not <nl> mmm a / arangod / Utils / CollectionKeys . cpp <nl> ppp b / arangod / Utils / CollectionKeys . cpp <nl> <nl> # include " Basics / StaticStrings . h " <nl> # include " Basics / StringRef . h " <nl> # include " MMFiles / MMFilesLogfileManager . h " / / TODO - - REMOVE <nl> - # include " MMFiles / MMFilesCollection . h " / / TODO - - REMOVE <nl> + # include " MMFiles / MMFilesCollection . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " StorageEngine / EngineSelectorFeature . h " <nl> # include " StorageEngine / StorageEngine . h " <nl> # include " Transaction / Helpers . h " <nl> # include " Utils / CollectionGuard . h " <nl> # include " Utils / SingleCollectionTransaction . h " <nl> # include " Utils / StandaloneTransactionContext . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / ticks . h " <nl> # include " VocBase / vocbase . h " <nl> void CollectionKeys : : create ( TRI_voc_tick_t maxTick ) { <nl> StorageEngine * engine = EngineSelectorFeature : : ENGINE ; <nl> engine - > preventCompaction ( _collection - > vocbase ( ) , [ this ] ( TRI_vocbase_t * vocbase ) { <nl> / / create a ditch under the compaction lock <nl> - _ditch = toMMFilesCollection ( _collection ) - > ditches ( ) - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> + _ditch = arangodb : : MMFilesCollection : : toMMFilesCollection ( _collection ) <nl> + - > ditches ( ) <nl> + - > createDocumentDitch ( false , __FILE__ , __LINE__ ) ; <nl> } ) ; <nl> <nl> / / now we either have a ditch or not <nl> mmm a / arangod / Utils / SingleCollectionTransaction . cpp <nl> ppp b / arangod / Utils / SingleCollectionTransaction . cpp <nl> <nl> # include " Utils / OperationResult . h " <nl> # include " Transaction / Methods . h " <nl> # include " Utils / TransactionContext . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> <nl> using namespace arangodb ; <nl> mmm a / arangod / Utils / TransactionContext . cpp <nl> ppp b / arangod / Utils / TransactionContext . cpp <nl> <nl> <nl> # include " Basics / MutexLocker . h " <nl> # include " Basics / StringBuffer . h " <nl> - # include " MMFiles / MMFilesCollection . h " / / Used to create Ditches <nl> + # include " MMFiles / MMFilesCollection . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " RestServer / TransactionManagerFeature . h " <nl> # include " Transaction / Helpers . h " <nl> # include " Transaction / Methods . h " <nl> # include " TransactionContext . h " <nl> # include " Utils / CollectionNameResolver . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / ManagedDocumentResult . h " <nl> # include " VocBase / TransactionManager . h " <nl> DocumentDitch * TransactionContext : : orderDitch ( LogicalCollection * collection ) { <nl> } <nl> <nl> / / this method will not throw , but may return a nullptr <nl> - auto ditch = toMMFilesCollection ( collection ) - > ditches ( ) - > createDocumentDitch ( true , __FILE__ , __LINE__ ) ; <nl> + auto ditch = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) - > ditches ( ) - > createDocumentDitch ( true , __FILE__ , __LINE__ ) ; <nl> <nl> if ( ditch ! = nullptr ) { <nl> try { <nl> mmm a / arangod / VocBase / replication - dump . cpp <nl> ppp b / arangod / VocBase / replication - dump . cpp <nl> <nl> # include " Logger / Logger . h " <nl> # include " MMFiles / MMFilesLogfileManager . h " / / TODO - - remove <nl> # include " MMFiles / MMFilesCompactionLocker . h " <nl> - # include " MMFiles / MMFilesCollection . h " <nl> - # include " VocBase / Ditch . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / vocbase . h " <nl> <nl> int TRI_DumpCollectionReplication ( TRI_replication_dump_t * dump , <nl> auto customTypeHandler = dump - > _transactionContext - > orderCustomTypeHandler ( ) ; <nl> dump - > _vpackOptions . customTypeHandler = customTypeHandler . get ( ) ; <nl> <nl> - auto mmfiles = toMMFilesCollection ( collection ) ; <nl> + auto mmfiles = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) ; <nl> / / create a barrier so the underlying collection is not unloaded <nl> auto b = mmfiles - > ditches ( ) - > createReplicationDitch ( __FILE__ , __LINE__ ) ; <nl> <nl> int TRI_DumpCollectionReplication ( TRI_replication_dump_t * dump , <nl> / / block compaction <nl> int res ; <nl> { <nl> - auto mmfiles = toMMFilesCollection ( collection ) ; <nl> + auto mmfiles = arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) ; <nl> CompactionPreventer compactionPreventer ( mmfiles ) ; <nl> <nl> try { <nl> mmm a / arangod / VocBase / vocbase . cpp <nl> ppp b / arangod / VocBase / vocbase . cpp <nl> <nl> # include " Basics / threads . h " <nl> # include " Basics / tri - strings . h " <nl> # include " Logger / Logger . h " <nl> + # include " MMFiles / MMFilesCollection . h " <nl> + # include " MMFiles / MMFilesDitch . h " <nl> # include " MMFiles / MMFilesLogfileManager . h " <nl> - # include " MMFiles / MMFilesCollection . h " / / TODO - REMOVE <nl> # include " RestServer / DatabaseFeature . h " <nl> # include " StorageEngine / EngineSelectorFeature . h " <nl> # include " StorageEngine / StorageEngine . h " <nl> <nl> # include " Utils / CursorRepository . h " <nl> # include " Utils / Events . h " <nl> # include " V8Server / v8 - user - structures . h " <nl> - # include " VocBase / Ditch . h " <nl> # include " VocBase / LogicalCollection . h " <nl> # include " VocBase / PhysicalCollection . h " <nl> # include " VocBase / replication - applier . h " <nl> bool TRI_vocbase_t : : UnloadCollectionCallback ( LogicalCollection * collection ) { <nl> return false ; <nl> } <nl> <nl> - auto ditches = toMMFilesCollection ( collection ) - > ditches ( ) ; <nl> + auto ditches = <nl> + arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) - > ditches ( ) ; <nl> <nl> if ( ditches - > contains ( arangodb : : Ditch : : TRI_DITCH_DOCUMENT ) | | <nl> ditches - > contains ( arangodb : : Ditch : : TRI_DITCH_REPLICATION ) | | <nl> int TRI_vocbase_t : : loadCollection ( arangodb : : LogicalCollection * collection , <nl> / / release the WRITE lock and try again <nl> if ( collection - > status ( ) = = TRI_VOC_COL_STATUS_UNLOADING ) { <nl> / / check if there is a deferred drop action going on for this collection <nl> - if ( toMMFilesCollection ( collection ) - > ditches ( ) - > contains ( <nl> - arangodb : : Ditch : : TRI_DITCH_COLLECTION_DROP ) ) { <nl> + if ( arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > contains ( arangodb : : Ditch : : TRI_DITCH_COLLECTION_DROP ) ) { <nl> / / drop call going on , we must abort <nl> locker . unlock ( ) ; <nl> <nl> int TRI_vocbase_t : : unloadCollection ( arangodb : : LogicalCollection * collection , boo <nl> collection - > setStatus ( TRI_VOC_COL_STATUS_UNLOADING ) ; <nl> <nl> / / add callback for unload <nl> - toMMFilesCollection ( collection ) - > ditches ( ) - > createUnloadCollectionDitch ( <nl> - collection , UnloadCollectionCallback , __FILE__ , <nl> - __LINE__ ) ; <nl> + arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > createUnloadCollectionDitch ( collection , UnloadCollectionCallback , <nl> + __FILE__ , __LINE__ ) ; <nl> } / / release locks <nl> <nl> collection - > unload ( ) ; <nl> int TRI_vocbase_t : : dropCollection ( arangodb : : LogicalCollection * collection , bool <nl> DropCollectionCallback ( collection ) ; <nl> } else { <nl> / / add callback for dropping <nl> - toMMFilesCollection ( collection ) - > ditches ( ) - > createDropCollectionDitch ( <nl> - collection , DropCollectionCallback , <nl> - __FILE__ , __LINE__ ) ; <nl> + arangodb : : MMFilesCollection : : toMMFilesCollection ( collection ) <nl> + - > ditches ( ) <nl> + - > createDropCollectionDitch ( collection , DropCollectionCallback , <nl> + __FILE__ , __LINE__ ) ; <nl> <nl> / / wake up the cleanup thread <nl> StorageEngine * engine = EngineSelectorFeature : : ENGINE ; <nl>
Moved ditches into MMFiles .
arangodb/arangodb
5d452edec6b52c093f8e83424fe9abc0bed0f3a0
2017-02-23T08:02:34Z
mmm a / Code / CryPlugins / CryUQS / Client / client / ItemListProxy . h <nl> ppp b / Code / CryPlugins / CryUQS / Client / client / ItemListProxy . h <nl> namespace UQS <nl> public : <nl> explicit CItemListProxy_Writable ( Core : : IItemList & itemList ) ; <nl> void CreateItemsByItemFactory ( size_t numItemsToCreate ) ; <nl> + void CloneItems ( const void * pOriginalItems , size_t numItemsToClone ) ; <nl> TItem & GetItemAtIndex ( size_t index ) ; <nl> Core : : IItemList & GetUnderlyingItemList ( ) ; <nl> <nl> namespace UQS <nl> m_itemCount = numItemsToCreate ; <nl> } <nl> <nl> + template < class TItem > <nl> + void CItemListProxy_Writable < TItem > : : CloneItems ( const void * pOriginalItems , size_t numItemsToClone ) <nl> + { <nl> + assert ( pOriginalItems ) ; <nl> + <nl> + m_itemList . CloneItems ( pOriginalItems , numItemsToClone ) ; <nl> + <nl> + / / retrieve the items in case they hadn ' t been created in a previous roundtrip <nl> + m_pItems = m_itemList . GetItems ( ) ; <nl> + m_itemCount = numItemsToClone ; <nl> + } <nl> + <nl> template < class TItem > <nl> TItem & CItemListProxy_Writable < TItem > : : GetItemAtIndex ( size_t index ) <nl> { <nl> mmm a / Code / CryPlugins / CryUQS / Core / core / ItemList . cpp <nl> ppp b / Code / CryPlugins / CryUQS / Core / core / ItemList . cpp <nl> namespace UQS <nl> m_numItems = numItemsToCreate ; <nl> } <nl> <nl> + void CItemList : : CloneItems ( const void * pOriginalItems , size_t numItemsToClone ) <nl> + { <nl> + assert ( pOriginalItems ) ; <nl> + <nl> + / / ensure SetItemFactory ( ) has been called prior <nl> + assert ( m_pItemFactory ) ; <nl> + <nl> + / / ensure that no items have been created yet ( we don ' t support recycling the item list ) <nl> + assert ( ! m_pItems ) ; <nl> + <nl> + m_pItems = m_pItemFactory - > CloneItems ( pOriginalItems , numItemsToClone ) ; <nl> + m_numItems = numItemsToClone ; <nl> + } <nl> + <nl> size_t CItemList : : GetItemCount ( ) const <nl> { <nl> return m_numItems ; <nl> mmm a / Code / CryPlugins / CryUQS / Core / core / ItemList . h <nl> ppp b / Code / CryPlugins / CryUQS / Core / core / ItemList . h <nl> namespace UQS <nl> public : <nl> explicit CItemList ( ) ; <nl> ~ CItemList ( ) ; <nl> + <nl> + / / IItemList <nl> virtual void CreateItemsByItemFactory ( size_t numItemsToCreate ) override ; <nl> + virtual void CloneItems ( const void * pOriginalItems , size_t numItemsToClone ) override ; <nl> virtual size_t GetItemCount ( ) const override ; <nl> virtual Client : : IItemFactory & GetItemFactory ( ) const override ; <nl> virtual void * GetItems ( ) const override ; <nl> virtual void CopyOtherToSelf ( const IItemList & other ) override ; <nl> + / / ~ IItemList <nl> <nl> void SetItemFactory ( Client : : IItemFactory & itemFactory ) ; <nl> void CopyOtherToSelfViaIndexList ( const IItemList & other , const size_t * pIndexes , size_t numIndexes ) ; <nl> mmm a / Code / CryPlugins / CryUQS / Core / core / QueryBase . cpp <nl> ppp b / Code / CryPlugins / CryUQS / Core / core / QueryBase . cpp <nl> namespace UQS <nl> <nl> CQueryBase : : EUpdateState CQueryBase : : Update ( const CTimeValue & amountOfGrantedTime , Shared : : CUqsString & error ) <nl> { <nl> + m_timeBudgetForCurrentUpdate . Restart ( amountOfGrantedTime ) ; <nl> + <nl> + const CTimeValue startTime = gEnv - > pTimer - > GetAsyncTime ( ) ; <nl> + <nl> + + m_totalElapsedFrames ; <nl> <nl> / / immediate debug - rendering ON / OFF <nl> namespace UQS <nl> m_blackboard . pDebugRenderWorldImmediate = nullptr ; <nl> } <nl> <nl> - const CTimeValue startTime = gEnv - > pTimer - > GetAsyncTime ( ) ; <nl> - <nl> bool bCorruptionOccurred = false ; <nl> <nl> / / <nl> namespace UQS <nl> / / allow the derived class to update itself if no item corruption has occurred yet <nl> / / <nl> <nl> - m_timeBudgetForCurrentUpdate . Restart ( amountOfGrantedTime ) ; <nl> const EUpdateState state = bCorruptionOccurred ? EUpdateState : : ExceptionOccurred : OnUpdate ( error ) ; <nl> <nl> / / <nl> mmm a / Code / CryPlugins / CryUQS / Core / core / QueryManager . cpp <nl> ppp b / Code / CryPlugins / CryUQS / Core / core / QueryManager . cpp <nl> namespace UQS <nl> else if ( bThisQueryRequiresSomeTimeBudgetForExecution ) <nl> { <nl> / / <nl> - / / check for having exceeded the granted time by some percentage <nl> + / / check for having exceeded the granted time by some percentage <nl> / / - > if this is the case , then issue a warning to the console and to the query history <nl> / / <nl> <nl> const float allowedTimeBudgetExcess = ( SCvars : : timeBudgetExcessThresholdInPercentBeforeWarning * 0 . 01f ) * timeBudgetForThisQuery . GetMilliSeconds ( ) ; <nl> - const bool bExceededTimeBudgetTooMuch = ( timeUsedByThisQuery - timeBudgetForThisQuery ) > allowedTimeBudgetExcess ; <nl> + const bool bExceededTimeBudgetTooMuch = ( timeUsedByThisQuery - timeBudgetForThisQuery ) . GetMilliSeconds ( ) > allowedTimeBudgetExcess ; <nl> <nl> if ( bExceededTimeBudgetTooMuch ) <nl> { <nl> mmm a / Code / CryPlugins / CryUQS / Core / core / Query_Regular . cpp <nl> ppp b / Code / CryPlugins / CryUQS / Core / core / Query_Regular . cpp <nl> namespace UQS <nl> CQuery_Regular : : CQuery_Regular ( const SCtorContext & ctorContext ) <nl> : CQueryBase ( ctorContext , true ) / / true = yes , we need some time budget from CQueryManager for some potentially complex computations <nl> , m_currentPhaseFn ( & CQuery_Regular : : Phase1_PrepareGenerationPhase ) <nl> + , m_currentItemIndexForCreatingDebugRepresentations ( 0 ) <nl> , m_maxCandidates ( 0 ) <nl> , m_remainingItemWorkingDatasIndexForCheapInstantEvaluators ( 0 ) <nl> { <nl> namespace UQS <nl> { <nl> assert ( m_currentPhaseFn ) ; / / query has already finished before ; cannot recycle a query <nl> <nl> - + + m_elapsedFramesPerPhase . back ( ) ; <nl> - <nl> const SPhaseUpdateContext phaseUpdateContext ( error ) ; <nl> <nl> EUpdateState status = EUpdateState : : StillRunning ; <nl> namespace UQS <nl> } <nl> <nl> / / if we ' re still in the same phase , it means that the phase figured that it either ran out of time or that it just couldn ' t do any more work in the current frame <nl> - / / - > we prematurely interrupt the running query and continue from here on the next frame <nl> + / / - > we prematurely interrupt the running query and continue from here on the next frame ( and reflect that in the current phase ' s frame counter ) <nl> if ( oldPhaseFn = = m_currentPhaseFn ) <nl> { <nl> + + + m_elapsedFramesPerPhase . back ( ) ; <nl> break ; <nl> } <nl> else <nl> namespace UQS <nl> const Client : : IItemFactory & itemFactory = m_generatedItems . GetItemFactory ( ) ; <nl> CDebugRenderWorldPersistent & debugRenderWorld = m_pHistory - > GetDebugRenderWorldPersistent ( ) ; <nl> <nl> - for ( size_t i = 0 , n = m_generatedItems . GetItemCount ( ) ; i < n ; + + i ) <nl> + for ( size_t n = m_generatedItems . GetItemCount ( ) ; m_currentItemIndexForCreatingDebugRepresentations < n ; + + m_currentItemIndexForCreatingDebugRepresentations ) <nl> { <nl> - const void * pItem = m_generatedItems . GetItemAtIndex ( i ) ; <nl> - m_pHistory - > CreateItemDebugProxyViaItemFactoryForItem ( itemFactory , pItem , i ) ; <nl> - debugRenderWorld . AssociateAllUpcomingAddedPrimitivesWithItem ( i ) ; <nl> + const void * pItem = m_generatedItems . GetItemAtIndex ( m_currentItemIndexForCreatingDebugRepresentations ) ; <nl> + m_pHistory - > CreateItemDebugProxyViaItemFactoryForItem ( itemFactory , pItem , m_currentItemIndexForCreatingDebugRepresentations ) ; <nl> + debugRenderWorld . AssociateAllUpcomingAddedPrimitivesWithItem ( m_currentItemIndexForCreatingDebugRepresentations ) ; <nl> debugRenderWorld . ItemConstructionBegin ( ) ; <nl> itemFactory . AddItemToDebugRenderWorld ( pItem , debugRenderWorld ) ; <nl> debugRenderWorld . ItemConstructionEnd ( ) ; <nl> + <nl> + / / check for having run out of time every 16th item <nl> + if ( ( m_currentItemIndexForCreatingDebugRepresentations & 0xF ) = = 0 & & m_timeBudgetForCurrentUpdate . IsExhausted ( ) ) <nl> + { <nl> + / / continue in the next frame <nl> + return EPhaseStatus : : Ok ; <nl> + } <nl> } <nl> } <nl> m_currentPhaseFn = & CQuery_Regular : : Phase4_PrepareEvaluationPhase ; <nl> mmm a / Code / CryPlugins / CryUQS / Core / core / Query_Regular . h <nl> ppp b / Code / CryPlugins / CryUQS / Core / core / Query_Regular . h <nl> namespace UQS <nl> / / phase 2 <nl> CItemList m_generatedItems ; / / all the items that are being evaluated ; this is kind of a read - only storage after they have been generated <nl> <nl> + / / phase 3 <nl> + size_t m_currentItemIndexForCreatingDebugRepresentations ; / / for continuing with creating debug - visualization and debug - proxies of all generated items in the next frame ( in case we run out of time ) <nl> + <nl> / / phase 4 <nl> std : : unique_ptr < SItemIterationContext > m_pItemIterationContext ; / / this gets instantiated right after all items got generated ; it ' s used to provide the functions in the evaluation phase with the current item we ' re iterating on <nl> std : : vector < std : : unique_ptr < CFunctionCallHierarchy > > m_functionCallHierarchyPerInstantEvalBP ; / / the function call hierarchy of each instant - evaluator - blueprint is re - used for the particular evaluator during item iteration <nl> mmm a / Code / CryPlugins / CryUQS / EditorPlugin / Editor / Blueprints . cpp <nl> ppp b / Code / CryPlugins / CryUQS / EditorPlugin / Editor / Blueprints . cpp <nl> SERIALIZATION_ENUM ( EEvaluatorType : : Deferred , " Deferred " , " Deferred " ) <nl> SERIALIZATION_ENUM ( EEvaluatorType : : Undefined , " Undefined " , " Undefined " ) <nl> SERIALIZATION_ENUM_END ( ) <nl> <nl> + SERIALIZATION_ENUM_BEGIN ( EEvaluatorCost , " EvaluatorCost " ) <nl> + SERIALIZATION_ENUM ( EEvaluatorCost : : Cheap , " Cheap " , " Cheap " ) <nl> + SERIALIZATION_ENUM ( EEvaluatorCost : : Expensive , " Expensive " , " Expensive " ) <nl> + SERIALIZATION_ENUM ( EEvaluatorCost : : Undefined , " Undefined " , " Undefined " ) <nl> + SERIALIZATION_ENUM_END ( ) <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> class CSyntaxErrorCollector : public UQS : : DataSource : : ISyntaxErrorCollector <nl> class CEvaluatorFactoryHelper <nl> } <nl> } <nl> <nl> + EEvaluatorCost GetCost ( ) const <nl> + { <nl> + if ( m_pInstantFactory ) <nl> + { <nl> + switch ( m_pInstantFactory - > GetCostCategory ( ) ) <nl> + { <nl> + case UQS : : Client : : IInstantEvaluatorFactory : : ECostCategory : : Cheap : <nl> + return EEvaluatorCost : : Cheap ; <nl> + <nl> + case UQS : : Client : : IInstantEvaluatorFactory : : ECostCategory : : Expensive : <nl> + return EEvaluatorCost : : Expensive ; <nl> + <nl> + default : <nl> + assert ( 0 ) ; <nl> + return EEvaluatorCost : : Undefined ; <nl> + } <nl> + } <nl> + else if ( m_pDeferredFactory ) <nl> + { <nl> + / / deferred evaluators are implicitly always expensive <nl> + return EEvaluatorCost : : Expensive ; <nl> + } <nl> + else <nl> + { <nl> + return EEvaluatorCost : : Undefined ; <nl> + } <nl> + } <nl> + <nl> const char * GetDescription ( ) const <nl> { <nl> if ( m_pInstantFactory ) <nl> CEvaluator : : CEvaluator ( const EEvaluatorType type ) <nl> , m_inputs ( ) <nl> , m_pErrorCollector ( new CErrorCollector ) <nl> , m_evaluatorType ( EEvaluatorType : : Undefined ) <nl> + , m_evaluatorCost ( EEvaluatorCost : : Undefined ) <nl> { <nl> SetType ( type ) ; <nl> } <nl> CEvaluator : : CEvaluator ( CEvaluator & & other ) <nl> , m_bNegateDiscard ( other . m_bNegateDiscard ) <nl> , m_pErrorCollector ( std : : move ( other . m_pErrorCollector ) ) <nl> , m_evaluatorType ( other . m_evaluatorType ) <nl> + , m_evaluatorCost ( other . m_evaluatorCost ) <nl> , m_interfaceAdapter ( std : : move ( other . m_interfaceAdapter ) ) <nl> { <nl> if ( m_interfaceAdapter ) <nl> CEvaluator : : CEvaluator ( ) <nl> , m_inputs ( ) <nl> , m_pErrorCollector ( new CErrorCollector ) <nl> , m_evaluatorType ( EEvaluatorType : : Undefined ) <nl> + , m_evaluatorCost ( EEvaluatorCost : : Undefined ) <nl> , m_interfaceAdapter ( ) <nl> { <nl> <nl> CEvaluator & CEvaluator : : operator = ( CEvaluator & & other ) <nl> m_bNegateDiscard = other . m_bNegateDiscard ; <nl> m_pErrorCollector = std : : move ( other . m_pErrorCollector ) ; <nl> m_evaluatorType = other . m_evaluatorType ; <nl> + m_evaluatorCost = other . m_evaluatorCost ; <nl> m_interfaceAdapter = std : : move ( other . m_interfaceAdapter ) ; <nl> if ( m_interfaceAdapter ) <nl> { <nl> void CEvaluator : : Serialize ( Serialization : : IArchive & archive ) <nl> if ( factory . IsValid ( ) ) <nl> { <nl> SetType ( factory . GetType ( ) ) ; <nl> + m_evaluatorCost = factory . GetCost ( ) ; <nl> if ( bGUIDChanged ) <nl> { <nl> m_inputs . ResetChildrenFromFactory ( factory , * pContext ) ; <nl> void CEvaluator : : Serialize ( Serialization : : IArchive & archive ) <nl> archive . warning ( m_evaluatorType , " Undefined evaluator type " ) ; <nl> } <nl> <nl> + / / Evaluator cost ( read - only ) <nl> + archive ( m_evaluatorCost , " evaluatorCost " , " ! Evaluator cost " ) ; <nl> + <nl> archive ( m_weight , " weight " , " Weight " ) ; <nl> <nl> SerializeScoreTransformGUID ( archive , " scoreTransformGUID " , " ^ Score Transform " , * pContext ) ; <nl> mmm a / Code / CryPlugins / CryUQS / EditorPlugin / Editor / Blueprints . h <nl> ppp b / Code / CryPlugins / CryUQS / EditorPlugin / Editor / Blueprints . h <nl> enum class EEvaluatorType <nl> Deferred <nl> } ; <nl> <nl> + enum class EEvaluatorCost <nl> + { <nl> + Undefined , <nl> + Cheap , <nl> + Expensive <nl> + } ; <nl> + <nl> class CEvaluator <nl> { <nl> public : <nl> class CEvaluator <nl> mutable std : : shared_ptr < CErrorCollector > m_pErrorCollector ; <nl> <nl> EEvaluatorType m_evaluatorType ; <nl> + EEvaluatorCost m_evaluatorCost ; <nl> std : : unique_ptr < SEvaluatorBlueprintAdapter > m_interfaceAdapter ; <nl> } ; <nl> <nl> mmm a / Code / CryPlugins / CryUQS / EditorPlugin_HistoryInspector / Editor / MainEditorWindow . cpp <nl> ppp b / Code / CryPlugins / CryUQS / EditorPlugin_HistoryInspector / Editor / MainEditorWindow . cpp <nl> void CMainEditorWindow : : CUQSHistoryPostRenderer : : OnPostRender ( ) const <nl> } <nl> <nl> CMainEditorWindow : : CMainEditorWindow ( ) <nl> - : m_pQueryHistoryManager ( nullptr ) <nl> + : m_windowTitle ( " UQS History " ) <nl> + , m_pQueryHistoryManager ( nullptr ) <nl> , m_pFreshlyAddedOrUpdatedQuery ( nullptr ) <nl> , m_pHistoryPostRenderer ( nullptr ) <nl> { <nl> const char * CMainEditorWindow : : GetPaneTitle ( ) const <nl> / / check for whether the UQS engine plugin has been loaded <nl> if ( UQS : : Core : : IHubPlugin : : GetHubPtr ( ) ) <nl> { <nl> - return " UQS History " ; <nl> + return m_windowTitle ; <nl> } <nl> else <nl> { <nl> void CMainEditorWindow : : OnSaveLiveHistoryToFile ( ) <nl> CryWarning ( VALIDATOR_MODULE_GAME , VALIDATOR_ERROR , " UQS Query History Inspector : % s " , error . c_str ( ) ) ; <nl> QMessageBox : : warning ( this , " Error saving the live query history " , error . c_str ( ) ) ; <nl> } <nl> + else <nl> + { <nl> + / / change the window title to also show the file name <nl> + m_windowTitle . Format ( " UQS History - % s " , sFilePath . c_str ( ) ) ; <nl> + setWindowTitle ( QtUtil : : ToQString ( m_windowTitle ) ) ; <nl> + } <nl> } <nl> } <nl> <nl> void CMainEditorWindow : : OnLoadHistoryFromFile ( ) <nl> { <nl> / / ensure the " deserialized " entry in the history origin combo - box is selected <nl> m_pComboBoxHistoryOrigin - > setCurrentIndex ( 1 ) ; <nl> + <nl> + / / change the window title to also show the file name <nl> + m_windowTitle . Format ( " UQS History - % s " , sFilePath . c_str ( ) ) ; <nl> + setWindowTitle ( QtUtil : : ToQString ( m_windowTitle ) ) ; <nl> } <nl> else <nl> { <nl> mmm a / Code / CryPlugins / CryUQS / EditorPlugin_HistoryInspector / Editor / MainEditorWindow . h <nl> ppp b / Code / CryPlugins / CryUQS / EditorPlugin_HistoryInspector / Editor / MainEditorWindow . h <nl> class CMainEditorWindow : public CDockableWindow , public UQS : : Core : : IQueryHistor <nl> void OnTreeViewCurrentChanged ( const QModelIndex & current , const QModelIndex & previous ) ; <nl> <nl> private : <nl> + string m_windowTitle ; <nl> UQS : : Core : : IQueryHistoryManager * m_pQueryHistoryManager ; <nl> SQuery * m_pFreshlyAddedOrUpdatedQuery ; <nl> CHistoricQueryTreeView * m_pTreeView ; <nl> mmm a / Code / CryPlugins / CryUQS / Interfaces / core / IItemList . h <nl> ppp b / Code / CryPlugins / CryUQS / Interfaces / core / IItemList . h <nl> namespace UQS <nl> { <nl> virtual ~ IItemList ( ) { } <nl> virtual void CreateItemsByItemFactory ( size_t numItemsToCreate ) = 0 ; <nl> + virtual void CloneItems ( const void * pOriginalItems , size_t numItemsToClone ) = 0 ; <nl> virtual size_t GetItemCount ( ) const = 0 ; <nl> virtual Client : : IItemFactory & GetItemFactory ( ) const = 0 ; <nl> virtual void * GetItems ( ) const = 0 ; <nl>
! O ( UQS ) CQuery_Regular : time - slicing phase 3 now ( in case we create debug visualization for " a lot " of items , e . g . 2000 points in 3D space )
CRYTEK/CRYENGINE
33aba1bddd9b4a21c984bb40bc5ce5ca13443034
2017-11-10T13:06:48Z
mmm a / doc / shared - libraries . md <nl> ppp b / doc / shared - libraries . md <nl> The purpose of this library is to make the verification functionality that is cr <nl> <nl> # # # API <nl> <nl> - The interface is defined in the C header ` bitcoinconsensus . h ` located in ` src / script / bitcoinconsensus . h ` . <nl> + The interface is defined in the C header ` bitcoinconsensus . h ` located in ` src / script / bitcoinconsensus . h ` . <nl> <nl> # # # # Version <nl> <nl> - ` bitcoinconsensus_version ` returns an ` unsigned int ` with the API version * ( currently at an experimental ` 0 ` ) * . <nl> + ` bitcoinconsensus_version ` returns an ` unsigned int ` with the API version * ( currently ` 1 ` ) * . <nl> <nl> # # # # Script Validation <nl> <nl>
doc : correct bitcoinconsensus_version in shared - libraries
bitcoin/bitcoin
8ae6d020b83572235f85ee68ce87045f2e97cbc0
2019-04-07T13:42:32Z
mmm a / contracts / eosio . system / eosio . system . abi <nl> ppp b / contracts / eosio . system / eosio . system . abi <nl> <nl> { " name " : " base_per_action_cpu_usage " , " type " : " uint32 " } , <nl> { " name " : " base_setcode_cpu_usage " , " type " : " uint32 " } , <nl> { " name " : " per_signature_cpu_usage " , " type " : " uint32 " } , <nl> + { " name " : " per_lock_net_usage " , " type " : " uint32 " } , <nl> + { " name " : " context_free_discount_cpu_usage_num " , " type " : " uint64 " } , <nl> + { " name " : " context_free_discount_cpu_usage_den " , " type " : " uint64 " } , <nl> + { " name " : " max_transaction_cpu_usage " , " type " : " uint32 " } , <nl> + { " name " : " max_transaction_net_usage " , " type " : " uint32 " } , <nl> { " name " : " max_transaction_lifetime " , " type " : " uint32 " } , <nl> { " name " : " max_transaction_exec_time " , " type " : " uint32 " } , <nl> { " name " : " max_authority_depth " , " type " : " uint16 " } , <nl> mmm a / contracts / eosio . system / voting . hpp <nl> ppp b / contracts / eosio . system / voting . hpp <nl> namespace eosiosystem { <nl> std : : array < uint32_t , 21 > base_per_action_cpu_usage ; <nl> std : : array < uint32_t , 21 > base_setcode_cpu_usage ; <nl> std : : array < uint32_t , 21 > per_signature_cpu_usage ; <nl> + std : : array < uint32_t , 21 > per_lock_net_usage ; <nl> + std : : array < uint64_t , 21 > context_free_discount_cpu_usage_num ; <nl> + std : : array < uint64_t , 21 > context_free_discount_cpu_usage_den ; <nl> + std : : array < uint32_t , 21 > max_transaction_cpu_usage ; <nl> + std : : array < uint32_t , 21 > max_transaction_net_usage ; <nl> std : : array < uint32_t , 21 > max_transaction_lifetime ; <nl> std : : array < uint16_t , 21 > max_authority_depth ; <nl> std : : array < uint32_t , 21 > max_transaction_exec_time ; <nl> namespace eosiosystem { <nl> base_per_action_cpu_usage [ n ] = it - > prefs . base_per_action_cpu_usage ; <nl> base_setcode_cpu_usage [ n ] = it - > prefs . base_setcode_cpu_usage ; <nl> per_signature_cpu_usage [ n ] = it - > prefs . per_signature_cpu_usage ; <nl> + per_lock_net_usage [ n ] = it - > prefs . per_lock_net_usage ; <nl> + context_free_discount_cpu_usage_num [ n ] = it - > prefs . context_free_discount_cpu_usage_num ; <nl> + context_free_discount_cpu_usage_den [ n ] = it - > prefs . context_free_discount_cpu_usage_den ; <nl> + max_transaction_cpu_usage [ n ] = it - > prefs . max_transaction_cpu_usage ; <nl> + max_transaction_net_usage [ n ] = it - > prefs . max_transaction_net_usage ; <nl> max_transaction_lifetime [ n ] = it - > prefs . max_transaction_lifetime ; <nl> max_authority_depth [ n ] = it - > prefs . max_authority_depth ; <nl> max_transaction_exec_time [ n ] = it - > prefs . max_transaction_exec_time ; <nl> namespace eosiosystem { <nl> std : : sort ( base_per_action_cpu_usage . begin ( ) , base_per_action_cpu_usage . begin ( ) + n ) ; <nl> std : : sort ( base_setcode_cpu_usage . begin ( ) , base_setcode_cpu_usage . begin ( ) + n ) ; <nl> std : : sort ( per_signature_cpu_usage . begin ( ) , per_signature_cpu_usage . begin ( ) + n ) ; <nl> + std : : sort ( per_lock_net_usage . begin ( ) , per_lock_net_usage . begin ( ) + n ) ; <nl> + std : : sort ( context_free_discount_cpu_usage_num . begin ( ) , context_free_discount_cpu_usage_num . begin ( ) + n ) ; <nl> + std : : sort ( context_free_discount_cpu_usage_den . begin ( ) , context_free_discount_cpu_usage_den . begin ( ) + n ) ; <nl> + std : : sort ( max_transaction_cpu_usage . begin ( ) , max_transaction_cpu_usage . begin ( ) + n ) ; <nl> + std : : sort ( max_transaction_net_usage . begin ( ) , max_transaction_net_usage . begin ( ) + n ) ; <nl> std : : sort ( max_transaction_lifetime . begin ( ) , max_transaction_lifetime . begin ( ) + n ) ; <nl> std : : sort ( max_transaction_exec_time . begin ( ) , max_transaction_exec_time . begin ( ) + n ) ; <nl> std : : sort ( max_authority_depth . begin ( ) , max_authority_depth . begin ( ) + n ) ; <nl> namespace eosiosystem { <nl> parameters . base_per_action_cpu_usage = base_per_action_cpu_usage [ median ] ; <nl> parameters . base_setcode_cpu_usage = base_setcode_cpu_usage [ median ] ; <nl> parameters . per_signature_cpu_usage = per_signature_cpu_usage [ median ] ; <nl> + parameters . per_lock_net_usage = per_lock_net_usage [ median ] ; <nl> + parameters . context_free_discount_cpu_usage_num = context_free_discount_cpu_usage_num [ median ] ; <nl> + parameters . context_free_discount_cpu_usage_den = context_free_discount_cpu_usage_den [ median ] ; <nl> + parameters . max_transaction_cpu_usage = max_transaction_cpu_usage [ median ] ; <nl> + parameters . max_transaction_net_usage = max_transaction_net_usage [ median ] ; <nl> parameters . max_transaction_lifetime = max_transaction_lifetime [ median ] ; <nl> parameters . max_transaction_exec_time = max_transaction_exec_time [ median ] ; <nl> parameters . max_authority_depth = max_authority_depth [ median ] ; <nl> mmm a / contracts / eosiolib / privileged . hpp <nl> ppp b / contracts / eosiolib / privileged . hpp <nl> namespace eosio { <nl> uint32_t base_per_action_cpu_usage ; <nl> uint32_t base_setcode_cpu_usage ; <nl> uint32_t per_signature_cpu_usage ; <nl> + uint32_t per_lock_net_usage ; <nl> + uint64_t context_free_discount_cpu_usage_num ; <nl> + uint64_t context_free_discount_cpu_usage_den ; <nl> + uint32_t max_transaction_cpu_usage ; <nl> + uint32_t max_transaction_net_usage ; <nl> uint32_t max_transaction_lifetime ; <nl> uint32_t max_transaction_exec_time ; <nl> uint16_t max_authority_depth ; <nl> namespace eosio { <nl> <nl> EOSLIB_SERIALIZE ( blockchain_parameters , <nl> ( base_per_transaction_net_usage ) ( base_per_transaction_cpu_usage ) ( base_per_action_cpu_usage ) <nl> - ( base_setcode_cpu_usage ) ( per_signature_cpu_usage ) <nl> + ( base_setcode_cpu_usage ) ( per_signature_cpu_usage ) ( per_lock_net_usage ) <nl> + ( context_free_discount_cpu_usage_num ) ( context_free_discount_cpu_usage_den ) <nl> + ( max_transaction_cpu_usage ) ( max_transaction_net_usage ) <nl> ( max_transaction_lifetime ) ( max_transaction_exec_time ) ( max_authority_depth ) <nl> ( max_inline_depth ) ( max_inline_action_size ) ( max_generated_transaction_size ) <nl> ( max_generated_transaction_count ) <nl> mmm a / libraries / chain / CMakeLists . txt <nl> ppp b / libraries / chain / CMakeLists . txt <nl> add_library ( eosio_chain <nl> name . cpp <nl> transaction . cpp <nl> block . cpp <nl> + block_trace . cpp <nl> wast_to_wasm . cpp <nl> wasm_interface . cpp <nl> wasm_eosio_validation . cpp <nl> mmm a / libraries / chain / block . cpp <nl> ppp b / libraries / chain / block . cpp <nl> namespace eosio { namespace chain { <nl> return merkle ( std : : move ( merkle_of_each_shard ) ) ; <nl> } <nl> <nl> - void shard_trace : : finalize_shard ( ) { <nl> - static const size_t GUESS_ACTS_PER_TX = 10 ; <nl> - <nl> - vector < digest_type > action_roots ; <nl> - cpu_usage = 0 ; <nl> - action_roots . reserve ( transaction_traces . size ( ) * GUESS_ACTS_PER_TX ) ; <nl> - for ( const auto & tx : transaction_traces ) { <nl> - for ( const auto & at : tx . action_traces ) { <nl> - digest_type : : encoder enc ; <nl> - <nl> - fc : : raw : : pack ( enc , at . receiver ) ; <nl> - fc : : raw : : pack ( enc , at . act . account ) ; <nl> - fc : : raw : : pack ( enc , at . act . name ) ; <nl> - fc : : raw : : pack ( enc , at . act . data ) ; <nl> - fc : : raw : : pack ( enc , at . region_id ) ; <nl> - fc : : raw : : pack ( enc , at . cycle_index ) ; <nl> - fc : : raw : : pack ( enc , at . data_access ) ; <nl> - <nl> - action_roots . emplace_back ( enc . result ( ) ) ; <nl> - <nl> - cpu_usage + = at . cpu_usage ; <nl> - } <nl> - } <nl> - shard_root = merkle ( action_roots ) ; <nl> - } <nl> - <nl> - digest_type block_trace : : calculate_action_merkle_root ( ) const { <nl> - vector < digest_type > shard_roots ; <nl> - shard_roots . reserve ( 1024 ) ; <nl> - for ( const auto & rt : region_traces ) { <nl> - for ( const auto & ct : rt . cycle_traces ) { <nl> - for ( const auto & st : ct . shard_traces ) { <nl> - shard_roots . emplace_back ( st . shard_root ) ; <nl> - } <nl> - } <nl> - } <nl> - return merkle ( shard_roots ) ; <nl> - } <nl> - <nl> - uint64_t block_trace : : calculate_cpu_usage ( ) const { <nl> - uint64_t cpu_usage = 0 ; <nl> - for ( const auto & rt : region_traces ) { <nl> - for ( const auto & ct : rt . cycle_traces ) { <nl> - for ( const auto & st : ct . shard_traces ) { <nl> - cpu_usage + = st . cpu_usage ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - return cpu_usage ; <nl> - } <nl> - <nl> } } <nl> new file mode 100644 <nl> index 0000000000 . . c29873b1bd <nl> mmm / dev / null <nl> ppp b / libraries / chain / block_trace . cpp <nl> <nl> + / * * <nl> + * @ file <nl> + * @ copyright defined in eos / LICENSE . txt <nl> + * / <nl> + # include < eosio / chain / block_trace . hpp > <nl> + # include < eosio / chain / merkle . hpp > <nl> + # include < fc / io / raw . hpp > <nl> + # include < fc / bitutil . hpp > <nl> + # include < algorithm > <nl> + <nl> + namespace eosio { namespace chain { <nl> + <nl> + void shard_trace : : finalize_shard ( ) { <nl> + static const size_t GUESS_ACTS_PER_TX = 10 ; <nl> + <nl> + vector < digest_type > action_roots ; <nl> + cpu_usage = 0 ; <nl> + action_roots . reserve ( transaction_traces . size ( ) * GUESS_ACTS_PER_TX ) ; <nl> + for ( const auto & tx : transaction_traces ) { <nl> + for ( const auto & at : tx . action_traces ) { <nl> + digest_type : : encoder enc ; <nl> + <nl> + fc : : raw : : pack ( enc , at . receiver ) ; <nl> + fc : : raw : : pack ( enc , at . act . account ) ; <nl> + fc : : raw : : pack ( enc , at . act . name ) ; <nl> + fc : : raw : : pack ( enc , at . act . data ) ; <nl> + fc : : raw : : pack ( enc , at . region_id ) ; <nl> + fc : : raw : : pack ( enc , at . cycle_index ) ; <nl> + fc : : raw : : pack ( enc , at . data_access ) ; <nl> + <nl> + action_roots . emplace_back ( enc . result ( ) ) ; <nl> + <nl> + cpu_usage + = at . cpu_usage ; <nl> + } <nl> + } <nl> + shard_root = merkle ( action_roots ) ; <nl> + } <nl> + <nl> + digest_type block_trace : : calculate_action_merkle_root ( ) const { <nl> + vector < digest_type > shard_roots ; <nl> + shard_roots . reserve ( 1024 ) ; <nl> + for ( const auto & rt : region_traces ) { <nl> + for ( const auto & ct : rt . cycle_traces ) { <nl> + for ( const auto & st : ct . shard_traces ) { <nl> + shard_roots . emplace_back ( st . shard_root ) ; <nl> + } <nl> + } <nl> + } <nl> + return merkle ( shard_roots ) ; <nl> + } <nl> + <nl> + uint64_t block_trace : : calculate_cpu_usage ( ) const { <nl> + uint64_t cpu_usage = 0 ; <nl> + for ( const auto & rt : region_traces ) { <nl> + for ( const auto & ct : rt . cycle_traces ) { <nl> + for ( const auto & st : ct . shard_traces ) { <nl> + cpu_usage + = st . cpu_usage ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + return cpu_usage ; <nl> + } <nl> + <nl> + } } <nl> mmm a / libraries / chain / chain_controller . cpp <nl> ppp b / libraries / chain / chain_controller . cpp <nl> transaction_trace chain_controller : : _push_transaction ( const packed_transaction & <nl> <nl> } FC_CAPTURE_AND_RETHROW ( ) } <nl> <nl> - static void record_locks_for_data_access ( const vector < action_trace > & action_traces , vector < shard_lock > & read_locks , vector < shard_lock > & write_locks ) { <nl> - for ( const auto & at : action_traces ) { <nl> + static void record_locks_for_data_access ( transaction_trace & trace , flat_set < shard_lock > & read_locks , flat_set < shard_lock > & write_locks ) { <nl> + for ( const auto & at : trace . action_traces ) { <nl> for ( const auto & access : at . data_access ) { <nl> if ( access . type = = data_access_info : : read ) { <nl> - read_locks . emplace_back ( shard_lock { access . code , access . scope } ) ; <nl> + trace . read_locks . emplace ( shard_lock { access . code , access . scope } ) ; <nl> } else { <nl> - write_locks . emplace_back ( shard_lock { access . code , access . scope } ) ; <nl> + trace . write_locks . emplace ( shard_lock { access . code , access . scope } ) ; <nl> } <nl> } <nl> } <nl> + <nl> + / / remove read locks for write locks taken by other actions <nl> + trace . read_locks . erase ( trace . write_locks . begin ( ) , trace . write_locks . end ( ) ) ; <nl> + read_locks . erase ( trace . write_locks . begin ( ) , trace . write_locks . end ( ) ) ; <nl> + <nl> + read_locks . insert ( trace . read_locks . begin ( ) , trace . read_locks . end ( ) ) ; <nl> + write_locks . insert ( trace . write_locks . begin ( ) , trace . write_locks . end ( ) ) ; <nl> } <nl> <nl> transaction_trace chain_controller : : _push_transaction ( transaction_metadata & & data ) <nl> void chain_controller : : _start_pending_shard ( ) <nl> <nl> void chain_controller : : _finalize_pending_cycle ( ) <nl> { <nl> - for ( auto & shard : _pending_cycle_trace - > shard_traces ) { <nl> - shard . finalize_shard ( ) ; <nl> + for ( int idx = 0 ; idx < _pending_cycle_trace - > shard_traces . size ( ) ; idx + + ) { <nl> + auto & trace = _pending_cycle_trace - > shard_traces . at ( idx ) ; <nl> + auto & shard = _pending_block - > regions . back ( ) . cycles_summary . back ( ) . at ( idx ) ; <nl> + <nl> + trace . finalize_shard ( ) ; <nl> + shard . read_locks . reserve ( trace . read_locks . size ( ) ) ; <nl> + shard . write_locks . insert ( shard . read_locks . end ( ) , trace . read_locks . begin ( ) , trace . read_locks . end ( ) ) ; <nl> + <nl> + shard . write_locks . reserve ( trace . write_locks . size ( ) ) ; <nl> + shard . write_locks . insert ( shard . write_locks . end ( ) , trace . write_locks . begin ( ) , trace . write_locks . end ( ) ) ; <nl> } <nl> <nl> _apply_cycle_trace ( * _pending_cycle_trace ) ; <nl> void chain_controller : : __apply_block ( const signed_block & next_block ) <nl> write_locks [ s ] = shard_index ; <nl> } <nl> <nl> - vector < shard_lock > used_read_locks ; <nl> - vector < shard_lock > used_write_locks ; <nl> + flat_set < shard_lock > used_read_locks ; <nl> + flat_set < shard_lock > used_write_locks ; <nl> <nl> shard_trace s_trace ; <nl> for ( const auto & receipt : shard . transactions ) { <nl> void chain_controller : : __apply_block ( const signed_block & next_block ) <nl> mtrx - > processing_deadline = processing_deadline ; <nl> <nl> s_trace . transaction_traces . emplace_back ( _apply_transaction ( * mtrx ) ) ; <nl> - record_locks_for_data_access ( s_trace . transaction_traces . back ( ) . action_traces , used_read_locks , used_write_locks ) ; <nl> + record_locks_for_data_access ( s_trace . transaction_traces . back ( ) , used_read_locks , used_write_locks ) ; <nl> <nl> FC_ASSERT ( receipt . status = = s_trace . transaction_traces . back ( ) . status ) ; <nl> <nl> void chain_controller : : __apply_block ( const signed_block & next_block ) <nl> / / check_transaction_authorization ( trx , true ) ; <nl> } / / / for each transaction id <nl> <nl> - / / Validate that the producer didn ' t list extra locks to bloat the size of the block <nl> - / / TODO : this check can be removed when blocks are irreversible <nl> - fc : : deduplicate ( used_read_locks ) ; <nl> - fc : : deduplicate ( used_write_locks ) ; <nl> - <nl> - auto newend = boost : : remove_if ( used_read_locks , <nl> - [ & ] ( const auto & l ) { <nl> - return boost : : find ( used_write_locks , l ) ! = used_write_locks . end ( ) ; <nl> - } ) ; <nl> - used_read_locks . erase ( newend , used_read_locks . end ( ) ) ; <nl> - <nl> - EOS_ASSERT ( boost : : equal ( used_read_locks , shard . read_locks ) , <nl> + EOS_ASSERT ( boost : : equal ( used_read_locks , shard . read_locks ) , <nl> block_lock_exception , " Read locks for executing shard : $ { s } do not match those listed in the block " , ( " s " , shard_index ) ) ; <nl> EOS_ASSERT ( boost : : equal ( used_write_locks , shard . write_locks ) , <nl> block_lock_exception , " Write locks for executing shard : $ { s } do not match those listed in the block " , ( " s " , shard_index ) ) ; <nl> void chain_controller : : record_transaction ( const transaction & trx ) <nl> } <nl> } <nl> <nl> - void chain_controller : : update_resource_usage ( transaction_trace & trace , const transaction_metadata & meta ) { <nl> - const auto & chain_configuration = get_global_properties ( ) . configuration ; <nl> - <nl> + static uint32_t calculate_transaction_cpu_usage ( const transaction_trace & trace , const transaction_metadata & meta , const chain_config & chain_configuration ) { <nl> + / / calculate the sum of all actions retired <nl> uint32_t action_cpu_usage = 0 ; <nl> for ( const auto & at : trace . action_traces ) { <nl> action_cpu_usage + = chain_configuration . base_per_action_cpu_usage + at . cpu_usage ; <nl> void chain_controller : : update_resource_usage ( transaction_trace & trace , const tr <nl> } <nl> } <nl> <nl> - trace . net_usage = meta . bandwidth_usage + chain_configuration . base_per_transaction_net_usage ; <nl> - trace . cpu_usage = action_cpu_usage + chain_configuration . base_per_transaction_cpu_usage ; <nl> - <nl> / / charge a system controlled amount for signature verification / recovery <nl> + uint32_t signature_cpu_usage = 0 ; <nl> if ( meta . signing_keys ) { <nl> - trace . cpu_usage + = meta . signing_keys - > size ( ) * chain_configuration . per_signature_cpu_usage ; <nl> + signature_cpu_usage = ( uint32_t ) meta . signing_keys - > size ( ) * chain_configuration . per_signature_cpu_usage ; <nl> } <nl> <nl> + / / charge a system discounted amount for context free cpu usage <nl> + uint32_t context_free_cpu_usage = meta . trx ( ) . context_free_kilo_cpu_usage . value * 1024UL ; <nl> + context_free_cpu_usage = ( uint32_t ) ( ( uint64_t ) context_free_cpu_usage * chain_configuration . context_free_discount_cpu_usage_num / chain_configuration . context_free_discount_cpu_usage_den ) ; <nl> + <nl> + return chain_configuration . base_per_transaction_cpu_usage + <nl> + action_cpu_usage + <nl> + context_free_cpu_usage + <nl> + signature_cpu_usage ; <nl> + } <nl> + <nl> + static uint32_t calculate_tranasaction_net_usage ( const transaction_trace & trace , const transaction_metadata & meta , const chain_config & chain_configuration ) { <nl> + / / charge a system controlled per - lock overhead to account for shard bloat <nl> + uint32_t lock_net_usage = uint32_t ( trace . read_locks . size ( ) + trace . write_locks . size ( ) ) * chain_configuration . per_lock_net_usage ; <nl> + <nl> + return chain_configuration . base_per_transaction_net_usage + <nl> + meta . bandwidth_usage + <nl> + lock_net_usage ; <nl> + } <nl> + <nl> + void chain_controller : : update_resource_usage ( transaction_trace & trace , const transaction_metadata & meta ) { <nl> + const auto & chain_configuration = get_global_properties ( ) . configuration ; <nl> + <nl> + trace . cpu_usage = calculate_transaction_cpu_usage ( trace , meta , chain_configuration ) ; <nl> + trace . net_usage = calculate_tranasaction_net_usage ( trace , meta , chain_configuration ) ; <nl> + <nl> + / / enforce that the system controlled per tx limits are not violated <nl> + EOS_ASSERT ( trace . cpu_usage < = chain_configuration . max_transaction_cpu_usage , <nl> + tx_resource_exhausted , " Transaction exceeds the maximum cpu usage [ used : $ { used } , max : $ { max } ] " , <nl> + ( " usage " , trace . cpu_usage ) ( " max " , chain_configuration . max_transaction_cpu_usage ) ) ; <nl> + <nl> + EOS_ASSERT ( trace . net_usage < = chain_configuration . max_transaction_net_usage , <nl> + tx_resource_exhausted , " Transaction exceeds the maximum net usage [ used : $ { used } , max : $ { max } ] " , <nl> + ( " usage " , trace . net_usage ) ( " max " , chain_configuration . max_transaction_net_usage ) ) ; <nl> + <nl> / / determine the accounts to bill <nl> set < std : : pair < account_name , permission_name > > authorizations ; <nl> for ( const auto & act : meta . trx ( ) . actions ) <nl> mmm a / libraries / chain / contracts / eosio_contract . cpp <nl> ppp b / libraries / chain / contracts / eosio_contract . cpp <nl> void apply_eosio_setcode ( apply_context & context ) { <nl> / * * TODO : consider whether a microsecond level local timestamp is sufficient to detect code version changes * / <nl> # warning TODO : update setcode message to include the hash , then validate it in validate <nl> a . code_version = code_id ; <nl> + / / Added resize ( 0 ) here to avoid bug in boost vector container <nl> a . code . resize ( 0 ) ; <nl> a . code . resize ( code_size ) ; <nl> a . last_code_update = context . controller . head_block_time ( ) ; <nl> mmm a / libraries / chain / include / eosio / chain / account_object . hpp <nl> ppp b / libraries / chain / include / eosio / chain / account_object . hpp <nl> namespace eosio { namespace chain { <nl> shared_vector < char > abi ; <nl> <nl> void set_abi ( const eosio : : chain : : contracts : : abi_def & a ) { <nl> + / / Added resize ( 0 ) here to avoid bug in boost vector container <nl> abi . resize ( 0 ) ; <nl> abi . resize ( fc : : raw : : pack_size ( a ) ) ; <nl> fc : : datastream < char * > ds ( abi . data ( ) , abi . size ( ) ) ; <nl> mmm a / libraries / chain / include / eosio / chain / apply_context . hpp <nl> ppp b / libraries / chain / include / eosio / chain / apply_context . hpp <nl> <nl> * @ copyright defined in eos / LICENSE . txt <nl> * / <nl> # pragma once <nl> - # include < eosio / chain / block . hpp > <nl> + # include < eosio / chain / block_trace . hpp > <nl> # include < eosio / chain / transaction . hpp > <nl> # include < eosio / chain / transaction_metadata . hpp > <nl> # include < eosio / chain / contracts / contract_table_objects . hpp > <nl> mmm a / libraries / chain / include / eosio / chain / block . hpp <nl> ppp b / libraries / chain / include / eosio / chain / block . hpp <nl> namespace eosio { namespace chain { <nl> vector < packed_transaction > input_transactions ; <nl> } ; <nl> <nl> - struct shard_trace { <nl> - digest_type shard_root ; <nl> - vector < transaction_trace > transaction_traces ; <nl> - uint64_t cpu_usage ; <nl> - <nl> - void append ( transaction_trace & & res ) { <nl> - transaction_traces . emplace_back ( move ( res ) ) ; <nl> - } <nl> - <nl> - void append ( const transaction_trace & res ) { <nl> - transaction_traces . emplace_back ( res ) ; <nl> - } <nl> - <nl> - void finalize_shard ( ) ; <nl> - } ; <nl> - <nl> - struct cycle_trace { <nl> - vector < shard_trace > shard_traces ; <nl> - } ; <nl> - <nl> - struct region_trace { <nl> - vector < cycle_trace > cycle_traces ; <nl> - } ; <nl> - <nl> - struct block_trace { <nl> - explicit block_trace ( const signed_block & s ) <nl> - : block ( s ) <nl> - { } <nl> - <nl> - const signed_block & block ; <nl> - vector < region_trace > region_traces ; <nl> - vector < transaction > implicit_transactions ; <nl> - digest_type calculate_action_merkle_root ( ) const ; <nl> - uint64_t calculate_cpu_usage ( ) const ; <nl> - } ; <nl> - <nl> - <nl> } } / / eosio : : chain <nl> <nl> FC_REFLECT ( eosio : : chain : : block_header , ( previous ) ( timestamp ) <nl> FC_REFLECT ( eosio : : chain : : shard_summary , ( read_locks ) ( write_locks ) ( transactions ) <nl> FC_REFLECT ( eosio : : chain : : region_summary , ( region ) ( cycles_summary ) ) <nl> FC_REFLECT_DERIVED ( eosio : : chain : : signed_block_summary , ( eosio : : chain : : signed_block_header ) , ( regions ) ) <nl> FC_REFLECT_DERIVED ( eosio : : chain : : signed_block , ( eosio : : chain : : signed_block_summary ) , ( input_transactions ) ) <nl> - FC_REFLECT ( eosio : : chain : : shard_trace , ( shard_root ) ( transaction_traces ) ) <nl> - FC_REFLECT ( eosio : : chain : : cycle_trace , ( shard_traces ) ) <nl> - FC_REFLECT ( eosio : : chain : : region_trace , ( cycle_traces ) ) <nl> - FC_REFLECT ( eosio : : chain : : block_trace , ( region_traces ) ) <nl> new file mode 100644 <nl> index 0000000000 . . 3be648c20f <nl> mmm / dev / null <nl> ppp b / libraries / chain / include / eosio / chain / block_trace . hpp <nl> <nl> + / * * <nl> + * @ file <nl> + * @ copyright defined in eos / LICENSE . txt <nl> + * / <nl> + # pragma once <nl> + # include < eosio / chain / block . hpp > <nl> + # include < eosio / chain / transaction_trace . hpp > <nl> + <nl> + namespace eosio { namespace chain { <nl> + <nl> + struct shard_trace { <nl> + digest_type shard_root ; <nl> + vector < transaction_trace > transaction_traces ; <nl> + uint64_t cpu_usage ; <nl> + <nl> + flat_set < shard_lock > read_locks ; <nl> + flat_set < shard_lock > write_locks ; <nl> + <nl> + void append ( transaction_trace & & res ) { <nl> + transaction_traces . emplace_back ( move ( res ) ) ; <nl> + } <nl> + <nl> + void append ( const transaction_trace & res ) { <nl> + transaction_traces . emplace_back ( res ) ; <nl> + } <nl> + <nl> + void finalize_shard ( ) ; <nl> + } ; <nl> + <nl> + struct cycle_trace { <nl> + vector < shard_trace > shard_traces ; <nl> + } ; <nl> + <nl> + struct region_trace { <nl> + vector < cycle_trace > cycle_traces ; <nl> + } ; <nl> + <nl> + struct block_trace { <nl> + explicit block_trace ( const signed_block & s ) <nl> + : block ( s ) <nl> + { } <nl> + <nl> + const signed_block & block ; <nl> + vector < region_trace > region_traces ; <nl> + vector < transaction > implicit_transactions ; <nl> + digest_type calculate_action_merkle_root ( ) const ; <nl> + uint64_t calculate_cpu_usage ( ) const ; <nl> + } ; <nl> + <nl> + <nl> + } } / / eosio : : chain <nl> + <nl> + FC_REFLECT ( eosio : : chain : : shard_trace , ( shard_root ) ( transaction_traces ) ( cpu_usage ) ( read_locks ) ( write_locks ) ) <nl> + FC_REFLECT ( eosio : : chain : : cycle_trace , ( shard_traces ) ) <nl> + FC_REFLECT ( eosio : : chain : : region_trace , ( cycle_traces ) ) <nl> + FC_REFLECT ( eosio : : chain : : block_trace , ( region_traces ) ) <nl> mmm a / libraries / chain / include / eosio / chain / chain_config . hpp <nl> ppp b / libraries / chain / include / eosio / chain / chain_config . hpp <nl> struct chain_config { <nl> uint32_t base_per_action_cpu_usage ; / / / < the base amount of cpu usage billed for an action to cover incidentals <nl> uint32_t base_setcode_cpu_usage ; / / / < the base amount of cpu usage billed for a setcode action to cover compilation / etc <nl> uint32_t per_signature_cpu_usage ; / / / < the cpu usage billed for every signature on a transaction <nl> + uint32_t per_lock_net_usage ; / / / < the net usage billed for every lock on a transaction to cover overhead in the block shards <nl> + <nl> + uint64_t context_free_discount_cpu_usage_num ; / / / < the numerator for the discount on cpu usage for CFA ' s <nl> + uint64_t context_free_discount_cpu_usage_den ; / / / < the denominator for the discount on cpu usage for CFA ' s <nl> + <nl> + uint32_t max_transaction_cpu_usage ; / / / < the maximum objectively measured cpu usage that the chain will allow regardless of account limits <nl> + uint32_t max_transaction_net_usage ; / / / < the maximum objectively measured net usage that the chain will allow regardless of account limits <nl> + <nl> uint32_t max_transaction_lifetime ; <nl> uint32_t max_transaction_exec_time ; <nl> uint16_t max_authority_depth ; <nl> struct chain_config { <nl> < < " Base Per - Action CPU Usage : " < < c . base_per_action_cpu_usage < < " , " <nl> < < " Base Setcode CPU Usage : " < < c . base_setcode_cpu_usage < < " , " <nl> < < " Per - Signature CPU Usage : " < < c . per_signature_cpu_usage < < " , " <nl> + < < " Per - Lock NET Usage : " < < c . per_lock_net_usage < < " , " <nl> + < < " Context - Free Action CPU Usage Discount : " < < ( double ) c . context_free_discount_cpu_usage_num * 100 . 0 / ( double ) c . context_free_discount_cpu_usage_den < < " % , " <nl> + < < " Max Transaction CPU Usage : " < < c . max_transaction_cpu_usage < < " , " <nl> + < < " Max Transaction Net Usage : " < < c . max_transaction_net_usage < < " , " <nl> < < " Max Transaction Lifetime : " < < c . max_transaction_lifetime < < " , " <nl> < < " Max Authority Depth : " < < c . max_authority_depth < < " , " <nl> < < " Max Inline Depth : " < < c . max_inline_depth < < " , " <nl> FC_REFLECT ( eosio : : chain : : chain_config , <nl> ( base_per_transaction_cpu_usage ) <nl> ( base_per_action_cpu_usage ) <nl> ( base_setcode_cpu_usage ) <nl> - ( per_signature_cpu_usage ) <nl> + ( per_signature_cpu_usage ) ( per_lock_net_usage ) <nl> + ( context_free_discount_cpu_usage_num ) ( context_free_discount_cpu_usage_den ) <nl> + ( max_transaction_cpu_usage ) ( max_transaction_net_usage ) <nl> ( max_transaction_lifetime ) ( max_transaction_exec_time ) ( max_authority_depth ) <nl> ( max_inline_depth ) ( max_inline_action_size ) ( max_generated_transaction_size ) <nl> ( max_generated_transaction_count ) <nl> mmm a / libraries / chain / include / eosio / chain / chain_controller . hpp <nl> ppp b / libraries / chain / include / eosio / chain / chain_controller . hpp <nl> <nl> # include < eosio / chain / permission_object . hpp > <nl> # include < eosio / chain / fork_database . hpp > <nl> # include < eosio / chain / block_log . hpp > <nl> + # include < eosio / chain / block_trace . hpp > <nl> <nl> # include < chainbase / chainbase . hpp > <nl> # include < fc / scoped_exit . hpp > <nl> namespace eosio { namespace chain { <nl> <nl> auto & bcycle = _pending_block - > regions . back ( ) . cycles_summary . back ( ) ; <nl> auto & bshard = bcycle . front ( ) ; <nl> + auto & bshard_trace = _pending_cycle_trace - > shard_traces . at ( 0 ) ; <nl> <nl> - record_locks_for_data_access ( result . action_traces , bshard . read_locks , bshard . write_locks ) ; <nl> - <nl> - fc : : deduplicate ( bshard . read_locks ) ; <nl> - fc : : deduplicate ( bshard . write_locks ) ; <nl> - auto newend = boost : : remove_if ( bshard . read_locks , <nl> - [ & ] ( const auto & l ) { <nl> - return boost : : find ( bshard . write_locks , l ) ! = bshard . write_locks . end ( ) ; <nl> - } ) ; <nl> - bshard . read_locks . erase ( newend , bshard . read_locks . end ( ) ) ; <nl> + record_locks_for_data_access ( result , bshard_trace . read_locks , bshard_trace . write_locks ) ; <nl> <nl> bshard . transactions . emplace_back ( result ) ; <nl> <nl> - _pending_cycle_trace - > shard_traces . at ( 0 ) . append ( result ) ; <nl> + bshard_trace . append ( result ) ; <nl> <nl> / / The transaction applied successfully . Merge its changes into the pending block session . <nl> temp_session . squash ( ) ; <nl> mmm a / libraries / chain / include / eosio / chain / contracts / abi_serializer . hpp <nl> ppp b / libraries / chain / include / eosio / chain / contracts / abi_serializer . hpp <nl> <nl> * / <nl> # pragma once <nl> # include < eosio / chain / contracts / types . hpp > <nl> - # include < eosio / chain / transaction . hpp > <nl> - # include < eosio / chain / block . hpp > <nl> + # include < eosio / chain / block_trace . hpp > <nl> # include < eosio / chain / exceptions . hpp > <nl> # include < fc / variant_object . hpp > <nl> <nl> mmm a / libraries / chain / include / eosio / chain / contracts / contract_table_objects . hpp <nl> ppp b / libraries / chain / include / eosio / chain / contracts / contract_table_objects . hpp <nl> namespace eosio { namespace chain { namespace contracts { <nl> uint64_t primary_key ; <nl> shared_string value ; <nl> account_name payer = 0 ; <nl> - uint16_t billed_overhead = 0 ; <nl> } ; <nl> <nl> using key_value_index = chainbase : : shared_multi_index_container < <nl> mmm a / libraries / chain / include / eosio / chain / transaction . hpp <nl> ppp b / libraries / chain / include / eosio / chain / transaction . hpp <nl> namespace eosio { namespace chain { <nl> account_name sender ; <nl> uint128_t sender_id ; <nl> } ; <nl> - <nl> - struct data_access_info { <nl> - enum access_type { <nl> - read = 0 , / / / < scope was read by this action <nl> - write = 1 , / / / < scope was ( potentially ) written to by this action <nl> - } ; <nl> - <nl> - access_type type ; <nl> - account_name code ; <nl> - scope_name scope ; <nl> - <nl> - uint64_t sequence ; <nl> - } ; <nl> - <nl> - struct action_trace { <nl> - account_name receiver ; <nl> - uint64_t cpu_usage ; <nl> - action act ; <nl> - string console ; <nl> - uint32_t region_id ; <nl> - uint32_t cycle_index ; <nl> - vector < data_access_info > data_access ; <nl> - <nl> - fc : : microseconds _profiling_us = fc : : microseconds ( 0 ) ; <nl> - } ; <nl> - <nl> - struct transaction_trace : transaction_receipt { <nl> - using transaction_receipt : : transaction_receipt ; <nl> - <nl> - vector < action_trace > action_traces ; <nl> - vector < fc : : static_variant < deferred_transaction , deferred_reference > > deferred_transaction_requests ; <nl> - <nl> - uint64_t cpu_usage ; <nl> - uint64_t net_usage ; <nl> - <nl> - fc : : microseconds _profiling_us = fc : : microseconds ( 0 ) ; <nl> - fc : : microseconds _setup_profiling_us = fc : : microseconds ( 0 ) ; <nl> - } ; <nl> } } / / eosio : : chain <nl> <nl> FC_REFLECT ( eosio : : chain : : permission_level , ( actor ) ( permission ) ) <nl> FC_REFLECT ( eosio : : chain : : action , ( account ) ( name ) ( authorization ) ( data ) ) <nl> + FC_REFLECT ( eosio : : chain : : transaction_receipt , ( status ) ( id ) ) <nl> FC_REFLECT ( eosio : : chain : : transaction_header , ( expiration ) ( region ) ( ref_block_num ) ( ref_block_prefix ) ( net_usage_words ) ( context_free_kilo_cpu_usage ) ) <nl> FC_REFLECT_DERIVED ( eosio : : chain : : transaction , ( eosio : : chain : : transaction_header ) , ( context_free_actions ) ( actions ) ) <nl> FC_REFLECT_DERIVED ( eosio : : chain : : signed_transaction , ( eosio : : chain : : transaction ) , ( signatures ) ( context_free_data ) ) <nl> FC_REFLECT_ENUM ( eosio : : chain : : packed_transaction : : compression_type , ( none ) ( zlib <nl> FC_REFLECT ( eosio : : chain : : packed_transaction , ( signatures ) ( context_free_data ) ( compression ) ( data ) ) <nl> FC_REFLECT_DERIVED ( eosio : : chain : : deferred_transaction , ( eosio : : chain : : transaction ) , ( sender_id ) ( sender ) ( payer ) ( execute_after ) ) <nl> FC_REFLECT ( eosio : : chain : : deferred_reference , ( sender_id ) ( sender ) ) <nl> - FC_REFLECT_ENUM ( eosio : : chain : : data_access_info : : access_type , ( read ) ( write ) ) <nl> - FC_REFLECT ( eosio : : chain : : data_access_info , ( type ) ( code ) ( scope ) ( sequence ) ) <nl> - FC_REFLECT ( eosio : : chain : : action_trace , ( receiver ) ( cpu_usage ) ( act ) ( console ) ( region_id ) ( cycle_index ) ( data_access ) ( _profiling_us ) ) <nl> - FC_REFLECT ( eosio : : chain : : transaction_receipt , ( status ) ( id ) ) <nl> - FC_REFLECT_ENUM ( eosio : : chain : : transaction_receipt : : status_enum , ( executed ) ( soft_fail ) ( hard_fail ) ( delayed ) ) <nl> - FC_REFLECT_DERIVED ( eosio : : chain : : transaction_trace , ( eosio : : chain : : transaction_receipt ) , ( action_traces ) ( deferred_transaction_requests ) ( cpu_usage ) ( net_usage ) ( _profiling_us ) ( _setup_profiling_us ) ) <nl> <nl> <nl> <nl> new file mode 100644 <nl> index 0000000000 . . e4d217ee85 <nl> mmm / dev / null <nl> ppp b / libraries / chain / include / eosio / chain / transaction_trace . hpp <nl> <nl> + / * * <nl> + * @ file <nl> + * @ copyright defined in eos / LICENSE . txt <nl> + * / <nl> + # pragma once <nl> + # include < eosio / chain / types . hpp > <nl> + # include < eosio / chain / transaction . hpp > <nl> + # include < eosio / chain / block . hpp > <nl> + <nl> + # include < numeric > <nl> + <nl> + namespace eosio { namespace chain { <nl> + <nl> + struct data_access_info { <nl> + enum access_type { <nl> + read = 0 , / / / < scope was read by this action <nl> + write = 1 , / / / < scope was ( potentially ) written to by this action <nl> + } ; <nl> + <nl> + access_type type ; <nl> + account_name code ; <nl> + scope_name scope ; <nl> + <nl> + uint64_t sequence ; <nl> + } ; <nl> + <nl> + struct action_trace { <nl> + account_name receiver ; <nl> + uint64_t cpu_usage ; <nl> + action act ; <nl> + string console ; <nl> + uint32_t region_id ; <nl> + uint32_t cycle_index ; <nl> + vector < data_access_info > data_access ; <nl> + <nl> + fc : : microseconds _profiling_us = fc : : microseconds ( 0 ) ; <nl> + } ; <nl> + <nl> + struct transaction_trace : transaction_receipt { <nl> + using transaction_receipt : : transaction_receipt ; <nl> + <nl> + vector < action_trace > action_traces ; <nl> + vector < fc : : static_variant < deferred_transaction , deferred_reference > > deferred_transaction_requests ; <nl> + <nl> + flat_set < shard_lock > read_locks ; <nl> + flat_set < shard_lock > write_locks ; <nl> + <nl> + uint64_t cpu_usage ; <nl> + uint64_t net_usage ; <nl> + <nl> + fc : : microseconds _profiling_us = fc : : microseconds ( 0 ) ; <nl> + fc : : microseconds _setup_profiling_us = fc : : microseconds ( 0 ) ; <nl> + } ; <nl> + } } / / eosio : : chain <nl> + <nl> + FC_REFLECT_ENUM ( eosio : : chain : : data_access_info : : access_type , ( read ) ( write ) ) <nl> + FC_REFLECT ( eosio : : chain : : data_access_info , ( type ) ( code ) ( scope ) ( sequence ) ) <nl> + FC_REFLECT ( eosio : : chain : : action_trace , ( receiver ) ( cpu_usage ) ( act ) ( console ) ( region_id ) ( cycle_index ) ( data_access ) ( _profiling_us ) ) <nl> + FC_REFLECT_ENUM ( eosio : : chain : : transaction_receipt : : status_enum , ( executed ) ( soft_fail ) ( hard_fail ) ( delayed ) ) <nl> + FC_REFLECT_DERIVED ( eosio : : chain : : transaction_trace , ( eosio : : chain : : transaction_receipt ) , ( action_traces ) ( deferred_transaction_requests ) ( read_locks ) ( write_locks ) ( cpu_usage ) ( net_usage ) ( _profiling_us ) ( _setup_profiling_us ) ) <nl> + <nl> + <nl> + <nl> mmm a / tests / wasm_tests / eosio . system_tests . cpp <nl> ppp b / tests / wasm_tests / eosio . system_tests . cpp <nl> fc : : mutable_variant_object config_to_variant ( const eosio : : chain : : chain_config & <nl> ( " base_per_action_cpu_usage " , config . base_per_action_cpu_usage ) <nl> ( " base_setcode_cpu_usage " , config . base_setcode_cpu_usage ) <nl> ( " per_signature_cpu_usage " , config . per_signature_cpu_usage ) <nl> + ( " per_lock_net_usage " , config . per_lock_net_usage ) <nl> + ( " context_free_discount_cpu_usage_num " , config . context_free_discount_cpu_usage_num ) <nl> + ( " context_free_discount_cpu_usage_den " , config . context_free_discount_cpu_usage_den ) <nl> + ( " max_transaction_cpu_usage " , config . max_transaction_cpu_usage ) <nl> + ( " max_transaction_net_usage " , config . max_transaction_net_usage ) <nl> ( " max_transaction_lifetime " , config . max_transaction_lifetime ) <nl> ( " max_transaction_exec_time " , config . max_transaction_exec_time ) <nl> ( " max_authority_depth " , config . max_authority_depth ) <nl>
- added in per lock net usage
EOSIO/eos
ed4fe2f3d1bb3a482f4b9a3d52b9cd4ec974e142
2018-03-30T13:39:39Z
mmm a / src / qt / src / gui / kernel / qapplication_mac . mm <nl> ppp b / src / qt / src / gui / kernel / qapplication_mac . mm <nl> void qt_init ( QApplicationPrivate * priv , int ) <nl> [ newDelegate setReflectionDelegate : oldDelegate ] ; <nl> [ cocoaApp setDelegate : newDelegate ] ; <nl> <nl> + / / https : / / bugreports . qt . nokia . com / browse / QTBUG - 5952 <nl> QT_MANGLE_NAMESPACE ( QCocoaMenuLoader ) * qtMenuLoader = [ [ QT_MANGLE_NAMESPACE ( QCocoaMenuLoader ) alloc ] init ] ; <nl> if ( [ NSBundle loadNibNamed : @ " qt_menu " owner : qtMenuLoader ] = = false ) { <nl> + # if 0 <nl> qFatal ( " Qt internal error : qt_menu . nib could not be loaded . The . nib file " <nl> " should be placed in QtGui . framework / Versions / Current / Resources / " <nl> " or in the resources directory of your application bundle . " ) ; <nl> + # endif <nl> } <nl> <nl> [ cocoaApp setMenu : [ qtMenuLoader menu ] ] ; <nl>
Qt Mac : workaround qt_menu . nib problem .
ariya/phantomjs
0d77f588ec41309c1651ab6ce037e5fef0b6d25b
2012-03-02T15:25:31Z
mmm a / src / arch / linux / message_hub . cc <nl> ppp b / src / arch / linux / message_hub . cc <nl> linux_message_hub_t : : linux_message_hub_t ( linux_event_queue_t * queue , linux_threa <nl> <nl> res = pthread_spin_init ( & queues [ i ] . lock , PTHREAD_PROCESS_PRIVATE ) ; <nl> check ( " Could not initialize spin lock " , res ! = 0 ) ; <nl> - } <nl> - <nl> - / / Create notify fd for other cores that send work to us <nl> - <nl> - core_notify_fd = eventfd ( 0 , 0 ) ; <nl> - check ( " Could not create core notification fd " , core_notify_fd = = - 1 ) ; <nl> <nl> - res = fcntl ( core_notify_fd , F_SETFL , O_NONBLOCK ) ; <nl> - check ( " Could not make core notify fd non - blocking " , res ! = 0 ) ; <nl> + / / Create notify fd for other cores that send work to us <nl> + notify [ i ] . notifier_cpu = i ; <nl> + notify [ i ] . parent = this ; <nl> + <nl> + notify [ i ] . fd = eventfd ( 0 , 0 ) ; <nl> + check ( " Could not create core notification fd " , notify [ i ] . fd = = - 1 ) ; <nl> + <nl> + res = fcntl ( notify [ i ] . fd , F_SETFL , O_NONBLOCK ) ; <nl> + check ( " Could not make core notify fd non - blocking " , res ! = 0 ) ; <nl> <nl> - queue - > watch_resource ( core_notify_fd , EPOLLET | EPOLLIN , this ) ; <nl> + queue - > watch_resource ( notify [ i ] . fd , EPOLLET | EPOLLIN , & notify [ i ] ) ; <nl> + } <nl> } <nl> <nl> linux_message_hub_t : : ~ linux_message_hub_t ( ) { <nl> linux_message_hub_t : : ~ linux_message_hub_t ( ) { <nl> <nl> res = pthread_spin_destroy ( & queues [ i ] . lock ) ; <nl> check ( " Could not destroy spin lock " , res ! = 0 ) ; <nl> + <nl> + res = close ( notify [ i ] . fd ) ; <nl> + check ( " Could not close core_notify_fd " , res ! = 0 ) ; <nl> } <nl> - <nl> - res = close ( core_notify_fd ) ; <nl> - check ( " Could not close core_notify_fd " , res ! = 0 ) ; <nl> } <nl> <nl> / / Collects a message for a given CPU onto a local list . <nl> void linux_message_hub_t : : insert_external_message ( linux_cpu_message_t * msg ) { <nl> pthread_spin_unlock ( & queues [ current_cpu ] . lock ) ; <nl> <nl> / / Wakey wakey eggs and bakey <nl> - int res = eventfd_write ( thread_pool - > threads [ current_cpu ] - > message_hub . core_notify_fd , 1 ) ; <nl> + int res = eventfd_write ( notify [ current_cpu ] . fd , 1 ) ; <nl> check ( " Could not write to core_notify_fd " , res ! = 0 ) ; <nl> } <nl> <nl> - void linux_message_hub_t : : on_epoll ( int events ) { <nl> - / / TODO : this is really stupid and is probably the cause of our <nl> - / / performance woes . Eventfd tells us there are messages from A <nl> - / / cpu , but we go collect them from ALL cpus . Even if there are <nl> - / / messages from other CPUs , we go there again on its <nl> - / / eventfd . Stupid stupid stupid . ( problem is - eventfd can ' t <nl> - / / support enough info to tell us which CPU to go to ) . <nl> - for ( int i = 0 ; i < thread_pool - > n_threads ; i + + ) { <nl> - thread_pool - > threads [ i ] - > message_hub . pull_messages ( current_cpu ) ; <nl> - } <nl> + void linux_message_hub_t : : notify_t : : on_epoll ( int events ) { <nl> + parent - > thread_pool - > threads [ notifier_cpu ] - > message_hub . pull_messages ( parent - > current_cpu ) ; <nl> } <nl> <nl> / / Pulls the messages stored in global lists for a given CPU . <nl> void linux_message_hub_t : : push_messages ( ) { <nl> pthread_spin_unlock ( & queue - > lock ) ; <nl> <nl> / / Wakey wakey eggs and bakey <nl> - int res = eventfd_write ( thread_pool - > threads [ i ] - > message_hub . core_notify_fd , 1 ) ; <nl> + int res = eventfd_write ( thread_pool - > threads [ i ] - > message_hub . notify [ current_cpu ] . fd , 1 ) ; <nl> check ( " Could not write to core_notify_fd " , res ! = 0 ) ; <nl> } <nl> <nl> mmm a / src / arch / linux / message_hub . hpp <nl> ppp b / src / arch / linux / message_hub . hpp <nl> struct linux_cpu_message_t : public intrusive_list_node_t < linux_cpu_message_t > <nl> virtual void on_cpu_switch ( ) = 0 ; <nl> } ; <nl> <nl> - struct linux_message_hub_t : <nl> - public linux_epoll_callback_t <nl> + struct linux_message_hub_t <nl> { <nl> <nl> public : <nl> struct linux_message_hub_t : <nl> ~ linux_message_hub_t ( ) ; <nl> <nl> private : <nl> - void on_epoll ( int events ) ; <nl> void pull_messages ( int cpu ) ; <nl> <nl> - fd_t core_notify_fd ; <nl> linux_event_queue_t * queue ; <nl> linux_thread_pool_t * thread_pool ; <nl> <nl> + / * We maintain a queue structure for every other cpu on the <nl> + * system . We interact with those CPUs through this queue . * / <nl> struct cpu_queue_t { <nl> <nl> / / Lists of messages for each CPU local to this thread . <nl> struct linux_message_hub_t : <nl> <nl> / / Spinlock for the global list <nl> pthread_spinlock_t lock ; <nl> - } ; <nl> - cpu_queue_t queues [ MAX_CPUS ] ; <nl> + } queues [ MAX_CPUS ] ; <nl> + <nl> + / / Each notify_fd represents a message from the appropriate cpu <nl> + / / ( denoted by the index in the array ) . We listen for each of <nl> + / / these , and when a cpu wants to notify us it ' s got messages for <nl> + / / us , it should signal the appropriate fd . <nl> + struct notify_t : public linux_epoll_callback_t <nl> + { <nl> + public : <nl> + void on_epoll ( int events ) ; <nl> + <nl> + public : <nl> + int notifier_cpu ; / / the cpu that notifies us it ' s got messages for us <nl> + fd_t fd ; / / the eventfd to call <nl> + linux_message_hub_t * parent ; <nl> + } notify [ MAX_CPUS ] ; <nl> <nl> unsigned int current_cpu ; <nl> } ; <nl>
Modifying the message hub to only pull messages from the cpu that sent it to us , not everyone
rethinkdb/rethinkdb
0936d464dcf6786efea1be7ca6d86b8ab89d630d
2010-10-14T00:48:54Z
mmm a / src / mongo / db / s / config / configsvr_commit_chunk_migration_command . cpp <nl> ppp b / src / mongo / db / s / config / configsvr_commit_chunk_migration_command . cpp <nl> class ConfigSvrCommitChunkMigrationCommand : public Command { <nl> } <nl> <nl> auto applyOpsCommandResponse = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> + Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> txn , <nl> ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> nss . db ( ) . toString ( ) , <nl> mmm a / src / mongo / db / s / migration_source_manager . cpp <nl> ppp b / src / mongo / db / s / migration_source_manager . cpp <nl> Status MigrationSourceManager : : commitDonateChunk ( OperationContext * txn ) { <nl> <nl> MONGO_FAIL_POINT_PAUSE_WHILE_SET ( hangBeforeCommitMigration ) ; <nl> <nl> - auto commitChunkMigrationResponse = <nl> - grid . shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - builder . obj ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto commitChunkMigrationResponse = grid . shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + builder . obj ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( MONGO_FAIL_POINT ( failCommitMigrationCommand ) ) { <nl> commitChunkMigrationResponse = Status ( <nl> mmm a / src / mongo / db / s / split_chunk_command . cpp <nl> ppp b / src / mongo / db / s / split_chunk_command . cpp <nl> class SplitChunkCommand : public Command { <nl> auto configCmdObj = request . toConfigCommandBSON ( <nl> BSON ( WriteConcernOptions : : kWriteConcernField < < WriteConcernOptions : : Majority ) ) ; <nl> <nl> - auto cmdResponseStatus = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - configCmdObj , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto cmdResponseStatus = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + configCmdObj , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> / / <nl> / / Refresh chunk metadata regardless of whether or not the split succeeded <nl> mmm a / src / mongo / s / balancer / balancer . cpp <nl> ppp b / src / mongo / s / balancer / balancer . cpp <nl> bool Balancer : : _checkOIDs ( OperationContext * txn ) { <nl> } <nl> const auto s = shardStatus . getValue ( ) ; <nl> <nl> - auto result = uassertStatusOK ( <nl> - s - > runCommandWithFixedRetryAttempts ( txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - BSON ( " features " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto result = <nl> + uassertStatusOK ( s - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + BSON ( " features " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( result . commandStatus ) ; <nl> BSONObj f = std : : move ( result . response ) ; <nl> <nl> bool Balancer : : _checkOIDs ( OperationContext * txn ) { <nl> log ( ) < < " error : 2 machines have " < < x < < " as oid machine piece : " < < shardId <nl> < < " and " < < oids [ x ] ; <nl> <nl> - result = uassertStatusOK ( s - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - BSON ( " features " < < 1 < < " oidReset " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + result = uassertStatusOK ( <nl> + s - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + BSON ( " features " < < 1 < < " oidReset " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( result . commandStatus ) ; <nl> <nl> auto otherShardStatus = shardingContext - > shardRegistry ( ) - > getShard ( txn , oids [ x ] ) ; <nl> if ( otherShardStatus . isOK ( ) ) { <nl> - result = uassertStatusOK ( <nl> - otherShardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - BSON ( " features " < < 1 < < " oidReset " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + result = uassertStatusOK ( otherShardStatus . getValue ( ) - > runCommand ( <nl> + txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + BSON ( " features " < < 1 < < " oidReset " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( result . commandStatus ) ; <nl> } <nl> <nl> mmm a / src / mongo / s / balancer / cluster_statistics_impl . cpp <nl> ppp b / src / mongo / s / balancer / cluster_statistics_impl . cpp <nl> StatusWith < string > retrieveShardMongoDVersion ( OperationContext * txn , ShardId sha <nl> } <nl> auto shard = shardStatus . getValue ( ) ; <nl> <nl> - auto commandResponse = <nl> - shard - > runCommandWithFixedRetryAttempts ( txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - BSON ( " serverStatus " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto commandResponse = shard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + BSON ( " serverStatus " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! commandResponse . isOK ( ) ) { <nl> return commandResponse . getStatus ( ) ; <nl> } <nl> mmm a / src / mongo / s / catalog / replset / dist_lock_catalog_impl . cpp <nl> ppp b / src / mongo / s / catalog / replset / dist_lock_catalog_impl . cpp <nl> Status DistLockCatalogImpl : : ping ( OperationContext * txn , StringData processID , Da <nl> request . setUpsert ( true ) ; <nl> request . setWriteConcern ( kMajorityWriteConcern ) ; <nl> <nl> - auto resultStatus = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - _locksNS . db ( ) . toString ( ) , <nl> - request . toBSON ( ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> + auto resultStatus = <nl> + _client - > getConfigShard ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + _locksNS . db ( ) . toString ( ) , <nl> + request . toBSON ( ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> <nl> auto findAndModifyStatus = extractFindAndModifyNewObj ( std : : move ( resultStatus ) ) ; <nl> return findAndModifyStatus . getStatus ( ) ; <nl> StatusWith < LocksType > DistLockCatalogImpl : : grabLock ( OperationContext * txn , <nl> request . setShouldReturnNew ( true ) ; <nl> request . setWriteConcern ( kMajorityWriteConcern ) ; <nl> <nl> - auto resultStatus = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> + auto resultStatus = _client - > getConfigShard ( ) - > runCommand ( <nl> txn , <nl> ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> _locksNS . db ( ) . toString ( ) , <nl> StatusWith < LocksType > DistLockCatalogImpl : : overtakeLock ( OperationContext * txn , <nl> request . setShouldReturnNew ( true ) ; <nl> request . setWriteConcern ( kMajorityWriteConcern ) ; <nl> <nl> - auto resultStatus = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - _locksNS . db ( ) . toString ( ) , <nl> - request . toBSON ( ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> + auto resultStatus = <nl> + _client - > getConfigShard ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + _locksNS . db ( ) . toString ( ) , <nl> + request . toBSON ( ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> <nl> auto findAndModifyStatus = extractFindAndModifyNewObj ( std : : move ( resultStatus ) ) ; <nl> if ( ! findAndModifyStatus . isOK ( ) ) { <nl> Status DistLockCatalogImpl : : unlock ( OperationContext * txn , <nl> } <nl> <nl> Status DistLockCatalogImpl : : _unlock ( OperationContext * txn , const FindAndModifyRequest & request ) { <nl> - auto resultStatus = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - _locksNS . db ( ) . toString ( ) , <nl> - request . toBSON ( ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto resultStatus = <nl> + _client - > getConfigShard ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + _locksNS . db ( ) . toString ( ) , <nl> + request . toBSON ( ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> auto findAndModifyStatus = extractFindAndModifyNewObj ( std : : move ( resultStatus ) ) ; <nl> if ( findAndModifyStatus = = ErrorCodes : : LockStateChangeFailed ) { <nl> Status DistLockCatalogImpl : : unlockAll ( OperationContext * txn , const std : : string & <nl> <nl> BSONObj cmdObj = request . toBSON ( ) ; <nl> <nl> - auto response = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - _locksNS . db ( ) . toString ( ) , <nl> - cmdObj , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto response = <nl> + _client - > getConfigShard ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + _locksNS . db ( ) . toString ( ) , <nl> + cmdObj , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! response . isOK ( ) ) { <nl> return response . getStatus ( ) ; <nl> Status DistLockCatalogImpl : : unlockAll ( OperationContext * txn , const std : : string & <nl> } <nl> <nl> StatusWith < DistLockCatalog : : ServerInfo > DistLockCatalogImpl : : getServerInfo ( OperationContext * txn ) { <nl> - auto resultStatus = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - kReadPref , <nl> - " admin " , <nl> - BSON ( " serverStatus " < < 1 ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto resultStatus = _client - > getConfigShard ( ) - > runCommand ( txn , <nl> + kReadPref , <nl> + " admin " , <nl> + BSON ( " serverStatus " < < 1 ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! resultStatus . isOK ( ) ) { <nl> return resultStatus . getStatus ( ) ; <nl> Status DistLockCatalogImpl : : stopPing ( OperationContext * txn , StringData processId <nl> FindAndModifyRequest : : makeRemove ( _lockPingNS , BSON ( LockpingsType : : process ( ) < < processId ) ) ; <nl> request . setWriteConcern ( kMajorityWriteConcern ) ; <nl> <nl> - auto resultStatus = _client - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - _locksNS . db ( ) . toString ( ) , <nl> - request . toBSON ( ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> + auto resultStatus = <nl> + _client - > getConfigShard ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + _locksNS . db ( ) . toString ( ) , <nl> + request . toBSON ( ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> <nl> auto findAndModifyStatus = extractFindAndModifyNewObj ( std : : move ( resultStatus ) ) ; <nl> return findAndModifyStatus . getStatus ( ) ; <nl> mmm a / src / mongo / s / catalog / replset / sharding_catalog_client_impl . cpp <nl> ppp b / src / mongo / s / catalog / replset / sharding_catalog_client_impl . cpp <nl> Status ShardingCatalogClientImpl : : shardCollection ( OperationContext * txn , <nl> } <nl> auto shard = shardStatus . getValue ( ) ; <nl> <nl> - auto ssvResponse = <nl> - shard - > runCommandWithFixedRetryAttempts ( txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - ssv . toBSON ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto ssvResponse = shard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + ssv . toBSON ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> auto status = ssvResponse . isOK ( ) ? std : : move ( ssvResponse . getValue ( ) . commandStatus ) <nl> : std : : move ( ssvResponse . getStatus ( ) ) ; <nl> if ( ! status . isOK ( ) ) { <nl> Status ShardingCatalogClientImpl : : dropCollection ( OperationContext * txn , const Na <nl> if ( ! shardStatus . isOK ( ) ) { <nl> return shardStatus . getStatus ( ) ; <nl> } <nl> - auto dropResult = shardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> + auto dropResult = shardStatus . getValue ( ) - > runCommand ( <nl> txn , <nl> ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> ns . db ( ) . toString ( ) , <nl> Status ShardingCatalogClientImpl : : dropCollection ( OperationContext * txn , const Na <nl> } <nl> auto shard = shardStatus . getValue ( ) ; <nl> <nl> - auto ssvResult = shard - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - ssv . toBSON ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto ssvResult = shard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + ssv . toBSON ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! ssvResult . isOK ( ) ) { <nl> return ssvResult . getStatus ( ) ; <nl> Status ShardingCatalogClientImpl : : dropCollection ( OperationContext * txn , const Na <nl> return ssvStatus ; <nl> } <nl> <nl> - auto unsetShardingStatus = shard - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - BSON ( " unsetSharding " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto unsetShardingStatus = <nl> + shard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + BSON ( " unsetSharding " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! unsetShardingStatus . isOK ( ) ) { <nl> return unsetShardingStatus . getStatus ( ) ; <nl> bool ShardingCatalogClientImpl : : runUserManagementWriteCommand ( OperationContext * <nl> cmdToRun = modifiedCmd . obj ( ) ; <nl> } <nl> <nl> - auto response = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - dbname , <nl> - cmdToRun , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> + auto response = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + dbname , <nl> + cmdToRun , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> <nl> if ( ! response . isOK ( ) ) { <nl> return Command : : appendCommandStatus ( * result , response . getStatus ( ) ) ; <nl> bool ShardingCatalogClientImpl : : runReadCommandForTest ( OperationContext * txn , <nl> cmdBuilder . appendElements ( cmdObj ) ; <nl> _appendReadConcern ( & cmdBuilder ) ; <nl> <nl> - auto resultStatus = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , kConfigReadSelector , dbname , cmdBuilder . done ( ) , Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto resultStatus = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , kConfigReadSelector , dbname , cmdBuilder . done ( ) , Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( resultStatus . isOK ( ) ) { <nl> result - > appendElements ( resultStatus . getValue ( ) . response ) ; <nl> return resultStatus . getValue ( ) . commandStatus . isOK ( ) ; <nl> bool ShardingCatalogClientImpl : : runUserManagementReadCommand ( OperationContext * t <nl> const std : : string & dbname , <nl> const BSONObj & cmdObj , <nl> BSONObjBuilder * result ) { <nl> - auto resultStatus = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - kConfigPrimaryPreferredSelector , <nl> - dbname , <nl> - cmdObj , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto resultStatus = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , <nl> + kConfigPrimaryPreferredSelector , <nl> + dbname , <nl> + cmdObj , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( resultStatus . isOK ( ) ) { <nl> result - > appendElements ( resultStatus . getValue ( ) . response ) ; <nl> return resultStatus . getValue ( ) . commandStatus . isOK ( ) ; <nl> Status ShardingCatalogClientImpl : : applyChunkOpsDeprecated ( OperationContext * txn , <nl> < < WriteConcernOptions : : kWriteConcernField <nl> < < writeConcern . toBSON ( ) ) ; <nl> <nl> - auto response = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " config " , <nl> - cmd , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto response = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " config " , <nl> + cmd , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! response . isOK ( ) ) { <nl> return response . getStatus ( ) ; <nl> Status ShardingCatalogClientImpl : : _createCappedConfigCollection ( <nl> < < WriteConcernOptions : : kWriteConcernField <nl> < < writeConcern . toBSON ( ) ) ; <nl> <nl> - auto result = <nl> - Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " config " , <nl> - createCmd , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto result = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) - > runCommand ( <nl> + txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " config " , <nl> + createCmd , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! result . isOK ( ) ) { <nl> return result . getStatus ( ) ; <nl> StatusWith < long long > ShardingCatalogClientImpl : : _runCountCommandOnConfig ( Operat <nl> _appendReadConcern ( & countBuilder ) ; <nl> <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto resultStatus = <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kConfigReadSelector , <nl> - ns . db ( ) . toString ( ) , <nl> - countBuilder . done ( ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto resultStatus = configShard - > runCommand ( txn , <nl> + kConfigReadSelector , <nl> + ns . db ( ) . toString ( ) , <nl> + countBuilder . done ( ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! resultStatus . isOK ( ) ) { <nl> return resultStatus . getStatus ( ) ; <nl> } <nl> void ShardingCatalogClientImpl : : _appendReadConcern ( BSONObjBuilder * builder ) { <nl> Status ShardingCatalogClientImpl : : appendInfoForConfigServerDatabases ( OperationContext * txn , <nl> BSONArrayBuilder * builder ) { <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto resultStatus = <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kConfigPrimaryPreferredSelector , <nl> - " admin " , <nl> - BSON ( " listDatabases " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto resultStatus = configShard - > runCommand ( txn , <nl> + kConfigPrimaryPreferredSelector , <nl> + " admin " , <nl> + BSON ( " listDatabases " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> <nl> if ( ! resultStatus . isOK ( ) ) { <nl> return resultStatus . getStatus ( ) ; <nl> mmm a / src / mongo / s / chunk_manager . cpp <nl> ppp b / src / mongo / s / chunk_manager . cpp <nl> void ChunkManager : : calcInitSplitsAndShards ( OperationContext * txn , <nl> auto primaryShard = uassertStatusOK ( grid . shardRegistry ( ) - > getShard ( txn , primaryShardId ) ) ; <nl> const NamespaceString nss { getns ( ) } ; <nl> <nl> - auto result = uassertStatusOK ( primaryShard - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> - nss . db ( ) . toString ( ) , <nl> - BSON ( " count " < < nss . coll ( ) ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto result = uassertStatusOK ( <nl> + primaryShard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> + nss . db ( ) . toString ( ) , <nl> + BSON ( " count " < < nss . coll ( ) ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> <nl> long long numObjects = 0 ; <nl> uassertStatusOK ( result . commandStatus ) ; <nl> mmm a / src / mongo / s / client / shard . cpp <nl> ppp b / src / mongo / s / client / shard . cpp <nl> StatusWith < Shard : : CommandResponse > Shard : : runCommand ( OperationContext * txn , <nl> const std : : string & dbName , <nl> const BSONObj & cmdObj , <nl> RetryPolicy retryPolicy ) { <nl> - MONGO_UNREACHABLE ; <nl> + return runCommand ( txn , readPref , dbName , cmdObj , Milliseconds : : max ( ) , retryPolicy ) ; <nl> } <nl> <nl> StatusWith < Shard : : CommandResponse > Shard : : runCommand ( OperationContext * txn , <nl> StatusWith < Shard : : CommandResponse > Shard : : runCommand ( OperationContext * txn , <nl> const BSONObj & cmdObj , <nl> Milliseconds maxTimeMSOverride , <nl> RetryPolicy retryPolicy ) { <nl> - MONGO_UNREACHABLE ; <nl> - } <nl> - <nl> - StatusWith < Shard : : CommandResponse > Shard : : runCommandWithFixedRetryAttempts ( <nl> - OperationContext * txn , <nl> - const ReadPreferenceSetting & readPref , <nl> - const std : : string & dbName , <nl> - const BSONObj & cmdObj , <nl> - RetryPolicy retryPolicy ) { <nl> - return runCommandWithFixedRetryAttempts ( <nl> - txn , readPref , dbName , cmdObj , Milliseconds : : max ( ) , retryPolicy ) ; <nl> - } <nl> - <nl> - StatusWith < Shard : : CommandResponse > Shard : : runCommandWithFixedRetryAttempts ( <nl> - OperationContext * txn , <nl> - const ReadPreferenceSetting & readPref , <nl> - const std : : string & dbName , <nl> - const BSONObj & cmdObj , <nl> - Milliseconds maxTimeMSOverride , <nl> - RetryPolicy retryPolicy ) { <nl> for ( int retry = 1 ; retry < = kOnErrorNumRetries ; + + retry ) { <nl> auto hostWithResponse = _runCommand ( txn , readPref , dbName , maxTimeMSOverride , cmdObj ) ; <nl> auto swCmdResponse = std : : move ( hostWithResponse . commandResponse ) ; <nl> mmm a / src / mongo / s / client / shard . h <nl> ppp b / src / mongo / s / client / shard . h <nl> class Shard { <nl> Milliseconds maxTimeMSOverride , <nl> RetryPolicy retryPolicy ) ; <nl> <nl> - / * * <nl> - * Same as runCommand , but will only retry failed operations up to 3 times , regardless of <nl> - * the retryPolicy or the remaining maxTimeMs . <nl> - * Wherever possible this method should be avoided in favor of runCommand . <nl> - * / <nl> - StatusWith < CommandResponse > runCommandWithFixedRetryAttempts ( <nl> - OperationContext * txn , <nl> - const ReadPreferenceSetting & readPref , <nl> - const std : : string & dbName , <nl> - const BSONObj & cmdObj , <nl> - RetryPolicy retryPolicy ) ; <nl> - <nl> - / * * <nl> - * Same as runCommand , but will only retry failed operations up to 3 times , regardless of <nl> - * the retryPolicy or the remaining maxTimeMs . <nl> - * Wherever possible this method should be avoided in favor of runCommand . <nl> - * / <nl> - StatusWith < CommandResponse > runCommandWithFixedRetryAttempts ( <nl> - OperationContext * txn , <nl> - const ReadPreferenceSetting & readPref , <nl> - const std : : string & dbName , <nl> - const BSONObj & cmdObj , <nl> - Milliseconds maxTimeMSOverride , <nl> - RetryPolicy retryPolicy ) ; <nl> - <nl> / * * <nl> * Expects a single - entry batch wrtie command and runs it on the config server ' s primary using <nl> * the specified retry policy . <nl> mmm a / src / mongo / s / client / shard_local_test . cpp <nl> ppp b / src / mongo / s / client / shard_local_test . cpp <nl> StatusWith < Shard : : CommandResponse > ShardLocalTest : : runFindAndModifyRunCommand ( Na <nl> findAndModifyRequest . setWriteConcern ( WriteConcernOptions ( <nl> WriteConcernOptions : : kMajority , WriteConcernOptions : : SyncMode : : UNSET , Seconds ( 15 ) ) ) ; <nl> <nl> - return _shardLocal - > runCommandWithFixedRetryAttempts ( <nl> - _txn . get ( ) , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - nss . db ( ) . toString ( ) , <nl> - findAndModifyRequest . toBSON ( ) , <nl> - Shard : : RetryPolicy : : kNoRetry ) ; <nl> + return _shardLocal - > runCommand ( _txn . get ( ) , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + nss . db ( ) . toString ( ) , <nl> + findAndModifyRequest . toBSON ( ) , <nl> + Shard : : RetryPolicy : : kNoRetry ) ; <nl> } <nl> <nl> StatusWith < std : : vector < BSONObj > > ShardLocalTest : : getIndexes ( NamespaceString nss ) { <nl> - auto response = _shardLocal - > runCommandWithFixedRetryAttempts ( <nl> - _txn . get ( ) , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - nss . db ( ) . toString ( ) , <nl> - BSON ( " listIndexes " < < nss . coll ( ) . toString ( ) ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto response = _shardLocal - > runCommand ( _txn . get ( ) , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + nss . db ( ) . toString ( ) , <nl> + BSON ( " listIndexes " < < nss . coll ( ) . toString ( ) ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! response . isOK ( ) ) { <nl> return response . getStatus ( ) ; <nl> } <nl> mmm a / src / mongo / s / commands / cluster_add_shard_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_add_shard_cmd . cpp <nl> class AddShardCmd : public Command { <nl> auto parsedRequest = uassertStatusOK ( AddShardRequest : : parseFromMongosCommand ( cmdObj ) ) ; <nl> <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto cmdResponseStatus = uassertStatusOK ( <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - parsedRequest . toCommandForConfig ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto cmdResponseStatus = <nl> + uassertStatusOK ( configShard - > runCommand ( txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + parsedRequest . toCommandForConfig ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( cmdResponseStatus . commandStatus ) ; <nl> <nl> string shardAdded ; <nl> mmm a / src / mongo / s / commands / cluster_add_shard_to_zone_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_add_shard_to_zone_cmd . cpp <nl> class AddShardToZoneCmd : public Command { <nl> cmdBuilder . append ( " writeConcern " , kMajorityWriteConcern . toBSON ( ) ) ; <nl> <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto cmdResponseStatus = uassertStatusOK ( <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - cmdBuilder . obj ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto cmdResponseStatus = <nl> + uassertStatusOK ( configShard - > runCommand ( txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + cmdBuilder . obj ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( cmdResponseStatus . commandStatus ) ; <nl> return true ; <nl> } <nl> mmm a / src / mongo / s / commands / cluster_control_balancer_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_control_balancer_cmd . cpp <nl> class BalancerControlCommand : public Command { <nl> std : : string & errmsg , <nl> BSONObjBuilder & result ) override { <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto cmdResponse = uassertStatusOK ( <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - BSON ( _configsvrCommandName < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto cmdResponse = <nl> + uassertStatusOK ( configShard - > runCommand ( txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + BSON ( _configsvrCommandName < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( cmdResponse . commandStatus ) ; <nl> <nl> / / Append any return value from the response , which the config server returned <nl> mmm a / src / mongo / s / commands / cluster_fsync_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_fsync_cmd . cpp <nl> class FsyncCommand : public Command { <nl> } <nl> const auto s = shardStatus . getValue ( ) ; <nl> <nl> - auto response = uassertStatusOK ( s - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - BSON ( " fsync " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto response = <nl> + uassertStatusOK ( s - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + BSON ( " fsync " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( response . commandStatus ) ; <nl> BSONObj x = std : : move ( response . response ) ; <nl> <nl> mmm a / src / mongo / s / commands / cluster_list_databases_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_list_databases_cmd . cpp <nl> class ListDatabasesCmd : public Command { <nl> } <nl> const auto s = shardStatus . getValue ( ) ; <nl> <nl> - auto response = uassertStatusOK ( s - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> - " admin " , <nl> - BSON ( " listDatabases " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto response = uassertStatusOK ( <nl> + s - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> + " admin " , <nl> + BSON ( " listDatabases " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( response . commandStatus ) ; <nl> BSONObj x = std : : move ( response . response ) ; <nl> <nl> mmm a / src / mongo / s / commands / cluster_remove_shard_from_zone_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_remove_shard_from_zone_cmd . cpp <nl> class RemoveShardFromZoneCmd : public Command { <nl> cmdBuilder . append ( " writeConcern " , kMajorityWriteConcern . toBSON ( ) ) ; <nl> <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto cmdResponseStatus = uassertStatusOK ( <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - cmdBuilder . obj ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto cmdResponseStatus = <nl> + uassertStatusOK ( configShard - > runCommand ( txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + cmdBuilder . obj ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( cmdResponseStatus . commandStatus ) ; <nl> return true ; <nl> } <nl> mmm a / src / mongo / s / commands / cluster_set_feature_compatibility_version_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_set_feature_compatibility_version_cmd . cpp <nl> class SetFeatureCompatibilityVersionCmd : public Command { <nl> <nl> / / Forward to config shard , which will forward to all shards . <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto response = configShard - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - dbname , <nl> - BSON ( " _configsvrSetFeatureCompatibilityVersion " < < version ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto response = <nl> + configShard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + dbname , <nl> + BSON ( " _configsvrSetFeatureCompatibilityVersion " < < version ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> uassertStatusOK ( response ) ; <nl> uassertStatusOK ( response . getValue ( ) . commandStatus ) ; <nl> <nl> mmm a / src / mongo / s / commands / cluster_update_zone_key_range_cmd . cpp <nl> ppp b / src / mongo / s / commands / cluster_update_zone_key_range_cmd . cpp <nl> class UpdateZoneKeyRangeCmd : public Command { <nl> cmdBuilder . append ( " writeConcern " , kMajorityWriteConcern . toBSON ( ) ) ; <nl> <nl> auto configShard = Grid : : get ( txn ) - > shardRegistry ( ) - > getConfigShard ( ) ; <nl> - auto cmdResponseStatus = uassertStatusOK ( <nl> - configShard - > runCommandWithFixedRetryAttempts ( txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - cmdBuilder . obj ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> + auto cmdResponseStatus = <nl> + uassertStatusOK ( configShard - > runCommand ( txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + cmdBuilder . obj ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ) ; <nl> uassertStatusOK ( cmdResponseStatus . commandStatus ) ; <nl> return true ; <nl> } <nl> mmm a / src / mongo / s / commands / cluster_user_management_commands . cpp <nl> ppp b / src / mongo / s / commands / cluster_user_management_commands . cpp <nl> Status runUpgradeOnAllShards ( OperationContext * txn , int maxSteps , BSONObjBuilder <nl> if ( ! shardStatus . isOK ( ) ) { <nl> return shardStatus . getStatus ( ) ; <nl> } <nl> - auto cmdResult = shardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - cmdObj , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto cmdResult = <nl> + shardStatus . getValue ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + cmdObj , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> auto status = cmdResult . isOK ( ) ? std : : move ( cmdResult . getValue ( ) . commandStatus ) <nl> : std : : move ( cmdResult . getStatus ( ) ) ; <nl> if ( ! status . isOK ( ) ) { <nl> mmm a / src / mongo / s / config_server_client . cpp <nl> ppp b / src / mongo / s / config_server_client . cpp <nl> Status moveChunk ( OperationContext * txn , <nl> bool waitForDelete ) { <nl> auto shardRegistry = Grid : : get ( txn ) - > shardRegistry ( ) ; <nl> auto shard = shardRegistry - > getConfigShard ( ) ; <nl> - auto cmdResponseStatus = shard - > runCommandWithFixedRetryAttempts ( <nl> + auto cmdResponseStatus = shard - > runCommand ( <nl> txn , <nl> kPrimaryOnlyReadPreference , <nl> " admin " , <nl> Status moveChunk ( OperationContext * txn , <nl> Status rebalanceChunk ( OperationContext * txn , const ChunkType & chunk ) { <nl> auto shardRegistry = Grid : : get ( txn ) - > shardRegistry ( ) ; <nl> auto shard = shardRegistry - > getConfigShard ( ) ; <nl> - auto cmdResponseStatus = shard - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - kPrimaryOnlyReadPreference , <nl> - " admin " , <nl> - BalanceChunkRequest : : serializeToRebalanceCommandForConfig ( chunk ) , <nl> - Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> + auto cmdResponseStatus = <nl> + shard - > runCommand ( txn , <nl> + kPrimaryOnlyReadPreference , <nl> + " admin " , <nl> + BalanceChunkRequest : : serializeToRebalanceCommandForConfig ( chunk ) , <nl> + Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> if ( ! cmdResponseStatus . isOK ( ) ) { <nl> return cmdResponseStatus . getStatus ( ) ; <nl> } <nl> mmm a / src / mongo / s / config_server_test_fixture . cpp <nl> ppp b / src / mongo / s / config_server_test_fixture . cpp <nl> Status ConfigServerTestFixture : : insertToConfigCollection ( OperationContext * txn , <nl> auto config = getConfigShard ( ) ; <nl> invariant ( config ) ; <nl> <nl> - auto insertResponse = <nl> - config - > runCommandWithFixedRetryAttempts ( txn , <nl> - kReadPref , <nl> - ns . db ( ) . toString ( ) , <nl> - request . toBSON ( ) , <nl> - Shard : : kDefaultConfigCommandTimeout , <nl> - Shard : : RetryPolicy : : kNoRetry ) ; <nl> + auto insertResponse = config - > runCommand ( txn , <nl> + kReadPref , <nl> + ns . db ( ) . toString ( ) , <nl> + request . toBSON ( ) , <nl> + Shard : : kDefaultConfigCommandTimeout , <nl> + Shard : : RetryPolicy : : kNoRetry ) ; <nl> <nl> BatchedCommandResponse batchResponse ; <nl> auto status = Shard : : CommandResponse : : processBatchWriteResponse ( insertResponse , & batchResponse ) ; <nl> StatusWith < std : : vector < BSONObj > > ConfigServerTestFixture : : getIndexes ( OperationCo <nl> const NamespaceString & ns ) { <nl> auto configShard = getConfigShard ( ) ; <nl> <nl> - auto response = configShard - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - ns . db ( ) . toString ( ) , <nl> - BSON ( " listIndexes " < < ns . coll ( ) . toString ( ) ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto response = configShard - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + ns . db ( ) . toString ( ) , <nl> + BSON ( " listIndexes " < < ns . coll ( ) . toString ( ) ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! response . isOK ( ) ) { <nl> return response . getStatus ( ) ; <nl> } <nl> mmm a / src / mongo / s / shard_util . cpp <nl> ppp b / src / mongo / s / shard_util . cpp <nl> StatusWith < long long > retrieveTotalShardSize ( OperationContext * txn , const ShardI <nl> return shardStatus . getStatus ( ) ; <nl> } <nl> <nl> - auto listDatabasesStatus = shardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> - " admin " , <nl> - BSON ( " listDatabases " < < 1 ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto listDatabasesStatus = <nl> + shardStatus . getValue ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> + " admin " , <nl> + BSON ( " listDatabases " < < 1 ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! listDatabasesStatus . isOK ( ) ) { <nl> return std : : move ( listDatabasesStatus . getStatus ( ) ) ; <nl> } <nl> StatusWith < BSONObj > selectMedianKey ( OperationContext * txn , <nl> return shardStatus . getStatus ( ) ; <nl> } <nl> <nl> - auto cmdStatus = shardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> - " admin " , <nl> - cmd . obj ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto cmdStatus = <nl> + shardStatus . getValue ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> + " admin " , <nl> + cmd . obj ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! cmdStatus . isOK ( ) ) { <nl> return std : : move ( cmdStatus . getStatus ( ) ) ; <nl> } <nl> StatusWith < std : : vector < BSONObj > > selectChunkSplitPoints ( OperationContext * txn , <nl> return shardStatus . getStatus ( ) ; <nl> } <nl> <nl> - auto cmdStatus = shardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> - " admin " , <nl> - cmd . obj ( ) , <nl> - Shard : : RetryPolicy : : kIdempotent ) ; <nl> + auto cmdStatus = <nl> + shardStatus . getValue ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryPreferred } , <nl> + " admin " , <nl> + cmd . obj ( ) , <nl> + Shard : : RetryPolicy : : kIdempotent ) ; <nl> if ( ! cmdStatus . isOK ( ) ) { <nl> return std : : move ( cmdStatus . getStatus ( ) ) ; <nl> } <nl> StatusWith < boost : : optional < ChunkRange > > splitChunkAtMultiplePoints ( <nl> if ( ! shardStatus . isOK ( ) ) { <nl> status = shardStatus . getStatus ( ) ; <nl> } else { <nl> - auto cmdStatus = shardStatus . getValue ( ) - > runCommandWithFixedRetryAttempts ( <nl> - txn , <nl> - ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> - " admin " , <nl> - cmdObj , <nl> - Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> + auto cmdStatus = <nl> + shardStatus . getValue ( ) - > runCommand ( txn , <nl> + ReadPreferenceSetting { ReadPreference : : PrimaryOnly } , <nl> + " admin " , <nl> + cmdObj , <nl> + Shard : : RetryPolicy : : kNotIdempotent ) ; <nl> if ( ! cmdStatus . isOK ( ) ) { <nl> status = std : : move ( cmdStatus . getStatus ( ) ) ; <nl> } else { <nl>
Revert " SERVER - 25832 Rename Shard : : runCommand to Shard : : runCommandWithFixedRetryAttempts "
mongodb/mongo
f21afe8e60b5ab6f061613c3ee0f8ff9896e881a
2016-08-27T03:32:30Z
mmm a / buildscripts / resmokeconfig / suites / sharding_last_stable_mongos_and_mixed_shards . yml <nl> ppp b / buildscripts / resmokeconfig / suites / sharding_last_stable_mongos_and_mixed_shards . yml <nl> selector : <nl> - jstests / sharding / safe_secondary_reads_single_migration_suspend_range_deletion . js <nl> - jstests / sharding / safe_secondary_reads_single_migration_waitForDelete . js <nl> - jstests / sharding / secondary_shard_versioning . js <nl> + - jstests / sharding / secondary_shard_version_protocol_with_causal_consistency . js <nl> - jstests / sharding / session_info_in_oplog . js <nl> - jstests / sharding / enable_sharding_basic . js <nl> - jstests / sharding / retryable_writes . js <nl> mmm a / jstests / sharding / safe_secondary_reads_drop_recreate . js <nl> ppp b / jstests / sharding / safe_secondary_reads_drop_recreate . js <nl> <nl> / * * <nl> - * Tests that commands that can be sent to secondaries for sharded collections are " safe " : <nl> - * - the secondary participates in the shard versioning protocol <nl> - * - the secondary filters returned documents using its routing table cache . <nl> + * Tests that commands that can be sent to secondaries for sharded collections can be " safe " : <nl> + * - When non - ' available ' read concern is specified ( local in this case ) , the secondary participates <nl> + * in the shard versioning protocol and filters returned documents using its routing table cache . <nl> * <nl> * Since some commands are unversioned even against primaries or cannot be run on sharded <nl> * collections , this file declaratively defines the expected behavior for each command . <nl> <nl> st . rs0 . getPrimary ( ) . getDB ( ' admin ' ) . runCommand ( { forceRoutingTableRefresh : nss } ) ) ; <nl> st . rs0 . awaitReplication ( ) ; <nl> <nl> - let res = staleMongos . getDB ( db ) . runCommand ( <nl> - Object . assign ( { } , test . command , { $ readPreference : { mode : ' secondary ' } } ) ) ; <nl> + let res = staleMongos . getDB ( db ) . runCommand ( Object . assign ( <nl> + { } , <nl> + test . command , <nl> + { $ readPreference : { mode : ' secondary ' } , readConcern : { ' level ' : ' local ' } } ) ) ; <nl> <nl> test . checkResults ( res ) ; <nl> <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : false } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> st . rs0 . getPrimary ( ) . getDB ( ' admin ' ) . runCommand ( { forceRoutingTableRefresh : nss } ) ) ; <nl> st . rs0 . awaitReplication ( ) ; <nl> <nl> - let res = staleMongos . getDB ( db ) . runCommand ( <nl> - Object . assign ( { } , test . command , { $ readPreference : { mode : ' secondary ' } } ) ) ; <nl> + let res = staleMongos . getDB ( db ) . runCommand ( Object . assign ( <nl> + { } , <nl> + test . command , <nl> + { $ readPreference : { mode : ' secondary ' } , readConcern : { ' level ' : ' local ' } } ) ) ; <nl> <nl> test . checkResults ( res ) ; <nl> <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : false } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> writeConcern : { w : 2 } , <nl> } ) ) ; <nl> <nl> - let res = staleMongos . getDB ( db ) . runCommand ( <nl> - Object . assign ( { } , test . command , { $ readPreference : { mode : ' secondary ' } } ) ) ; <nl> + let res = staleMongos . getDB ( db ) . runCommand ( Object . assign ( <nl> + { } , <nl> + test . command , <nl> + { $ readPreference : { mode : ' secondary ' } , readConcern : { ' level ' : ' local ' } } ) ) ; <nl> <nl> test . checkResults ( res ) ; <nl> <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : false } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> mmm a / jstests / sharding / safe_secondary_reads_single_migration_suspend_range_deletion . js <nl> ppp b / jstests / sharding / safe_secondary_reads_single_migration_suspend_range_deletion . js <nl> <nl> / * * <nl> - * Tests that commands that can be sent to secondaries for sharded collections are " safe " : <nl> - * - the secondary participates in the shard versioning protocol <nl> - * - the secondary filters returned documents using its routing table cache . <nl> + * Tests that commands that can be sent to secondaries for sharded collections can be " safe " : <nl> + * - When non - ' available ' read concern is specified ( local in this case ) , the secondary participates <nl> + * in the shard versioning protocol and filters returned documents using its routing table cache . <nl> + * - When ' available ' read concern is specified , the secondary does not check shard version nor <nl> + * filters results . <nl> + * - When no read concern is specified , the secondary defaults to ' available ' read concern . <nl> * <nl> * Since some commands are unversioned even against primaries or cannot be run on sharded <nl> * collections , this file declaratively defines the expected behavior for each command . <nl> <nl> JSON . parse ( JSON . stringify ( cmdReadPreferenceSecondary ) ) ; <nl> Object . extend ( cmdPrefSecondaryConcernAvailable , { readConcern : { level : ' available ' } } ) ; <nl> <nl> + / / Make a read preference secondary and read concern ' local ' copy of the command . <nl> + let cmdPrefSecondaryConcernLocal = JSON . parse ( JSON . stringify ( cmdReadPreferenceSecondary ) ) ; <nl> + Object . extend ( cmdPrefSecondaryConcernLocal , { readConcern : { level : ' local ' } } ) ; <nl> + <nl> let availableReadConcernRes = <nl> staleMongos . getDB ( db ) . runCommand ( cmdPrefSecondaryConcernAvailable ) ; <nl> test . checkAvailableReadConcernResults ( availableReadConcernRes ) ; <nl> <nl> - let res = staleMongos . getDB ( db ) . runCommand ( cmdReadPreferenceSecondary ) ; <nl> - test . checkResults ( res ) ; <nl> + / / A request sent to a secondary without read concern defaults to ' available ' read concern . <nl> + let defaultReadConcernRes = staleMongos . getDB ( db ) . runCommand ( cmdReadPreferenceSecondary ) ; <nl> + test . checkAvailableReadConcernResults ( defaultReadConcernRes ) ; <nl> + <nl> + let localReadConcernRes = staleMongos . getDB ( db ) . runCommand ( cmdPrefSecondaryConcernLocal ) ; <nl> + test . checkResults ( localReadConcernRes ) ; <nl> <nl> / / Build the query to identify the command in the system profiler . <nl> let commandProfile = buildCommandProfile ( test . command ) ; <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : false } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> - " command . readConcern " : { " $ exists " : false } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> profilerHasZeroMatchingEntriesOrThrow ( <nl> { profileDB : recipientShardSecondary . getDB ( db ) , filter : commandProfile } ) ; <nl> } else if ( test . behavior = = = " versioned " ) { <nl> - / / Check that the donor shard secondary received the ' available ' read concern request <nl> - / / and returned success , despite the mongos ' stale routing table . <nl> + / / Check that the donor shard secondary received both the ' available ' read concern <nl> + / / request and read concern not specified request and returned success for both , despite <nl> + / / the mongos ' stale routing table . <nl> profilerHasSingleMatchingEntryOrThrow ( { <nl> profileDB : donorShardSecondary . getDB ( db ) , <nl> filter : Object . extend ( { <nl> <nl> } , <nl> commandProfile ) <nl> } ) ; <nl> - <nl> - / / Check that the donor shard secondary then returned stale shardVersion for the regular <nl> - / / request ( sans ' available ' read concern ) . <nl> profilerHasSingleMatchingEntryOrThrow ( { <nl> profileDB : donorShardSecondary . getDB ( db ) , <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> " command . readConcern " : { " $ exists " : false } , <nl> + " exceptionCode " : { " $ exists " : false } <nl> + } , <nl> + commandProfile ) <nl> + } ) ; <nl> + <nl> + / / Check that the donor shard secondary then returned stale shardVersion for the request <nl> + / / with local read concern . <nl> + profilerHasSingleMatchingEntryOrThrow ( { <nl> + profileDB : donorShardSecondary . getDB ( db ) , <nl> + filter : Object . extend ( { <nl> + " command . shardVersion " : { " $ exists " : true } , <nl> + " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> } ) ; <nl> <nl> - / / Check that the recipient shard secondary received the regular request and also <nl> - / / returned stale shardVersion once , even though the mongos is fresh , because the <nl> - / / secondary was stale . <nl> + / / Check that the recipient shard secondary received the request with local read concern <nl> + / / and also returned stale shardVersion once , even though the mongos is fresh , because <nl> + / / the secondary was stale . <nl> profilerHasSingleMatchingEntryOrThrow ( { <nl> profileDB : recipientShardSecondary . getDB ( db ) , <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> - " command . readConcern " : { " $ exists " : false } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> } ) ; <nl> <nl> - / / Check that the recipient shard secondary received the regular request again and <nl> - / / finally returned success . <nl> + / / Check that the recipient shard secondary received the request with local read concern <nl> + / / again and finally returned success . <nl> profilerHasSingleMatchingEntryOrThrow ( { <nl> profileDB : recipientShardSecondary . getDB ( db ) , <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> - " command . readConcern " : { " $ exists " : false } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> mmm a / jstests / sharding / safe_secondary_reads_single_migration_waitForDelete . js <nl> ppp b / jstests / sharding / safe_secondary_reads_single_migration_waitForDelete . js <nl> <nl> / * * <nl> - * Tests that commands that can be sent to secondaries for sharded collections are " safe " : <nl> - * - the secondary participates in the shard versioning protocol <nl> - * - the secondary filters returned documents using its routing table cache . <nl> + * Tests that commands that can be sent to secondaries for sharded collections can be " safe " : <nl> + * - When non - ' available ' read concern is specified ( local in this case ) , the secondary participates <nl> + * in the shard versioning protocol and filters returned documents using its routing table cache . <nl> * <nl> * Since some commands are unversioned even against primaries or cannot be run on sharded <nl> * collections , this file declaratively defines the expected behavior for each command . <nl> <nl> writeConcern : { w : 2 } , <nl> } ) ) ; <nl> <nl> - let res = staleMongos . getDB ( db ) . runCommand ( <nl> - Object . extend ( test . command , { $ readPreference : { mode : ' secondary ' } } ) ) ; <nl> + let res = staleMongos . getDB ( db ) . runCommand ( Object . extend ( <nl> + test . command , { $ readPreference : { mode : ' secondary ' } , readConcern : { ' level ' : ' local ' } } ) ) ; <nl> <nl> test . checkResults ( res ) ; <nl> <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : false } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } , <nl> commandProfile ) <nl> <nl> filter : Object . extend ( { <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } , <nl> commandProfile ) <nl> new file mode 100644 <nl> index 000000000000 . . d344032102aa <nl> mmm / dev / null <nl> ppp b / jstests / sharding / secondary_shard_version_protocol_with_causal_consistency . js <nl> <nl> + / * * <nl> + * Tests the shard version protocol on secondaries with causal consistency . A secondary request with <nl> + * read concern level ' available ' and afterClusterTime specified should error because they ensure <nl> + * contradictory things . A secondary request with afterClusterTime specified and no read concern <nl> + * level should default to ' local ' read concern level , using the shard version protocol . <nl> + * / <nl> + ( function ( ) { <nl> + " use strict " ; <nl> + <nl> + load ( ' jstests / libs / profiler . js ' ) ; / / for profilerHasSingleMatchingEntryOrThrow ( ) <nl> + <nl> + / / Set the secondaries to priority 0 and votes 0 to prevent the primaries from stepping down . <nl> + let rsOpts = { nodes : [ { rsConfig : { votes : 1 } } , { rsConfig : { priority : 0 , votes : 0 } } ] } ; <nl> + let st = <nl> + new ShardingTest ( { mongos : 2 , shards : { rs0 : rsOpts , rs1 : rsOpts } , causallyConsistent : true } ) ; <nl> + let dbName = ' test ' , collName = ' foo ' , ns = ' test . foo ' ; <nl> + <nl> + assert . commandWorked ( st . s0 . adminCommand ( { enableSharding : dbName } ) ) ; <nl> + st . ensurePrimaryShard ( dbName , st . shard0 . shardName ) ; <nl> + <nl> + assert . commandWorked ( st . s0 . adminCommand ( { shardCollection : ns , key : { x : 1 } } ) ) ; <nl> + assert . commandWorked ( st . s0 . adminCommand ( { split : ns , middle : { x : 0 } } ) ) ; <nl> + <nl> + let freshMongos = st . s0 ; <nl> + let staleMongos = st . s1 ; <nl> + <nl> + jsTest . log ( " do insert from stale mongos to make it load the routing table before the move " ) ; <nl> + assert . writeOK ( staleMongos . getCollection ( ns ) . insert ( { x : 1 } ) ) ; <nl> + <nl> + jsTest . log ( " do moveChunk from fresh mongos " ) ; <nl> + assert . commandWorked ( freshMongos . adminCommand ( { <nl> + moveChunk : ns , <nl> + find : { x : 0 } , <nl> + to : st . shard1 . shardName , <nl> + secondaryThrottle : true , <nl> + _waitForDelete : true , <nl> + writeConcern : { w : 2 } , <nl> + } ) ) ; <nl> + <nl> + / / Turn on system profiler on secondaries to collect data on all future operations on the db . <nl> + let donorShardSecondary = st . rs0 . getSecondary ( ) ; <nl> + let recipientShardSecondary = st . rs1 . getSecondary ( ) ; <nl> + assert . commandWorked ( donorShardSecondary . getDB ( dbName ) . setProfilingLevel ( 2 ) ) ; <nl> + assert . commandWorked ( recipientShardSecondary . getDB ( dbName ) . setProfilingLevel ( 2 ) ) ; <nl> + <nl> + / / Note : this query will not be registered by the profiler because it errors before reaching the <nl> + / / storage level . <nl> + jsTest . log ( " Do a secondary read from stale mongos with afterClusterTime and level ' available ' " ) ; <nl> + assert . commandFailedWithCode ( staleMongos . getDB ( dbName ) . runCommand ( { <nl> + count : collName , <nl> + query : { x : 1 } , <nl> + $ readPreference : { mode : " secondary " } , <nl> + readConcern : { ' afterClusterTime ' : staleMongos . getOperationTime ( ) , ' level ' : ' available ' } <nl> + } ) , <nl> + ErrorCodes . InvalidOptions ) ; <nl> + <nl> + jsTest . log ( " Do a secondary read from stale mongos with afterClusterTime and no level " ) ; <nl> + let res = staleMongos . getDB ( ' test ' ) . runCommand ( { <nl> + count : collName , <nl> + query : { x : 1 } , <nl> + $ readPreference : { mode : " secondary " } , <nl> + readConcern : { ' afterClusterTime ' : staleMongos . getOperationTime ( ) } , <nl> + } ) ; <nl> + assert ( res . ok ) ; <nl> + assert . eq ( 1 , res . n , tojson ( res ) ) ; <nl> + <nl> + / / The stale mongos will first go to the donor shard and receive a stale shard version , <nl> + / / prompting the stale mongos to refresh it ' s routing table and retarget to the recipient shard . <nl> + profilerHasSingleMatchingEntryOrThrow ( { <nl> + profileDB : donorShardSecondary . getDB ( dbName ) , <nl> + filter : { <nl> + " ns " : ns , <nl> + " command . count " : collName , <nl> + " command . query " : { x : 1 } , <nl> + " command . shardVersion " : { " $ exists " : true } , <nl> + " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern . afterClusterTime " : { " $ exists " : true } , <nl> + " exceptionCode " : ErrorCodes . StaleConfig <nl> + } <nl> + } ) ; <nl> + <nl> + / / The recipient shard will then return a stale shard version error because it needs to refresh <nl> + / / its own routing table . <nl> + profilerHasSingleMatchingEntryOrThrow ( { <nl> + profileDB : recipientShardSecondary . getDB ( dbName ) , <nl> + filter : { <nl> + " ns " : ns , <nl> + " command . count " : collName , <nl> + " command . query " : { x : 1 } , <nl> + " command . shardVersion " : { " $ exists " : true } , <nl> + " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern . afterClusterTime " : { " $ exists " : true } , <nl> + " exceptionCode " : ErrorCodes . StaleConfig <nl> + } <nl> + } ) ; <nl> + <nl> + / / Finally , the command is retried on the recipient shard and succeeds . <nl> + profilerHasSingleMatchingEntryOrThrow ( { <nl> + profileDB : recipientShardSecondary . getDB ( dbName ) , <nl> + filter : { <nl> + " ns " : ns , <nl> + " command . count " : collName , <nl> + " command . query " : { x : 1 } , <nl> + " command . shardVersion " : { " $ exists " : true } , <nl> + " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern . afterClusterTime " : { " $ exists " : true } , <nl> + " exceptionCode " : { " $ exists " : false } <nl> + } <nl> + } ) ; <nl> + <nl> + st . stop ( ) ; <nl> + } ) ( ) ; <nl> mmm a / jstests / sharding / secondary_shard_versioning . js <nl> ppp b / jstests / sharding / secondary_shard_versioning . js <nl> <nl> assert . commandWorked ( donorShardSecondary . getDB ( ' test ' ) . setProfilingLevel ( 2 ) ) ; <nl> assert . commandWorked ( recipientShardSecondary . getDB ( ' test ' ) . setProfilingLevel ( 2 ) ) ; <nl> <nl> - / / Use the mongos with the stale routing table to send read requests to the secondaries . Check <nl> - / / that the donor shard returns a stale shardVersion error , which provokes mongos to refresh its <nl> - / / routing table and re - target ; that the recipient shard secondary refreshes its routing table <nl> - / / on hearing the fresh version from mongos ; and that the recipient shard secondary returns <nl> - / / the results . <nl> + / / Use the mongos with the stale routing table to send read requests to the secondaries . ' local ' <nl> + / / read concern level must be specified in the request because secondaries default to <nl> + / / ' available ' , which doesn ' t participate in the version protocol . Check that the donor shard <nl> + / / returns a stale shardVersion error , which provokes mongos to refresh its routing table and <nl> + / / re - target ; that the recipient shard secondary refreshes its routing table on hearing the <nl> + / / fresh version from mongos ; and that the recipient shard secondary returns the results . <nl> <nl> jsTest . log ( " do secondary read from stale mongos " ) ; <nl> - let res = staleMongos . getDB ( ' test ' ) . runCommand ( <nl> - { count : ' foo ' , query : { x : 1 } , $ readPreference : { mode : " secondary " } } ) ; <nl> + let res = staleMongos . getDB ( ' test ' ) . runCommand ( { <nl> + count : ' foo ' , <nl> + query : { x : 1 } , <nl> + $ readPreference : { mode : " secondary " } , <nl> + readConcern : { " level " : " local " } <nl> + } ) ; <nl> assert ( res . ok ) ; <nl> assert . eq ( 1 , res . n , tojson ( res ) ) ; <nl> <nl> <nl> " command . query " : { x : 1 } , <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } <nl> } ) ; <nl> <nl> " command . query " : { x : 1 } , <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : ErrorCodes . StaleConfig <nl> } <nl> } ) ; <nl> <nl> " command . query " : { x : 1 } , <nl> " command . shardVersion " : { " $ exists " : true } , <nl> " command . $ readPreference " : { " mode " : " secondary " } , <nl> + " command . readConcern " : { " level " : " local " } , <nl> " exceptionCode " : { " $ exists " : false } <nl> } <nl> } ) ; <nl> mmm a / src / mongo / db / repl / read_concern_args . cpp <nl> ppp b / src / mongo / db / repl / read_concern_args . cpp <nl> ReadConcernLevel ReadConcernArgs : : getLevel ( ) const { <nl> return _level . value_or ( ReadConcernLevel : : kLocalReadConcern ) ; <nl> } <nl> <nl> + bool ReadConcernArgs : : hasLevel ( ) const { <nl> + return _level . is_initialized ( ) ; <nl> + } <nl> + <nl> + bool ReadConcernArgs : : isLevelAvailable ( ) const { <nl> + return hasLevel ( ) & & _level . get ( ) = = ReadConcernLevel : : kAvailableReadConcern ; <nl> + } <nl> + <nl> boost : : optional < OpTime > ReadConcernArgs : : getArgsOpTime ( ) const { <nl> return _opTime ; <nl> } <nl> mmm a / src / mongo / db / repl / read_concern_args . h <nl> ppp b / src / mongo / db / repl / read_concern_args . h <nl> class ReadConcernArgs { <nl> * / <nl> ReadConcernLevel getLevel ( ) const ; <nl> <nl> + / * * <nl> + * Checks whether _level is explicitly set . <nl> + * / <nl> + bool hasLevel ( ) const ; <nl> + <nl> + / * * <nl> + * Checks whether ' available ' read concern level is set . <nl> + * / <nl> + bool isLevelAvailable ( ) const ; <nl> + <nl> / * * <nl> * Returns the opTime . Deprecated : will be replaced with getArgsClusterTime . <nl> * / <nl> mmm a / src / mongo / db / service_entry_point_mongod . cpp <nl> ppp b / src / mongo / db / service_entry_point_mongod . cpp <nl> void execCommandDatabase ( OperationContext * opCtx , <nl> request . body , <nl> command - > supportsNonLocalReadConcern ( request . getDatabase ( ) . toString ( ) , request . body ) ) ) ; <nl> <nl> - / / We do not redo shard version handling if this command was issued via the direct client . <nl> - if ( ( serverGlobalParams . featureCompatibility . version . load ( ) = = <nl> - ServerGlobalParams : : FeatureCompatibility : : Version : : k36 | | <nl> - iAmPrimary ) & & <nl> + / / Don ' t handle the shard version that may have been sent along with the command iff <nl> + / / fcv = = 3 . 4 : This is a secondary . <nl> + / / fcv = = 3 . 6 : The ' available ' rc - level is specified , or this is a secondary and neither the <nl> + / / clusterTime nor rc - level was specified - - secondaries default to ' available ' <nl> + / / when neither clusterTime nor rc - level is set . <nl> + / / or this command was issued via the direct client . <nl> + if ( ( iAmPrimary | | ( serverGlobalParams . featureCompatibility . version . load ( ) = = <nl> + ServerGlobalParams : : FeatureCompatibility : : Version : : k36 & & <nl> + ( repl : : ReadConcernArgs : : get ( opCtx ) . hasLevel ( ) | | <nl> + repl : : ReadConcernArgs : : get ( opCtx ) . getArgsClusterTime ( ) ) ) ) & & <nl> ! opCtx - > getClient ( ) - > isInDirectClient ( ) & & <nl> - repl : : ReadConcernArgs : : get ( opCtx ) . getLevel ( ) ! = <nl> - repl : : ReadConcernLevel : : kAvailableReadConcern ) { <nl> - / / Handle a shard version that may have been sent along with the command . <nl> + ( serverGlobalParams . featureCompatibility . version . load ( ) = = <nl> + ServerGlobalParams : : FeatureCompatibility : : Version : : k34 | | <nl> + ! repl : : ReadConcernArgs : : get ( opCtx ) . isLevelAvailable ( ) ) ) { <nl> auto commandNS = NamespaceString ( command - > parseNs ( dbname , request . body ) ) ; <nl> auto & oss = OperationShardingState : : get ( opCtx ) ; <nl> oss . initializeShardVersion ( commandNS , shardVersionFieldIdx ) ; <nl>
SERVER - 31032 Make secondary requests default to ' available ' rc - level when both rc - level and afterClusterTime are not specified
mongodb/mongo
44a2de49607e5340efc7e84d265216723d403add
2017-09-20T17:45:33Z
mmm a / src / SConscript <nl> ppp b / src / SConscript <nl> SOURCES = { <nl> ' flags . cc ' , ' frames . cc ' , ' global - handles . cc ' , ' handles . cc ' , ' hashmap . cc ' , <nl> ' heap . cc ' , ' ic . cc ' , ' interpreter - irregexp . cc ' , ' jsregexp . cc ' , <nl> ' jump - target . cc ' , ' log . cc ' , ' mark - compact . cc ' , ' messages . cc ' , ' objects . cc ' , <nl> - ' parser . cc ' , ' property . cc ' , ' regexp - macro - assembler . cc ' , <nl> + ' oprofile - agent . cc ' , ' parser . cc ' , ' property . cc ' , ' regexp - macro - assembler . cc ' , <nl> ' regexp - macro - assembler - irregexp . cc ' , ' regexp - stack . cc ' , <nl> ' register - allocator . cc ' , ' rewriter . cc ' , ' runtime . cc ' , ' scanner . cc ' , <nl> ' scopeinfo . cc ' , ' scopes . cc ' , ' serialize . cc ' , ' snapshot - common . cc ' , <nl> SOURCES = { <nl> ] , <nl> ' simulator : arm ' : [ ' simulator - arm . cc ' ] , <nl> ' os : freebsd ' : [ ' platform - freebsd . cc ' ] , <nl> - ' os : linux ' : [ ' platform - linux . cc ' , ' oprofile - agent . cc ' ] , <nl> + ' os : linux ' : [ ' platform - linux . cc ' ] , <nl> ' os : macos ' : [ ' platform - macos . cc ' ] , <nl> ' os : nullos ' : [ ' platform - nullos . cc ' ] , <nl> ' os : win32 ' : [ ' platform - win32 . cc ' ] , <nl> mmm a / tools / v8 . xcodeproj / project . pbxproj <nl> ppp b / tools / v8 . xcodeproj / project . pbxproj <nl> <nl> 89F23C9E0E78D5FD006B2466 / * macro - assembler - arm . cc in Sources * / = { isa = PBXBuildFile ; fileRef = 897FF1540E719B8F00D62E90 / * macro - assembler - arm . cc * / ; } ; <nl> 89F23C9F0E78D604006B2466 / * simulator - arm . cc in Sources * / = { isa = PBXBuildFile ; fileRef = 897FF17D0E719B8F00D62E90 / * simulator - arm . cc * / ; } ; <nl> 89F23CA00E78D609006B2466 / * stub - cache - arm . cc in Sources * / = { isa = PBXBuildFile ; fileRef = 897FF18A0E719B8F00D62E90 / * stub - cache - arm . cc * / ; } ; <nl> + 9FC86ABD0F5FEDAC00F22668 / * oprofile - agent . cc in Sources * / = { isa = PBXBuildFile ; fileRef = 9FC86ABB0F5FEDAC00F22668 / * oprofile - agent . cc * / ; } ; <nl> + 9FC86ABE0F5FEDAC00F22668 / * oprofile - agent . cc in Sources * / = { isa = PBXBuildFile ; fileRef = 9FC86ABB0F5FEDAC00F22668 / * oprofile - agent . cc * / ; } ; <nl> / * End PBXBuildFile section * / <nl> <nl> / * Begin PBXContainerItemProxy section * / <nl> <nl> 89B12E8D0E7FF2A40080BA62 / * presubmit . py * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = text . script . python ; path = presubmit . py ; sourceTree = " < group > " ; } ; <nl> 89F23C870E78D5B2006B2466 / * libv8 - arm . a * / = { isa = PBXFileReference ; explicitFileType = archive . ar ; includeInIndex = 0 ; path = " libv8 - arm . a " ; sourceTree = BUILT_PRODUCTS_DIR ; } ; <nl> 89F23C950E78D5B6006B2466 / * v8_shell - arm * / = { isa = PBXFileReference ; explicitFileType = " compiled . mach - o . executable " ; includeInIndex = 0 ; path = " v8_shell - arm " ; sourceTree = BUILT_PRODUCTS_DIR ; } ; <nl> + 9FC86ABB0F5FEDAC00F22668 / * oprofile - agent . cc * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . cpp . cpp ; path = " oprofile - agent . cc " ; sourceTree = " < group > " ; } ; <nl> + 9FC86ABC0F5FEDAC00F22668 / * oprofile - agent . h * / = { isa = PBXFileReference ; fileEncoding = 4 ; lastKnownFileType = sourcecode . c . h ; path = " oprofile - agent . h " ; sourceTree = " < group > " ; } ; <nl> / * End PBXFileReference section * / <nl> <nl> / * Begin PBXFrameworksBuildPhase section * / <nl> <nl> 897FF1610E719B8F00D62E90 / * objects - inl . h * / , <nl> 897FF1620E719B8F00D62E90 / * objects . cc * / , <nl> 897FF1630E719B8F00D62E90 / * objects . h * / , <nl> + 9FC86ABB0F5FEDAC00F22668 / * oprofile - agent . cc * / , <nl> + 9FC86ABC0F5FEDAC00F22668 / * oprofile - agent . h * / , <nl> 897FF1640E719B8F00D62E90 / * parser . cc * / , <nl> 897FF1650E719B8F00D62E90 / * parser . h * / , <nl> 89A15C6D0EE466A900B48DEB / * platform - freebsd . cc * / , <nl> <nl> 58950D660F5551C200F3E8BA / * virtual - frame . cc in Sources * / , <nl> 58950D670F5551C400F3E8BA / * virtual - frame - ia32 . cc in Sources * / , <nl> 89A88E2E0E71A6D60043BA31 / * zone . cc in Sources * / , <nl> + 9FC86ABD0F5FEDAC00F22668 / * oprofile - agent . cc in Sources * / , <nl> ) ; <nl> runOnlyForDeploymentPostprocessing = 0 ; <nl> } ; <nl> <nl> 58950D680F5551CB00F3E8BA / * virtual - frame . cc in Sources * / , <nl> 58950D690F5551CE00F3E8BA / * virtual - frame - arm . cc in Sources * / , <nl> 89F23C820E78D5B2006B2466 / * zone . cc in Sources * / , <nl> + 9FC86ABE0F5FEDAC00F22668 / * oprofile - agent . cc in Sources * / , <nl> ) ; <nl> runOnlyForDeploymentPostprocessing = 0 ; <nl> } ; <nl> mmm a / tools / visual_studio / v8_base . vcproj <nl> ppp b / tools / visual_studio / v8_base . vcproj <nl> <nl> RelativePath = " . . \ . . \ src \ objects . h " <nl> > <nl> < / File > <nl> + < File <nl> + RelativePath = " . . \ . . \ src \ oprofile - agent . cc " <nl> + > <nl> + < / File > <nl> + < File <nl> + RelativePath = " . . \ . . \ src \ oprofile - agent . h " <nl> + > <nl> + < / File > <nl> < File <nl> RelativePath = " . . \ . . \ src \ parser . cc " <nl> > <nl>
Fixed projects after adding oprofile - agent * sources .
v8/v8
0554042907d1a0e92c7cb318b19e7f1ee1035284
2009-03-05T11:35:44Z
mmm a / Source / Multiverso / include / multiverso / multiverso . h <nl> ppp b / Source / Multiverso / include / multiverso / multiverso . h <nl> enum Role { <nl> kAll = 3 <nl> } ; <nl> <nl> + void MV_Init ( int * argc = nullptr , <nl> + char * argv [ ] = nullptr , <nl> + int role = kAll ) ; <nl> + <nl> + void MV_Barrier ( ) ; <nl> + <nl> + void MV_ShutDown ( bool finalize_mpi = true ) ; <nl> + <nl> + int MV_Rank ( ) ; <nl> + <nl> + / / will deprecate the following function name <nl> void MultiversoInit ( int * argc = nullptr , <nl> char * argv [ ] = nullptr , <nl> int role = kAll ) ; <nl> mmm a / Source / Multiverso / include / multiverso / net / mpi_net . h <nl> ppp b / Source / Multiverso / include / multiverso / net / mpi_net . h <nl> class MPINetWrapper : public NetInterface { <nl> } <nl> <nl> void set_msg ( MessagePtr & msg ) { msg_ = std : : move ( msg ) ; } <nl> - <nl> + const MessagePtr & msg ( ) const { return msg_ ; } <nl> void set_size ( size_t size ) { size_ = size ; } <nl> size_t size ( ) const { return size_ ; } <nl> <nl> class MPINetWrapper : public NetInterface { <nl> } <nl> MPI_Comm_rank ( MPI_COMM_WORLD , & rank_ ) ; <nl> MPI_Comm_size ( MPI_COMM_WORLD , & size_ ) ; <nl> - MPI_Barrier ( MPI_COMM_WORLD ) ; <nl> + / / MPI_Barrier ( MPI_COMM_WORLD ) ; <nl> Log : : Debug ( " % s net util inited , rank = % d , size = % d \ n " , <nl> name ( ) . c_str ( ) , rank ( ) , size ( ) ) ; <nl> } <nl> class MPINetWrapper : public NetInterface { <nl> } <nl> } <nl> MPIMsgHandle * handle = new MPIMsgHandle ( ) ; <nl> - size_t size = SendAsync ( msg , handle ) ; <nl> handle - > set_msg ( msg ) ; <nl> + size_t size = SendAsync ( handle - > msg ( ) , handle ) ; <nl> handle - > set_size ( size ) ; <nl> msg_handles_ . push ( handle ) ; <nl> return size ; <nl> class MPINetWrapper : public NetInterface { <nl> } <nl> <nl> private : <nl> - / / size_t SendMsg ( const MessagePtr & msg ) { <nl> - / / size_t size = Message : : kHeaderSize ; <nl> - / / MPI_Send ( msg - > header ( ) , Message : : kHeaderSize , MPI_BYTE , <nl> - / / msg - > dst ( ) , 0 , MPI_COMM_WORLD ) ; <nl> - / / / / Send multiple msg <nl> - / / for ( auto & blob : msg - > data ( ) ) { <nl> - / / CHECK_NOTNULL ( blob . data ( ) ) ; <nl> - / / MPI_Send ( blob . data ( ) , static_cast < int > ( blob . size ( ) ) , MPI_BYTE , msg - > dst ( ) , <nl> - / / 0 , MPI_COMM_WORLD ) ; <nl> - / / size + = blob . size ( ) ; <nl> - / / } <nl> - / / / / Send an extra over tag indicating the finish of this Message <nl> - / / MPI_Send ( & more_ , sizeof ( char ) , MPI_BYTE , msg - > dst ( ) , <nl> - / / 0 , MPI_COMM_WORLD ) ; <nl> - / / / / Log : : Debug ( " MPI - Net : rank % d send msg size = % d \ n " , rank ( ) , size + 4 ) ; <nl> - / / return size + sizeof ( char ) ; <nl> - / / } <nl> - <nl> size_t SendAsync ( const MessagePtr & msg , <nl> MPIMsgHandle * msg_handle ) { <nl> size_t size = Message : : kHeaderSize ; <nl> class MPINetWrapper : public NetInterface { <nl> <nl> # endif / / MULTIVERSO_USE_MPI <nl> <nl> - # endif / / MULTIVERSO_NET_MPI_NET_H_ <nl> \ No newline at end of file <nl> + # endif / / MULTIVERSO_NET_MPI_NET_H_ <nl> Binary files a / Source / Multiverso / x64 / release / libmultiverso . a and b / Source / Multiverso / x64 / release / libmultiverso . a differ <nl> mmm a / Source / SGDLib / SGD . cpp <nl> ppp b / Source / SGDLib / SGD . cpp <nl> void SGD < ElemType > : : TrainOrAdaptModel ( int startEpoch , ComputationNetworkPtr net , <nl> / / Multiverso Warpper for ASGD logic init <nl> if ( m_parallelizationMethod = = ParallelizationMethod : : DataParallelASGD ) <nl> { <nl> - g_mpi - > WaitAll ( ) ; <nl> m_multiverso = new MultiversoWrapper < ElemType > ( learnableNodes , <nl> g_mpi - > NumNodesInUse ( ) , <nl> m_isPipeline , <nl>
experiment updating
microsoft/CNTK
97502487784ce41eb302f3514e8662f8edf52324
2016-02-26T10:11:50Z
mmm a / test / IRGen / c_functions . swift <nl> ppp b / test / IRGen / c_functions . swift <nl> func test_indirect_by_val_alignment ( ) { <nl> <nl> <nl> / / We only want to test x86_64 . <nl> + / / aarch64 : define hidden swiftcc void @ _T011c_functions30test_indirect_by_val_alignmentyyF ( ) <nl> / / arm64 : define hidden swiftcc void @ _T011c_functions30test_indirect_by_val_alignmentyyF ( ) <nl> / / armv7k : define hidden swiftcc void @ _T011c_functions30test_indirect_by_val_alignmentyyF ( ) <nl> / / armv7s : define hidden swiftcc void @ _T011c_functions30test_indirect_by_val_alignmentyyF ( ) <nl> mmm a / test / IRGen / c_layout . sil <nl> ppp b / test / IRGen / c_layout . sil <nl> bb0 : <nl> / / CHECK - arm64 - LABEL : declare i32 @ ints ( i32 ) <nl> / / CHECK - arm64 - LABEL : declare i32 @ unsigneds ( i32 ) <nl> <nl> + / / CHECK - aarch64 - LABEL : define { { ( protected ) ? } } swiftcc void @ testIntegerExtension <nl> + / / CHECK - aarch64 : call signext i8 @ chareth ( i8 signext % 0 ) <nl> + / / CHECK - aarch64 : call signext i8 @ signedChareth ( i8 signext % 1 ) <nl> + / / CHECK - aarch64 : call zeroext i8 @ unsignedChareth ( i8 zeroext % 2 ) <nl> + / / CHECK - aarch64 : call signext i16 @ eatMyShorts ( i16 signext % 3 ) <nl> + / / CHECK - aarch64 : call zeroext i16 @ eatMyUnsignedShorts ( i16 zeroext % 4 ) <nl> + / / CHECK - aarch64 : call i32 @ ints ( i32 % 5 ) <nl> + / / CHECK - aarch64 : call i32 @ unsigneds ( i32 % 6 ) <nl> + / / CHECK - aarch64 - LABEL : declare signext i8 @ chareth ( i8 signext ) <nl> + / / CHECK - aarch64 - LABEL : declare signext i8 @ signedChareth ( i8 signext ) <nl> + / / CHECK - aarch64 - LABEL : declare zeroext i8 @ unsignedChareth ( i8 zeroext ) <nl> + / / CHECK - aarch64 - LABEL : declare signext i16 @ eatMyShorts ( i16 signext ) <nl> + / / CHECK - aarch64 - LABEL : declare zeroext i16 @ eatMyUnsignedShorts ( i16 zeroext ) <nl> + / / CHECK - aarch64 - LABEL : declare i32 @ ints ( i32 ) <nl> + / / CHECK - aarch64 - LABEL : declare i32 @ unsigneds ( i32 ) <nl> + <nl> / / CHECK - powerpc64 - LABEL : define { { ( protected ) ? } } swiftcc void @ testIntegerExtension <nl> / / CHECK - powerpc64 : call zeroext i8 @ chareth ( i8 zeroext % 0 ) <nl> / / CHECK - powerpc64 : call zeroext i8 @ signedChareth ( i8 zeroext % 1 ) <nl> mmm a / test / IRGen / objc_simd . sil <nl> ppp b / test / IRGen / objc_simd . sil <nl> func forceStuff ( x : float4 , y : float3 ) - > ( Float , Float , Float , Float ) { <nl> <nl> / / x86_64 - LABEL : define { { ( protected ) ? } } < 4 x float > @ simd_c_args ( < 4 x float > ) <nl> / / i386 - LABEL : define { { ( protected ) ? } } < 2 x i64 > @ simd_c_args ( < 4 x float > ) <nl> + / / aarch64 - LABEL : define { { ( protected ) ? } } < 4 x float > @ simd_c_args ( < 4 x float > ) <nl> / / arm64 - LABEL : define { { ( protected ) ? } } < 4 x float > @ simd_c_args ( < 4 x float > ) <nl> / / armv6 - LABEL : define { { ( protected ) ? } } < 4 x float > @ simd_c_args ( < 4 x float > ) <nl> / / armv7 - LABEL : define { { ( protected ) ? } } < 4 x float > @ simd_c_args ( < 4 x float > ) <nl> entry ( % x : $ float4 ) : <nl> <nl> / / x86_64 - LABEL : define { { ( protected ) ? } } < 3 x float > @ simd_c_args_float3 ( < 3 x float > ) <nl> / / i386 - LABEL : define { { ( protected ) ? } } < 2 x i64 > @ simd_c_args_float3 ( < 3 x float > ) <nl> + / / aarch64 - LABEL : define { { ( protected ) ? } } < 3 x float > @ simd_c_args_float3 ( < 4 x i32 > ) <nl> / / arm64 - LABEL : define { { ( protected ) ? } } < 3 x float > @ simd_c_args_float3 ( < 4 x i32 > ) <nl> / / armv6 - LABEL : define { { ( protected ) ? } } < 3 x float > @ simd_c_args_float3 ( < 4 x i32 > ) <nl> / / armv7 - LABEL : define { { ( protected ) ? } } < 3 x float > @ simd_c_args_float3 ( < 4 x i32 > ) <nl> entry ( % x : $ float3 ) : <nl> <nl> / / x86_64 - LABEL : define { { ( protected ) ? } } swiftcc { i64 , i64 } @ simd_native_args ( i64 , i64 ) <nl> / / i386 - LABEL : define { { ( protected ) ? } } swiftcc void @ simd_native_args ( % T4simd6float4V * noalias nocapture sret , % T4simd6float4V * noalias nocapture dereferenceable ( { { . * } } ) ) <nl> + / / aarch64 - LABEL : define { { ( protected ) ? } } swiftcc { i64 , i64 } @ simd_native_args ( i64 , i64 ) <nl> / / arm64 - LABEL : define { { ( protected ) ? } } swiftcc { i64 , i64 } @ simd_native_args ( i64 , i64 ) <nl> / / armv6 - LABEL : define { { ( protected ) ? } } swiftcc void @ simd_native_args ( % T4simd6float4V * noalias nocapture sret , % T4simd6float4V * noalias nocapture dereferenceable ( { { . * } } ) ) <nl> / / armv7 - LABEL : define { { ( protected ) ? } } swiftcc { float , float , float , float } @ simd_native_args ( float , float , float , float ) <nl> entry ( % x : $ float4 ) : <nl> <nl> / / x86_64 - LABEL : define { { ( protected ) ? } } swiftcc { i64 , float } @ simd_native_args_float3 ( i64 , float ) <nl> / / i386 - LABEL : define { { ( protected ) ? } } swiftcc { float , float , float } @ simd_native_args_float3 ( float , float , float ) <nl> + / / aarch64 - LABEL : define { { ( protected ) ? } } swiftcc { i64 , float } @ simd_native_args_float3 ( i64 , float ) <nl> / / arm64 - LABEL : define { { ( protected ) ? } } swiftcc { i64 , float } @ simd_native_args_float3 ( i64 , float ) <nl> / / armv6 - LABEL : define { { ( protected ) ? } } swiftcc { float , float , float } @ simd_native_args_float3 ( float , float , float ) <nl> / / armv7 - LABEL : define { { ( protected ) ? } } swiftcc { float , float , float } @ simd_native_args_float3 ( float , float , float ) <nl> mmm a / test / stdlib / FloatingPointIR . swift <nl> ppp b / test / stdlib / FloatingPointIR . swift <nl> func testConstantFoldFloatLiterals ( ) { <nl> / / arm64 : call swiftcc void @ _T015FloatingPointIR13acceptFloat32ySfF { { . * } } ( float 1 . 000000e + 00 ) <nl> / / arm64 : call swiftcc void @ _T015FloatingPointIR13acceptFloat64ySdF { { . * } } ( double 1 . 000000e + 00 ) <nl> <nl> + / / aarch64 : call swiftcc void @ _T015FloatingPointIR13acceptFloat32ySfF { { . * } } ( float 1 . 000000e + 00 ) <nl> + / / aarch64 : call swiftcc void @ _T015FloatingPointIR13acceptFloat64ySdF { { . * } } ( double 1 . 000000e + 00 ) <nl> + <nl> / / powerpc64 : call swiftcc void @ _T015FloatingPointIR13acceptFloat32ySfF { { . * } } ( float 1 . 000000e + 00 ) <nl> / / powerpc64 : call swiftcc void @ _T015FloatingPointIR13acceptFloat64ySdF { { . * } } ( double 1 . 000000e + 00 ) <nl> <nl>
test : duplicate some conditions for AArch64
apple/swift
99db384e2e07b973bd33d30f3c1040c90241b7e9
2017-09-22T06:48:28Z
mmm a / include / swift / AST / DiagnosticsParse . def <nl> ppp b / include / swift / AST / DiagnosticsParse . def <nl> ERROR ( sil_keypath_unknown_component_kind , none , <nl> ERROR ( sil_keypath_computed_property_missing_part , none , <nl> " keypath % select { gettable | settable } 0_property component needs an " <nl> " % select { id and getter | id , getter , and setter } 0 " , ( bool ) ) <nl> + ERROR ( sil_keypath_external_missing_part , none , <nl> + " keypath external component with indices needs an indices_equals and " <nl> + " indices_hash function " , ( ) ) <nl> ERROR ( sil_keypath_no_components , none , <nl> " keypath must have at least one component " , ( ) ) <nl> ERROR ( sil_keypath_no_root , none , <nl> mmm a / include / swift / SIL / SILInstruction . h <nl> ppp b / include / swift / SIL / SILInstruction . h <nl> class KeyPathPatternComponent { <nl> return Value . DeclRef ; <nl> } <nl> } ; <nl> - <nl> + <nl> enum class Kind : unsigned { <nl> StoredProperty , <nl> GettableProperty , <nl> SettableProperty , <nl> - Last_Packed = SettableProperty , / / Last enum value that can be packed in <nl> - / / a PointerIntPair <nl> + External , <nl> OptionalChain , <nl> OptionalForce , <nl> OptionalWrap , <nl> - External , <nl> } ; <nl> <nl> / / Description of a captured index value and its Hashable conformance for a <nl> class KeyPathPatternComponent { <nl> } ; <nl> <nl> private : <nl> - static constexpr const unsigned KindPackingBits = 2 ; <nl> - static constexpr const unsigned UnpackedKind = ( 1u < < KindPackingBits ) - 1 ; <nl> - static_assert ( ( unsigned ) Kind : : Last_Packed < UnpackedKind , <nl> - " too many kinds to pack " ) ; <nl> - <nl> + enum PackedKind : unsigned { <nl> + PackedStored , <nl> + PackedComputed , <nl> + PackedExternal , <nl> + Unpacked , <nl> + } ; <nl> + <nl> + static const unsigned KindPackingBits = 2 ; <nl> + <nl> + static unsigned getPackedKind ( Kind k ) { <nl> + switch ( k ) { <nl> + case Kind : : StoredProperty : <nl> + return PackedStored ; <nl> + case Kind : : GettableProperty : <nl> + case Kind : : SettableProperty : <nl> + return PackedComputed ; <nl> + case Kind : : External : <nl> + return PackedExternal ; <nl> + case Kind : : OptionalChain : <nl> + case Kind : : OptionalForce : <nl> + case Kind : : OptionalWrap : <nl> + return Unpacked ; <nl> + } <nl> + } <nl> + <nl> / / Value is the VarDecl * for StoredProperty , the SILFunction * of the <nl> / / Getter for computed properties , or the Kind for other kinds <nl> llvm : : PointerIntPair < void * , KindPackingBits , unsigned > ValueAndKind ; <nl> - llvm : : PointerIntPair < SILFunction * , 2 , <nl> - ComputedPropertyId : : KindType > SetterAndIdKind ; <nl> - ComputedPropertyId : : ValueType IdValue ; <nl> - ArrayRef < Index > Indices ; <nl> union { <nl> - / / Valid if Kind = = GettableProperty | | Value = = SettableProperty <nl> + / / Valid if Kind = = GettableProperty | | Kind = = SettableProperty <nl> struct { <nl> - SILFunction * Equal ; <nl> - SILFunction * Hash ; <nl> - } IndexEquality ; <nl> + llvm : : PointerIntPair < SILFunction * , 2 , <nl> + ComputedPropertyId : : KindType > SetterAndIdKind ; <nl> + ComputedPropertyId : : ValueType IdValue ; <nl> + } Computed ; <nl> / / Valid if Kind = = External <nl> ArrayRef < Substitution > ExternalSubstitutions ; <nl> } ; <nl> + ArrayRef < Index > Indices ; <nl> + struct { <nl> + SILFunction * Equal ; <nl> + SILFunction * Hash ; <nl> + } IndexEquality ; <nl> CanType ComponentType ; <nl> <nl> - unsigned kindForPacking ( Kind k ) { <nl> - auto value = ( unsigned ) k ; <nl> - assert ( value < = ( unsigned ) Kind : : Last_Packed ) ; <nl> - return value ; <nl> - } <nl> - <nl> - KeyPathPatternComponent ( Kind kind , CanType ComponentType ) <nl> - : ValueAndKind ( ( void * ) ( ( uintptr_t ) kind < < KindPackingBits ) , UnpackedKind ) , <nl> - ComponentType ( ComponentType ) <nl> - { <nl> - assert ( kind > Kind : : Last_Packed & & " wrong initializer " ) ; <nl> - } <nl> - <nl> - KeyPathPatternComponent ( VarDecl * storedProp , Kind kind , <nl> + / / / Constructor for stored components <nl> + KeyPathPatternComponent ( VarDecl * storedProp , <nl> CanType ComponentType ) <nl> - : ValueAndKind ( storedProp , kindForPacking ( kind ) ) , <nl> + : ValueAndKind ( storedProp , PackedStored ) , <nl> ComponentType ( ComponentType ) { } <nl> <nl> - KeyPathPatternComponent ( ComputedPropertyId id , Kind kind , <nl> + / / / Constructor for computed components <nl> + KeyPathPatternComponent ( ComputedPropertyId id , <nl> SILFunction * getter , <nl> SILFunction * setter , <nl> ArrayRef < Index > indices , <nl> SILFunction * indicesEqual , <nl> SILFunction * indicesHash , <nl> CanType ComponentType ) <nl> - : ValueAndKind ( getter , kindForPacking ( kind ) ) , <nl> - SetterAndIdKind ( setter , id . Kind ) , <nl> - IdValue ( id . Value ) , <nl> + : ValueAndKind ( getter , PackedComputed ) , <nl> + Computed { { setter , id . Kind } , { id . Value } } , <nl> Indices ( indices ) , <nl> IndexEquality { indicesEqual , indicesHash } , <nl> ComponentType ( ComponentType ) { <nl> } <nl> <nl> + / / / Constructor for external components <nl> KeyPathPatternComponent ( AbstractStorageDecl * externalStorage , <nl> ArrayRef < Substitution > substitutions , <nl> ArrayRef < Index > indices , <nl> + SILFunction * indicesEqual , <nl> + SILFunction * indicesHash , <nl> CanType componentType ) <nl> - : ValueAndKind ( ( void * ) ( ( uintptr_t ) Kind : : External < < KindPackingBits ) , <nl> - UnpackedKind ) , <nl> - IdValue ( externalStorage ) , <nl> - Indices ( indices ) , <nl> + : ValueAndKind ( externalStorage , PackedExternal ) , <nl> ExternalSubstitutions ( substitutions ) , <nl> + Indices ( indices ) , <nl> + IndexEquality { indicesEqual , indicesHash } , <nl> ComponentType ( componentType ) { <nl> } <nl> + <nl> + / / / Constructor for optional components . <nl> + KeyPathPatternComponent ( Kind kind , CanType componentType ) <nl> + : ValueAndKind ( ( void * ) ( ( uintptr_t ) kind < < KindPackingBits ) , Unpacked ) , <nl> + ComponentType ( componentType ) { <nl> + assert ( ( unsigned ) kind > = ( unsigned ) Kind : : OptionalChain <nl> + & & " not an optional component " ) ; <nl> + } <nl> <nl> public : <nl> KeyPathPatternComponent ( ) : ValueAndKind ( nullptr , 0 ) { } <nl> class KeyPathPatternComponent { <nl> <nl> Kind getKind ( ) const { <nl> auto packedKind = ValueAndKind . getInt ( ) ; <nl> - if ( packedKind ! = UnpackedKind ) <nl> - return ( Kind ) packedKind ; <nl> - return ( Kind ) ( ( uintptr_t ) ValueAndKind . getPointer ( ) > > KindPackingBits ) ; <nl> + switch ( ( PackedKind ) packedKind ) { <nl> + case PackedStored : <nl> + return Kind : : StoredProperty ; <nl> + case PackedComputed : <nl> + return Computed . SetterAndIdKind . getPointer ( ) <nl> + ? Kind : : SettableProperty : Kind : : GettableProperty ; <nl> + case PackedExternal : <nl> + return Kind : : External ; <nl> + case Unpacked : <nl> + return ( Kind ) ( ( uintptr_t ) ValueAndKind . getPointer ( ) > > KindPackingBits ) ; <nl> + } <nl> } <nl> <nl> CanType getComponentType ( ) const { <nl> class KeyPathPatternComponent { <nl> llvm_unreachable ( " not a computed property " ) ; <nl> case Kind : : GettableProperty : <nl> case Kind : : SettableProperty : <nl> - return ComputedPropertyId ( IdValue , SetterAndIdKind . getInt ( ) ) ; <nl> + return ComputedPropertyId ( Computed . IdValue , <nl> + Computed . SetterAndIdKind . getInt ( ) ) ; <nl> } <nl> llvm_unreachable ( " unhandled kind " ) ; <nl> } <nl> class KeyPathPatternComponent { <nl> case Kind : : External : <nl> llvm_unreachable ( " not a settable computed property " ) ; <nl> case Kind : : SettableProperty : <nl> - return SetterAndIdKind . getPointer ( ) ; <nl> + return Computed . SetterAndIdKind . getPointer ( ) ; <nl> } <nl> llvm_unreachable ( " unhandled kind " ) ; <nl> } <nl> class KeyPathPatternComponent { <nl> case Kind : : OptionalChain : <nl> case Kind : : OptionalForce : <nl> case Kind : : OptionalWrap : <nl> - case Kind : : External : <nl> llvm_unreachable ( " not a computed property " ) ; <nl> + case Kind : : External : <nl> case Kind : : GettableProperty : <nl> case Kind : : SettableProperty : <nl> return IndexEquality . Equal ; <nl> class KeyPathPatternComponent { <nl> case Kind : : OptionalChain : <nl> case Kind : : OptionalForce : <nl> case Kind : : OptionalWrap : <nl> - case Kind : : External : <nl> llvm_unreachable ( " not a computed property " ) ; <nl> + case Kind : : External : <nl> case Kind : : GettableProperty : <nl> case Kind : : SettableProperty : <nl> return IndexEquality . Hash ; <nl> class KeyPathPatternComponent { <nl> <nl> static KeyPathPatternComponent forStoredProperty ( VarDecl * property , <nl> CanType ty ) { <nl> - return KeyPathPatternComponent ( property , Kind : : StoredProperty , ty ) ; <nl> + return KeyPathPatternComponent ( property , ty ) ; <nl> } <nl> <nl> AbstractStorageDecl * getExternalDecl ( ) const { <nl> assert ( getKind ( ) = = Kind : : External <nl> & & " not an external property " ) ; <nl> - return IdValue . Property ; <nl> + return ( AbstractStorageDecl * ) ValueAndKind . getPointer ( ) ; <nl> } <nl> <nl> ArrayRef < Substitution > getExternalSubstitutions ( ) const { <nl> class KeyPathPatternComponent { <nl> SILFunction * indicesEquals , <nl> SILFunction * indicesHash , <nl> CanType ty ) { <nl> - return KeyPathPatternComponent ( identifier , Kind : : GettableProperty , <nl> + return KeyPathPatternComponent ( identifier , <nl> getter , nullptr , indices , <nl> indicesEquals , indicesHash , ty ) ; <nl> } <nl> class KeyPathPatternComponent { <nl> SILFunction * indicesEquals , <nl> SILFunction * indicesHash , <nl> CanType ty ) { <nl> - return KeyPathPatternComponent ( identifier , Kind : : SettableProperty , <nl> + return KeyPathPatternComponent ( identifier , <nl> getter , setter , indices , <nl> indicesEquals , indicesHash , ty ) ; <nl> } <nl> class KeyPathPatternComponent { <nl> forExternal ( AbstractStorageDecl * externalDecl , <nl> ArrayRef < Substitution > substitutions , <nl> ArrayRef < Index > indices , <nl> + SILFunction * indicesEquals , <nl> + SILFunction * indicesHash , <nl> CanType ty ) { <nl> - return KeyPathPatternComponent ( externalDecl , substitutions , indices , ty ) ; <nl> + return KeyPathPatternComponent ( externalDecl , substitutions , <nl> + indices , indicesEquals , indicesHash , ty ) ; <nl> } <nl> <nl> void incrementRefCounts ( ) const ; <nl> mmm a / include / swift / SIL / SILProperty . h <nl> ppp b / include / swift / SIL / SILProperty . h <nl> class SILProperty : public llvm : : ilist_node < SILProperty > , <nl> const KeyPathPatternComponent & getComponent ( ) const { return Component ; } <nl> <nl> void print ( SILPrintContext & Ctx ) const ; <nl> + void dump ( ) const ; <nl> + <nl> + void verify ( const SILModule & M ) const ; <nl> } ; <nl> <nl> } / / end namespace swift <nl> mmm a / lib / IRGen / GenKeyPath . cpp <nl> ppp b / lib / IRGen / GenKeyPath . cpp <nl> IRGenModule : : getAddrOfKeyPathPattern ( KeyPathPattern * pattern , <nl> / / instantiation more likely to avoid needing an allocation . <nl> unsigned argSize = descriptorArgs . size ( ) ; <nl> if ( isInstantiableInPlace ) { <nl> - argSize = std : : max ( argSize , 5u ) ; <nl> + argSize = std : : max ( argSize , 3u ) ; <nl> } <nl> <nl> fields . addInt32 ( argSize ) ; <nl> fields . add ( getAddrOfPropertyDescriptor ( component . getExternalDecl ( ) ) ) ; <nl> <nl> / / Add an initializer function that copies generic arguments out of the <nl> - / / pattern argument buffer into the instantiated object , or null if there <nl> - / / are no arguments . <nl> - if ( component . getSubscriptIndices ( ) . empty ( ) ) <nl> + / / pattern argument buffer into the instantiated object , along with the <nl> + / / index equality / hash operations we have from our perspective , or null <nl> + / / if there are no arguments . <nl> + if ( component . getSubscriptIndices ( ) . empty ( ) ) { <nl> fields . addInt ( IntPtrTy , 0 ) ; <nl> - else <nl> + fields . addInt ( IntPtrTy , 0 ) ; <nl> + fields . addInt ( IntPtrTy , 0 ) ; <nl> + } else { <nl> fields . add ( getInitializerForComputedComponent ( * this , component , <nl> operands , <nl> genericEnv , <nl> requirements ) ) ; <nl> + fields . add ( getAddrOfSILFunction ( component . getSubscriptIndexEquals ( ) , <nl> + NotForDefinition ) ) ; <nl> + fields . add ( getAddrOfSILFunction ( component . getSubscriptIndexHash ( ) , <nl> + NotForDefinition ) ) ; <nl> + } <nl> <nl> / / Add the generic arguments for the external context . <nl> for ( auto arg : descriptorArgs ) <nl> mmm a / lib / ParseSIL / ParseSIL . cpp <nl> ppp b / lib / ParseSIL / ParseSIL . cpp <nl> SILParser : : parseKeyPathPatternComponent ( KeyPathPatternComponent & component , <nl> diag : : expected_tok_in_sil_instr , " $ " ) <nl> | | parseASTType ( ty , patternEnv ) ) <nl> return true ; <nl> - <nl> + <nl> + SILFunction * equals = nullptr ; <nl> + SILFunction * hash = nullptr ; <nl> + <nl> + while ( P . consumeIf ( tok : : comma ) ) { <nl> + Identifier subKind ; <nl> + SourceLoc subKindLoc ; <nl> + if ( parseSILIdentifier ( subKind , subKindLoc , <nl> + diag : : sil_keypath_expected_component_kind ) ) <nl> + return true ; <nl> + <nl> + if ( subKind . str ( ) = = " indices_equals " ) { <nl> + if ( parseSILFunctionRef ( InstLoc , equals ) ) <nl> + return true ; <nl> + } else if ( subKind . str ( ) = = " indices_hash " ) { <nl> + if ( parseSILFunctionRef ( InstLoc , hash ) ) <nl> + return true ; <nl> + } else { <nl> + P . diagnose ( subKindLoc , diag : : sil_keypath_unknown_component_kind , <nl> + subKind ) ; <nl> + return true ; <nl> + } <nl> + } <nl> + <nl> + if ( ! indexes . empty ( ) ! = ( equals & & hash ) ) { <nl> + P . diagnose ( componentLoc , <nl> + diag : : sil_keypath_external_missing_part ) ; <nl> + return true ; <nl> + } <nl> + <nl> if ( ! parsedSubs . empty ( ) ) { <nl> auto genericEnv = externalDecl - > getInnermostDeclContext ( ) <nl> - > getGenericEnvironmentOfContext ( ) ; <nl> SILParser : : parseKeyPathPatternComponent ( KeyPathPatternComponent & component , <nl> sub = sub . getCanonicalSubstitution ( ) ; <nl> } <nl> <nl> + <nl> auto indexesCopy = P . Context . AllocateCopy ( indexes ) ; <nl> auto subsCopy = P . Context . AllocateCopy ( subs ) ; <nl> <nl> component = KeyPathPatternComponent : : forExternal ( <nl> cast < AbstractStorageDecl > ( externalDecl ) , <nl> - subsCopy , indexesCopy , ty ) ; <nl> + subsCopy , indexesCopy , equals , hash , ty ) ; <nl> return false ; <nl> } else if ( componentKind . str ( ) = = " gettable_property " <nl> | | componentKind . str ( ) = = " settable_property " ) { <nl> mmm a / lib / SIL / SILPrinter . cpp <nl> ppp b / lib / SIL / SILPrinter . cpp <nl> class SILPrinter : public SILInstructionVisitor < SILPrinter > { <nl> } <nl> <nl> * this < < " : $ " < < component . getComponentType ( ) ; <nl> + <nl> + if ( ! component . getSubscriptIndices ( ) . empty ( ) ) { <nl> + * this < < " , indices_equals " ; <nl> + component . getSubscriptIndexEquals ( ) - > printName ( PrintState . OS ) ; <nl> + * this < < " : " <nl> + < < component . getSubscriptIndexEquals ( ) - > getLoweredType ( ) ; <nl> + * this < < " , indices_hash " ; <nl> + component . getSubscriptIndexHash ( ) - > printName ( PrintState . OS ) ; <nl> + * this < < " : " <nl> + < < component . getSubscriptIndexHash ( ) - > getLoweredType ( ) ; <nl> + } <nl> } <nl> } <nl> } <nl> void SILProperty : : print ( SILPrintContext & Ctx ) const { <nl> OS < < " ) \ n " ; <nl> } <nl> <nl> + void SILProperty : : dump ( ) const { <nl> + SILPrintContext context ( llvm : : errs ( ) ) ; <nl> + print ( context ) ; <nl> + } <nl> + <nl> static void printSILProperties ( SILPrintContext & Ctx , <nl> const SILModule : : PropertyListType & Properties ) { <nl> for ( const SILProperty & P : Properties ) { <nl> mmm a / lib / SIL / SILVerifier . cpp <nl> ppp b / lib / SIL / SILVerifier . cpp <nl> class SILVerifierBase : public SILInstructionVisitor < Impl > { <nl> <nl> namespace { <nl> <nl> + / / / Verify invariants on a key path component . <nl> + void verifyKeyPathComponent ( SILModule & M , <nl> + llvm : : function_ref < void ( bool , StringRef ) > require , <nl> + CanType & baseTy , <nl> + CanType leafTy , <nl> + const KeyPathPatternComponent & component , <nl> + ArrayRef < Operand > operands , <nl> + CanGenericSignature patternSig , <nl> + SubstitutionList patternSubList , <nl> + bool forPropertyDescriptor , <nl> + bool hasIndices ) { <nl> + auto & C = M . getASTContext ( ) ; <nl> + <nl> + SubstitutionMap patternSubs ; <nl> + if ( patternSig ) <nl> + patternSubs = patternSig - > getSubstitutionMap ( patternSubList ) ; <nl> + <nl> + auto loweredBaseTy = <nl> + M . Types . getLoweredType ( AbstractionPattern : : getOpaque ( ) , baseTy ) ; <nl> + auto componentTy = component . getComponentType ( ) . subst ( patternSubs ) <nl> + - > getCanonicalType ( ) ; <nl> + auto loweredComponentTy = <nl> + M . Types . getLoweredType ( AbstractionPattern : : getOpaque ( ) , componentTy ) ; <nl> + <nl> + auto checkIndexEqualsAndHash = [ & ] { <nl> + if ( ! component . getSubscriptIndices ( ) . empty ( ) ) { <nl> + / / Equals should be <nl> + / / < Sig . . . > @ convention ( thin ) ( RawPointer , RawPointer ) - > Bool <nl> + { <nl> + auto equals = component . getSubscriptIndexEquals ( ) ; <nl> + require ( equals , " key path pattern with indexes must have equals " <nl> + " operator " ) ; <nl> + <nl> + auto substEqualsType = equals - > getLoweredFunctionType ( ) <nl> + - > substGenericArgs ( M , patternSubList ) ; <nl> + <nl> + require ( substEqualsType - > getParameters ( ) . size ( ) = = 2 , <nl> + " must have two arguments " ) ; <nl> + for ( unsigned i = 0 ; i < 2 ; + + i ) { <nl> + auto param = substEqualsType - > getParameters ( ) [ i ] ; <nl> + require ( param . getConvention ( ) <nl> + = = ParameterConvention : : Direct_Unowned , <nl> + " indices pointer should be trivial " ) ; <nl> + require ( param . getType ( ) - > getAnyNominal ( ) <nl> + = = C . getUnsafeRawPointerDecl ( ) , <nl> + " indices pointer should be an UnsafeRawPointer " ) ; <nl> + } <nl> + <nl> + require ( substEqualsType - > getResults ( ) . size ( ) = = 1 , <nl> + " must have one result " ) ; <nl> + <nl> + require ( substEqualsType - > getResults ( ) [ 0 ] . getConvention ( ) <nl> + = = ResultConvention : : Unowned , <nl> + " result should be unowned " ) ; <nl> + require ( substEqualsType - > getResults ( ) [ 0 ] . getType ( ) - > getAnyNominal ( ) <nl> + = = C . getBoolDecl ( ) , <nl> + " result should be Bool " ) ; <nl> + } <nl> + { <nl> + / / Hash should be <nl> + / / < Sig . . . > @ convention ( thin ) ( RawPointer ) - > Int <nl> + auto hash = component . getSubscriptIndexHash ( ) ; <nl> + require ( hash , " key path pattern with indexes must have hash " <nl> + " operator " ) ; <nl> + <nl> + auto substHashType = hash - > getLoweredFunctionType ( ) <nl> + - > substGenericArgs ( M , patternSubList ) ; <nl> + <nl> + require ( substHashType - > getParameters ( ) . size ( ) = = 1 , <nl> + " must have two arguments " ) ; <nl> + auto param = substHashType - > getParameters ( ) [ 0 ] ; <nl> + require ( param . getConvention ( ) <nl> + = = ParameterConvention : : Direct_Unowned , <nl> + " indices pointer should be trivial " ) ; <nl> + require ( param . getType ( ) - > getAnyNominal ( ) <nl> + = = C . getUnsafeRawPointerDecl ( ) , <nl> + " indices pointer should be an UnsafeRawPointer " ) ; <nl> + <nl> + require ( substHashType - > getResults ( ) . size ( ) = = 1 , <nl> + " must have one result " ) ; <nl> + <nl> + require ( substHashType - > getResults ( ) [ 0 ] . getConvention ( ) <nl> + = = ResultConvention : : Unowned , <nl> + " result should be unowned " ) ; <nl> + require ( substHashType - > getResults ( ) [ 0 ] . getType ( ) - > getAnyNominal ( ) <nl> + = = C . getIntDecl ( ) , <nl> + " result should be Int " ) ; <nl> + } <nl> + } else { <nl> + require ( ! component . getSubscriptIndexEquals ( ) <nl> + & & ! component . getSubscriptIndexHash ( ) , <nl> + " component without indexes must not have equals / hash " ) ; <nl> + } <nl> + } ; <nl> + <nl> + switch ( auto kind = component . getKind ( ) ) { <nl> + case KeyPathPatternComponent : : Kind : : StoredProperty : { <nl> + auto property = component . getStoredPropertyDecl ( ) ; <nl> + require ( property - > getDeclContext ( ) <nl> + = = baseTy - > getAnyNominal ( ) , <nl> + " property decl should be a member of the component base type " ) ; <nl> + switch ( property - > getStorageKind ( ) ) { <nl> + case AbstractStorageDecl : : Stored : <nl> + case AbstractStorageDecl : : StoredWithObservers : <nl> + case AbstractStorageDecl : : StoredWithTrivialAccessors : <nl> + break ; <nl> + case AbstractStorageDecl : : Addressed : <nl> + case AbstractStorageDecl : : AddressedWithObservers : <nl> + case AbstractStorageDecl : : AddressedWithTrivialAccessors : <nl> + case AbstractStorageDecl : : Computed : <nl> + case AbstractStorageDecl : : ComputedWithMutableAddress : <nl> + case AbstractStorageDecl : : InheritedWithObservers : <nl> + require ( false , " property must be stored " ) ; <nl> + } <nl> + auto propertyTy = loweredBaseTy . getFieldType ( property , M ) ; <nl> + require ( propertyTy . getObjectType ( ) <nl> + = = loweredComponentTy . getObjectType ( ) , <nl> + " component type should match the maximal abstraction of the " <nl> + " formal type " ) ; <nl> + break ; <nl> + } <nl> + <nl> + case KeyPathPatternComponent : : Kind : : GettableProperty : <nl> + case KeyPathPatternComponent : : Kind : : SettableProperty : { <nl> + if ( forPropertyDescriptor ) { <nl> + require ( component . getSubscriptIndices ( ) . empty ( ) <nl> + & & ! component . getSubscriptIndexEquals ( ) <nl> + & & ! component . getSubscriptIndexHash ( ) , <nl> + " property descriptor should not have index information " ) ; <nl> + } else { <nl> + require ( hasIndices = = ! component . getSubscriptIndices ( ) . empty ( ) , <nl> + " component for subscript should have indices " ) ; <nl> + } <nl> + <nl> + ParameterConvention normalArgConvention ; <nl> + if ( M . getOptions ( ) . EnableGuaranteedNormalArguments ) <nl> + normalArgConvention = ParameterConvention : : Indirect_In_Guaranteed ; <nl> + else <nl> + normalArgConvention = ParameterConvention : : Indirect_In ; <nl> + <nl> + / / Getter should be < Sig . . . > @ convention ( thin ) ( @ in_guaranteed Base ) - > @ out Result <nl> + { <nl> + auto getter = component . getComputedPropertyGetter ( ) ; <nl> + auto substGetterType = getter - > getLoweredFunctionType ( ) <nl> + - > substGenericArgs ( M , patternSubList ) ; <nl> + require ( substGetterType - > getRepresentation ( ) = = <nl> + SILFunctionTypeRepresentation : : Thin , <nl> + " getter should be a thin function " ) ; <nl> + <nl> + require ( substGetterType - > getNumParameters ( ) = = 1 + hasIndices , <nl> + " getter should have one parameter " ) ; <nl> + auto baseParam = substGetterType - > getParameters ( ) [ 0 ] ; <nl> + require ( baseParam . getConvention ( ) = = normalArgConvention , <nl> + " getter base parameter should have normal arg convention " ) ; <nl> + require ( baseParam . getType ( ) = = loweredBaseTy . getSwiftRValueType ( ) , <nl> + " getter base parameter should match base of component " ) ; <nl> + <nl> + if ( hasIndices ) { <nl> + auto indicesParam = substGetterType - > getParameters ( ) [ 1 ] ; <nl> + require ( indicesParam . getConvention ( ) <nl> + = = ParameterConvention : : Direct_Unowned , <nl> + " indices pointer should be trivial " ) ; <nl> + require ( indicesParam . getType ( ) - > getAnyNominal ( ) <nl> + = = C . getUnsafeRawPointerDecl ( ) , <nl> + " indices pointer should be an UnsafeRawPointer " ) ; <nl> + } <nl> + <nl> + require ( substGetterType - > getNumResults ( ) = = 1 , <nl> + " getter should have one result " ) ; <nl> + auto result = substGetterType - > getResults ( ) [ 0 ] ; <nl> + require ( result . getConvention ( ) = = ResultConvention : : Indirect , <nl> + " getter result should be @ out " ) ; <nl> + require ( result . getType ( ) = = loweredComponentTy . getSwiftRValueType ( ) , <nl> + " getter result should match the maximal abstraction of the " <nl> + " formal component type " ) ; <nl> + } <nl> + <nl> + if ( kind = = KeyPathPatternComponent : : Kind : : SettableProperty ) { <nl> + / / Setter should be <nl> + / / < Sig . . . > @ convention ( thin ) ( @ in_guaranteed Result , @ in Base ) - > ( ) <nl> + <nl> + auto setter = component . getComputedPropertySetter ( ) ; <nl> + auto substSetterType = setter - > getLoweredFunctionType ( ) <nl> + - > substGenericArgs ( M , patternSubList ) ; <nl> + <nl> + require ( substSetterType - > getRepresentation ( ) = = <nl> + SILFunctionTypeRepresentation : : Thin , <nl> + " setter should be a thin function " ) ; <nl> + <nl> + require ( substSetterType - > getNumParameters ( ) = = 2 + hasIndices , <nl> + " setter should have two parameters " ) ; <nl> + <nl> + auto newValueParam = substSetterType - > getParameters ( ) [ 0 ] ; <nl> + / / TODO : This should probably be unconditionally + 1 when we <nl> + / / can represent that . <nl> + require ( newValueParam . getConvention ( ) = = normalArgConvention , <nl> + " setter value parameter should havee normal arg convention " ) ; <nl> + <nl> + auto baseParam = substSetterType - > getParameters ( ) [ 1 ] ; <nl> + require ( baseParam . getConvention ( ) = = normalArgConvention <nl> + | | baseParam . getConvention ( ) = = <nl> + ParameterConvention : : Indirect_Inout , <nl> + " setter base parameter should be normal arg convention " <nl> + " or @ inout " ) ; <nl> + <nl> + if ( hasIndices ) { <nl> + auto indicesParam = substSetterType - > getParameters ( ) [ 2 ] ; <nl> + require ( indicesParam . getConvention ( ) <nl> + = = ParameterConvention : : Direct_Unowned , <nl> + " indices pointer should be trivial " ) ; <nl> + require ( indicesParam . getType ( ) - > getAnyNominal ( ) <nl> + = = C . getUnsafeRawPointerDecl ( ) , <nl> + " indices pointer should be an UnsafeRawPointer " ) ; <nl> + } <nl> + <nl> + require ( newValueParam . getType ( ) = = <nl> + loweredComponentTy . getSwiftRValueType ( ) , <nl> + " setter value should match the maximal abstraction of the " <nl> + " formal component type " ) ; <nl> + <nl> + require ( substSetterType - > getNumResults ( ) = = 0 , <nl> + " setter should have no results " ) ; <nl> + } <nl> + <nl> + if ( ! forPropertyDescriptor ) { <nl> + for ( auto & index : component . getSubscriptIndices ( ) ) { <nl> + auto opIndex = index . Operand ; <nl> + auto contextType = <nl> + index . LoweredType . subst ( M , patternSubs ) ; <nl> + require ( contextType = = operands [ opIndex ] . get ( ) - > getType ( ) , <nl> + " operand must match type required by pattern " ) ; <nl> + SILType loweredType = index . LoweredType ; <nl> + require ( loweredType . isLoweringOf ( M , index . FormalType ) , <nl> + " pattern index formal type doesn ' t match lowered type " ) ; <nl> + } <nl> + <nl> + checkIndexEqualsAndHash ( ) ; <nl> + } <nl> + <nl> + break ; <nl> + } <nl> + case KeyPathPatternComponent : : Kind : : External : { <nl> + / / The component type should match the substituted type of the <nl> + / / referenced property . <nl> + auto decl = component . getExternalDecl ( ) ; <nl> + auto sig = decl - > getInnermostDeclContext ( ) <nl> + - > getGenericSignatureOfContext ( ) ; <nl> + SubstitutionMap subs ; <nl> + CanGenericSignature canSig = nullptr ; <nl> + if ( sig ) { <nl> + canSig = sig - > getCanonicalSignature ( ) ; <nl> + subs = sig - > getSubstitutionMap ( component . getExternalSubstitutions ( ) ) ; <nl> + } <nl> + auto substType = component . getExternalDecl ( ) - > getStorageInterfaceType ( ) <nl> + . subst ( subs ) ; <nl> + require ( substType - > isEqual ( component . getComponentType ( ) ) , <nl> + " component type should match storage type of referenced " <nl> + " declaration " ) ; <nl> + <nl> + / / Index types should match the lowered index types expected by the <nl> + / / external declaration . <nl> + if ( auto sub = dyn_cast < SubscriptDecl > ( decl ) ) { <nl> + auto indexParams = sub - > getIndices ( ) ; <nl> + require ( indexParams - > size ( ) = = component . getSubscriptIndices ( ) . size ( ) , <nl> + " number of subscript indices should match referenced decl " ) ; <nl> + for ( unsigned i : indices ( * indexParams ) ) { <nl> + auto param = ( * indexParams ) [ i ] ; <nl> + auto & index = component . getSubscriptIndices ( ) [ i ] ; <nl> + auto paramTy = param - > getInterfaceType ( ) - > getCanonicalType ( ) ; <nl> + auto substParamTy = paramTy . subst ( subs ) ; <nl> + auto loweredTy = M . Types . getLoweredType ( <nl> + AbstractionPattern ( canSig , paramTy ) , substParamTy ) ; <nl> + require ( index . LoweredType = = loweredTy , <nl> + " index lowered types should match referenced decl " ) ; <nl> + require ( index . FormalType = = substParamTy - > getCanonicalType ( ) , <nl> + " index formal types should match referenced decl " ) ; <nl> + } <nl> + <nl> + checkIndexEqualsAndHash ( ) ; <nl> + } else { <nl> + require ( component . getSubscriptIndices ( ) . empty ( ) , <nl> + " external var reference should not apply indices " ) ; <nl> + require ( ! component . getSubscriptIndexEquals ( ) <nl> + & & ! component . getSubscriptIndexHash ( ) , <nl> + " external var reference should not apply hash " ) ; <nl> + } <nl> + <nl> + break ; <nl> + } <nl> + case KeyPathPatternComponent : : Kind : : OptionalChain : { <nl> + require ( baseTy - > getOptionalObjectType ( ) - > isEqual ( componentTy ) , <nl> + " chaining component should unwrap optional " ) ; <nl> + require ( ( bool ) leafTy - > getOptionalObjectType ( ) , <nl> + " key path with chaining component should have optional " <nl> + " result " ) ; <nl> + break ; <nl> + } <nl> + case KeyPathPatternComponent : : Kind : : OptionalForce : { <nl> + require ( baseTy - > getOptionalObjectType ( ) - > isEqual ( componentTy ) , <nl> + " forcing component should unwrap optional " ) ; <nl> + break ; <nl> + } <nl> + case KeyPathPatternComponent : : Kind : : OptionalWrap : { <nl> + require ( componentTy - > getOptionalObjectType ( ) - > isEqual ( baseTy ) , <nl> + " wrapping component should wrap optional " ) ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + baseTy = componentTy ; <nl> + } <nl> + <nl> / / / The SIL verifier walks over a SIL function / basic block / instruction , <nl> / / / checking and enforcing its invariants . <nl> class SILVerifier : public SILVerifierBase < SILVerifier > { <nl> class SILVerifier : public SILVerifierBase < SILVerifier > { <nl> pattern - > getGenericSignature ( ) ) ; <nl> <nl> for ( auto & component : pattern - > getComponents ( ) ) { <nl> - auto loweredBaseTy = <nl> - F . getModule ( ) . Types . getLoweredType ( AbstractionPattern : : getOpaque ( ) , <nl> - baseTy ) ; <nl> - auto componentTy = component . getComponentType ( ) . subst ( patternSubs ) <nl> - - > getCanonicalType ( ) ; <nl> - auto loweredComponentTy = <nl> - F . getModule ( ) . Types . getLoweredType ( AbstractionPattern : : getOpaque ( ) , <nl> - componentTy ) ; <nl> - <nl> - switch ( auto kind = component . getKind ( ) ) { <nl> - case KeyPathPatternComponent : : Kind : : StoredProperty : { <nl> - auto property = component . getStoredPropertyDecl ( ) ; <nl> - require ( property - > getDeclContext ( ) <nl> - = = baseTy - > getAnyNominal ( ) , <nl> - " property decl should be a member of the component base type " ) ; <nl> - switch ( property - > getStorageKind ( ) ) { <nl> - case AbstractStorageDecl : : Stored : <nl> - case AbstractStorageDecl : : StoredWithObservers : <nl> - case AbstractStorageDecl : : StoredWithTrivialAccessors : <nl> - break ; <nl> - case AbstractStorageDecl : : Addressed : <nl> - case AbstractStorageDecl : : AddressedWithObservers : <nl> - case AbstractStorageDecl : : AddressedWithTrivialAccessors : <nl> - case AbstractStorageDecl : : Computed : <nl> - case AbstractStorageDecl : : ComputedWithMutableAddress : <nl> - case AbstractStorageDecl : : InheritedWithObservers : <nl> - require ( false , " property must be stored " ) ; <nl> - } <nl> - auto propertyTy = loweredBaseTy . getFieldType ( property , F . getModule ( ) ) ; <nl> - require ( propertyTy . getObjectType ( ) <nl> - = = loweredComponentTy . getObjectType ( ) , <nl> - " component type should match the maximal abstraction of the " <nl> - " formal type " ) ; <nl> - break ; <nl> - } <nl> - <nl> - case KeyPathPatternComponent : : Kind : : GettableProperty : <nl> - case KeyPathPatternComponent : : Kind : : SettableProperty : { <nl> - bool hasIndices = ! component . getSubscriptIndices ( ) . empty ( ) ; <nl> - <nl> - ParameterConvention normalArgConvention ; <nl> - if ( F . getModule ( ) . getOptions ( ) . EnableGuaranteedNormalArguments ) <nl> - normalArgConvention = ParameterConvention : : Indirect_In_Guaranteed ; <nl> + bool hasIndices ; <nl> + switch ( component . getKind ( ) ) { <nl> + case KeyPathPatternComponent : : Kind : : External : <nl> + if ( auto subscript = <nl> + dyn_cast < SubscriptDecl > ( component . getExternalDecl ( ) ) ) <nl> + hasIndices = subscript - > getIndices ( ) - > size ( ) ! = 0 ; <nl> else <nl> - normalArgConvention = ParameterConvention : : Indirect_In ; <nl> - <nl> - / / Getter should be < Sig . . . > @ convention ( thin ) ( @ in_guaranteed Base ) - > @ out Result <nl> - { <nl> - auto getter = component . getComputedPropertyGetter ( ) ; <nl> - auto substGetterType = getter - > getLoweredFunctionType ( ) <nl> - - > substGenericArgs ( F . getModule ( ) , KPI - > getSubstitutions ( ) ) ; <nl> - require ( substGetterType - > getRepresentation ( ) = = <nl> - SILFunctionTypeRepresentation : : Thin , <nl> - " getter should be a thin function " ) ; <nl> - <nl> - require ( substGetterType - > getNumParameters ( ) = = 1 + hasIndices , <nl> - " getter should have one parameter " ) ; <nl> - auto baseParam = substGetterType - > getParameters ( ) [ 0 ] ; <nl> - require ( baseParam . getConvention ( ) = = normalArgConvention , <nl> - " getter base parameter should have normal arg convention " ) ; <nl> - require ( baseParam . getType ( ) = = loweredBaseTy . getSwiftRValueType ( ) , <nl> - " getter base parameter should match base of component " ) ; <nl> - <nl> - if ( hasIndices ) { <nl> - auto indicesParam = substGetterType - > getParameters ( ) [ 1 ] ; <nl> - require ( indicesParam . getConvention ( ) <nl> - = = ParameterConvention : : Direct_Unowned , <nl> - " indices pointer should be trivial " ) ; <nl> - require ( indicesParam . getType ( ) - > getAnyNominal ( ) <nl> - = = C . getUnsafeRawPointerDecl ( ) , <nl> - " indices pointer should be an UnsafeRawPointer " ) ; <nl> - } <nl> - <nl> - require ( substGetterType - > getNumResults ( ) = = 1 , <nl> - " getter should have one result " ) ; <nl> - auto result = substGetterType - > getResults ( ) [ 0 ] ; <nl> - require ( result . getConvention ( ) = = ResultConvention : : Indirect , <nl> - " getter result should be @ out " ) ; <nl> - require ( result . getType ( ) = = loweredComponentTy . getSwiftRValueType ( ) , <nl> - " getter result should match the maximal abstraction of the " <nl> - " formal component type " ) ; <nl> - } <nl> - <nl> - if ( kind = = KeyPathPatternComponent : : Kind : : SettableProperty ) { <nl> - / / Setter should be <nl> - / / < Sig . . . > @ convention ( thin ) ( @ in_guaranteed Result , @ in Base ) - > ( ) <nl> - <nl> - auto setter = component . getComputedPropertySetter ( ) ; <nl> - auto substSetterType = setter - > getLoweredFunctionType ( ) <nl> - - > substGenericArgs ( F . getModule ( ) , KPI - > getSubstitutions ( ) ) ; <nl> - <nl> - require ( substSetterType - > getRepresentation ( ) = = <nl> - SILFunctionTypeRepresentation : : Thin , <nl> - " setter should be a thin function " ) ; <nl> - <nl> - require ( substSetterType - > getNumParameters ( ) = = 2 + hasIndices , <nl> - " setter should have two parameters " ) ; <nl> - <nl> - auto newValueParam = substSetterType - > getParameters ( ) [ 0 ] ; <nl> - / / TODO : This should probably be unconditionally + 1 when we <nl> - / / can represent that . <nl> - require ( newValueParam . getConvention ( ) = = normalArgConvention , <nl> - " setter value parameter should havee normal arg convention " ) ; <nl> - <nl> - auto baseParam = substSetterType - > getParameters ( ) [ 1 ] ; <nl> - require ( baseParam . getConvention ( ) = = normalArgConvention <nl> - | | baseParam . getConvention ( ) = = <nl> - ParameterConvention : : Indirect_Inout , <nl> - " setter base parameter should be normal arg convention " <nl> - " or @ inout " ) ; <nl> - <nl> - if ( hasIndices ) { <nl> - auto indicesParam = substSetterType - > getParameters ( ) [ 2 ] ; <nl> - require ( indicesParam . getConvention ( ) <nl> - = = ParameterConvention : : Direct_Unowned , <nl> - " indices pointer should be trivial " ) ; <nl> - require ( indicesParam . getType ( ) - > getAnyNominal ( ) <nl> - = = C . getUnsafeRawPointerDecl ( ) , <nl> - " indices pointer should be an UnsafeRawPointer " ) ; <nl> - } <nl> - <nl> - require ( newValueParam . getType ( ) = = <nl> - loweredComponentTy . getSwiftRValueType ( ) , <nl> - " setter value should match the maximal abstraction of the " <nl> - " formal component type " ) ; <nl> - <nl> - require ( substSetterType - > getNumResults ( ) = = 0 , <nl> - " setter should have no results " ) ; <nl> - } <nl> - <nl> - for ( auto & index : component . getSubscriptIndices ( ) ) { <nl> - auto opIndex = index . Operand ; <nl> - auto contextType = <nl> - index . LoweredType . subst ( F . getModule ( ) , patternSubs ) ; <nl> - requireSameType ( contextType , <nl> - KPI - > getAllOperands ( ) [ opIndex ] . get ( ) - > getType ( ) , <nl> - " operand must match type required by pattern " ) ; <nl> - require ( isLoweringOf ( index . LoweredType , index . FormalType ) , <nl> - " pattern index formal type doesn ' t match lowered type " ) ; <nl> - } <nl> - <nl> - if ( ! component . getSubscriptIndices ( ) . empty ( ) ) { <nl> - / / Equals should be <nl> - / / < Sig . . . > @ convention ( thin ) ( RawPointer , RawPointer ) - > Bool <nl> - { <nl> - auto equals = component . getSubscriptIndexEquals ( ) ; <nl> - require ( equals , " key path pattern with indexes must have equals " <nl> - " operator " ) ; <nl> - <nl> - auto substEqualsType = equals - > getLoweredFunctionType ( ) <nl> - - > substGenericArgs ( F . getModule ( ) , KPI - > getSubstitutions ( ) ) ; <nl> - <nl> - require ( substEqualsType - > getParameters ( ) . size ( ) = = 2 , <nl> - " must have two arguments " ) ; <nl> - for ( unsigned i = 0 ; i < 2 ; + + i ) { <nl> - auto param = substEqualsType - > getParameters ( ) [ i ] ; <nl> - require ( param . getConvention ( ) <nl> - = = ParameterConvention : : Direct_Unowned , <nl> - " indices pointer should be trivial " ) ; <nl> - require ( param . getType ( ) - > getAnyNominal ( ) <nl> - = = C . getUnsafeRawPointerDecl ( ) , <nl> - " indices pointer should be an UnsafeRawPointer " ) ; <nl> - } <nl> - <nl> - require ( substEqualsType - > getResults ( ) . size ( ) = = 1 , <nl> - " must have one result " ) ; <nl> - <nl> - require ( substEqualsType - > getResults ( ) [ 0 ] . getConvention ( ) <nl> - = = ResultConvention : : Unowned , <nl> - " result should be unowned " ) ; <nl> - require ( substEqualsType - > getResults ( ) [ 0 ] . getType ( ) - > getAnyNominal ( ) <nl> - = = C . getBoolDecl ( ) , <nl> - " result should be Bool " ) ; <nl> - } <nl> - { <nl> - / / Hash should be <nl> - / / < Sig . . . > @ convention ( thin ) ( RawPointer ) - > Int <nl> - auto hash = component . getSubscriptIndexHash ( ) ; <nl> - require ( hash , " key path pattern with indexes must have hash " <nl> - " operator " ) ; <nl> - <nl> - auto substHashType = hash - > getLoweredFunctionType ( ) <nl> - - > substGenericArgs ( F . getModule ( ) , KPI - > getSubstitutions ( ) ) ; <nl> - <nl> - require ( substHashType - > getParameters ( ) . size ( ) = = 1 , <nl> - " must have two arguments " ) ; <nl> - auto param = substHashType - > getParameters ( ) [ 0 ] ; <nl> - require ( param . getConvention ( ) <nl> - = = ParameterConvention : : Direct_Unowned , <nl> - " indices pointer should be trivial " ) ; <nl> - require ( param . getType ( ) - > getAnyNominal ( ) <nl> - = = C . getUnsafeRawPointerDecl ( ) , <nl> - " indices pointer should be an UnsafeRawPointer " ) ; <nl> - <nl> - require ( substHashType - > getResults ( ) . size ( ) = = 1 , <nl> - " must have one result " ) ; <nl> - <nl> - require ( substHashType - > getResults ( ) [ 0 ] . getConvention ( ) <nl> - = = ResultConvention : : Unowned , <nl> - " result should be unowned " ) ; <nl> - require ( substHashType - > getResults ( ) [ 0 ] . getType ( ) - > getAnyNominal ( ) <nl> - = = C . getIntDecl ( ) , <nl> - " result should be Int " ) ; <nl> - } <nl> - } else { <nl> - require ( ! component . getSubscriptIndexEquals ( ) <nl> - & & ! component . getSubscriptIndexHash ( ) , <nl> - " component without indexes must not have equals / hash " ) ; <nl> - } <nl> - <nl> + hasIndices = false ; <nl> break ; <nl> - } <nl> - case KeyPathPatternComponent : : Kind : : External : { <nl> - / / The component type should match the substituted type of the <nl> - / / referenced property . <nl> - auto decl = component . getExternalDecl ( ) ; <nl> - auto sig = decl - > getInnermostDeclContext ( ) <nl> - - > getGenericSignatureOfContext ( ) <nl> - - > getCanonicalSignature ( ) ; <nl> - auto subs = <nl> - sig - > getSubstitutionMap ( component . getExternalSubstitutions ( ) ) ; <nl> - auto substType = component . getExternalDecl ( ) - > getStorageInterfaceType ( ) <nl> - . subst ( subs ) ; <nl> - require ( substType - > isEqual ( component . getComponentType ( ) ) , <nl> - " component type should match storage type of referenced " <nl> - " declaration " ) ; <nl> - <nl> - / / Index types should match the lowered index types expected by the <nl> - / / external declaration . <nl> - if ( auto sub = dyn_cast < SubscriptDecl > ( decl ) ) { <nl> - auto indexParams = sub - > getIndices ( ) ; <nl> - require ( indexParams - > size ( ) = = component . getSubscriptIndices ( ) . size ( ) , <nl> - " number of subscript indices should match referenced decl " ) ; <nl> - for ( unsigned i : indices ( * indexParams ) ) { <nl> - auto param = ( * indexParams ) [ i ] ; <nl> - auto & index = component . getSubscriptIndices ( ) [ i ] ; <nl> - auto paramTy = param - > getInterfaceType ( ) - > getCanonicalType ( ) ; <nl> - auto substParamTy = paramTy . subst ( subs ) ; <nl> - auto loweredTy = F . getModule ( ) . Types . getLoweredType ( <nl> - AbstractionPattern ( sig , paramTy ) , substParamTy ) ; <nl> - requireSameType ( index . LoweredType , loweredTy , <nl> - " index lowered types should match referenced decl " ) ; <nl> - require ( index . FormalType = = substParamTy - > getCanonicalType ( ) , <nl> - " index formal types should match referenced decl " ) ; <nl> - } <nl> - } else { <nl> - require ( component . getSubscriptIndices ( ) . empty ( ) , <nl> - " external var reference should not apply indices " ) ; <nl> - } <nl> - <nl> - break ; <nl> - } <nl> - case KeyPathPatternComponent : : Kind : : OptionalChain : { <nl> - require ( baseTy - > getOptionalObjectType ( ) - > isEqual ( componentTy ) , <nl> - " chaining component should unwrap optional " ) ; <nl> - require ( leafTy - > getOptionalObjectType ( ) , <nl> - " key path with chaining component should have optional " <nl> - " result " ) ; <nl> - break ; <nl> - } <nl> - case KeyPathPatternComponent : : Kind : : OptionalForce : { <nl> - require ( baseTy - > getOptionalObjectType ( ) - > isEqual ( componentTy ) , <nl> - " forcing component should unwrap optional " ) ; <nl> + <nl> + case KeyPathPatternComponent : : Kind : : GettableProperty : <nl> + case KeyPathPatternComponent : : Kind : : SettableProperty : <nl> + hasIndices = ! component . getSubscriptIndices ( ) . empty ( ) ; <nl> break ; <nl> - } <nl> - case KeyPathPatternComponent : : Kind : : OptionalWrap : { <nl> - require ( componentTy - > getOptionalObjectType ( ) - > isEqual ( baseTy ) , <nl> - " wrapping component should wrap optional " ) ; <nl> + <nl> + case KeyPathPatternComponent : : Kind : : StoredProperty : <nl> + case KeyPathPatternComponent : : Kind : : OptionalChain : <nl> + case KeyPathPatternComponent : : Kind : : OptionalWrap : <nl> + case KeyPathPatternComponent : : Kind : : OptionalForce : <nl> + hasIndices = false ; <nl> break ; <nl> } <nl> - } <nl> - <nl> - baseTy = componentTy ; <nl> + <nl> + verifyKeyPathComponent ( F . getModule ( ) , <nl> + [ & ] ( bool reqt , StringRef message ) { _require ( reqt , message ) ; } , <nl> + baseTy , <nl> + leafTy , <nl> + component , <nl> + KPI - > getAllOperands ( ) , <nl> + KPI - > getPattern ( ) - > getGenericSignature ( ) , <nl> + KPI - > getSubstitutions ( ) , <nl> + / * property descriptor * / false , <nl> + hasIndices ) ; <nl> } <nl> } <nl> require ( CanType ( baseTy ) = = CanType ( leafTy ) , <nl> void SILFunction : : verify ( bool SingleFunction ) const { <nl> SILVerifier ( * this , SingleFunction ) . verify ( ) ; <nl> } <nl> <nl> + / / / Verify that a property descriptor follows invariants . <nl> + void SILProperty : : verify ( const SILModule & M ) const { <nl> + # ifdef NDEBUG <nl> + if ( ! M . getOptions ( ) . VerifyAll ) <nl> + return ; <nl> + # endif <nl> + <nl> + auto * decl = getDecl ( ) ; <nl> + auto * dc = decl - > getInnermostDeclContext ( ) ; <nl> + auto & component = getComponent ( ) ; <nl> + <nl> + / / TODO : base type for global / static descriptors <nl> + auto sig = dc - > getGenericSignatureOfContext ( ) ; <nl> + auto baseTy = dc - > getInnermostTypeContext ( ) - > getSelfInterfaceType ( ) <nl> + - > getCanonicalType ( sig ) ; <nl> + auto leafTy = decl - > getStorageInterfaceType ( ) - > getReferenceStorageReferent ( ) <nl> + - > getCanonicalType ( sig ) ; <nl> + SubstitutionList subs ; <nl> + if ( sig ) { <nl> + auto env = dc - > getGenericEnvironmentOfContext ( ) ; <nl> + subs = env - > getForwardingSubstitutions ( ) ; <nl> + baseTy = env - > mapTypeIntoContext ( baseTy ) - > getCanonicalType ( ) ; <nl> + leafTy = env - > mapTypeIntoContext ( leafTy ) - > getCanonicalType ( ) ; <nl> + } <nl> + bool hasIndices = false ; <nl> + if ( auto subscript = dyn_cast < SubscriptDecl > ( decl ) ) { <nl> + hasIndices = subscript - > getIndices ( ) - > size ( ) ! = 0 ; <nl> + } <nl> + <nl> + auto canSig = sig ? sig - > getCanonicalSignature ( ) : nullptr ; <nl> + Lowering : : GenericContextScope scope ( M . Types , canSig ) ; <nl> + <nl> + auto require = [ & ] ( bool reqt , StringRef message ) { <nl> + if ( ! reqt ) { <nl> + llvm : : errs ( ) < < message < < " \ n " ; <nl> + assert ( false & & " invoking standard assertion failure " ) ; <nl> + } <nl> + } ; <nl> + <nl> + verifyKeyPathComponent ( const_cast < SILModule & > ( M ) , <nl> + require , <nl> + baseTy , <nl> + leafTy , <nl> + component , <nl> + { } , <nl> + canSig , <nl> + subs , <nl> + / * property descriptor * / true , <nl> + hasIndices ) ; <nl> + <nl> + / / verifyKeyPathComponent updates baseTy to be the projected type of the <nl> + / / component , which should be the same as the type of the declared storage <nl> + require ( baseTy = = leafTy , <nl> + " component type of property descriptor should match type of storage " ) ; <nl> + } <nl> + <nl> / / / Verify that a vtable follows invariants . <nl> void SILVTable : : verify ( const SILModule & M ) const { <nl> # ifdef NDEBUG <nl> void SILModule : : verify ( ) const { <nl> } <nl> wt . verify ( * this ) ; <nl> } <nl> + <nl> + / / Check property descriptors . <nl> + DEBUG ( llvm : : dbgs ( ) < < " * * * Checking property descriptors * * * \ n " ) ; <nl> + for ( auto & prop : getPropertyList ( ) ) { <nl> + prop . verify ( * this ) ; <nl> + } <nl> } <nl> <nl> / / / Determine whether an instruction may not have a SILDebugScope . <nl> mmm a / lib / SILGen / SILGen . cpp <nl> ppp b / lib / SILGen / SILGen . cpp <nl> void SILGenModule : : tryEmitPropertyDescriptor ( AbstractStorageDecl * decl ) { <nl> <nl> Type baseTy ; <nl> if ( decl - > getDeclContext ( ) - > isTypeContext ( ) ) { <nl> - baseTy = decl - > getDeclContext ( ) - > getSelfInterfaceType ( ) ; <nl> + baseTy = decl - > getDeclContext ( ) - > getSelfInterfaceType ( ) <nl> + - > getCanonicalType ( decl - > getInnermostDeclContext ( ) <nl> + - > getGenericSignatureOfContext ( ) ) ; <nl> if ( decl - > isStatic ( ) ) { <nl> / / TODO : Static properties should eventually be referenceable as <nl> / / keypaths from T . Type - > Element <nl> void SILGenModule : : tryEmitPropertyDescriptor ( AbstractStorageDecl * decl ) { <nl> if ( genericEnv ) <nl> subs = genericEnv - > getForwardingSubstitutions ( ) ; <nl> <nl> - / / TODO : The hashable conformances for the indices need to be provided by the <nl> - / / client , since they may be post - hoc conformances , or a generic subscript <nl> - / / may be invoked with hashable substitutions . We may eventually allow for <nl> - / / non - hashable keypaths as well . <nl> - SmallVector < ProtocolConformanceRef , 4 > indexHashables ; <nl> if ( auto sub = dyn_cast < SubscriptDecl > ( decl ) ) { <nl> - auto hashable = getASTContext ( ) . getProtocol ( KnownProtocolKind : : Hashable ) ; <nl> for ( auto * index : * sub - > getIndices ( ) ) { <nl> + / / Keypaths can ' t capture inout indices . <nl> if ( index - > isInOut ( ) ) <nl> return ; <nl> + <nl> + / / TODO : Handle reabstraction and tuple explosion in thunk generation . <nl> + / / This wasn ' t previously a concern because anything that was Hashable <nl> + / / had only one abstraction level and no explosion . <nl> auto indexTy = index - > getInterfaceType ( ) ; <nl> + <nl> + if ( isa < TupleType > ( indexTy - > getCanonicalType ( sub - > getGenericSignature ( ) ) ) ) <nl> + return ; <nl> + <nl> if ( genericEnv ) <nl> indexTy = genericEnv - > mapTypeIntoContext ( indexTy ) ; <nl> <nl> - auto conformance = sub - > getModuleContext ( ) <nl> - - > lookupConformance ( indexTy , hashable ) ; <nl> - if ( ! conformance ) <nl> - return ; <nl> - if ( ! conformance - > getConditionalRequirements ( ) . empty ( ) ) <nl> + auto indexLoweredTy = Types . getLoweredType ( indexTy ) ; <nl> + auto indexOpaqueLoweredTy = <nl> + Types . getLoweredType ( AbstractionPattern : : getOpaque ( ) , indexTy ) ; <nl> + <nl> + if ( indexOpaqueLoweredTy . getAddressType ( ) <nl> + ! = indexLoweredTy . getAddressType ( ) ) <nl> return ; <nl> - indexHashables . push_back ( * conformance ) ; <nl> } <nl> } <nl> - <nl> + <nl> auto component = emitKeyPathComponentForDecl ( SILLocation ( decl ) , <nl> genericEnv , <nl> baseOperand , needsGenericContext , <nl> - subs , decl , indexHashables , <nl> - baseTy - > getCanonicalType ( ) ) ; <nl> + subs , decl , { } , <nl> + baseTy - > getCanonicalType ( ) , <nl> + / * property descriptor * / true ) ; <nl> <nl> ( void ) SILProperty : : create ( M , / * serialized * / false , decl , component ) ; <nl> } <nl> mmm a / lib / SILGen / SILGen . h <nl> ppp b / lib / SILGen / SILGen . h <nl> class LLVM_LIBRARY_VISIBILITY SILGenModule : public ASTVisitor < SILGenModule > { <nl> SubstitutionList subs , <nl> AbstractStorageDecl * storage , <nl> ArrayRef < ProtocolConformanceRef > indexHashables , <nl> - CanType baseTy ) ; <nl> + CanType baseTy , <nl> + bool forPropertyDescriptor ) ; <nl> <nl> / / / Known functions for bridging . <nl> SILDeclRef getStringToNSStringFn ( ) ; <nl> mmm a / lib / SILGen / SILGenExpr . cpp <nl> ppp b / lib / SILGen / SILGenExpr . cpp <nl> emitKeyPathRValueBase ( SILGenFunction & subSGF , <nl> return paramSubstValue ; <nl> } <nl> <nl> + using IndexTypePair = std : : pair < CanType , SILType > ; <nl> + <nl> / / / Helper function to load the captured indexes out of a key path component <nl> / / / in order to invoke the accessors on that key path . A component with captured <nl> / / / indexes passes down a pointer to those captures to the accessor thunks , <nl> / / / which we can copy out of to produce values we can pass to the real <nl> / / / accessor functions . <nl> static RValue loadIndexValuesForKeyPathComponent ( SILGenFunction & SGF , <nl> - SILLocation loc , <nl> - ArrayRef < KeyPathPatternComponent : : Index > indexes , <nl> - SILValue pointer ) { <nl> + SILLocation loc , <nl> + ArrayRef < IndexTypePair > indexes , <nl> + SILValue pointer ) { <nl> / / If no indexes , do nothing . <nl> if ( indexes . empty ( ) ) <nl> return RValue ( ) ; <nl> <nl> SmallVector < TupleTypeElt , 2 > indexElts ; <nl> for ( auto & elt : indexes ) { <nl> - indexElts . push_back ( SGF . F . mapTypeIntoContext ( elt . FormalType ) ) ; <nl> + indexElts . push_back ( SGF . F . mapTypeIntoContext ( elt . first ) ) ; <nl> } <nl> <nl> auto indexTupleTy = TupleType : : get ( indexElts , SGF . getASTContext ( ) ) <nl> static RValue loadIndexValuesForKeyPathComponent ( SILGenFunction & SGF , <nl> if ( indexes . size ( ) > 1 ) { <nl> eltAddr = SGF . B . createTupleElementAddr ( loc , eltAddr , i ) ; <nl> } <nl> - auto ty = SGF . F . mapTypeIntoContext ( indexes [ i ] . LoweredType ) ; <nl> + auto ty = SGF . F . mapTypeIntoContext ( indexes [ i ] . second ) ; <nl> auto value = SGF . emitLoad ( loc , eltAddr , <nl> SGF . getTypeLowering ( ty ) , <nl> SGFContext ( ) , IsNotTake ) ; <nl> - indexValue . addElement ( SGF , value , indexes [ i ] . FormalType , loc ) ; <nl> + indexValue . addElement ( SGF , value , indexes [ i ] . first , loc ) ; <nl> } <nl> <nl> return indexValue ; <nl> static SILFunction * getOrCreateKeyPathGetter ( SILGenModule & SGM , <nl> SubstitutionList subs , <nl> AccessStrategy strategy , <nl> GenericEnvironment * genericEnv , <nl> - ArrayRef < KeyPathPatternComponent : : Index > indexes , <nl> + ArrayRef < IndexTypePair > indexes , <nl> CanType baseType , <nl> CanType propertyType ) { <nl> auto genericSig = genericEnv <nl> SILFunction * getOrCreateKeyPathSetter ( SILGenModule & SGM , <nl> SubstitutionList subs , <nl> AccessStrategy strategy , <nl> GenericEnvironment * genericEnv , <nl> - ArrayRef < KeyPathPatternComponent : : Index > indexes , <nl> + ArrayRef < IndexTypePair > indexes , <nl> CanType baseType , <nl> CanType propertyType ) { <nl> auto genericSig = genericEnv <nl> getIdForKeyPathComponentComputedProperty ( SILGenModule & SGM , <nl> } <nl> <nl> static void <nl> - lowerKeyPathSubscriptIndexPatterns ( <nl> + lowerKeyPathSubscriptIndexTypes ( <nl> SILGenModule & SGM , <nl> - SmallVectorImpl < KeyPathPatternComponent : : Index > & indexPatterns , <nl> + SmallVectorImpl < IndexTypePair > & indexPatterns , <nl> SubscriptDecl * subscript , <nl> SubstitutionList subscriptSubs , <nl> - ArrayRef < ProtocolConformanceRef > indexHashables , <nl> - unsigned & baseOperand , <nl> bool & needsGenericContext ) { <nl> / / Capturing an index value dependent on the generic context means we <nl> / / need the generic context captured in the key path . <nl> lowerKeyPathSubscriptIndexPatterns ( <nl> } <nl> needsGenericContext | = subscriptSubstTy - > hasArchetype ( ) ; <nl> <nl> - unsigned i = 0 ; <nl> for ( auto * index : * subscript - > getIndices ( ) ) { <nl> auto indexTy = index - > getInterfaceType ( ) ; <nl> if ( sig ) { <nl> indexTy = indexTy . subst ( subMap ) ; <nl> } <nl> - auto hashable = indexHashables [ i + + ] ; <nl> - assert ( hashable . isAbstract ( ) | | <nl> - hashable . getConcrete ( ) - > getType ( ) - > isEqual ( indexTy ) ) ; <nl> - <nl> auto indexLoweredTy = SGM . Types . getLoweredType ( <nl> AbstractionPattern : : getOpaque ( ) , <nl> indexTy ) ; <nl> lowerKeyPathSubscriptIndexPatterns ( <nl> indexLoweredTy . getSwiftRValueType ( ) - > mapTypeOutOfContext ( ) <nl> - > getCanonicalType ( ) , <nl> indexLoweredTy . getCategory ( ) ) ; <nl> - indexPatterns . push_back ( { baseOperand + + , <nl> - indexTy - > mapTypeOutOfContext ( ) <nl> + indexPatterns . push_back ( { indexTy - > mapTypeOutOfContext ( ) <nl> - > getCanonicalType ( ) , <nl> - indexLoweredTy , <nl> - hashable } ) ; <nl> + indexLoweredTy } ) ; <nl> + } <nl> + } ; <nl> + <nl> + static void <nl> + lowerKeyPathSubscriptIndexPatterns ( <nl> + SmallVectorImpl < KeyPathPatternComponent : : Index > & indexPatterns , <nl> + ArrayRef < IndexTypePair > indexTypes , <nl> + ArrayRef < ProtocolConformanceRef > indexHashables , <nl> + unsigned & baseOperand ) { <nl> + for ( unsigned i : indices ( indexTypes ) ) { <nl> + CanType formalTy ; <nl> + SILType loweredTy ; <nl> + std : : tie ( formalTy , loweredTy ) = indexTypes [ i ] ; <nl> + auto hashable = indexHashables [ i ] ; <nl> + assert ( hashable . isAbstract ( ) | | <nl> + hashable . getConcrete ( ) - > getType ( ) - > mapTypeOutOfContext ( ) <nl> + - > isEqual ( formalTy ) ) ; <nl> + <nl> + indexPatterns . push_back ( { baseOperand + + , formalTy , loweredTy , hashable } ) ; <nl> } <nl> } ; <nl> <nl> SILGenModule : : emitKeyPathComponentForDecl ( SILLocation loc , <nl> SubstitutionList subs , <nl> AbstractStorageDecl * storage , <nl> ArrayRef < ProtocolConformanceRef > indexHashables , <nl> - CanType baseTy ) { <nl> + CanType baseTy , <nl> + bool forPropertyDescriptor ) { <nl> if ( auto var = dyn_cast < VarDecl > ( storage ) ) { <nl> CanType componentTy ; <nl> if ( ! var - > getDeclContext ( ) - > isTypeContext ( ) ) { <nl> SILGenModule : : emitKeyPathComponentForDecl ( SILLocation loc , <nl> } else { <nl> componentTy = baseTy - > getTypeOfMember ( SwiftModule , var ) <nl> - > getReferenceStorageReferent ( ) <nl> - - > getCanonicalType ( ) ; <nl> + - > getCanonicalType ( genericEnv ? genericEnv - > getGenericSignature ( ) <nl> + : nullptr ) ; <nl> } <nl> <nl> switch ( auto strategy = var - > getAccessStrategy ( AccessSemantics : : Ordinary , <nl> SILGenModule : : emitKeyPathComponentForDecl ( SILLocation loc , <nl> baseSubscriptTy - > mapTypeOutOfContext ( ) - > getCanonicalType ( ) ) ; <nl> auto componentTy = baseSubscriptInterfaceTy . getResult ( ) ; <nl> <nl> - SmallVector < KeyPathPatternComponent : : Index , 4 > indexPatterns ; <nl> - lowerKeyPathSubscriptIndexPatterns ( * this , indexPatterns , <nl> - decl , subs , indexHashables , <nl> - baseOperand , <nl> - needsGenericContext ) ; <nl> + SmallVector < IndexTypePair , 4 > indexTypes ; <nl> + lowerKeyPathSubscriptIndexTypes ( * this , indexTypes , <nl> + decl , subs , <nl> + needsGenericContext ) ; <nl> <nl> + SmallVector < KeyPathPatternComponent : : Index , 4 > indexPatterns ; <nl> SILFunction * indexEquals = nullptr , * indexHash = nullptr ; <nl> - / / TODO : Property descriptors for external key paths should get their <nl> - / / equality and hashing from the client . <nl> - getOrCreateKeyPathEqualsAndHash ( * this , loc , <nl> - needsGenericContext ? genericEnv : nullptr , <nl> - indexPatterns , <nl> - indexEquals , indexHash ) ; <nl> - <nl> + / / Property descriptors get their index information from the client . <nl> + if ( ! forPropertyDescriptor ) { <nl> + lowerKeyPathSubscriptIndexPatterns ( indexPatterns , <nl> + indexTypes , indexHashables , <nl> + baseOperand ) ; <nl> + <nl> + getOrCreateKeyPathEqualsAndHash ( * this , loc , <nl> + needsGenericContext ? genericEnv : nullptr , <nl> + indexPatterns , <nl> + indexEquals , indexHash ) ; <nl> + } <nl> + <nl> auto id = getIdForKeyPathComponentComputedProperty ( * this , decl , strategy ) ; <nl> auto getter = getOrCreateKeyPathGetter ( * this , loc , <nl> decl , subs , <nl> strategy , <nl> needsGenericContext ? genericEnv : nullptr , <nl> - indexPatterns , <nl> + indexTypes , <nl> baseTy , componentTy ) ; <nl> <nl> auto indexPatternsCopy = getASTContext ( ) . AllocateCopy ( indexPatterns ) ; <nl> SILGenModule : : emitKeyPathComponentForDecl ( SILLocation loc , <nl> decl , subs , <nl> strategy , <nl> needsGenericContext ? genericEnv : nullptr , <nl> - indexPatterns , <nl> + indexTypes , <nl> baseTy , componentTy ) ; <nl> return KeyPathPatternComponent : : forComputedSettableProperty ( id , <nl> getter , setter , <nl> RValue RValueEmitter : : visitKeyPathExpr ( KeyPathExpr * E , SGFContext C ) { <nl> ty = ty . subst ( subMap ) ; <nl> } <nl> <nl> + SILFunction * indexEquals = nullptr , * indexHash = nullptr ; <nl> if ( component . getKind ( ) = = KeyPathExpr : : Component : : Kind : : Subscript ) { <nl> unsigned numOperands = operands . size ( ) ; <nl> - lowerKeyPathSubscriptIndexPatterns ( SGF . SGM , <nl> - indices , <nl> - cast < SubscriptDecl > ( component . getDeclRef ( ) . getDecl ( ) ) , <nl> - component . getDeclRef ( ) . getSubstitutions ( ) , <nl> + SmallVector < IndexTypePair , 4 > indexTypes ; <nl> + auto sub = cast < SubscriptDecl > ( component . getDeclRef ( ) . getDecl ( ) ) ; <nl> + lowerKeyPathSubscriptIndexTypes ( SGF . SGM , indexTypes , <nl> + sub , component . getDeclRef ( ) . getSubstitutions ( ) , <nl> + needsGenericContext ) ; <nl> + lowerKeyPathSubscriptIndexPatterns ( indices , indexTypes , <nl> component . getSubscriptIndexHashableConformances ( ) , <nl> - numOperands , <nl> - needsGenericContext ) ; <nl> + numOperands ) ; <nl> <nl> lowerSubscriptOperands ( component ) ; <nl> <nl> assert ( numOperands = = operands . size ( ) <nl> & & " operand count out of sync " ) ; <nl> + getOrCreateKeyPathEqualsAndHash ( SGF . SGM , SILLocation ( E ) , <nl> + needsGenericContext ? SGF . F . getGenericEnvironment ( ) : nullptr , <nl> + indices , <nl> + indexEquals , indexHash ) ; <nl> } <nl> return KeyPathPatternComponent : : forExternal ( <nl> decl , subs , SGF . getASTContext ( ) . AllocateCopy ( indices ) , <nl> + indexEquals , indexHash , <nl> ty - > getCanonicalType ( ) ) ; <nl> } ; <nl> <nl> RValue RValueEmitter : : visitKeyPathExpr ( KeyPathExpr * E , SGFContext C ) { <nl> component . getDeclRef ( ) . getSubstitutions ( ) , <nl> decl , <nl> component . getSubscriptIndexHashableConformances ( ) , <nl> - baseTy ) ) ; <nl> + baseTy , <nl> + / * for descriptor * / false ) ) ; <nl> lowerSubscriptOperands ( component ) ; <nl> <nl> assert ( numOperands = = operands . size ( ) <nl> mmm a / lib / Serialization / DeserializeSIL . cpp <nl> ppp b / lib / Serialization / DeserializeSIL . cpp <nl> SILDeserializer : : readKeyPathComponent ( ArrayRef < uint64_t > ListOfValues , <nl> } <nl> <nl> indices = MF - > getContext ( ) . AllocateCopy ( indicesBuf ) ; <nl> - if ( ! indices . empty ( ) & & <nl> - kind ! = KeyPathComponentKindEncoding : : External ) { <nl> + if ( ! indices . empty ( ) ) { <nl> auto indicesEqualsName = MF - > getIdentifier ( ListOfValues [ nextValue + + ] ) ; <nl> auto indicesHashName = MF - > getIdentifier ( ListOfValues [ nextValue + + ] ) ; <nl> indicesEquals = getFuncForReference ( indicesEqualsName . str ( ) ) ; <nl> SILDeserializer : : readKeyPathComponent ( ArrayRef < uint64_t > ListOfValues , <nl> } <nl> handleComputedIndices ( ) ; <nl> return KeyPathPatternComponent : : forExternal ( decl , <nl> - MF - > getContext ( ) . AllocateCopy ( subs ) , indices , type ) ; <nl> + MF - > getContext ( ) . AllocateCopy ( subs ) , <nl> + indices , indicesEquals , indicesHash , type ) ; <nl> } <nl> } <nl> } <nl> mmm a / lib / Serialization / SerializeSIL . cpp <nl> ppp b / lib / Serialization / SerializeSIL . cpp <nl> SILSerializer : : writeKeyPathPatternComponent ( <nl> ListOfValues . push_back ( ( unsigned ) index . LoweredType . getCategory ( ) ) ; <nl> serializeAfter . push_back ( index . Hashable ) ; <nl> } <nl> - if ( ! indices . empty ( ) & & <nl> - component . getKind ( ) ! = KeyPathPatternComponent : : Kind : : External ) { <nl> + if ( ! indices . empty ( ) ) { <nl> ListOfValues . push_back ( <nl> addSILFunctionRef ( component . getSubscriptIndexEquals ( ) ) ) ; <nl> ListOfValues . push_back ( <nl> mmm a / test / IRGen / keypaths . sil <nl> ppp b / test / IRGen / keypaths . sil <nl> entry ( % 0 : $ * A , % 1 : $ * B , % 2 : $ * A , % 3 : $ * B , % 4 : $ * A , % 5 : $ * B ) : <nl> <nl> % u = keypath $ KeyPath < G < A > , A > , < X : Hashable , Y : Hashable > ( <nl> root $ G < Y > ; <nl> - external # G . subscript < Y , X > [ % $ 0 : $ X : $ * X ] : $ Y <nl> + external # G . subscript < Y , X > [ % $ 0 : $ X : $ * X ] : $ Y , <nl> + indices_equals @ s_equals : $ @ convention ( thin ) < A : Hashable , B : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> + indices_hash @ s_hash : $ @ convention ( thin ) < A : Hashable , B : Hashable > ( UnsafeRawPointer ) - > Int <nl> ) < B , A > ( % 1 ) <nl> <nl> % v = keypath $ KeyPath < G < G < B > > , B > , < X : Hashable , Y : Hashable > ( <nl> root $ G < G < X > > ; <nl> - external # G . subscript < G < X > , Y > [ % $ 1 : $ Y : $ * Y ] : $ G < X > ; <nl> - external # G . subscript < X , X > [ % $ 0 : $ X : $ * X ] : $ X <nl> + external # G . subscript < G < X > , Y > [ % $ 1 : $ Y : $ * Y ] : $ G < X > , <nl> + indices_equals @ s_equals : $ @ convention ( thin ) < A : Hashable , B : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> + indices_hash @ s_hash : $ @ convention ( thin ) < A : Hashable , B : Hashable > ( UnsafeRawPointer ) - > Int ; <nl> + external # G . subscript < X , X > [ % $ 0 : $ X : $ * X ] : $ X , <nl> + indices_equals @ s_equals : $ @ convention ( thin ) < A : Hashable , B : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> + indices_hash @ s_hash : $ @ convention ( thin ) < A : Hashable , B : Hashable > ( UnsafeRawPointer ) - > Int <nl> ) < B , A > ( % 3 , % 4 ) <nl> <nl> return undef : $ ( ) <nl> mmm a / test / SIL / Parser / keypath . sil <nl> ppp b / test / SIL / Parser / keypath . sil <nl> entry ( % z : $ * B ) : <nl> / / CHECK : % 3 = keypath $ KeyPath < External < Int > , Int > , < τ_0_0 > ( root $ External < τ_0_0 > ; external # External . ro < τ_0_0 > : $ τ_0_0 ) < Int > <nl> % c = keypath $ KeyPath < External < Int > , Int > , < F > ( root $ External < F > ; external # External . ro < F > : $ F ) < Int > <nl> <nl> - / / CHECK : % 4 = keypath $ KeyPath < External < A > , A > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_1 > ; external # External . subscript < τ_0_1 , τ_0_0 > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_1 ) < B , A > ( % 0 ) <nl> - % d = keypath $ KeyPath < External < A > , A > , < G : Hashable , H > ( root $ External < H > ; external # External . subscript < H , G > [ % $ 0 : $ G : $ * G ] : $ H ) < B , A > ( % z ) <nl> + / / CHECK : % 4 = keypath $ KeyPath < External < A > , A > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( <nl> + / / CHECK - SAME : root $ External < τ_0_1 > ; <nl> + / / CHECK - SAME : external # External . subscript < τ_0_1 , τ_0_0 > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_1 , <nl> + / / CHECK - SAME : indices_equals @ equals_external_subscript <nl> + / / CHECK - SAME : indices_hash @ hash_external_subscript <nl> + / / CHECK - SAME : ) < B , A > ( % 0 ) <nl> + % d = keypath $ KeyPath < External < A > , A > , < G : Hashable , H > ( <nl> + root $ External < H > ; <nl> + external # External . subscript < H , G > [ % $ 0 : $ G : $ * G ] : $ H , <nl> + indices_equals @ equals_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> + indices_hash @ hash_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer ) - > Int ) < B , A > ( % z ) <nl> <nl> return undef : $ ( ) <nl> } <nl> <nl> sil @ get_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( @ in External < T > , UnsafeRawPointer ) - > @ out T <nl> - sil @ equals_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool <nl> - sil @ hash_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer ) - > Int <nl> + sil @ equals_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool <nl> + sil @ hash_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer ) - > Int <nl> <nl> / / CHECK - LABEL : sil_property # External . ro < τ_0_0 > ( stored_property # External . ro : $ τ_0_0 ) <nl> sil_property # External . ro < T > ( stored_property # External . ro : $ T ) <nl> <nl> / / CHECK - LABEL : sil_property # External . subscript < τ_0_0 > < τ_1_0 where τ_1_0 : Hashable > ( gettable_property $ τ_0_0 , <nl> / / CHECK - SAME : id @ id_a : $ @ convention ( thin ) ( ) - > ( ) , <nl> - / / CHECK - SAME : getter @ get_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( @ in External < τ_0_0 > , UnsafeRawPointer ) - > @ out τ_0_0 , <nl> - / / CHECK - SAME : indices [ % $ 0 : $ τ_1_0 : $ * τ_1_0 ] , <nl> - / / CHECK - SAME : indices_equals @ equals_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> - / / CHECK - SAME : indices_hash @ hash_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( UnsafeRawPointer ) - > Int ) <nl> + / / CHECK - SAME : getter @ get_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( @ in External < τ_0_0 > , UnsafeRawPointer ) - > @ out τ_0_0 ) <nl> sil_property # External . subscript < T > < U : Hashable > ( gettable_property $ T , <nl> id @ id_a : $ @ convention ( thin ) ( ) - > ( ) , <nl> - getter @ get_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( @ in External < T > , UnsafeRawPointer ) - > @ out T , <nl> - indices [ % $ 0 : $ U : $ * U ] , <nl> - indices_equals @ equals_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> - indices_hash @ hash_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer ) - > Int ) <nl> - <nl> + getter @ get_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( @ in External < T > , UnsafeRawPointer ) - > @ out T ) <nl> <nl> mmm a / test / SIL / Serialization / keypath . sil <nl> ppp b / test / SIL / Serialization / keypath . sil <nl> struct Gen < A : P , B : Q , C : R > { <nl> } <nl> <nl> public struct External < T > { <nl> - var ro : T { get } <nl> + var ro : T <nl> <nl> subscript < U : Hashable > ( ro _ : U ) - > T { get } <nl> + <nl> + init ( ) <nl> } <nl> <nl> / / CHECK - LABEL : sil shared [ serialized ] @ stored_properties <nl> entry ( % z : $ * B ) : <nl> / / CHECK : % 3 = keypath $ KeyPath < External < Int > , Int > , < τ_0_0 > ( root $ External < τ_0_0 > ; external # External . ro < τ_0_0 > : $ τ_0_0 ) < Int > <nl> % c = keypath $ KeyPath < External < Int > , Int > , < F > ( root $ External < F > ; external # External . ro < F > : $ F ) < Int > <nl> <nl> - / / CHECK : % 4 = keypath $ KeyPath < External < A > , A > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_1 > ; external # External . subscript < τ_0_1 , τ_0_0 > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_1 ) < B , A > ( % 0 ) <nl> - % d = keypath $ KeyPath < External < A > , A > , < G : Hashable , H > ( root $ External < H > ; external # External . subscript < H , G > [ % $ 0 : $ G : $ * G ] : $ H ) < B , A > ( % z ) <nl> + / / CHECK : % 4 = keypath $ KeyPath < External < A > , A > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( <nl> + / / CHECK - SAME : root $ External < τ_0_1 > ; <nl> + / / CHECK - SAME : external # External . subscript < τ_0_1 , τ_0_0 > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_1 , <nl> + / / CHECK - SAME : indices_equals @ equals_external_subscript <nl> + / / CHECK - SAME : indices_hash @ hash_external_subscript <nl> + / / CHECK - SAME : ) < B , A > ( % 0 ) <nl> + % d = keypath $ KeyPath < External < A > , A > , < G : Hashable , H > ( <nl> + root $ External < H > ; <nl> + external # External . subscript < H , G > [ % $ 0 : $ G : $ * G ] : $ H , <nl> + indices_equals @ equals_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> + indices_hash @ hash_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer ) - > Int ) < B , A > ( % z ) <nl> <nl> return undef : $ ( ) <nl> } <nl> entry : <nl> } <nl> <nl> sil [ serialized ] @ get_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( @ in External < T > , UnsafeRawPointer ) - > @ out T <nl> - sil [ serialized ] @ equals_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool <nl> - sil [ serialized ] @ hash_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer ) - > Int <nl> + sil [ serialized ] @ equals_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool <nl> + sil [ serialized ] @ hash_external_subscript : $ @ convention ( thin ) < U : Hashable , T > ( UnsafeRawPointer ) - > Int <nl> <nl> / / CHECK - LABEL : sil_property [ serialized ] # External . ro < τ_0_0 > ( stored_property # External . ro : $ τ_0_0 ) <nl> sil_property [ serialized ] # External . ro < T > ( stored_property # External . ro : $ T ) <nl> <nl> / / CHECK - LABEL : sil_property [ serialized ] # External . subscript < τ_0_0 > < τ_1_0 where τ_1_0 : Hashable > ( gettable_property $ τ_0_0 , <nl> / / CHECK - SAME : id @ id_a : $ @ convention ( thin ) ( ) - > ( ) , <nl> - / / CHECK - SAME : getter @ get_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( @ in External < τ_0_0 > , UnsafeRawPointer ) - > @ out τ_0_0 , <nl> - / / CHECK - SAME : indices [ % $ 0 : $ τ_1_0 : $ * τ_1_0 ] , <nl> - / / CHECK - SAME : indices_equals @ equals_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> - / / CHECK - SAME : indices_hash @ hash_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( UnsafeRawPointer ) - > Int ) <nl> + / / CHECK - SAME : getter @ get_external_subscript : $ @ convention ( thin ) < τ_0_0 , τ_0_1 where τ_0_1 : Hashable > ( @ in External < τ_0_0 > , UnsafeRawPointer ) - > @ out τ_0_0 ) <nl> sil_property [ serialized ] # External . subscript < T > < U : Hashable > ( gettable_property $ T , <nl> id @ id_a : $ @ convention ( thin ) ( ) - > ( ) , <nl> - getter @ get_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( @ in External < T > , UnsafeRawPointer ) - > @ out T , <nl> - indices [ % $ 0 : $ U : $ * U ] , <nl> - indices_equals @ equals_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer , UnsafeRawPointer ) - > Bool , <nl> - indices_hash @ hash_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( UnsafeRawPointer ) - > Int ) <nl> + getter @ get_external_subscript : $ @ convention ( thin ) < T , U : Hashable > ( @ in External < T > , UnsafeRawPointer ) - > @ out T ) <nl> <nl> <nl> mmm a / test / SILGen / Inputs / ExternalKeyPaths . swift <nl> ppp b / test / SILGen / Inputs / ExternalKeyPaths . swift <nl> public struct External < A > { <nl> public var intProperty : Int <nl> public subscript < B : Hashable > ( index : B ) - > A { return property } <nl> } <nl> + <nl> + public struct ExternalEmptySubscript { <nl> + public subscript ( ) - > Int { return 0 } <nl> + } <nl> mmm a / test / SILGen / external - keypath . swift <nl> ppp b / test / SILGen / external - keypath . swift <nl> func externalKeyPaths < T : Hashable , U > ( _ x : T , _ y : U , _ z : Int ) { <nl> / / CHECK : keypath $ WritableKeyPath < External < U > , Int > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_1 > ; external # External . intProperty < U > : $ Int ) < T , U > <nl> _ = \ External < U > . intProperty <nl> <nl> - / / CHECK : keypath $ KeyPath < External < Int > , Int > , ( root $ External < Int > ; external # External . subscript < Int , Int > [ % $ 0 : $ Int : $ Int ] : $ Int ) ( % 2 ) <nl> + / / CHECK : keypath $ KeyPath < External < Int > , Int > , ( root $ External < Int > ; external # External . subscript < Int , Int > [ % $ 0 : $ Int : $ Int ] : $ Int , indices_equals @ { { . * } } ) ( % 2 ) <nl> _ = \ External < Int > . [ z ] <nl> <nl> - / / CHECK : keypath $ KeyPath < External < T > , T > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_0 > ; external # External . subscript < T , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_0 ) < T , U > ( { { . * } } ) <nl> + / / CHECK : keypath $ KeyPath < External < T > , T > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_0 > ; external # External . subscript < T , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_0 , indices_equals @ { { . * } } ) < T , U > ( { { . * } } ) <nl> _ = \ External < T > . [ x ] <nl> <nl> - / / CHECK : keypath $ KeyPath < External < U > , U > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_1 > ; external # External . subscript < U , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_1 ) < T , U > ( { { . * } } ) <nl> + / / CHECK : keypath $ KeyPath < External < U > , U > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( root $ External < τ_0_1 > ; external # External . subscript < U , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ τ_0_1 , indices_equals @ { { . * } } ) < T , U > ( { { . * } } ) <nl> _ = \ External < U > . [ x ] <nl> <nl> / / CHECK : keypath $ KeyPath < External < Local > , Int > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( <nl> / / CHECK - SAME : root $ External < Local > ; <nl> - / / CHECK - SAME : external # External . subscript < Local , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ Local ; <nl> + / / CHECK - SAME : external # External . subscript < Local , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ Local , indices_equals @ { { . * } } ; <nl> / / CHECK - SAME : stored_property # Local . x : $ Int ) < T , U > ( { { . * } } ) <nl> _ = \ External < Local > . [ x ] . x <nl> <nl> / / CHECK : keypath $ KeyPath < External < Local > , String > , < τ_0_0 , τ_0_1 where τ_0_0 : Hashable > ( <nl> / / CHECK - SAME : root $ External < Local > ; <nl> - / / CHECK - SAME : external # External . subscript < Local , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ Local ; <nl> + / / CHECK - SAME : external # External . subscript < Local , T > [ % $ 0 : $ τ_0_0 : $ * τ_0_0 ] : $ Local , indices_equals @ { { . * } } ; <nl> / / CHECK - SAME : stored_property # Local . y : $ String ) < T , U > ( { { . * } } ) <nl> _ = \ External < Local > . [ x ] . y <nl> + <nl> + / / CHECK : keypath $ KeyPath < ExternalEmptySubscript , Int > , ( <nl> + / / CHECK - SAME : root $ ExternalEmptySubscript ; <nl> + / / CHECK - SAME : external # ExternalEmptySubscript . subscript : $ Int ) <nl> + _ = \ ExternalEmptySubscript . [ ] <nl> } <nl> mmm a / test / SILGen / keypath_property_descriptors . swift <nl> ppp b / test / SILGen / keypath_property_descriptors . swift <nl> public struct A { <nl> / / CHECK - NOT : sil_property # A . f <nl> private static var f : Int = 0 <nl> <nl> - / / CHECK - LABEL : sil_property # A . subscript <nl> + / / CHECK - LABEL : sil_property # A . subscript { { . * } } id @ { { . * } } 1a <nl> public subscript ( a x : Int ) - > Int { return x } <nl> - / / CHECK - LABEL : sil_property # A . subscript <nl> + / / CHECK - LABEL : sil_property # A . subscript { { . * } } id @ { { . * } } 1b <nl> @ _inlineable <nl> public subscript ( b x : Int ) - > Int { return x } <nl> - / / CHECK - LABEL : sil_property # A . subscript <nl> + / / CHECK - LABEL : sil_property # A . subscript { { . * } } id @ { { . * } } 1c <nl> @ _versioned <nl> internal subscript ( c x : Int ) - > Int { return x } <nl> <nl> public struct A { <nl> fileprivate subscript ( e x : Int ) - > Int { return x } <nl> private subscript ( f x : Int ) - > Int { return x } <nl> <nl> - / / TODO : Subscripts with non - hashable subscripts should get descriptors <nl> + / / CHECK - LABEL : sil_property # A . subscript { { . * } } id @ { { . * } } 1a <nl> public subscript < T > ( a x : T ) - > T { return x } <nl> + / / CHECK - LABEL : sil_property # A . subscript { { . * } } id @ { { . * } } 1b <nl> @ _inlineable <nl> public subscript < T > ( b x : T ) - > T { return x } <nl> + / / CHECK - LABEL : sil_property # A . subscript { { . * } } id @ { { . * } } 1c <nl> @ _versioned <nl> internal subscript < T > ( c x : T ) - > T { return x } <nl> <nl> / / no descriptor <nl> + / / CHECK - NOT : sil_property # A . subscript <nl> internal subscript < T > ( d x : T ) - > T { return x } <nl> fileprivate subscript < T > ( e x : T ) - > T { return x } <nl> private subscript < T > ( f x : T ) - > T { return x } <nl>
Merge pull request from jckarter / keypath - resilience - index - hashing
apple/swift
2c782ff41dfd8a8b40c554267cd5531af1f7b97d
2018-03-14T21:44:58Z
new file mode 100644 <nl> index 000000000 . . 75d6bff2e <nl> mmm / dev / null <nl> ppp b / YogaKit / README . md <nl> <nl> + # YogaKit <nl> + <nl> + [ ! [ Cocoapods ] ( https : / / img . shields . io / cocoapods / v / YogaKit . svg ? style = flat ) ] ( https : / / cocoapods . org / pods / YogaKit ) <nl> + [ ! [ Platform ] ( https : / / img . shields . io / badge / platforms - iOS - orange . svg ) ] ( https : / / facebook . github . io / yoga / docs / api / yogakit / ) <nl> + [ ! [ Languages ] ( https : / / img . shields . io / badge / languages - ObjC % 20 % 7C % 20Swift - orange . svg ) ] ( https : / / facebook . github . io / yoga / docs / api / yogakit / ) <nl> + <nl> + # # Installation <nl> + YogaKit is available to install via [ Cocoapods ] ( https : / / cocoapods . org / ) . <nl> + <nl> + ` ` ` <nl> + pod ' YogaKit ' , ' ~ > 1 . 0 . 2 ' <nl> + ` ` ` <nl> + <nl> + # # Getting Started <nl> + Checkout the docs [ here ] ( https : / / facebook . github . io / yoga / docs / api / yogakit / ) . <nl> + <nl> + We also have a sample project . To try it out , clone this repo and open ` YogaKitSample . xcodeproj ` in the [ YogaKitSample ] ( https : / / github . com / facebook / yoga / tree / master / YogaKit / YogaKitSample ) directory . <nl> + <nl> + # # Contributing <nl> + We welcome all pull - requests ! At Facebook we sync the open source version of ` YogaKit ` daily , so we ' re always testing the latest changes . <nl> + <nl> + See the [ CONTRIBUTING ] ( https : / / github . com / facebook / yoga / blob / master / CONTRIBUTING ) file for how to help out . <nl>
Add README . md
facebook/yoga
c217553cf8d12312bc4deeee6d373160314496fa
2017-01-30T19:09:45Z
mmm a / . travis . yml <nl> ppp b / . travis . yml <nl> addons : <nl> before_install : <nl> - source dmlc - core / scripts / travis / travis_setup_env . sh <nl> - export PYTHONPATH = $ { PYTHONPATH } : $ { PWD } / python - package <nl> + - echo " MAVEN_OPTS = ' - Xmx2048m - XX : MaxPermSize = 1024m - XX : ReservedCodeCacheSize = 512m ' " > ~ / . mavenrc <nl> <nl> install : <nl> - source tests / travis / setup . sh <nl> mmm a / jvm - packages / pom . xml <nl> ppp b / jvm - packages / pom . xml <nl> <nl> < descriptorRefs > <nl> < descriptorRef > jar - with - dependencies < / descriptorRef > <nl> < / descriptorRefs > <nl> + < skipAssembly > true < / skipAssembly > <nl> < / configuration > <nl> < executions > <nl> < execution > <nl> mmm a / jvm - packages / xgboost4j - demo / pom . xml <nl> ppp b / jvm - packages / xgboost4j - demo / pom . xml <nl> <nl> < artifactId > xgboost4j - demo < / artifactId > <nl> < version > 0 . 1 < / version > <nl> < packaging > jar < / packaging > <nl> + < build > <nl> + < plugins > <nl> + < plugin > <nl> + < groupId > org . apache . maven . plugins < / groupId > <nl> + < artifactId > maven - assembly - plugin < / artifactId > <nl> + < configuration > <nl> + < skipAssembly > false < / skipAssembly > <nl> + < / configuration > <nl> + < / plugin > <nl> + < / plugins > <nl> + < / build > <nl> < dependencies > <nl> < dependency > <nl> < groupId > ml . dmlc < / groupId > <nl> mmm a / jvm - packages / xgboost4j - spark / pom . xml <nl> ppp b / jvm - packages / xgboost4j - spark / pom . xml <nl> <nl> < version > 0 . 1 < / version > <nl> < / parent > <nl> < artifactId > xgboost4jspark < / artifactId > <nl> + < build > <nl> + < plugins > <nl> + < plugin > <nl> + < groupId > org . apache . maven . plugins < / groupId > <nl> + < artifactId > maven - assembly - plugin < / artifactId > <nl> + < configuration > <nl> + < skipAssembly > false < / skipAssembly > <nl> + < / configuration > <nl> + < / plugin > <nl> + < / plugins > <nl> + < / build > <nl> < dependencies > <nl> < dependency > <nl> < groupId > ml . dmlc < / groupId > <nl> mmm a / jvm - packages / xgboost4j / pom . xml <nl> ppp b / jvm - packages / xgboost4j / pom . xml <nl> <nl> < nohelp > true < / nohelp > <nl> < / configuration > <nl> < / plugin > <nl> + < plugin > <nl> + < groupId > org . apache . maven . plugins < / groupId > <nl> + < artifactId > maven - assembly - plugin < / artifactId > <nl> + < configuration > <nl> + < skipAssembly > false < / skipAssembly > <nl> + < / configuration > <nl> + < / plugin > <nl> < plugin > <nl> < groupId > org . scalatest < / groupId > <nl> < artifactId > scalatest - maven - plugin < / artifactId > <nl>
try to get more memory from Travis
dmlc/xgboost
2cec10c46f93f60a692873021c93ee6ed8044d6b
2016-03-05T13:44:56Z
mmm a / fdbserver / DataDistribution . actor . cpp <nl> ppp b / fdbserver / DataDistribution . actor . cpp <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> AsyncVar < bool > zeroOptimalTeams ; <nl> <nl> AsyncMap < AddressExclusion , bool > excludedServers ; / / true if an address is in the excluded list in the database . Updated asynchronously ( eventually ) <nl> + std : : set < AddressExclusion > invalidLocalityAddr ; / / These address have invalidLocality for the configured storagePolicy <nl> <nl> std : : vector < Optional < Key > > includedDCs ; <nl> Optional < std : : vector < Optional < Key > > > otherTrackedDCs ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> Future < Void > badTeamRemover ; <nl> Future < Void > redundantMachineTeamRemover ; <nl> Future < Void > redundantServerTeamRemover ; <nl> + Future < Void > checkInvalidLocalities ; <nl> <nl> Reference < LocalitySet > storageServerSet ; <nl> std : : vector < LocalityEntry > forcedEntries , resultEntries ; <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> Reference < AsyncVar < bool > > zeroHealthyTeams , bool primary , <nl> Reference < AsyncVar < bool > > processingUnhealthy ) <nl> : cx ( cx ) , distributorId ( distributorId ) , lock ( lock ) , output ( output ) , <nl> - shardsAffectedByTeamFailure ( shardsAffectedByTeamFailure ) , doBuildTeams ( true ) , lastBuildTeamsFailed ( false ) , teamBuilder ( Void ( ) ) , <nl> - badTeamRemover ( Void ( ) ) , redundantMachineTeamRemover ( Void ( ) ) , redundantServerTeamRemover ( Void ( ) ) , <nl> - configuration ( configuration ) , readyToStart ( readyToStart ) , clearHealthyZoneFuture ( true ) , <nl> + shardsAffectedByTeamFailure ( shardsAffectedByTeamFailure ) , doBuildTeams ( true ) , lastBuildTeamsFailed ( false ) , <nl> + teamBuilder ( Void ( ) ) , badTeamRemover ( Void ( ) ) , redundantMachineTeamRemover ( Void ( ) ) , <nl> + redundantServerTeamRemover ( Void ( ) ) , checkInvalidLocalities ( Void ( ) ) , configuration ( configuration ) , <nl> + readyToStart ( readyToStart ) , clearHealthyZoneFuture ( true ) , <nl> checkTeamDelay ( delay ( SERVER_KNOBS - > CHECK_TEAM_DELAY , TaskPriority : : DataDistribution ) ) , <nl> initialFailureReactionDelay ( <nl> delayed ( readyToStart , SERVER_KNOBS - > INITIAL_FAILURE_REACTION_DELAY , TaskPriority : : DataDistribution ) ) , <nl> struct DDTeamCollection : ReferenceCounted < DDTeamCollection > { <nl> } <nl> <nl> / / Check if server or machine has a valid locality based on configured replication policy <nl> - bool isValidLocality ( Reference < IReplicationPolicy > storagePolicy , LocalityData & locality ) { <nl> + bool isValidLocality ( Reference < IReplicationPolicy > storagePolicy , const LocalityData & locality ) { <nl> / / Future : Once we add simulation test that misconfigure a cluster , such as not setting some locality entries , <nl> / / DD_VALIDATE_LOCALITY should always be true . Otherwise , simulation test may fail . <nl> if ( ! SERVER_KNOBS - > DD_VALIDATE_LOCALITY ) { <nl> ACTOR Future < Void > monitorStorageServerRecruitment ( DDTeamCollection * self ) { <nl> } <nl> } <nl> <nl> + ACTOR Future < Void > checkAndRemoveInvalidLocalityAddr ( DDTeamCollection * self ) { <nl> + state int checkCount = 0 ; <nl> + state Transaction tr ( self - > cx ) ; <nl> + <nl> + loop { <nl> + try { <nl> + wait ( delay ( SERVER_KNOBS - > DD_CHECK_INVALID_LOCALITY_DELAY ) ) ; <nl> + <nl> + tr . setOption ( FDBTransactionOptions : : READ_SYSTEM_KEYS ) ; <nl> + tr . setOption ( FDBTransactionOptions : : READ_LOCK_AWARE ) ; <nl> + <nl> + / / Because worker ' s processId can be changed when its locality is changed , we cannot watch on the old <nl> + / / processId ; This actor is inactive most time , so iterating all workers incurs little performance overhead . <nl> + Future < vector < ProcessData > > workers = getWorkers ( & tr ) ; <nl> + std : : set < AddressExclusion > existingAddrs ; <nl> + for ( int i = 0 ; i < workers . get ( ) . size ( ) ; i + + ) { <nl> + const ProcessData & workerData = workers . get ( ) [ i ] ; <nl> + AddressExclusion addr ( workerData . address . ip , workerData . address . port ) ; <nl> + existingAddrs . insert ( addr ) ; <nl> + if ( self - > invalidLocalityAddr . count ( addr ) & & <nl> + self - > isValidLocality ( self - > configuration . storagePolicy , workerData . locality ) ) { <nl> + / / The locality info on the addr has been corrected <nl> + self - > invalidLocalityAddr . erase ( addr ) ; <nl> + } <nl> + } <nl> + <nl> + / / In case system operator permanently excludes workers on the address with invalid locality <nl> + for ( auto addr = self - > invalidLocalityAddr . begin ( ) ; addr ! = self - > invalidLocalityAddr . end ( ) ; ) { <nl> + if ( ! existingAddrs . count ( * addr ) ) { <nl> + / / The address no longer has a worker <nl> + self - > invalidLocalityAddr . erase ( addr + + ) ; <nl> + } else { <nl> + + + addr ; <nl> + } <nl> + } <nl> + <nl> + if ( self - > invalidLocalityAddr . empty ( ) ) { <nl> + break ; <nl> + } <nl> + <nl> + checkCount + + ; <nl> + if ( checkCount > 100 ) { <nl> + / / The incorrect locality info is not properly correctly on time <nl> + TraceEvent ( SevWarn , " InvalidLocality " ) . detail ( " Addresses " , self - > invalidLocalityAddr . size ( ) ) ; <nl> + } <nl> + } catch ( Error & e ) { <nl> + wait ( tr . onError ( e ) ) ; <nl> + TraceEvent ( " CheckAndRemoveInvalidLocalityAddrRetry " , self - > distributorId ) ; <nl> + } <nl> + } <nl> + <nl> + return Void ( ) ; <nl> + } <nl> + <nl> ACTOR Future < Void > initializeStorage ( DDTeamCollection * self , RecruitStorageReply candidateWorker ) { <nl> / / Exclude the worker that has invalid locality <nl> if ( ! self - > isValidLocality ( self - > configuration . storagePolicy , candidateWorker . worker . locality ) ) { <nl> - TraceEvent ( SevWarn , " DDRecruiting " ) . detail ( " ExcludeWorkWithInvalidLocality " , candidateWorker . worker . id ( ) ) <nl> - . detail ( " WorkerLocality " , candidateWorker . worker . locality . toString ( ) ) . detail ( " Addr " , candidateWorker . worker . address ( ) ) ; <nl> + TraceEvent ( SevWarn , " DDRecruiting " ) <nl> + . detail ( " ExcludeWorkWithInvalidLocality " , candidateWorker . worker . id ( ) ) <nl> + . detail ( " WorkerLocality " , candidateWorker . worker . locality . toString ( ) ) <nl> + . detail ( " Addr " , candidateWorker . worker . address ( ) ) ; <nl> auto addr = candidateWorker . worker . address ( ) ; <nl> - self - > excludedServers . set ( AddressExclusion ( addr . ip , addr . port ) , true ) ; <nl> + self - > invalidLocalityAddr . insert ( AddressExclusion ( addr . ip , addr . port ) ) ; <nl> + if ( self - > checkInvalidLocalities . isReady ( ) ) { <nl> + self - > checkInvalidLocalities = checkAndRemoveInvalidLocalityAddr ( self ) ; <nl> + self - > addActor . send ( self - > checkInvalidLocalities ) ; <nl> + } <nl> self - > restartRecruiting . trigger ( ) ; <nl> return Void ( ) ; <nl> } <nl> ACTOR Future < Void > storageRecruiter ( DDTeamCollection * self , Reference < AsyncVar < <nl> } <nl> <nl> auto excl = self - > excludedServers . getKeys ( ) ; <nl> - for ( auto & s : excl ) <nl> + for ( auto & s : excl ) { <nl> if ( self - > excludedServers . get ( s ) ) { <nl> TraceEvent ( SevDebug , " DDRecruitExcl2 " ) . detail ( " Excluding " , s . toString ( ) ) ; <nl> exclusions . insert ( s ) ; <nl> } <nl> + } <nl> + <nl> + / / Exclude workers that have invalid locality <nl> + for ( auto & addr : self - > invalidLocalityAddr ) { <nl> + TraceEvent ( SevDebug , " DDRecruitExclInvalidAddr " ) . detail ( " Excluding " , addr . toString ( ) ) ; <nl> + exclusions . insert ( addr ) ; <nl> + } <nl> + <nl> rsr . criticalRecruitment = self - > healthyTeamCount = = 0 ; <nl> for ( auto it : exclusions ) { <nl> rsr . excludeAddresses . push_back ( it ) ; <nl> mmm a / fdbserver / Knobs . cpp <nl> ppp b / fdbserver / Knobs . cpp <nl> ServerKnobs : : ServerKnobs ( bool randomize , ClientKnobs * clientKnobs ) { <nl> init ( REBALANCE_MAX_RETRIES , 100 ) ; <nl> init ( DD_OVERLAP_PENALTY , 10000 ) ; <nl> init ( DD_VALIDATE_LOCALITY , true ) ; if ( randomize & & BUGGIFY ) DD_VALIDATE_LOCALITY = false ; <nl> + init ( DD_CHECK_INVALID_LOCALITY_DELAY , 60 ) ; if ( randomize & & BUGGIFY ) DD_CHECK_INVALID_LOCALITY_DELAY = 10 + deterministicRandom ( ) - > random01 ( ) * 600 ; <nl> <nl> / / TeamRemover <nl> TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER = false ; if ( randomize & & BUGGIFY ) TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER = deterministicRandom ( ) - > random01 ( ) < 0 . 1 ? true : false ; / / false by default . disable the consistency check when it ' s true <nl> mmm a / fdbserver / Knobs . h <nl> ppp b / fdbserver / Knobs . h <nl> class ServerKnobs : public Knobs { <nl> int REBALANCE_MAX_RETRIES ; <nl> int DD_OVERLAP_PENALTY ; <nl> bool DD_VALIDATE_LOCALITY ; <nl> + int DD_CHECK_INVALID_LOCALITY_DELAY ; <nl> <nl> / / TeamRemover to remove redundant teams <nl> bool TR_FLAG_DISABLE_MACHINE_TEAM_REMOVER ; / / disable the machineTeamRemover actor <nl>
DD : Handle worker with incorrect locality
apple/foundationdb
37d2318eedd47c8af544b0d74b5586a9ef7bf2c0
2019-09-14T19:12:56Z
mmm a / docs / faq . md <nl> ppp b / docs / faq . md <nl> <nl> <nl> # FAQ <nl> <nl> - # # # < font color = ' # 00007c ' > Unreal editor is slow when it is not the active window < / font > <nl> + # # # Unreal editor is slow when it is not the active window <nl> <nl> Go to Edit / Editor Preferences , select " All Settings " and type " CPU " in the sarch box . <nl> It should find the setting titled " Use Less CPU when in Background " , and you want to uncheck this checkbox . <nl> <nl> - # # # < font color = ' # 00007c ' > Drone doesn ' t fly properly , it just goes crazy < / font > <nl> + # # # Drone doesn ' t fly properly , it just goes crazy <nl> <nl> This can be a machine performance issue , check your [ hard drive performance ] ( hard_drive . md ) . <nl> <nl> - # # # < font color = ' # 00007c ' > How to get cmake to use GCC 6 without making GCC 6 my default < / font > <nl> + # # # How to get cmake to use GCC 6 without making GCC 6 my default <nl> <nl> Add these to your cmake command line ` - D CMAKE_C_COMPILER = gcc - 6 - D CMAKE_CXX_COMPILER = g + + - 6 ` . <nl> <nl>
strip html from . md
microsoft/AirSim
ff260b64828027423aa15f34fd7b6c6323feb3bd
2017-02-22T00:42:39Z
mmm a / vkd3d <nl> ppp b / vkd3d <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 91b7be72c548c87ef86c3aff58cfe6a5bbaf4ea0 <nl> + Subproject commit 40e4a74c04ad8bc5bd5c0ead950990e735490c99 <nl>
update vkd3d
ValveSoftware/Proton
022f40b3b6079942bcb45a6f9c2ba92e2053e470
2019-12-09T19:33:34Z
mmm a / README . md <nl> ppp b / README . md <nl> For business and partnership , please visit [ our website ] ( http : / / apollo . auto ) . <nl> <nl> The following diagram highlights the scope and features of each Apollo release : <nl> <nl> - ! [ image alt text ] ( docs / demo_guide / images / Apollo_versions . png ) <nl> + ! [ image alt text ] ( docs / demo_guide / images / apollo_versions_3 . png ) <nl> <nl> [ * * Apollo 1 . 0 : * * ] ( https : / / github . com / ApolloAuto / apollo / blob / master / docs / quickstart / apollo_1_0_hardware_system_installation_guide . md ) <nl> <nl>
version diagram
ApolloAuto/apollo
a69adb80be35d56418554945773141a0c9566e4f
2018-07-04T11:39:57Z
mmm a / modules / gapi / CMakeLists . txt <nl> ppp b / modules / gapi / CMakeLists . txt <nl> set ( gapi_srcs <nl> src / api / operators . cpp <nl> src / api / kernels_core . cpp <nl> src / api / kernels_imgproc . cpp <nl> + src / api / render . cpp <nl> <nl> # Compiler part <nl> src / compiler / gmodel . cpp <nl> new file mode 100644 <nl> index 00000000000 . . b157097b8c9 <nl> mmm / dev / null <nl> ppp b / modules / gapi / include / opencv2 / gapi / render . hpp <nl> <nl> + / / This file is part of OpenCV project . <nl> + / / It is subject to the license terms in the LICENSE file found in the top - level directory <nl> + / / of this distribution and at http : / / opencv . org / license . html . <nl> + / / <nl> + / / Copyright ( C ) 2018 Intel Corporation <nl> + <nl> + <nl> + # ifndef OPENCV_GAPI_RENDER_HPP <nl> + # define OPENCV_GAPI_RENDER_HPP <nl> + <nl> + # include < string > <nl> + # include < vector > <nl> + <nl> + # include < opencv2 / gapi / opencv_includes . hpp > <nl> + # include < opencv2 / gapi / util / variant . hpp > <nl> + # include < opencv2 / gapi / own / exports . hpp > <nl> + # include < opencv2 / gapi / own / scalar . hpp > <nl> + <nl> + namespace cv <nl> + { <nl> + namespace gapi <nl> + { <nl> + namespace wip <nl> + { <nl> + namespace draw <nl> + { <nl> + <nl> + / * * <nl> + * A structure to represent parameters for drawing a text string . <nl> + * / <nl> + struct Text <nl> + { <nl> + / * @ { * / <nl> + std : : string text ; / * * < The text string to be drawn * / <nl> + cv : : Point org ; / * * < The bottom - left corner of the text string in the image * / <nl> + int ff ; / * * < The font type , see # HersheyFonts * / <nl> + double fs ; / * * < The font scale factor that is multiplied by the font - specific base size * / <nl> + cv : : Scalar color ; / * * < The text color * / <nl> + int thick ; / * * < The thickness of the lines used to draw a text * / <nl> + int lt ; / * * < The line type . See # LineTypes * / <nl> + bool bottom_left_origin ; / * * < When true , the image data origin is at the bottom - left corner . Otherwise , <nl> + it is at the top - left corner . * / <nl> + / * @ { * / <nl> + } ; <nl> + <nl> + / * * <nl> + * A structure to represent parameters for drawing a rectangle <nl> + * / <nl> + struct Rect <nl> + { <nl> + cv : : Rect rect ; / * * Coordinates of the rectangle < * / <nl> + cv : : Scalar color ; / * * The rectangle color or brightness ( grayscale image ) < * / <nl> + int thick ; / * * The thickness of lines that make up the rectangle . Negative values , like # FILLED , < * / <nl> + int lt ; / * * The type of the line . See # LineTypes < * / <nl> + int shift ; / * * The number of fractional bits in the point coordinates < * / <nl> + } ; <nl> + <nl> + using Prim = util : : variant < Text , Rect > ; <nl> + using Prims = std : : vector < Prim > ; <nl> + <nl> + / * * @ brief The function renders on the input image passed drawing primitivies <nl> + <nl> + @ param bgr input image : 8 - bit unsigned 3 - channel image @ ref CV_8UC3 . <nl> + @ param prims vector of drawing primitivies <nl> + * / <nl> + GAPI_EXPORTS void render ( cv : : Mat & bgr , const Prims & prims ) ; <nl> + <nl> + / * * @ brief The function renders on two NV12 planes passed drawing primitivies <nl> + <nl> + @ param y_plane input image : 8 - bit unsigned 1 - channel image @ ref CV_8UC1 . <nl> + @ param uv_plane input image : 8 - bit unsigned 2 - channel image @ ref CV_8UC2 . <nl> + @ param prims vector of drawing primitivies <nl> + * / <nl> + GAPI_EXPORTS void render ( cv : : Mat & y_plane , cv : : Mat & uv_plane , const Prims & prims ) ; <nl> + <nl> + } / / namespace draw <nl> + } / / namespace wip <nl> + } / / namespace gapi <nl> + } / / namespace cv <nl> + <nl> + # endif / / OPENCV_GAPI_RENDER_HPP <nl> new file mode 100644 <nl> index 00000000000 . . 5dd4bb31f8e <nl> mmm / dev / null <nl> ppp b / modules / gapi / src / api / render . cpp <nl> <nl> + # include < opencv2 / imgproc . hpp > <nl> + <nl> + # include " opencv2 / gapi / render . hpp " <nl> + # include " opencv2 / gapi / own / assert . hpp " <nl> + <nl> + # include " api / render_priv . hpp " <nl> + <nl> + using namespace cv : : gapi : : wip : : draw ; <nl> + / / FXIME util : : visitor ? <nl> + void cv : : gapi : : wip : : draw : : render ( cv : : Mat & bgr , const Prims & prims ) <nl> + { <nl> + for ( const auto & p : prims ) <nl> + { <nl> + switch ( p . index ( ) ) <nl> + { <nl> + case Prim : : index_of < Rect > ( ) : <nl> + { <nl> + auto t_p = cv : : util : : get < Rect > ( p ) ; <nl> + cv : : rectangle ( bgr , t_p . rect , t_p . color , t_p . thick , t_p . lt , t_p . shift ) ; <nl> + break ; <nl> + } <nl> + <nl> + case Prim : : index_of < Text > ( ) : <nl> + { <nl> + auto t_p = cv : : util : : get < Text > ( p ) ; <nl> + cv : : putText ( bgr , t_p . text , t_p . org , t_p . ff , t_p . fs , <nl> + t_p . color , t_p . thick , t_p . bottom_left_origin ) ; <nl> + break ; <nl> + } <nl> + <nl> + default : util : : throw_error ( std : : logic_error ( " Unsupported draw event " ) ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void cv : : gapi : : wip : : draw : : render ( cv : : Mat & y_plane , cv : : Mat & uv_plane , const Prims & prims ) <nl> + { <nl> + cv : : Mat bgr ; <nl> + cv : : cvtColorTwoPlane ( y_plane , uv_plane , bgr , cv : : COLOR_YUV2BGR_NV12 ) ; <nl> + render ( bgr , prims ) ; <nl> + BGR2NV12 ( bgr , y_plane , uv_plane ) ; <nl> + } <nl> + <nl> + void cv : : gapi : : wip : : draw : : splitNV12TwoPlane ( const cv : : Mat & yuv , cv : : Mat & y_plane , cv : : Mat & uv_plane ) { <nl> + y_plane . create ( yuv . size ( ) , CV_8UC1 ) ; <nl> + uv_plane . create ( yuv . size ( ) / 2 , CV_8UC2 ) ; <nl> + <nl> + / / Fill Y plane <nl> + for ( int i = 0 ; i < yuv . rows ; + + i ) <nl> + { <nl> + const uchar * in = yuv . ptr < uchar > ( i ) ; <nl> + uchar * out = y_plane . ptr < uchar > ( i ) ; <nl> + for ( int j = 0 ; j < yuv . cols ; j + + ) { <nl> + out [ j ] = in [ 3 * j ] ; <nl> + } <nl> + } <nl> + <nl> + / / Fill UV plane <nl> + for ( int i = 0 ; i < uv_plane . rows ; i + + ) <nl> + { <nl> + const uchar * in = yuv . ptr < uchar > ( 2 * i ) ; <nl> + uchar * out = uv_plane . ptr < uchar > ( i ) ; <nl> + for ( int j = 0 ; j < uv_plane . cols ; j + + ) { <nl> + out [ j * 2 ] = in [ 6 * j + 1 ] ; <nl> + out [ j * 2 + 1 ] = in [ 6 * j + 2 ] ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void cv : : gapi : : wip : : draw : : BGR2NV12 ( const cv : : Mat & bgr , cv : : Mat & y_plane , cv : : Mat & uv_plane ) <nl> + { <nl> + GAPI_Assert ( bgr . size ( ) . width % 2 = = 0 ) ; <nl> + GAPI_Assert ( bgr . size ( ) . height % 2 = = 0 ) ; <nl> + <nl> + cvtColor ( bgr , bgr , cv : : COLOR_BGR2YUV ) ; <nl> + splitNV12TwoPlane ( bgr , y_plane , uv_plane ) ; <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 29805ea49a0 <nl> mmm / dev / null <nl> ppp b / modules / gapi / src / api / render_priv . hpp <nl> <nl> + / / This file is part of OpenCV project . <nl> + / / It is subject to the license terms in the LICENSE file found in the top - level directory <nl> + / / of this distribution and at http : / / opencv . org / license . html . <nl> + / / <nl> + / / Copyright ( C ) 2018 Intel Corporation <nl> + <nl> + <nl> + # ifndef OPENCV_RENDER_PRIV_HPP <nl> + # define OPENCV_RENDER_PRIV_HPP <nl> + <nl> + # include < opencv2 / gapi / render . hpp > <nl> + <nl> + namespace cv <nl> + { <nl> + namespace gapi <nl> + { <nl> + namespace wip <nl> + { <nl> + namespace draw <nl> + { <nl> + / / FIXME only for tests <nl> + GAPI_EXPORTS void BGR2NV12 ( const cv : : Mat & bgr , cv : : Mat & y_plane , cv : : Mat & uv_plane ) ; <nl> + void splitNV12TwoPlane ( const cv : : Mat & yuv , cv : : Mat & y_plane , cv : : Mat & uv_plane ) ; <nl> + <nl> + } / / namespace draw <nl> + } / / namespace wip <nl> + } / / namespace gapi <nl> + } / / namespace cv <nl> + <nl> + # endif / / OPENCV_RENDER_PRIV_HPP <nl> new file mode 100644 <nl> index 00000000000 . . 64e0f274ca4 <nl> mmm / dev / null <nl> ppp b / modules / gapi / test / gapi_render_test . cpp <nl> <nl> + / / This file is part of OpenCV project . <nl> + / / It is subject to the license terms in the LICENSE file found in the top - level directory <nl> + / / of this distribution and at http : / / opencv . org / license . html . <nl> + / / <nl> + / / Copyright ( C ) 2018 Intel Corporation <nl> + <nl> + # include " test_precomp . hpp " <nl> + <nl> + # include " api / render_priv . hpp " <nl> + <nl> + # include < opencv2 / imgproc . hpp > <nl> + # include < opencv2 / gapi / render . hpp > <nl> + # include < opencv2 / gapi / own / scalar . hpp > <nl> + <nl> + namespace opencv_test <nl> + { <nl> + <nl> + namespace <nl> + { <nl> + struct RenderTestFixture : public : : testing : : Test <nl> + { <nl> + cv : : Size size = { 30 , 40 } ; <nl> + int thick = 2 ; <nl> + int ff = cv : : FONT_HERSHEY_SIMPLEX ; <nl> + int lt = LINE_8 ; <nl> + double fs = 1 ; <nl> + <nl> + cv : : Mat ref_mat { 320 , 480 , CV_8UC3 , cv : : Scalar : : all ( 255 ) } ; <nl> + cv : : Mat out_mat { 320 , 480 , CV_8UC3 , cv : : Scalar : : all ( 255 ) } ; <nl> + cv : : Scalar color { 0 , 255 , 0 } ; <nl> + std : : string text { " some text " } ; <nl> + <nl> + } ; <nl> + } / / namespace <nl> + <nl> + TEST ( BGR2NV12Test , CorrectConversion ) <nl> + { <nl> + cv : : Mat in_mat ( 320 , 240 , CV_8UC3 ) ; <nl> + cv : : Mat out_y , out_uv , ref_y , yuv ; <nl> + cv : : randu ( in_mat , cv : : Scalar : : all ( 0 ) , cv : : Scalar : : all ( 255 ) ) ; <nl> + <nl> + cv : : cvtColor ( in_mat , yuv , cv : : COLOR_BGR2YUV ) ; <nl> + cv : : Mat channels [ 3 ] ; <nl> + cv : : split ( yuv , channels ) ; <nl> + <nl> + ref_y = channels [ 0 ] ; <nl> + cv : : Mat ref_uv ( in_mat . size ( ) / 2 , CV_8UC2 ) ; <nl> + cv : : resize ( channels [ 1 ] , channels [ 1 ] , channels [ 1 ] . size ( ) / 2 , 0 , 0 , cv : : INTER_NEAREST ) ; <nl> + cv : : resize ( channels [ 2 ] , channels [ 2 ] , channels [ 2 ] . size ( ) / 2 , 0 , 0 , cv : : INTER_NEAREST ) ; <nl> + cv : : merge ( channels + 1 , 2 , ref_uv ) ; <nl> + <nl> + cv : : gapi : : wip : : draw : : BGR2NV12 ( in_mat , out_y , out_uv ) ; <nl> + <nl> + EXPECT_EQ ( 0 , cv : : countNonZero ( out_y ! = ref_y ) ) ; <nl> + EXPECT_EQ ( 0 , cv : : countNonZero ( out_uv ! = ref_uv ) ) ; <nl> + } <nl> + <nl> + TEST_F ( RenderTestFixture , PutText ) <nl> + { <nl> + std : : vector < cv : : gapi : : wip : : draw : : Prim > prims ; <nl> + <nl> + for ( int i = 0 ; i < 5 ; + + i ) <nl> + { <nl> + cv : : Point point { 30 + i * 60 , 40 + i * 50 } ; <nl> + <nl> + cv : : putText ( ref_mat , text , point , ff , fs , color , thick ) ; <nl> + prims . emplace_back ( cv : : gapi : : wip : : draw : : Text { text , point , ff , fs , color , thick , lt , false } ) ; <nl> + } <nl> + <nl> + cv : : gapi : : wip : : draw : : render ( out_mat , prims ) ; <nl> + <nl> + EXPECT_EQ ( 0 , cv : : countNonZero ( out_mat ! = ref_mat ) ) ; <nl> + } <nl> + <nl> + TEST_F ( RenderTestFixture , Rectangle ) <nl> + { <nl> + std : : vector < cv : : gapi : : wip : : draw : : Prim > prims ; <nl> + <nl> + for ( int i = 0 ; i < 5 ; + + i ) <nl> + { <nl> + cv : : Rect rect { 30 + i * 60 , 40 + i * 50 , size . width , size . height } ; <nl> + cv : : rectangle ( ref_mat , rect , color , thick ) ; <nl> + prims . emplace_back ( cv : : gapi : : wip : : draw : : Rect { rect , color , thick , lt , 0 } ) ; <nl> + } <nl> + <nl> + cv : : gapi : : wip : : draw : : render ( out_mat , prims ) ; <nl> + <nl> + EXPECT_EQ ( 0 , cv : : countNonZero ( out_mat ! = ref_mat ) ) ; <nl> + } <nl> + <nl> + TEST_F ( RenderTestFixture , PutTextAndRectangle ) <nl> + { <nl> + std : : vector < cv : : gapi : : wip : : draw : : Prim > prims ; <nl> + <nl> + for ( int i = 0 ; i < 5 ; + + i ) <nl> + { <nl> + cv : : Point point { 30 + i * 60 , 40 + i * 50 } ; <nl> + cv : : Rect rect { point , size } ; <nl> + <nl> + cv : : rectangle ( ref_mat , rect , color , thick ) ; <nl> + cv : : putText ( ref_mat , text , point , ff , fs , color , thick ) ; <nl> + <nl> + prims . emplace_back ( cv : : gapi : : wip : : draw : : Rect { rect , color , thick , lt , 0 } ) ; <nl> + prims . emplace_back ( cv : : gapi : : wip : : draw : : Text { text , point , ff , fs , color , thick , lt , false } ) ; <nl> + } <nl> + <nl> + cv : : gapi : : wip : : draw : : render ( out_mat , prims ) ; <nl> + <nl> + EXPECT_EQ ( 0 , cv : : countNonZero ( out_mat ! = ref_mat ) ) ; <nl> + } <nl> + <nl> + TEST_F ( RenderTestFixture , PutTextAndRectangleNV12 ) <nl> + { <nl> + cv : : Mat y ; <nl> + cv : : Mat uv ; <nl> + cv : : gapi : : wip : : draw : : BGR2NV12 ( out_mat , y , uv ) ; <nl> + <nl> + std : : vector < cv : : gapi : : wip : : draw : : Prim > prims ; <nl> + <nl> + for ( int i = 0 ; i < 5 ; + + i ) <nl> + { <nl> + cv : : Point point { 30 + i * 60 , 40 + i * 50 } ; <nl> + cv : : Rect rect { point , size } ; <nl> + <nl> + cv : : rectangle ( ref_mat , rect , color , thick ) ; <nl> + cv : : putText ( ref_mat , text , point , ff , fs , color , thick ) ; <nl> + <nl> + prims . emplace_back ( cv : : gapi : : wip : : draw : : Rect { rect , color , thick , lt , 0 } ) ; <nl> + prims . emplace_back ( cv : : gapi : : wip : : draw : : Text { text , point , ff , fs , color , thick , lt , false } ) ; <nl> + } <nl> + <nl> + cv : : gapi : : wip : : draw : : render ( y , uv , prims ) ; <nl> + cv : : cvtColorTwoPlane ( y , uv , out_mat , cv : : COLOR_YUV2BGR_NV12 ) ; <nl> + <nl> + cv : : gapi : : wip : : draw : : BGR2NV12 ( ref_mat , y , uv ) ; <nl> + cv : : cvtColorTwoPlane ( y , uv , ref_mat , cv : : COLOR_YUV2BGR_NV12 ) ; <nl> + <nl> + EXPECT_EQ ( 0 , cv : : countNonZero ( out_mat ! = ref_mat ) ) ; <nl> + } <nl> + <nl> + } / / opencv_test <nl>
Merge pull request from TolyaTalamanov : at / cv_gapi_render
opencv/opencv
d3c0f4ef983e07a4e43e280bc403d6283240b3ab
2019-06-14T15:29:49Z
mmm a / PowerEditor / src / ScitillaComponent / AutoCompletion . cpp <nl> ppp b / PowerEditor / src / ScitillaComponent / AutoCompletion . cpp <nl> bool AutoCompletion : : showApiAndWordComplete ( ) <nl> / / Get word list <nl> generic_string words ; <nl> <nl> - for ( size_t i = 0 , len = wordArray . size ( ) ; i < len ; + + i ) <nl> + for ( size_t i = 0 , wordArrayLen = wordArray . size ( ) ; i < wordArrayLen ; + + i ) <nl> { <nl> words + = wordArray [ i ] ; <nl> - if ( i ! = len - 1 ) <nl> + if ( i ! = wordArrayLen - 1 ) <nl> words + = TEXT ( " " ) ; <nl> } <nl> <nl> bool AutoCompletion : : showWordComplete ( bool autoInsert ) <nl> / / Get word list <nl> generic_string words ( TEXT ( " " ) ) ; <nl> <nl> - for ( size_t i = 0 , len = wordArray . size ( ) ; i < len ; + + i ) <nl> + for ( size_t i = 0 , wordArrayLen = wordArray . size ( ) ; i < wordArrayLen ; + + i ) <nl> { <nl> words + = wordArray [ i ] ; <nl> - if ( i ! = wordArray . size ( ) - 1 ) <nl> + if ( i ! = wordArrayLen - 1 ) <nl> words + = TEXT ( " " ) ; <nl> } <nl> <nl> mmm a / PowerEditor / src / WinControls / Grid / BabyGridWrapper . cpp <nl> ppp b / PowerEditor / src / WinControls / Grid / BabyGridWrapper . cpp <nl> <nl> <nl> <nl> # include " BabyGridWrapper . h " <nl> + <nl> const TCHAR * babyGridClassName = TEXT ( " BABYGRID " ) ; <nl> <nl> bool BabyGridWrapper : : _isRegistered = false ; <nl> <nl> - void BabyGridWrapper : : init ( HINSTANCE hInst , HWND parent , int id ) <nl> + void BabyGridWrapper : : init ( HINSTANCE hInst , HWND parent , int16_t id ) <nl> { <nl> Window : : init ( hInst , parent ) ; <nl> <nl> mmm a / PowerEditor / src / WinControls / Grid / BabyGridWrapper . h <nl> ppp b / PowerEditor / src / WinControls / Grid / BabyGridWrapper . h <nl> <nl> / / Foundation , Inc . , 675 Mass Ave , Cambridge , MA 02139 , USA . <nl> <nl> <nl> - # ifndef BABYGRIDWRAPPER <nl> - # define BABYGRIDWRAPPER <nl> + # pragma once <nl> <nl> - # ifndef BABYGRID_H <nl> + # include " Parameters . h " <nl> # include " BabyGrid . h " <nl> - # endif / / BABYGRID_H <nl> - <nl> # include " Window . h " <nl> <nl> class BabyGridWrapper : public Window <nl> class BabyGridWrapper : public Window <nl> public : <nl> BabyGridWrapper ( ) : Window ( ) { } ; <nl> ~ BabyGridWrapper ( ) { } ; <nl> - virtual void init ( HINSTANCE hInst , HWND parent , int id ) ; <nl> + virtual void init ( HINSTANCE hInst , HWND parent , int16_t id ) ; <nl> virtual void destroy ( ) { <nl> : : DestroyWindow ( _hSelf ) ; <nl> } ; <nl> private : <nl> static bool _isRegistered ; <nl> } ; <nl> <nl> - # endif / / BABYGRIDWRAPPER <nl> <nl> mmm a / PowerEditor / visual . net / notepadPlus . vs2015 . vcxproj <nl> ppp b / PowerEditor / visual . net / notepadPlus . vs2015 . vcxproj <nl> <nl> < ClCompile > <nl> < Optimization > Disabled < / Optimization > <nl> < FavorSizeOrSpeed > Neither < / FavorSizeOrSpeed > <nl> - < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; . . \ src \ MISC \ md5 ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < PreprocessorDefinitions > WIN32 ; _WIN32_WINNT = 0x0501 ; _WINDOWS ; _USE_64BIT_TIME_T ; TIXML_USE_STL ; TIXMLA_USE_STL ; _CRT_NONSTDC_NO_DEPRECATE ; _CRT_SECURE_NO_WARNINGS ; _CRT_NON_CONFORMING_SWPRINTFS = 1 ; _CRT_NON_CONFORMING_WCSTOK ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < ExceptionHandling > Async < / ExceptionHandling > <nl> < BasicRuntimeChecks > UninitializedLocalUsageCheck < / BasicRuntimeChecks > <nl> <nl> < TreatWarningAsError > true < / TreatWarningAsError > <nl> < DebugInformationFormat > ProgramDatabase < / DebugInformationFormat > <nl> < MultiProcessorCompilation > true < / MultiProcessorCompilation > <nl> - < SmallerTypeCheck > true < / SmallerTypeCheck > <nl> + < SmallerTypeCheck > false < / SmallerTypeCheck > <nl> < DisableSpecificWarnings > 4091 ; 4456 ; 4457 ; 4459 < / DisableSpecificWarnings > <nl> + < WarningVersion > 18 < / WarningVersion > <nl> < / ClCompile > <nl> < Link > <nl> < AdditionalOptions > / fixed : no % ( AdditionalOptions ) < / AdditionalOptions > <nl> <nl> < ClCompile > <nl> < Optimization > Disabled < / Optimization > <nl> < FavorSizeOrSpeed > Neither < / FavorSizeOrSpeed > <nl> - < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; . . \ src \ MISC \ md5 ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < PreprocessorDefinitions > WIN32 ; _WIN32_WINNT = 0x0501 ; _WINDOWS ; _USE_64BIT_TIME_T ; TIXML_USE_STL ; TIXMLA_USE_STL ; _CRT_NONSTDC_NO_DEPRECATE ; _CRT_SECURE_NO_WARNINGS ; _CRT_NON_CONFORMING_SWPRINTFS = 1 ; _CRT_NON_CONFORMING_WCSTOK ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < ExceptionHandling > Async < / ExceptionHandling > <nl> < BasicRuntimeChecks > UninitializedLocalUsageCheck < / BasicRuntimeChecks > <nl> < RuntimeLibrary > MultiThreadedDebug < / RuntimeLibrary > <nl> < WarningLevel > Level4 < / WarningLevel > <nl> - < TreatWarningAsError > false < / TreatWarningAsError > <nl> + < TreatWarningAsError > true < / TreatWarningAsError > <nl> < DebugInformationFormat > ProgramDatabase < / DebugInformationFormat > <nl> < MultiProcessorCompilation > true < / MultiProcessorCompilation > <nl> - < SmallerTypeCheck > true < / SmallerTypeCheck > <nl> + < SmallerTypeCheck > false < / SmallerTypeCheck > <nl> < DisableSpecificWarnings > 4091 ; 4456 ; 4457 ; 4459 < / DisableSpecificWarnings > <nl> + < WarningVersion > 18 < / WarningVersion > <nl> < / ClCompile > <nl> < Link > <nl> < AdditionalOptions > / fixed : no % ( AdditionalOptions ) < / AdditionalOptions > <nl> <nl> < FavorSizeOrSpeed > Speed < / FavorSizeOrSpeed > <nl> < OmitFramePointers > false < / OmitFramePointers > <nl> < WholeProgramOptimization > false < / WholeProgramOptimization > <nl> - < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; . . \ src \ MISC \ md5 ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < PreprocessorDefinitions > WIN32 ; _WIN32_WINNT = 0x0501 ; NDEBUG ; _WINDOWS ; _USE_64BIT_TIME_T ; TIXML_USE_STL ; TIXMLA_USE_STL ; _CRT_NONSTDC_NO_DEPRECATE ; _CRT_SECURE_NO_WARNINGS ; _CRT_NON_CONFORMING_SWPRINTFS = 1 ; _CRT_NON_CONFORMING_WCSTOK ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < PreprocessToFile > false < / PreprocessToFile > <nl> < PreprocessSuppressLineNumbers > false < / PreprocessSuppressLineNumbers > <nl> <nl> < EnableEnhancedInstructionSet > NoExtensions < / EnableEnhancedInstructionSet > <nl> < MultiProcessorCompilation > true < / MultiProcessorCompilation > <nl> < DisableSpecificWarnings > 4091 ; 4456 ; 4457 ; 4459 < / DisableSpecificWarnings > <nl> + < WarningVersion > 18 < / WarningVersion > <nl> < / ClCompile > <nl> < Link > <nl> < AdditionalDependencies > comctl32 . lib ; shlwapi . lib ; shell32 . lib ; Oleacc . lib ; Dbghelp . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> copy . . \ src \ contextMenu . xml . . \ bin \ contextMenu . xml <nl> < FavorSizeOrSpeed > Speed < / FavorSizeOrSpeed > <nl> < OmitFramePointers > false < / OmitFramePointers > <nl> < WholeProgramOptimization > false < / WholeProgramOptimization > <nl> - < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < AdditionalIncludeDirectories > . . \ src \ WinControls \ AboutDlg ; . . \ . . \ scintilla \ include ; . . \ include ; . . \ src \ WinControls ; . . \ src \ WinControls \ ImageListSet ; . . \ src \ WinControls \ OpenSaveFileDialog ; . . \ src \ WinControls \ SplitterContainer ; . . \ src \ WinControls \ StaticDialog ; . . \ src \ WinControls \ TabBar ; . . \ src \ WinControls \ ToolBar ; . . \ src \ MISC \ Process ; . . \ src \ ScitillaComponent ; . . \ src \ MISC ; . . \ src \ MISC \ SysMsg ; . . \ src \ WinControls \ StatusBar ; . . \ src ; . . \ src \ WinControls \ StaticDialog \ RunDlg ; . . \ src \ tinyxml ; . . \ src \ WinControls \ ColourPicker ; . . \ src \ Win32Explr ; . . \ src \ MISC \ RegExt ; . . \ src \ WinControls \ TrayIcon ; . . \ src \ WinControls \ shortcut ; . . \ src \ WinControls \ Grid ; . . \ src \ WinControls \ ContextMenu ; . . \ src \ MISC \ PluginsManager ; . . \ src \ WinControls \ Preference ; . . \ src \ WinControls \ WindowsDlg ; . . \ src \ WinControls \ TaskList ; . . \ src \ WinControls \ DockingWnd ; . . \ src \ WinControls \ ToolTip ; . . \ src \ MISC \ Exception ; . . \ src \ MISC \ Common ; . . \ src \ tinyxml \ tinyXmlA ; . . \ src \ WinControls \ AnsiCharPanel ; . . \ src \ WinControls \ ClipboardHistory ; . . \ src \ WinControls \ FindCharsInRange ; . . \ src \ WinControls \ VerticalFileSwitcher ; . . \ src \ WinControls \ ProjectPanel ; . . \ src \ WinControls \ DocumentMap ; . . \ src \ WinControls \ FunctionList ; . . \ src \ uchardet ; . . \ src \ WinControls \ FileBrowser ; . . \ src \ WinControls \ ReadDirectoryChanges ; . . \ src \ MISC \ md5 ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> < PreprocessorDefinitions > WIN32 ; _WIN32_WINNT = 0x0501 ; NDEBUG ; _WINDOWS ; _USE_64BIT_TIME_T ; TIXML_USE_STL ; TIXMLA_USE_STL ; _CRT_NONSTDC_NO_DEPRECATE ; _CRT_SECURE_NO_WARNINGS ; _CRT_NON_CONFORMING_SWPRINTFS = 1 ; _CRT_NON_CONFORMING_WCSTOK ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < PreprocessToFile > false < / PreprocessToFile > <nl> < PreprocessSuppressLineNumbers > false < / PreprocessSuppressLineNumbers > <nl> copy . . \ src \ contextMenu . xml . . \ bin \ contextMenu . xml <nl> < RuntimeLibrary > MultiThreaded < / RuntimeLibrary > <nl> < FunctionLevelLinking > true < / FunctionLevelLinking > <nl> < WarningLevel > Level4 < / WarningLevel > <nl> - < TreatWarningAsError > false < / TreatWarningAsError > <nl> + < TreatWarningAsError > true < / TreatWarningAsError > <nl> < DebugInformationFormat > ProgramDatabase < / DebugInformationFormat > <nl> < EnableEnhancedInstructionSet > NoExtensions < / EnableEnhancedInstructionSet > <nl> < MultiProcessorCompilation > true < / MultiProcessorCompilation > <nl> < DisableSpecificWarnings > 4091 ; 4456 ; 4457 ; 4459 < / DisableSpecificWarnings > <nl> + < WarningVersion > 18 < / WarningVersion > <nl> < / ClCompile > <nl> < Link > <nl> < AdditionalDependencies > comctl32 . lib ; shlwapi . lib ; shell32 . lib ; Oleacc . lib ; Dbghelp . lib ; % ( AdditionalDependencies ) < / AdditionalDependencies > <nl> copy . . \ src \ contextMenu . xml . . \ bin64 \ contextMenu . xml <nl> < ItemGroup > <nl> < ClCompile Include = " . . \ src \ MISC \ Common \ LongRunningOperation . cpp " / > <nl> < ClCompile Include = " . . \ src \ MISC \ Common \ mutex . cpp " / > <nl> + < ClCompile Include = " . . \ src \ MISC \ md5 \ md5Dlgs . cpp " / > <nl> < ClCompile Include = " . . \ src \ WinControls \ AboutDlg \ AboutDlg . cpp " / > <nl> < ClCompile Include = " . . \ src \ WinControls \ AnsiCharPanel \ ansiCharPanel . cpp " / > <nl> < ClCompile Include = " . . \ src \ ScitillaComponent \ AutoCompletion . cpp " / > <nl> copy . . \ src \ contextMenu . xml . . \ bin64 \ contextMenu . xml <nl> < Image Include = " . . \ src \ icons \ zoomOut_on . ico " / > <nl> < / ItemGroup > <nl> < ItemGroup > <nl> + < ResourceCompile Include = " . . \ src \ MISC \ md5 \ md5Dlgs . rc " / > <nl> < ResourceCompile Include = " . . \ src \ WinControls \ AnsiCharPanel \ ansiCharPanel . rc " / > <nl> < ResourceCompile Include = " . . \ src \ WinControls \ ClipboardHistory \ clipboardHistoryPanel . rc " / > <nl> < ResourceCompile Include = " . . \ src \ WinControls \ ColourPicker \ ColourPopup . rc " / > <nl> copy . . \ src \ contextMenu . xml . . \ bin64 \ contextMenu . xml <nl> < ClInclude Include = " . . \ src \ MISC \ Common \ LongRunningOperation . h " / > <nl> < ClInclude Include = " . . \ src \ MISC \ Common \ mutex . h " / > <nl> < ClInclude Include = " . . \ src \ MISC \ Common \ mutex . hxx " / > <nl> + < ClInclude Include = " . . \ src \ MISC \ md5 \ md5 . h " / > <nl> + < ClInclude Include = " . . \ src \ MISC \ md5 \ md5Dlgs . h " / > <nl> + < ClInclude Include = " . . \ src \ MISC \ md5 \ md5Dlgs_rc . h " / > <nl> < ClInclude Include = " . . \ src \ WinControls \ AboutDlg \ AboutDlg . h " / > <nl> < ClInclude Include = " . . \ src \ WinControls \ AnsiCharPanel \ ansiCharPanel . h " / > <nl> < ClInclude Include = " . . \ src \ ScitillaComponent \ AutoCompletion . h " / > <nl> copy . . \ src \ contextMenu . xml . . \ bin64 \ contextMenu . xml <nl> < Import Project = " $ ( VCTargetsPath ) \ Microsoft . Cpp . targets " / > <nl> < ImportGroup Label = " ExtensionTargets " > <nl> < / ImportGroup > <nl> - < / Project > <nl> + < / Project > <nl> \ No newline at end of file <nl>
Fix the shadow declarations & make VS2015 compile again
notepad-plus-plus/notepad-plus-plus
b0a625913c9519c99420126b8e462afa347996ed
2017-01-10T00:09:18Z
mmm a / include / spdlog / details / os . h <nl> ppp b / include / spdlog / details / os . h <nl> namespace details <nl> namespace os <nl> { <nl> <nl> + # if defined __linux__ & & defined SPDLOG_CLOCK_MONOTONIC <nl> + inline uint64_t clock_offset ( ) <nl> + { <nl> + timespec ts_realtime ; <nl> + : : clock_gettime ( CLOCK_REALTIME , & ts_realtime ) ; <nl> + timespec ts_monotonic ; <nl> + : : clock_gettime ( CLOCK_MONOTONIC , & ts_monotonic ) ; <nl> + <nl> + const uint64_t realtime = ts_realtime . tv_sec * 1000000000 + ts_realtime . tv_nsec ; <nl> + const uint64_t monotonic = ts_monotonic . tv_sec * 1000000000 + ts_monotonic . tv_nsec ; <nl> + return realtime - monotonic ; <nl> + } <nl> + # endif <nl> + <nl> inline spdlog : : log_clock : : time_point now ( ) <nl> { <nl> <nl> inline spdlog : : log_clock : : time_point now ( ) <nl> std : : chrono : : duration_cast < typename log_clock : : duration > ( <nl> std : : chrono : : seconds ( ts . tv_sec ) + std : : chrono : : nanoseconds ( ts . tv_nsec ) ) ) ; <nl> <nl> + # elif defined __linux__ & & defined SPDLOG_CLOCK_MONOTONIC <nl> + static const auto offset = std : : chrono : : nanoseconds ( clock_offset ( ) ) ; <nl> + <nl> + timespec ts ; <nl> + : : clock_gettime ( CLOCK_MONOTONIC , & ts ) ; <nl> + return std : : chrono : : time_point < log_clock , typename log_clock : : duration > ( <nl> + std : : chrono : : duration_cast < typename log_clock : : duration > ( <nl> + offset + std : : chrono : : seconds ( ts . tv_sec ) + std : : chrono : : nanoseconds ( ts . tv_nsec ) ) ) ; <nl> # else <nl> return log_clock : : now ( ) ; <nl> # endif <nl> inline bool file_exists ( const std : : string & filename ) <nl> # elif __linux__ <nl> struct stat buffer ; <nl> return ( stat ( filename . c_str ( ) , & buffer ) = = 0 ) ; <nl> - # else <nl> + # else <nl> auto * file = fopen ( filename . c_str ( ) , " r " ) ; <nl> if ( file ! = nullptr ) <nl> { <nl> mmm a / include / spdlog / tweakme . h <nl> ppp b / include / spdlog / tweakme . h <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Under Linux , the much faster CLOCK_MONOTONIC clock can be used . <nl> + / / This clock is more accurate than CLOCK_REALTIME_COARSE and faster than regular clock . <nl> + / / Uncomment to use it instead of the regular clock . <nl> + / / # define SPDLOG_CLOCK_MONOTONIC <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + <nl> + <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / Uncomment if date / time logging is not needed . <nl> / / This will prevent spdlog from quering the clock on each log call . <nl>
Merge pull request from ksergey / clock_tweak
gabime/spdlog
e3c3f91c116f52d5cf2f076d226d39e395b9ad2e
2015-12-22T07:47:44Z
mmm a / build / fbcode_builder / manifests / libsai <nl> ppp b / build / fbcode_builder / manifests / libsai <nl> <nl> name = libsai <nl> <nl> [ download ] <nl> - url = https : / / github . com / opencomputeproject / SAI / archive / v1 . 4 . 0 . tar . gz <nl> - sha256 = 3eb65724b053886236c6cc408853a419fea9a0db19081e38209c2e8718b724b3 <nl> + url = https : / / github . com / opencomputeproject / SAI / archive / v1 . 5 . 0 . tar . gz <nl> + sha256 = f7f1ab22350de6fff4032d1a604c12c76b591d02afbc36471b79ae9edd3ad8ab <nl> <nl> [ build ] <nl> builder = nop <nl> - subdir = SAI - 1 . 4 . 0 <nl> + subdir = SAI - 1 . 5 . 0 <nl> <nl> [ install . files ] <nl> inc = include <nl>
Switch OSS build to SAI 1 . 5
facebook/folly
15e365c94263dfd6a244f50bf8b76951a819ee18
2020-02-21T05:56:20Z
mmm a / src / mongo / db / catalog / collection_validation . cpp <nl> ppp b / src / mongo / db / catalog / collection_validation . cpp <nl> <nl> # include " mongo / db / storage / durable_catalog . h " <nl> # include " mongo / db / storage / record_store . h " <nl> # include " mongo / db / views / view_catalog . h " <nl> + # include " mongo / util / fail_point . h " <nl> # include " mongo / util / log . h " <nl> <nl> namespace mongo { <nl> <nl> + using logger : : LogComponent ; <nl> using std : : string ; <nl> <nl> - using logger : : LogComponent ; <nl> + MONGO_FAIL_POINT_DEFINE ( pauseCollectionValidationWithLock ) ; <nl> <nl> namespace CollectionValidation { <nl> <nl> namespace { <nl> <nl> using ValidateResultsMap = std : : map < string , ValidateResults > ; <nl> <nl> + / / Indicates whether the failpoint turned on by testing has been reached . <nl> + AtomicWord < bool > _validationIsPausedForTest { false } ; <nl> + <nl> / * * <nl> * Opens a cursor on each index in the given ' indexCatalog ' . <nl> * <nl> void _validateIndexes ( <nl> / / of the index ) . Check if this is consistent with ' numTraversedKeys ' from traverseIndex <nl> / / above . <nl> if ( level = = kValidateFull ) { <nl> + invariant ( <nl> + opCtx - > lockState ( ) - > isCollectionLockedForMode ( descriptor - > parentNS ( ) , MODE_X ) ) ; <nl> + <nl> / / Ensure that this index was validated in _validateIndexesInternalStructure . <nl> const auto numIndexKeysIt = numIndexKeysPerIndex . find ( descriptor - > indexName ( ) ) ; <nl> invariant ( numIndexKeysIt ! = numIndexKeysPerIndex . end ( ) ) ; <nl> void _validateIndexes ( <nl> / / comprised ( which was set in _validateIndexesInternalStructure ) . If the index is <nl> / / corrupted , there is no use in checking if the traversal yielded the same key count . <nl> if ( curIndexResults . valid ) { <nl> - <nl> if ( numIndexKeys ! = numTraversedKeys ) { <nl> curIndexResults . valid = false ; <nl> string msg = str : : stream ( ) <nl> void _validateIndexKeyCount ( OperationContext * opCtx , <nl> } <nl> <nl> void _reportValidationResults ( OperationContext * opCtx , <nl> - IndexCatalog * indexCatalog , <nl> + Collection * collection , <nl> ValidateResultsMap * indexNsResultsMap , <nl> BSONObjBuilder * keysPerIndex , <nl> ValidateCmdLevel level , <nl> ValidateResults * results , <nl> BSONObjBuilder * output ) { <nl> - <nl> std : : unique_ptr < BSONObjBuilder > indexDetails ; <nl> if ( level = = kValidateFull ) { <nl> + invariant ( opCtx - > lockState ( ) - > isCollectionLockedForMode ( collection - > ns ( ) , MODE_X ) ) ; <nl> indexDetails = std : : make_unique < BSONObjBuilder > ( ) ; <nl> } <nl> <nl> / / Report index validation results . <nl> for ( const auto & it : * indexNsResultsMap ) { <nl> - const string indexNs = it . first ; <nl> + const string indexName = it . first ; <nl> const ValidateResults & vr = it . second ; <nl> <nl> if ( ! vr . valid ) { <nl> void _reportValidationResults ( OperationContext * opCtx , <nl> } <nl> <nl> if ( indexDetails ) { <nl> - BSONObjBuilder bob ( indexDetails - > subobjStart ( indexNs ) ) ; <nl> + BSONObjBuilder bob ( indexDetails - > subobjStart ( indexName ) ) ; <nl> bob . appendBool ( " valid " , vr . valid ) ; <nl> <nl> if ( ! vr . warnings . empty ( ) ) { <nl> void _reportValidationResults ( OperationContext * opCtx , <nl> results - > errors . insert ( results - > errors . end ( ) , vr . errors . begin ( ) , vr . errors . end ( ) ) ; <nl> } <nl> <nl> - output - > append ( " nIndexes " , indexCatalog - > numIndexesReady ( opCtx ) ) ; <nl> + output - > append ( " nIndexes " , collection - > getIndexCatalog ( ) - > numIndexesReady ( opCtx ) ) ; <nl> output - > append ( " keysPerIndex " , keysPerIndex - > done ( ) ) ; <nl> if ( indexDetails ) { <nl> output - > append ( " indexDetails " , indexDetails - > done ( ) ) ; <nl> Status validate ( OperationContext * opCtx , <nl> / / Full validation code is executed before we open cursors because it may close <nl> / / and / or invalidate all open cursors . <nl> if ( level = = kValidateFull ) { <nl> + invariant ( opCtx - > lockState ( ) - > isCollectionLockedForMode ( nss , MODE_X ) ) ; <nl> + <nl> / / For full validation we use the storage engine ' s validation functionality . <nl> collection - > getRecordStore ( ) - > validate ( opCtx , results , output ) ; <nl> + <nl> / / For full validation , we validate the internal structure of each index and save the <nl> / / number of keys in the index to compare against _validateIndexes ( ) ' s count results . <nl> numIndexKeysPerIndex = _validateIndexesInternalStructure ( <nl> Status validate ( OperationContext * opCtx , <nl> dataThrottle - > turnThrottlingOff ( ) ; <nl> } <nl> <nl> + / / Background validation will read from the last stable checkpoint instead of the latest <nl> + / / data . This allows concurrent writes to go ahead without interfering with validation ' s <nl> + / / view of the data . <nl> + / / The checkpoint lock must be taken around cursor creation to ensure all cursors <nl> + / / point at the same checkpoint , i . e . a consistent view of the collection data . <nl> + std : : unique_ptr < StorageEngine : : CheckpointLock > checkpointCursorsLock ; <nl> + if ( background ) { <nl> + auto storageEngine = opCtx - > getServiceContext ( ) - > getStorageEngine ( ) ; <nl> + invariant ( storageEngine - > supportsCheckpoints ( ) ) ; <nl> + opCtx - > recoveryUnit ( ) - > abandonSnapshot ( ) ; <nl> + opCtx - > recoveryUnit ( ) - > setTimestampReadSource ( RecoveryUnit : : ReadSource : : kCheckpoint ) ; <nl> + checkpointCursorsLock = storageEngine - > getCheckpointLock ( opCtx ) ; <nl> + } <nl> + <nl> / / Open all cursors at once before running non - full validation code so that all steps of <nl> / / validation during background validation use the same view of the data . <nl> const std : : map < std : : string , std : : unique_ptr < SortedDataInterfaceThrottleCursor > > <nl> Status validate ( OperationContext * opCtx , <nl> std : : make_unique < SeekableRecordThrottleCursor > ( <nl> opCtx , collection - > getRecordStore ( ) , dataThrottle ) ; <nl> <nl> + checkpointCursorsLock . reset ( ) ; <nl> + <nl> / / Because SeekableRecordCursors don ' t have a method to reset to the start , we save and then <nl> / / use a seek to the first RecordId to reset the cursor ( and reuse it ) as needed . When <nl> / / iterating through a Record Store cursor , we initialize the loop ( and obtain the first <nl> Status validate ( OperationContext * opCtx , <nl> / / Validate in - memory catalog information with persisted info . <nl> _validateCatalogEntry ( opCtx , collection , collection - > getValidatorDoc ( ) , results ) ; <nl> <nl> + / / Pause collection validation while a lock is held and between collection and index data <nl> + / / valiation . <nl> + / / <nl> + / / The IndexConsistency object saves document key information during collection data <nl> + / / validation and then compares against that key information during index data validation . <nl> + / / This fail point is placed in between them , in an attempt to catch any inconsistencies <nl> + / / that concurrent CRUD ops might cause if we were to have a bug . <nl> + / / <nl> + / / Only useful for background validation because we hold an intent lock instead of an <nl> + / / exclusive lock , and thus allow concurrent operations . <nl> + if ( MONGO_FAIL_POINT ( pauseCollectionValidationWithLock ) ) { <nl> + invariant ( opCtx - > lockState ( ) - > isCollectionLockedForMode ( collection - > ns ( ) , MODE_IX ) ) ; <nl> + _validationIsPausedForTest . store ( true ) ; <nl> + MONGO_FAIL_POINT_PAUSE_WHILE_SET ( pauseCollectionValidationWithLock ) ; <nl> + _validationIsPausedForTest . store ( false ) ; <nl> + } <nl> + <nl> / / Validate indexes and check for mismatches . <nl> if ( results - > valid ) { <nl> _validateIndexes ( opCtx , <nl> Status validate ( OperationContext * opCtx , <nl> } <nl> <nl> / / Report the validation results for the user to see . <nl> - _reportValidationResults ( opCtx , <nl> - collection - > getIndexCatalog ( ) , <nl> - & indexNsResultsMap , <nl> - & keysPerIndex , <nl> - level , <nl> - results , <nl> - output ) ; <nl> + _reportValidationResults ( <nl> + opCtx , collection , & indexNsResultsMap , & keysPerIndex , level , results , output ) ; <nl> <nl> if ( ! results - > valid ) { <nl> log ( LogComponent : : kIndex ) < < " Validation complete for collection " < < collection - > ns ( ) <nl> Status validate ( OperationContext * opCtx , <nl> <nl> return Status : : OK ( ) ; <nl> } <nl> + <nl> + bool getIsValidationPausedForTest ( ) { <nl> + return _validationIsPausedForTest . load ( ) ; <nl> + } <nl> + <nl> } / / namespace CollectionValidation <nl> } / / namespace mongo <nl> mmm a / src / mongo / db / catalog / collection_validation . h <nl> ppp b / src / mongo / db / catalog / collection_validation . h <nl> Status validate ( OperationContext * opCtx , <nl> ValidateResults * results , <nl> BSONObjBuilder * output ) ; <nl> <nl> + / * * <nl> + * Checks whether a failpoint has been hit in the above validate ( ) code . . <nl> + * / <nl> + bool getIsValidationPausedForTest ( ) ; <nl> + <nl> } / / namespace CollectionValidation <nl> } / / namespace mongo <nl> mmm a / src / mongo / db / catalog / collection_validation_test . cpp <nl> ppp b / src / mongo / db / catalog / collection_validation_test . cpp <nl> <nl> # include " mongo / db / catalog / catalog_test_fixture . h " <nl> # include " mongo / db / catalog / collection . h " <nl> # include " mongo / db / db_raii . h " <nl> + # include " mongo / stdx / thread . h " <nl> # include " mongo / unittest / unittest . h " <nl> + # include " mongo / util / fail_point_service . h " <nl> <nl> namespace mongo { <nl> <nl> void foregroundValidate ( <nl> for ( auto level : levels ) { <nl> ValidateResults validateResults ; <nl> BSONObjBuilder output ; <nl> - ASSERT_OK ( <nl> - CollectionValidation : : validate ( opCtx , kNss , level , false , & validateResults , & output ) ) ; <nl> + ASSERT_OK ( CollectionValidation : : validate ( <nl> + opCtx , kNss , level , / * background * / false , & validateResults , & output ) ) ; <nl> ASSERT_EQ ( validateResults . valid , valid ) ; <nl> ASSERT_EQ ( validateResults . errors . size ( ) , static_cast < long unsigned int > ( numErrors ) ) ; <nl> <nl> void backgroundValidate ( OperationContext * opCtx , <nl> foregroundValidate ( opCtx , valid , numRecords , numInvalidDocuments , numErrors ) ; <nl> } <nl> <nl> + / / This function will force a checkpoint , so background validation can then read from that <nl> + / / checkpoint . <nl> + opCtx - > recoveryUnit ( ) - > waitUntilUnjournaledWritesDurable ( opCtx ) ; <nl> + <nl> ValidateResults validateResults ; <nl> BSONObjBuilder output ; <nl> ASSERT_OK ( CollectionValidation : : validate ( opCtx , <nl> void backgroundValidate ( OperationContext * opCtx , <nl> } <nl> <nl> / * * <nl> - * Inserts a few documents into the kNss collection and then returns that count . <nl> + * Inserts a range of documents into the kNss collection and then returns that count . <nl> + * The range is defined by [ startIDNum , endIDNum ) , not inclusive of endIDNum , using the numbers as <nl> + * values for ' _id ' of the document being inserted . <nl> * / <nl> - int setUpValidData ( OperationContext * opCtx ) { <nl> - AutoGetCollection autoColl ( opCtx , kNss , MODE_X ) ; <nl> - Collection * coll = autoColl . getCollection ( ) ; <nl> + int insertDataRange ( OperationContext * opCtx , int startIDNum , int endIDNum ) { <nl> + invariant ( startIDNum < endIDNum , <nl> + str : : stream ( ) < < " attempted to insert invalid data range from " < < startIDNum <nl> + < < " to " < < endIDNum ) ; <nl> <nl> + <nl> + AutoGetCollection autoColl ( opCtx , kNss , MODE_IX ) ; <nl> + Collection * coll = autoColl . getCollection ( ) ; <nl> std : : vector < InsertStatement > inserts ; <nl> - int numRecords = 5 ; <nl> - for ( int i = 0 ; i < numRecords ; i + + ) { <nl> + for ( int i = startIDNum ; i < endIDNum ; + + i ) { <nl> auto doc = BSON ( " _id " < < i ) ; <nl> inserts . push_back ( InsertStatement ( doc ) ) ; <nl> } <nl> int setUpValidData ( OperationContext * opCtx ) { <nl> ASSERT_OK ( coll - > insertDocuments ( opCtx , inserts . begin ( ) , inserts . end ( ) , nullptr , false ) ) ; <nl> wuow . commit ( ) ; <nl> } <nl> - return numRecords ; <nl> + return endIDNum - startIDNum ; <nl> } <nl> <nl> / * * <nl> * Inserts a single invalid document into the kNss collection and then returns that count . <nl> * / <nl> int setUpInvalidData ( OperationContext * opCtx ) { <nl> - AutoGetCollection autoColl ( opCtx , kNss , MODE_X ) ; <nl> + AutoGetCollection autoColl ( opCtx , kNss , MODE_IX ) ; <nl> Collection * coll = autoColl . getCollection ( ) ; <nl> RecordStore * rs = coll - > getRecordStore ( ) ; <nl> <nl> int setUpInvalidData ( OperationContext * opCtx ) { <nl> return 1 ; <nl> } <nl> <nl> - / / TODO ( SERVER - 42223 ) : right now background validation is mostly identical to foreground , except <nl> - / / that background runs with an IX lock instead of a X lock . SERVER - 42223 will set up real <nl> - / / background validation . <nl> - <nl> / / Verify that calling validate ( ) on an empty collection with different validation levels returns an <nl> / / OK status . <nl> TEST_F ( CollectionValidationTest , ValidateEmpty ) { <nl> TEST_F ( CollectionValidationTest , Validate ) { <nl> auto opCtx = operationContext ( ) ; <nl> foregroundValidate ( opCtx , <nl> / * valid * / true , <nl> - / * numRecords * / setUpValidData ( opCtx ) , <nl> + / * numRecords * / insertDataRange ( opCtx , 0 , 5 ) , <nl> / * numInvalidDocuments * / 0 , <nl> / * numErrors * / 0 ) ; <nl> } <nl> TEST_F ( BackgroundCollectionValidationTest , BackgroundValidate ) { <nl> auto opCtx = operationContext ( ) ; <nl> backgroundValidate ( opCtx , <nl> / * valid * / true , <nl> - / * numRecords * / setUpValidData ( opCtx ) , <nl> + / * numRecords * / insertDataRange ( opCtx , 0 , 5 ) , <nl> / * numInvalidDocuments * / 0 , <nl> / * numErrors * / 0 , <nl> / * runForegroundAsWell * / true ) ; <nl> TEST_F ( BackgroundCollectionValidationTest , BackgroundValidateError ) { <nl> / * runForegroundAsWell * / true ) ; <nl> } <nl> <nl> + / * * <nl> + * Waits for a parallel running collection validation operation to start and then hang at a <nl> + * failpoint . <nl> + * <nl> + * A failpoint in the validate ( ) code should have been set prior to calling this function . <nl> + * / <nl> + void waitUntilValidateFailpointHasBeenReached ( ) { <nl> + while ( ! CollectionValidation : : getIsValidationPausedForTest ( ) ) { <nl> + sleepmillis ( 100 ) ; / / a fairly arbitrary sleep period . <nl> + } <nl> + ASSERT ( CollectionValidation : : getIsValidationPausedForTest ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( BackgroundCollectionValidationTest , BackgroundValidateRunsConcurrentlyWithWrites ) { <nl> + auto opCtx = operationContext ( ) ; <nl> + auto serviceContext = opCtx - > getServiceContext ( ) ; <nl> + <nl> + / / Set up some data in the collection so that we can validate it . <nl> + int numRecords = insertDataRange ( opCtx , 0 , 5 ) ; <nl> + <nl> + stdx : : thread runBackgroundValidate ; <nl> + int numRecords2 ; <nl> + { <nl> + / / Set a failpoint in the collection validation code and then start a parallel operation to <nl> + / / run background validation in parallel . <nl> + FailPointEnableBlock failPoint ( " pauseCollectionValidationWithLock " ) ; <nl> + runBackgroundValidate = stdx : : thread ( [ & serviceContext , & numRecords ] { <nl> + ThreadClient tc ( " BackgroundValidateConcurrentWithCRUD - thread " , serviceContext ) ; <nl> + auto threadOpCtx = tc - > makeOperationContext ( ) ; <nl> + backgroundValidate ( <nl> + threadOpCtx . get ( ) , true , numRecords , 0 , 0 , / * runForegroundAsWell * / false ) ; <nl> + } ) ; <nl> + <nl> + / / Wait until validate starts and hangs mid - way on a failpoint , then do concurrent writes , <nl> + / / which should succeed and not affect the background validation . <nl> + waitUntilValidateFailpointHasBeenReached ( ) ; <nl> + numRecords2 = insertDataRange ( opCtx , 5 , 15 ) ; <nl> + } <nl> + <nl> + / / Make sure the background validation finishes successfully . <nl> + runBackgroundValidate . join ( ) ; <nl> + <nl> + / / Run regular foreground collection validation to make sure everything is OK . <nl> + foregroundValidate ( opCtx , / * valid * / true , / * numRecords * / numRecords + numRecords2 , 0 , 0 ) ; <nl> + } <nl> + <nl> } / / namespace <nl> } / / namespace mongo <nl> mmm a / src / mongo / dbtests / validate_tests . cpp <nl> ppp b / src / mongo / dbtests / validate_tests . cpp <nl> class ValidateBase { <nl> _isInRecordIdOrder = <nl> autoGetCollection . getCollection ( ) - > getRecordStore ( ) - > isInRecordIdOrder ( ) ; <nl> } <nl> + _engineSupportsCheckpoints = <nl> + _opCtx . getServiceContext ( ) - > getStorageEngine ( ) - > supportsCheckpoints ( ) ; <nl> } <nl> <nl> ~ ValidateBase ( ) { <nl> class ValidateBase { <nl> <nl> protected : <nl> ValidateResults runValidate ( ) { <nl> + / / validate ( ) will set a kCheckpoint read source . Callers continue to do operations after <nl> + / / running validate , so we must reset the read source back to normal before returning . <nl> + auto originalReadSource = _opCtx . recoveryUnit ( ) - > getTimestampReadSource ( ) ; <nl> + ON_BLOCK_EXIT ( [ & ] { <nl> + _opCtx . recoveryUnit ( ) - > abandonSnapshot ( ) ; <nl> + _opCtx . recoveryUnit ( ) - > setTimestampReadSource ( originalReadSource ) ; <nl> + } ) ; <nl> + <nl> + / / This function will force a checkpoint , so background validation can then read from that <nl> + / / checkpoint and see all the new data . <nl> + _opCtx . recoveryUnit ( ) - > waitUntilUnjournaledWritesDurable ( & _opCtx ) ; <nl> + <nl> ValidateResults results ; <nl> BSONObjBuilder output ; <nl> <nl> class ValidateBase { <nl> unique_ptr < AutoGetDb > _autoDb ; <nl> Database * _db ; <nl> bool _isInRecordIdOrder ; <nl> + bool _engineSupportsCheckpoints ; <nl> } ; <nl> <nl> template < bool full , bool background > <nl> class ValidateIdIndexCount : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateSecondaryIndexCount : public ValidateBase { <nl> ValidateSecondaryIndexCount ( ) : ValidateBase ( full , background ) { } <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateSecondaryIndex : public ValidateBase { <nl> ValidateSecondaryIndex ( ) : ValidateBase ( full , background ) { } <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateIdIndex : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateMultiKeyIndex : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateSparseIndex : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidatePartialIndex : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidatePartialIndexOnCollectionWithNonIndexableFields : public ValidateBa <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateCompoundIndex : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateIndexEntry : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateIndexOrdering : public ValidateBase { <nl> <nl> void run ( ) { <nl> <nl> - / / Can ' t do it in background if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateWildCardIndex : public ValidateBase { <nl> ValidateWildCardIndex ( ) : ValidateBase ( full , background ) { } <nl> <nl> void run ( ) { <nl> - / / Can ' t perform background validation if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateWildCardIndexWithProjection : public ValidateBase { <nl> ValidateWildCardIndexWithProjection ( ) : ValidateBase ( full , background ) { } <nl> <nl> void run ( ) { <nl> - / / Can ' t perform background validation if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateMissingAndExtraIndexEntryResults : public ValidateBase { <nl> ValidateMissingAndExtraIndexEntryResults ( ) : ValidateBase ( full , background ) { } <nl> <nl> void run ( ) { <nl> - / / Can ' t perform background validation if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateMissingAndExtraIndexEntryResults : public ValidateBase { <nl> releaseDb ( ) ; <nl> <nl> { <nl> + / / This function will force a checkpoint , so background validation can then read from <nl> + / / that checkpoint and see all the new data . <nl> + _opCtx . recoveryUnit ( ) - > waitUntilUnjournaledWritesDurable ( & _opCtx ) ; <nl> + <nl> ValidateResults results ; <nl> BSONObjBuilder output ; <nl> <nl> class ValidateMissingIndexEntryResults : public ValidateBase { <nl> ValidateMissingIndexEntryResults ( ) : ValidateBase ( full , background ) { } <nl> <nl> void run ( ) { <nl> - / / Can ' t perform background validation if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateMissingIndexEntryResults : public ValidateBase { <nl> } <nl> <nl> { <nl> + / / This function will force a checkpoint , so background validation can then read from <nl> + / / that checkpoint and see all the new data . <nl> + _opCtx . recoveryUnit ( ) - > waitUntilUnjournaledWritesDurable ( & _opCtx ) ; <nl> + <nl> ValidateResults results ; <nl> BSONObjBuilder output ; <nl> <nl> class ValidateExtraIndexEntryResults : public ValidateBase { <nl> ValidateExtraIndexEntryResults ( ) : ValidateBase ( full , background ) { } <nl> <nl> void run ( ) { <nl> - / / Can ' t perform background validation if the RecordStore is not in RecordId order . <nl> - if ( _background & & ! _isInRecordIdOrder ) { <nl> + / / Cannot run validate with { background : true } if either <nl> + / / - the RecordStore cursor does not retrieve documents in RecordId order <nl> + / / - or the storage engine does not support checkpoints . <nl> + if ( _background & & ( ! _isInRecordIdOrder | | ! _engineSupportsCheckpoints ) ) { <nl> return ; <nl> } <nl> <nl> class ValidateExtraIndexEntryResults : public ValidateBase { <nl> } <nl> <nl> { <nl> + / / This function will force a checkpoint , so background validation can then read from <nl> + / / that checkpoint and see all the new data . <nl> + _opCtx . recoveryUnit ( ) - > waitUntilUnjournaledWritesDurable ( & _opCtx ) ; <nl> + <nl> ValidateResults results ; <nl> BSONObjBuilder output ; <nl> <nl>
SERVER - 42223 Use checkpoint cursors for collection validation when { background : true } is requested
mongodb/mongo
82eb1202120ce29c57f55333000a93d338c65baa
2019-09-03T23:14:19Z
mmm a / docs / python_docs / python / tutorials / performance / backend / amp . md <nl> ppp b / docs / python_docs / python / tutorials / performance / backend / amp . md <nl> In order to start using AMP , we need to import and initialize it . This has to ha <nl> <nl> <nl> ` ` ` { . python . input } <nl> - from mxnet . contrib import amp <nl> + from mxnet import amp <nl> <nl> amp . init ( ) <nl> ` ` ` <nl> mmm a / example / automatic - mixed - precision / amp_model_conversion . py <nl> ppp b / example / automatic - mixed - precision / amp_model_conversion . py <nl> <nl> from common import modelzoo <nl> import gluoncv <nl> from gluoncv . model_zoo import get_model <nl> - from mxnet . contrib . amp import amp <nl> + from mxnet import amp <nl> import numpy as np <nl> <nl> <nl> similarity index 100 % <nl> rename from python / mxnet / contrib / amp / __init__ . py <nl> rename to python / mxnet / amp / __init__ . py <nl> similarity index 98 % <nl> rename from python / mxnet / contrib / amp / amp . py <nl> rename to python / mxnet / amp / amp . py <nl> mmm a / python / mxnet / contrib / amp / amp . py <nl> ppp b / python / mxnet / amp / amp . py <nl> <nl> import numpy as np <nl> <nl> from mxnet import numpy <nl> - from . . . import symbol <nl> - from . . . context import gpu <nl> - from . . . symbol import Symbol <nl> - from . . . symbol import contrib as symbol_contrib <nl> - from . . . import ndarray <nl> - from . . . ndarray import NDArray , _DTYPE_NP_TO_MX , _DTYPE_MX_TO_NP <nl> + from . . import symbol <nl> + from . . context import gpu <nl> + from . . symbol import Symbol <nl> + from . . symbol import contrib as symbol_contrib <nl> + from . . import ndarray <nl> + from . . ndarray import NDArray , _DTYPE_NP_TO_MX , _DTYPE_MX_TO_NP <nl> from . import lists <nl> - from . . . gluon import Block , trainer <nl> - from . . . import base <nl> - from . . . base import ( _NP_OP_PREFIX , _NP_OP_SUBMODULE_LIST , _NP_EXT_OP_PREFIX , <nl> - _NP_EXT_OP_SUBMODULE_LIST , _NP_INTERNAL_OP_PREFIX , <nl> - c_str_array , SymbolHandle , check_call , _LIB , mx_uint , c_array_buf ) <nl> - from . . . import optimizer as opt <nl> + from . . gluon import Block , trainer <nl> + from . . import base <nl> + from . . base import ( _NP_OP_PREFIX , _NP_OP_SUBMODULE_LIST , _NP_EXT_OP_PREFIX , <nl> + _NP_EXT_OP_SUBMODULE_LIST , _NP_INTERNAL_OP_PREFIX , <nl> + c_str_array , SymbolHandle , check_call , _LIB , mx_uint , c_array_buf ) <nl> + from . . import optimizer as opt <nl> from . loss_scaler import LossScaler <nl> - from . . . operator import get_all_registered_operators_grouped <nl> + from . . operator import get_all_registered_operators_grouped <nl> <nl> bfloat16 = np . dtype ( [ ( ' bfloat16 ' , np . uint16 ) ] ) <nl> <nl> def convert_hybrid_block ( block , target_dtype = " float16 " , target_dtype_ops = None , <nl> because of a cast layer following it , but will reduce the computation and memory <nl> overhead of the model if casted . <nl> " " " <nl> - from . . . gluon import HybridBlock , SymbolBlock <nl> + from . . gluon import HybridBlock , SymbolBlock <nl> assert isinstance ( block , HybridBlock ) , " block input should be a HybridBlock " <nl> if not block . _cached_graph : <nl> raise RuntimeError ( <nl> similarity index 100 % <nl> rename from python / mxnet / contrib / amp / lists / __init__ . py <nl> rename to python / mxnet / amp / lists / __init__ . py <nl> similarity index 100 % <nl> rename from python / mxnet / contrib / amp / lists / symbol_bf16 . py <nl> rename to python / mxnet / amp / lists / symbol_bf16 . py <nl> similarity index 99 % <nl> rename from python / mxnet / contrib / amp / lists / symbol_fp16 . py <nl> rename to python / mxnet / amp / lists / symbol_fp16 . py <nl> mmm a / python / mxnet / contrib / amp / lists / symbol_fp16 . py <nl> ppp b / python / mxnet / amp / lists / symbol_fp16 . py <nl> <nl> # coding : utf - 8 <nl> " " " Lists of functions whitelisted / blacklisted for automatic mixed precision in symbol API . " " " <nl> <nl> - from . . . . runtime import Features <nl> + from . . . runtime import Features <nl> <nl> <nl> # Functions that should be cast to lower precision <nl> similarity index 96 % <nl> rename from python / mxnet / contrib / amp / loss_scaler . py <nl> rename to python / mxnet / amp / loss_scaler . py <nl> mmm a / python / mxnet / contrib / amp / loss_scaler . py <nl> ppp b / python / mxnet / amp / loss_scaler . py <nl> <nl> " " " Dynamic loss scaler for AMP . " " " <nl> import logging <nl> <nl> - from . . . import autograd as ag <nl> - from . . . import ndarray <nl> - from . . . util import is_np_array <nl> + from . . import autograd as ag <nl> + from . . import ndarray <nl> + from . . util import is_np_array <nl> <nl> class LossScaler ( object ) : <nl> " " " Dynamic loss scaler for AMP . <nl> old mode 100755 <nl> new mode 100644 <nl> similarity index 88 % <nl> rename from src / operator / contrib / all_finite - inl . h <nl> rename to src / operator / all_finite - inl . h <nl> index cf63fce2def . . d646d5b1933 <nl> mmm a / src / operator / contrib / all_finite - inl . h <nl> ppp b / src / operator / all_finite - inl . h <nl> <nl> * \ author Clement Fuji Tsang <nl> * / <nl> <nl> - # ifndef MXNET_OPERATOR_CONTRIB_ALL_FINITE_INL_H_ <nl> - # define MXNET_OPERATOR_CONTRIB_ALL_FINITE_INL_H_ <nl> + # ifndef MXNET_OPERATOR_ALL_FINITE_INL_H_ <nl> + # define MXNET_OPERATOR_ALL_FINITE_INL_H_ <nl> # include < dmlc / parameter . h > <nl> # include < mxnet / operator . h > <nl> # include < mxnet / operator_util . h > <nl> <nl> # include < nnvm / op . h > <nl> # include < nnvm / op_attr_types . h > <nl> # include < vector > <nl> - # include " . . / operator_common . h " <nl> - # include " . . / mshadow_op . h " <nl> - # include " . . / elemwise_op_common . h " <nl> - # include " . . / mxnet_op . h " <nl> - # include " . . / tensor / init_op . h " <nl> - # include " . . / tensor / util / tensor_util - inl . h " <nl> + # include " operator_common . h " <nl> + # include " mshadow_op . h " <nl> + # include " elemwise_op_common . h " <nl> + # include " mxnet_op . h " <nl> + # include " tensor / init_op . h " <nl> + # include " tensor / util / tensor_util - inl . h " <nl> <nl> namespace mxnet { <nl> namespace op { <nl> MultiAllFiniteKernelParam < DType > FillMultiAllFiniteParam ( const MultiAllFinitePar <nl> } / / namespace op <nl> } / / namespace mxnet <nl> <nl> - # endif / / MXNET_OPERATOR_CONTRIB_ALL_FINITE_INL_H_ <nl> + # endif / / MXNET_OPERATOR_ALL_FINITE_INL_H_ <nl> old mode 100755 <nl> new mode 100644 <nl> similarity index 100 % <nl> rename from src / operator / contrib / all_finite . cc <nl> rename to src / operator / all_finite . cc <nl> old mode 100755 <nl> new mode 100644 <nl> similarity index 100 % <nl> rename from src / operator / contrib / all_finite . cu <nl> rename to src / operator / all_finite . cu <nl> similarity index 100 % <nl> rename from src / operator / contrib / amp_graph_pass . cc <nl> rename to src / operator / amp_graph_pass . cc <nl> similarity index 98 % <nl> rename from tests / python / gpu / test_contrib_amp . py <nl> rename to tests / python / gpu / test_amp . py <nl> mmm a / tests / python / gpu / test_contrib_amp . py <nl> ppp b / tests / python / gpu / test_amp . py <nl> <nl> import warnings <nl> import collections <nl> import ctypes <nl> - import mxnet . contrib . amp as amp <nl> + from mxnet import amp <nl> import pytest <nl> from mxnet . test_utils import set_default_context , same_symbol_structure <nl> from mxnet . gluon . model_zoo . vision import get_model <nl> from mxnet . gluon import SymbolBlock , nn , rnn <nl> - from mxnet . contrib . amp import amp <nl> from mxnet . operator import get_all_registered_operators_grouped <nl> curr_path = os . path . dirname ( os . path . abspath ( os . path . expanduser ( __file__ ) ) ) <nl> sys . path . insert ( 0 , os . path . join ( curr_path , ' . . / unittest ' ) ) <nl> def test_amp_coverage ( amp_tests ) : <nl> safest option " " " <nl> diff = required - covered <nl> assert not diff , f " { len ( diff ) } operators { sorted ( diff ) } do not exist in AMP lists ( in " \ <nl> - f " python / mxnet / contrib / amp / lists / symbol_fp16 . py ) - please add them . " \ <nl> + f " python / mxnet / amp / lists / symbol_fp16 . py ) - please add them . " \ <nl> f " \ n { guidelines } " <nl> <nl> @ with_seed ( ) <nl> similarity index 98 % <nl> rename from tests / python / mkl / test_contrib_amp . py <nl> rename to tests / python / mkl / test_amp . py <nl> mmm a / tests / python / mkl / test_contrib_amp . py <nl> ppp b / tests / python / mkl / test_amp . py <nl> <nl> import warnings <nl> import collections <nl> import ctypes <nl> - import mxnet . contrib . amp as amp <nl> + from mxnet import amp <nl> import pytest <nl> from mxnet . test_utils import set_default_context , same_symbol_structure , assert_almost_equal <nl> from mxnet . gluon . model_zoo . vision import get_model <nl> from mxnet . gluon import SymbolBlock , nn , rnn <nl> - from mxnet . contrib . amp import amp <nl> curr_path = os . path . dirname ( os . path . abspath ( os . path . expanduser ( __file__ ) ) ) <nl> sys . path . insert ( 0 , os . path . join ( curr_path , ' . . / unittest ' ) ) <nl> from common import with_seed <nl> def test_amp_coverage ( ) : <nl> <nl> if ret1 ! = set ( ) : <nl> warnings . warn ( " Operators " + str ( ret1 ) + " do not exist in AMP lists ( in " <nl> - " python / mxnet / contrib / amp / lists / symbol_bf16 . py ) - please add them . " <nl> + " python / mxnet / amp / lists / symbol_bf16 . py ) - please add them . " <nl> " " " Please follow these guidelines for choosing a proper list : <nl> - if your operator is not to be used in a computational graph <nl> ( e . g . image manipulation operators , optimizers ) or does not have <nl> mmm a / tests / python / mkl / test_bf16_operator . py <nl> ppp b / tests / python / mkl / test_bf16_operator . py <nl> <nl> import collections <nl> import ctypes <nl> import itertools <nl> - import mxnet . contrib . amp as amp <nl> + from mxnet import amp <nl> from mxnet . test_utils import set_default_context , same_symbol_structure , assert_almost_equal_with_err , rand_shape_nd <nl> from mxnet . gluon . model_zoo . vision import get_model <nl> from mxnet . gluon import SymbolBlock , nn , rnn <nl> - from mxnet . contrib . amp import amp <nl> curr_path = os . path . dirname ( os . path . abspath ( os . path . expanduser ( __file__ ) ) ) <nl> sys . path . insert ( 0 , os . path . join ( curr_path , ' . . / unittest ' ) ) <nl> from common import with_seed <nl>
Move AMP from contrib to core ( )
apache/incubator-mxnet
9e9f972d3b59dbed7667495300707cd71a9f206c
2020-10-21T17:41:09Z
mmm a / tools / fuzzer / build_and_run_fuzzer . sh <nl> ppp b / tools / fuzzer / build_and_run_fuzzer . sh <nl> set - ex <nl> <nl> git submodule update - - init <nl> make run_dep_checks <nl> - make CONFIG = $ config $ 1 - j3 <nl> + make CONFIG = $ config $ 1 <nl> bins / $ config / $ 1 <nl>
x
grpc/grpc
be615dc9da786e852c470093cc77eb8f34a841a2
2016-03-17T22:01:41Z
mmm a / hphp / runtime / vm / jit / hhbc - translator . h <nl> ppp b / hphp / runtime / vm / jit / hhbc - translator . h <nl> struct HhbcTranslator { <nl> * for the whole instruction and is updated as the translator makes <nl> * progress . <nl> * <nl> - * We have a m_baseType in case we have more information about the type <nl> - * than m_base - > type ( ) has ( this may be the case with pointers to locals or <nl> - * stack slots right now , for example ) . If m_base is not nullptr , <nl> - * m_base - > type ( ) is always a supertype of m_baseType , and m_baseType is <nl> - * always large enough to accommodate the type the base ends up having at <nl> - * runtime . <nl> + * We have a separate type in case we have more information about the type <nl> + * than m_base . value - > type ( ) has ( this may be the case with pointers to <nl> + * locals or stack slots right now , for example ) . If m_base . value is not <nl> + * nullptr , m_base . value - > type ( ) is always a supertype of m_base . type , and <nl> + * m_base . type is always large enough to accommodate the type the base ends <nl> + * up having at runtime . <nl> * <nl> - * Don ' t change m_base directly ; use setBase , to update m_baseType <nl> + * Don ' t change m_base directly ; use setBase , to update m_base . type <nl> * automatically . <nl> * / <nl> - SSATmp * m_base ; <nl> - Type m_baseType ; <nl> + struct { <nl> + SSATmp * value = nullptr ; <nl> + Type type { Type : : Bottom } ; <nl> + } m_base ; <nl> <nl> / * Value computed before we do anything to allow better translations for <nl> * common , simple operations . * / <nl> mmm a / hphp / runtime / vm / jit / minstr - translator . cpp <nl> ppp b / hphp / runtime / vm / jit / minstr - translator . cpp <nl> HhbcTranslator : : MInstrTranslator : : MInstrTranslator ( <nl> , m_iInd ( m_mii . valCount ( ) ) <nl> , m_needMIS ( true ) <nl> , m_misBase ( nullptr ) <nl> - , m_base ( nullptr ) <nl> - , m_baseType { Type : : Bottom } <nl> , m_result ( nullptr ) <nl> , m_strTestResult ( nullptr ) <nl> , m_failedSetBlock ( nullptr ) <nl> void HhbcTranslator : : MInstrTranslator : : emit ( ) { <nl> / / Returns a pointer to the base of the current MInstrState struct , or <nl> / / a null pointer if it ' s not needed . <nl> SSATmp * HhbcTranslator : : MInstrTranslator : : genMisPtr ( ) { <nl> - assert ( m_base & & " genMisPtr called before emitBaseOp " ) ; <nl> + assert ( m_base . value & & " genMisPtr called before emitBaseOp " ) ; <nl> <nl> if ( m_needMIS ) { <nl> return gen ( LdMIStateAddr , m_misBase , cns ( kReservedRSPSpillSpace ) ) ; <nl> void HhbcTranslator : : MInstrTranslator : : checkMIState ( ) { <nl> return ; <nl> } <nl> <nl> - Type baseType = m_baseType . derefIfPtr ( ) ; <nl> + Type baseType = m_base . type . derefIfPtr ( ) ; <nl> const bool baseArr = baseType < = Type : : Arr ; <nl> const bool isCGetM = m_ni . mInstrOp ( ) = = OpCGetM ; <nl> const bool isSetM = m_ni . mInstrOp ( ) = = OpSetM ; <nl> void HhbcTranslator : : MInstrTranslator : : numberStackInputs ( ) { <nl> void <nl> HhbcTranslator : : MInstrTranslator : : setBase ( SSATmp * tmp , <nl> folly : : Optional < Type > baseType ) { <nl> - m_base = tmp ; <nl> - m_baseType = baseType ? * baseType : m_base - > type ( ) ; <nl> - always_assert ( m_baseType < = m_base - > type ( ) ) ; <nl> + m_base . value = tmp ; <nl> + m_base . type = baseType ? * baseType : m_base . value - > type ( ) ; <nl> + always_assert ( m_base . type < = m_base . value - > type ( ) ) ; <nl> } <nl> <nl> SSATmp * HhbcTranslator : : MInstrTranslator : : getBase ( TypeConstraint tc ) { <nl> void HhbcTranslator : : MInstrTranslator : : constrainBase ( TypeConstraint tc ) { <nl> / / Member operations only care about the inner type of the base if it ' s <nl> / / boxed , so this handles the logic of using the inner constraint when <nl> / / appropriate . <nl> - if ( m_baseType . maybeBoxed ( ) ) { <nl> + if ( m_base . type . maybeBoxed ( ) ) { <nl> / / tc . innerCat = tc . category ; <nl> tc . category = DataTypeCountness ; <nl> } <nl> - m_irb . constrainValue ( m_base , tc ) ; <nl> + m_irb . constrainValue ( m_base . value , tc ) ; <nl> } <nl> <nl> SSATmp * HhbcTranslator : : MInstrTranslator : : getInput ( unsigned i , <nl> void HhbcTranslator : : MInstrTranslator : : emitBaseLCR ( ) { <nl> sinfo . knownType . ptr ( Ptr : : Stk ) <nl> ) ; <nl> } <nl> - assert ( m_base - > type ( ) . isPtr ( ) ) ; <nl> - assert ( m_baseType . isPtr ( ) ) ; <nl> + assert ( m_base . value - > type ( ) . isPtr ( ) ) ; <nl> + assert ( m_base . type . isPtr ( ) ) ; <nl> <nl> / / TODO ( t2598894 ) : We do this for consistency with the old guard relaxation <nl> / / code , but may change it in the future . <nl> bool HhbcTranslator : : MInstrTranslator : : constrainCollectionOpBase ( ) { <nl> case SimpleOp : : Array : <nl> case SimpleOp : : ProfiledArray : <nl> case SimpleOp : : String : <nl> - m_irb . constrainValue ( m_base , DataTypeSpecific ) ; <nl> + m_irb . constrainValue ( m_base . value , DataTypeSpecific ) ; <nl> return true ; <nl> <nl> case SimpleOp : : PackedArray : <nl> bool HhbcTranslator : : MInstrTranslator : : constrainCollectionOpBase ( ) { <nl> case SimpleOp : : Vector : <nl> case SimpleOp : : Map : <nl> case SimpleOp : : Pair : <nl> - always_assert ( m_baseType < Type : : Obj & & <nl> - m_baseType . isSpecialized ( ) ) ; <nl> - constrainBase ( TypeConstraint ( m_baseType . getClass ( ) ) ) ; <nl> + always_assert ( m_base . type < Type : : Obj & & <nl> + m_base . type . isSpecialized ( ) ) ; <nl> + constrainBase ( TypeConstraint ( m_base . type . getClass ( ) ) ) ; <nl> return true ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitIntermediateOp ( ) { <nl> PropInfo HhbcTranslator : : MInstrTranslator : : getCurrentPropertyOffset ( <nl> const Class * & knownCls <nl> ) { <nl> - auto const baseType = m_baseType . derefIfPtr ( ) ; <nl> + auto const baseType = m_base . type . derefIfPtr ( ) ; <nl> if ( ! knownCls ) { <nl> if ( baseType < ( Type : : Obj | Type : : InitNull ) & & baseType . isSpecialized ( ) ) { <nl> knownCls = baseType . getClass ( ) ; <nl> PropInfo HhbcTranslator : : MInstrTranslator : : getCurrentPropertyOffset ( <nl> baseCls - > name ( ) - > data ( ) , knownCls - > name ( ) - > data ( ) <nl> ) ; <nl> <nl> - if ( m_irb . constrainValue ( m_base , TypeConstraint ( baseCls ) . setWeak ( ) ) ) { <nl> + if ( m_irb . constrainValue ( m_base . value , TypeConstraint ( baseCls ) . setWeak ( ) ) ) { <nl> / / We can ' t use this specialized class without making a guard more <nl> / / expensive , so don ' t do it . <nl> knownCls = nullptr ; <nl> void HhbcTranslator : : MInstrTranslator : : emitPropGeneric ( ) { <nl> MemberCode mCode = m_ni . immVecM [ m_mInd ] ; <nl> MInstrAttr mia = MInstrAttr ( m_mii . getAttr ( mCode ) & MIA_intermediate_prop ) ; <nl> <nl> - if ( ( mia & Unset ) & & m_baseType . strip ( ) . not ( Type : : Obj ) ) { <nl> + if ( ( mia & Unset ) & & m_base . type . strip ( ) . not ( Type : : Obj ) ) { <nl> constrainBase ( DataTypeSpecific ) ; <nl> setBase ( m_irb . genPtrToInitNull ( ) ) ; <nl> return ; <nl> void HhbcTranslator : : MInstrTranslator : : emitPropGeneric ( ) { <nl> auto const key = getKey ( ) ; <nl> if ( mia & Define ) { <nl> setBase ( gen ( PropDX , makeCatch ( ) , MInstrAttrData { mia } , <nl> - m_base , key , genMisPtr ( ) ) ) ; <nl> + m_base . value , key , genMisPtr ( ) ) ) ; <nl> } else { <nl> setBase ( gen ( PropX , makeCatch ( ) , MInstrAttrData { mia } , <nl> - m_base , key , genMisPtr ( ) ) ) ; <nl> + m_base . value , key , genMisPtr ( ) ) ) ; <nl> } <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitPropSpecialized ( const MInstrAttr mia , <nl> SCOPE_EXIT { <nl> / / After this function , m_base is either a pointer to init_null_variant or <nl> / / a property in the object that we ' ve verified isn ' t uninit . <nl> - assert ( m_baseType . isPtr ( ) ) ; <nl> + assert ( m_base . type . isPtr ( ) ) ; <nl> } ; <nl> <nl> / * <nl> void HhbcTranslator : : MInstrTranslator : : emitPropSpecialized ( const MInstrAttr mia , <nl> * analysis . The caller of this function will use it to know whether it can <nl> * avoid a generic incref , unbox , etc . <nl> * / <nl> - if ( m_baseType < = Type : : Obj ) { <nl> + if ( m_base . type < = Type : : Obj ) { <nl> auto const propAddr = gen ( <nl> LdPropAddr , <nl> convertToType ( propInfo . repoAuthType ) . ptr ( Ptr : : Prop ) , <nl> - m_base , <nl> + m_base . value , <nl> cns ( propInfo . offset ) <nl> ) ; <nl> - setBase ( checkInitProp ( m_base , propAddr , propInfo , doWarn , doDefine ) ) ; <nl> + setBase ( checkInitProp ( m_base . value , propAddr , propInfo , doWarn , doDefine ) ) ; <nl> return ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitPropSpecialized ( const MInstrAttr mia , <nl> auto const newBase = m_irb . cond ( <nl> 0 , <nl> [ & ] ( Block * taken ) { <nl> - gen ( CheckTypeMem , Type : : Obj , taken , m_base ) ; <nl> + gen ( CheckTypeMem , Type : : Obj , taken , m_base . value ) ; <nl> } , <nl> [ & ] { <nl> / / Next : Base is an object . Load property and check for uninit . <nl> auto const obj = gen ( <nl> LdMem , <nl> - m_baseType . deref ( ) & Type : : Obj , <nl> - m_base , <nl> + m_base . type . deref ( ) & Type : : Obj , <nl> + m_base . value , <nl> cns ( 0 ) <nl> ) ; <nl> auto const propAddr = gen ( <nl> void HhbcTranslator : : MInstrTranslator : : emitElem ( ) { <nl> const bool warn = mia & Warn ; <nl> const bool unset = mia & Unset ; <nl> const bool define = mia & Define ; <nl> - if ( m_baseType < = Type : : PtrToArr & & <nl> + if ( m_base . type < = Type : : PtrToArr & & <nl> ! unset & & ! define & & <nl> ( key - > isA ( Type : : Int ) | | key - > isA ( Type : : Str ) ) ) { <nl> - setBase ( gen ( warn ? ElemArrayW : ElemArray , makeCatch ( ) , m_base , key ) ) ; <nl> + setBase ( gen ( warn ? ElemArrayW : ElemArray , makeCatch ( ) , m_base . value , key ) ) ; <nl> return ; <nl> } <nl> <nl> assert ( ! ( define & & unset ) ) ; <nl> if ( unset ) { <nl> auto const uninit = m_irb . genPtrToUninit ( ) ; <nl> - auto const baseType = m_baseType . strip ( ) ; <nl> + auto const baseType = m_base . type . strip ( ) ; <nl> constrainBase ( DataTypeSpecific ) ; <nl> if ( baseType < = Type : : Str ) { <nl> m_ht . exceptionBarrier ( ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitElem ( ) { <nl> define ? ElemDX : ElemUX , <nl> makeCatch ( ) , <nl> MInstrAttrData { mia } , <nl> - m_base , <nl> + m_base . value , <nl> key , <nl> genMisPtr ( ) <nl> ) ) ; <nl> return ; <nl> } <nl> setBase ( <nl> - gen ( ElemX , makeCatch ( ) , MInstrAttrData { mia } , m_base , key , <nl> + gen ( ElemX , makeCatch ( ) , MInstrAttrData { mia } , m_base . value , key , <nl> genMisPtr ( ) ) <nl> ) ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitRatchetRefs ( ) { <nl> gen ( StMem , m_misBase , cns ( MISOFF ( tvRef ) ) , cns ( Type : : Uninit ) ) ; <nl> <nl> / / Adjust base pointer . <nl> - assert ( m_baseType . isPtr ( ) ) ; <nl> + assert ( m_base . type . isPtr ( ) ) ; <nl> return gen ( LdMIStateAddr , m_misBase , cns ( MISOFF ( tvRef2 ) ) ) ; <nl> } , <nl> [ & ] { / / Taken : tvRef is Uninit . Do nothing . <nl> - return m_base ; <nl> + return m_base . value ; <nl> } <nl> ) ) ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitCGetProp ( ) { <nl> emitPropSpecialized ( MIA_warn , propInfo ) ; <nl> <nl> if ( ! RuntimeOption : : RepoAuthoritative ) { <nl> - auto const cellPtr = gen ( UnboxPtr , m_base ) ; <nl> + auto const cellPtr = gen ( UnboxPtr , m_base . value ) ; <nl> m_result = gen ( LdMem , Type : : Cell , cellPtr , cns ( 0 ) ) ; <nl> gen ( IncRef , m_result ) ; <nl> return ; <nl> } <nl> <nl> - auto const ty = m_baseType . deref ( ) ; <nl> - auto const cellPtr = ty . maybeBoxed ( ) ? gen ( UnboxPtr , m_base ) : m_base ; <nl> + auto const ty = m_base . type . deref ( ) ; <nl> + auto const cellPtr = ty . maybeBoxed ( ) ? gen ( UnboxPtr , m_base . value ) <nl> + : m_base . value ; <nl> m_result = gen ( LdMem , ty . unbox ( ) , cellPtr , cns ( 0 ) ) ; <nl> gen ( IncRef , m_result ) ; <nl> return ; <nl> } <nl> <nl> auto const key = getKey ( ) ; <nl> - m_result = gen ( CGetProp , makeCatch ( ) , m_base , key , genMisPtr ( ) ) ; <nl> + m_result = gen ( CGetProp , makeCatch ( ) , m_base . value , key , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitVGetProp ( ) { <nl> auto const key = getKey ( ) ; <nl> m_result = genStk ( VGetProp , makeCatch ( ) , NoExtraData { } , <nl> - m_base , key , genMisPtr ( ) ) ; <nl> + m_base . value , key , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitIssetProp ( ) { <nl> auto const key = getKey ( ) ; <nl> - m_result = gen ( IssetProp , makeCatch ( ) , m_base , key ) ; <nl> + m_result = gen ( IssetProp , makeCatch ( ) , m_base . value , key ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitEmptyProp ( ) { <nl> auto const key = getKey ( ) ; <nl> - m_result = gen ( EmptyProp , makeCatch ( ) , m_base , key ) ; <nl> + m_result = gen ( EmptyProp , makeCatch ( ) , m_base . value , key ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitSetProp ( ) { <nl> void HhbcTranslator : : MInstrTranslator : : emitSetProp ( ) { <nl> ! mightCallMagicPropMethod ( Define , knownCls , propInfo ) ) { <nl> emitPropSpecialized ( MIA_define , propInfo ) ; <nl> <nl> - auto const propTy = m_baseType . deref ( ) ; <nl> + auto const propTy = m_base . type . deref ( ) ; <nl> auto const cellTy = propTy . maybeBoxed ( ) ? propTy . unbox ( ) : propTy ; <nl> - auto const cellPtr = propTy . maybeBoxed ( ) ? gen ( UnboxPtr , m_base ) : m_base ; <nl> + auto const cellPtr = propTy . maybeBoxed ( ) ? gen ( UnboxPtr , m_base . value ) <nl> + : m_base . value ; <nl> auto const oldVal = gen ( LdMem , cellTy , cellPtr , cns ( 0 ) ) ; <nl> <nl> gen ( IncRef , value ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitSetProp ( ) { <nl> <nl> / / Emit the appropriate helper call . <nl> auto const key = getKey ( ) ; <nl> - genStk ( SetProp , makeCatchSet ( ) , NoExtraData { } , m_base , key , value ) ; <nl> + genStk ( SetProp , makeCatchSet ( ) , NoExtraData { } , m_base . value , key , value ) ; <nl> m_result = value ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitSetOpProp ( ) { <nl> auto const key = getKey ( ) ; <nl> auto const value = getValue ( ) ; <nl> m_result = genStk ( SetOpProp , makeCatch ( ) , SetOpData { op } , <nl> - m_base , key , value , genMisPtr ( ) ) ; <nl> + m_base . value , key , value , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitIncDecProp ( ) { <nl> IncDecOp op = static_cast < IncDecOp > ( m_ni . imm [ 0 ] . u_OA ) ; <nl> auto const key = getKey ( ) ; <nl> m_result = genStk ( IncDecProp , makeCatch ( ) , IncDecData { op } , <nl> - m_base , key , genMisPtr ( ) ) ; <nl> + m_base . value , key , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitBindProp ( ) { <nl> auto const key = getKey ( ) ; <nl> auto const box = getValue ( ) ; <nl> - genStk ( BindProp , makeCatch ( ) , NoExtraData { } , m_base , key , box , genMisPtr ( ) ) ; <nl> + genStk ( BindProp , makeCatch ( ) , NoExtraData { } , m_base . value , key , box , <nl> + genMisPtr ( ) ) ; <nl> m_result = box ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitUnsetProp ( ) { <nl> SSATmp * key = getKey ( ) ; <nl> <nl> - if ( m_baseType . strip ( ) . not ( Type : : Obj ) ) { <nl> + if ( m_base . type . strip ( ) . not ( Type : : Obj ) ) { <nl> / / Noop <nl> constrainBase ( DataTypeSpecific ) ; <nl> return ; <nl> } <nl> <nl> - gen ( UnsetProp , makeCatch ( ) , m_base , key ) ; <nl> + gen ( UnsetProp , makeCatch ( ) , m_base . value , key ) ; <nl> } <nl> <nl> SSATmp * HhbcTranslator : : MInstrTranslator : : emitPackedArrayGet ( SSATmp * base , <nl> SSATmp * HhbcTranslator : : MInstrTranslator : : emitPackedArrayGet ( SSATmp * base , <nl> } <nl> <nl> SSATmp * HhbcTranslator : : MInstrTranslator : : emitArrayGet ( SSATmp * key ) { <nl> - return gen ( ArrayGet , makeCatch ( ) , m_base , key ) ; <nl> + return gen ( ArrayGet , makeCatch ( ) , m_base . value , key ) ; <nl> } <nl> <nl> const StaticString s_PackedArray ( " PackedArray " ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitProfiledArrayGet ( SSATmp * key ) { <nl> m_irb . marker ( ) , <nl> s_PackedArray . get ( ) ) ; <nl> if ( prof . profiling ( ) ) { <nl> - gen ( ProfileArray , RDSHandleData { prof . handle ( ) } , m_base ) ; <nl> + gen ( ProfileArray , RDSHandleData { prof . handle ( ) } , m_base . value ) ; <nl> m_result = emitArrayGet ( key ) ; <nl> return ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitProfiledArrayGet ( SSATmp * key ) { <nl> / / NonPackedArrayProfile data counts how many times a non - packed <nl> / / array was observed . <nl> auto const typePackedArr = Type : : Arr . specialize ( ArrayData : : kPackedKind ) ; <nl> - if ( data . count = = 0 & & m_baseType . maybe ( typePackedArr ) ) { <nl> + if ( data . count = = 0 & & m_base . type . maybe ( typePackedArr ) ) { <nl> m_ht . emitIncStat ( Stats : : ArrayGet_Mono , 1 , false ) ; <nl> m_result = m_irb . cond ( <nl> 1 , <nl> [ & ] ( Block * taken ) { <nl> - return gen ( CheckType , typePackedArr , taken , m_base ) ; <nl> + return gen ( CheckType , typePackedArr , taken , m_base . value ) ; <nl> } , <nl> [ & ] ( SSATmp * base ) { / / Next <nl> m_ht . emitIncStat ( Stats : : ArrayGet_Packed , 1 , false ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitProfiledArrayGet ( SSATmp * key ) { <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitStringGet ( SSATmp * key ) { <nl> assert ( key - > isA ( Type : : Int ) ) ; <nl> - m_result = gen ( StringGet , makeCatch ( ) , m_base , key ) ; <nl> + m_result = gen ( StringGet , makeCatch ( ) , m_base . value , key ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitVectorGet ( SSATmp * key ) { <nl> void HhbcTranslator : : MInstrTranslator : : emitVectorGet ( SSATmp * key ) { <nl> if ( key - > isConst ( ) & & key - > intVal ( ) < 0 ) { <nl> PUNT ( emitVectorGet ) ; <nl> } <nl> - auto const size = gen ( LdVectorSize , m_base ) ; <nl> + auto const size = gen ( LdVectorSize , m_base . value ) ; <nl> gen ( CheckBounds , makeCatch ( ) , key , size ) ; <nl> - auto const base = gen ( LdVectorBase , m_base ) ; <nl> + auto const base = gen ( LdVectorBase , m_base . value ) ; <nl> static_assert ( sizeof ( TypedValue ) = = 16 , <nl> " TypedValue size expected to be 16 bytes " ) ; <nl> auto idx = gen ( Shl , key , cns ( 4 ) ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitPairGet ( SSATmp * key ) { <nl> PUNT ( emitPairGet ) ; <nl> } <nl> / / no reason to check bounds <nl> - auto const base = gen ( LdPairBase , m_base ) ; <nl> + auto const base = gen ( LdPairBase , m_base . value ) ; <nl> auto index = cns ( key - > intVal ( ) < < 4 ) ; <nl> m_result = gen ( LdElem , base , index ) ; <nl> } else { <nl> gen ( CheckBounds , makeCatch ( ) , key , cns ( 1 ) ) ; <nl> - auto const base = gen ( LdPairBase , m_base ) ; <nl> + auto const base = gen ( LdPairBase , m_base . value ) ; <nl> auto idx = gen ( Shl , key , cns ( 4 ) ) ; <nl> m_result = gen ( LdElem , base , idx ) ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitCGetElem ( ) { <nl> m_result = emitArrayGet ( key ) ; <nl> break ; <nl> case SimpleOp : : PackedArray : <nl> - m_result = emitPackedArrayGet ( m_base , key ) ; <nl> + m_result = emitPackedArrayGet ( m_base . value , key ) ; <nl> break ; <nl> case SimpleOp : : ProfiledArray : <nl> emitProfiledArrayGet ( key ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitCGetElem ( ) { <nl> emitPairGet ( key ) ; <nl> break ; <nl> case SimpleOp : : Map : <nl> - m_result = gen ( MapGet , makeCatch ( ) , m_base , key ) ; <nl> + m_result = gen ( MapGet , makeCatch ( ) , m_base . value , key ) ; <nl> break ; <nl> case SimpleOp : : None : <nl> - m_result = gen ( CGetElem , makeCatch ( ) , m_base , key , genMisPtr ( ) ) ; <nl> + m_result = gen ( CGetElem , makeCatch ( ) , m_base . value , key , genMisPtr ( ) ) ; <nl> break ; <nl> } <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitCGetElem ( ) { <nl> void HhbcTranslator : : MInstrTranslator : : emitVGetElem ( ) { <nl> auto const key = getKey ( ) ; <nl> m_result = genStk ( VGetElem , makeCatch ( ) , NoExtraData { } , <nl> - m_base , key , genMisPtr ( ) ) ; <nl> + m_base . value , key , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitPackedArrayIsset ( ) { <nl> - assert ( m_baseType . getArrayKind ( ) = = ArrayData : : kPackedKind ) ; <nl> + assert ( m_base . type . getArrayKind ( ) = = ArrayData : : kPackedKind ) ; <nl> auto const key = getKey ( ) ; <nl> m_result = m_irb . cond ( <nl> 0 , <nl> [ & ] ( Block * taken ) { <nl> - gen ( CheckPackedArrayBounds , taken , m_base , key ) ; <nl> + gen ( CheckPackedArrayBounds , taken , m_base . value , key ) ; <nl> } , <nl> [ & ] { / / Next : <nl> - return gen ( IsPackedArrayElemNull , m_base , key ) ; <nl> + return gen ( IsPackedArrayElemNull , m_base . value , key ) ; <nl> } , <nl> [ & ] { / / Taken : <nl> return cns ( false ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitIssetElem ( ) { <nl> switch ( m_simpleOp ) { <nl> case SimpleOp : : Array : <nl> case SimpleOp : : ProfiledArray : <nl> - m_result = gen ( ArrayIsset , makeCatch ( ) , m_base , getKey ( ) ) ; <nl> + m_result = gen ( ArrayIsset , makeCatch ( ) , m_base . value , getKey ( ) ) ; <nl> break ; <nl> case SimpleOp : : PackedArray : <nl> emitPackedArrayIsset ( ) ; <nl> break ; <nl> case SimpleOp : : String : <nl> - m_result = gen ( StringIsset , m_base , getKey ( ) ) ; <nl> + m_result = gen ( StringIsset , m_base . value , getKey ( ) ) ; <nl> break ; <nl> case SimpleOp : : Vector : <nl> - m_result = gen ( VectorIsset , m_base , getKey ( ) ) ; <nl> + m_result = gen ( VectorIsset , m_base . value , getKey ( ) ) ; <nl> break ; <nl> case SimpleOp : : Pair : <nl> - m_result = gen ( PairIsset , m_base , getKey ( ) ) ; <nl> + m_result = gen ( PairIsset , m_base . value , getKey ( ) ) ; <nl> break ; <nl> case SimpleOp : : Map : <nl> - m_result = gen ( MapIsset , m_base , getKey ( ) ) ; <nl> + m_result = gen ( MapIsset , m_base . value , getKey ( ) ) ; <nl> break ; <nl> case SimpleOp : : None : <nl> { <nl> auto const key = getKey ( ) ; <nl> - m_result = gen ( IssetElem , makeCatch ( ) , m_base , key , genMisPtr ( ) ) ; <nl> + m_result = gen ( IssetElem , makeCatch ( ) , m_base . value , key , genMisPtr ( ) ) ; <nl> } <nl> break ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitIssetElem ( ) { <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitEmptyElem ( ) { <nl> auto const key = getKey ( ) ; <nl> - m_result = gen ( EmptyElem , makeCatch ( ) , m_base , key , genMisPtr ( ) ) ; <nl> + m_result = gen ( EmptyElem , makeCatch ( ) , m_base . value , key , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitArraySet ( SSATmp * key , <nl> void HhbcTranslator : : MInstrTranslator : : emitArraySet ( SSATmp * key , <nl> assert ( base . location . space = = Location : : Local | | <nl> base . location . space = = Location : : Stack ) ; <nl> auto const box = getInput ( baseStkIdx , DataTypeSpecific ) ; <nl> - gen ( ArraySetRef , makeCatch ( ) , m_base , key , value , box ) ; <nl> + gen ( ArraySetRef , makeCatch ( ) , m_base . value , key , value , box ) ; <nl> / / Unlike the non - ref case , we don ' t need to do anything to the stack <nl> / / because any load of the box will be guarded . <nl> m_result = value ; <nl> return ; <nl> } <nl> <nl> - auto const newArr = gen ( ArraySet , makeCatch ( ) , m_base , key , value ) ; <nl> + auto const newArr = gen ( ArraySet , makeCatch ( ) , m_base . value , key , value ) ; <nl> <nl> / / Update the base ' s value with the new array <nl> if ( base . location . space = = Location : : Local ) { <nl> void HhbcTranslator : : MInstrTranslator : : emitArraySet ( SSATmp * key , <nl> void HhbcTranslator : : MInstrTranslator : : emitSetWithRefLElem ( ) { <nl> SSATmp * key = getKey ( ) ; <nl> SSATmp * locAddr = getValAddr ( ) ; <nl> - if ( m_baseType . strip ( ) < = Type : : Arr & & <nl> + if ( m_base . type . strip ( ) < = Type : : Arr & & <nl> ! locAddr - > type ( ) . deref ( ) . maybeBoxed ( ) ) { <nl> constrainBase ( DataTypeSpecific ) ; <nl> emitSetElem ( ) ; <nl> assert ( m_strTestResult = = nullptr ) ; <nl> } else { <nl> genStk ( SetWithRefElem , makeCatch ( ) , NoExtraData { } , <nl> - m_base , key , locAddr , genMisPtr ( ) ) ; <nl> + m_base . value , key , locAddr , genMisPtr ( ) ) ; <nl> } <nl> m_result = nullptr ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitSetWithRefRProp ( ) { <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitSetWithRefNewElem ( ) { <nl> - if ( m_baseType . strip ( ) < = Type : : Arr & & getValue ( ) - > type ( ) . notBoxed ( ) ) { <nl> + if ( m_base . type . strip ( ) < = Type : : Arr & & getValue ( ) - > type ( ) . notBoxed ( ) ) { <nl> constrainBase ( DataTypeSpecific ) ; <nl> emitSetNewElem ( ) ; <nl> } else { <nl> genStk ( SetWithRefNewElem , makeCatch ( ) , <nl> NoExtraData { } , <nl> - m_base , getValAddr ( ) , genMisPtr ( ) ) ; <nl> + m_base . value , getValAddr ( ) , genMisPtr ( ) ) ; <nl> } <nl> m_result = nullptr ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitVectorSet ( <nl> if ( key - > isConst ( ) & & key - > intVal ( ) < 0 ) { <nl> PUNT ( emitVectorSet ) ; / / will throw <nl> } <nl> - SSATmp * size = gen ( LdVectorSize , m_base ) ; <nl> + SSATmp * size = gen ( LdVectorSize , m_base . value ) ; <nl> gen ( CheckBounds , makeCatch ( ) , key , size ) ; <nl> <nl> m_irb . ifThen ( [ & ] ( Block * taken ) { <nl> - gen ( VectorHasImmCopy , taken , m_base ) ; <nl> + gen ( VectorHasImmCopy , taken , m_base . value ) ; <nl> } , <nl> [ & ] { <nl> m_irb . hint ( Block : : Hint : : Unlikely ) ; <nl> - gen ( VectorDoCow , m_base ) ; <nl> + gen ( VectorDoCow , m_base . value ) ; <nl> } ) ; <nl> <nl> gen ( IncRef , value ) ; <nl> - SSATmp * vecBase = gen ( LdVectorBase , m_base ) ; <nl> + SSATmp * vecBase = gen ( LdVectorBase , m_base . value ) ; <nl> SSATmp * oldVal ; <nl> static_assert ( sizeof ( TypedValue ) = = 16 , <nl> " TypedValue size expected to be 16 bytes " ) ; <nl> void HhbcTranslator : : MInstrTranslator : : emitSetElem ( ) { <nl> emitVectorSet ( key , value ) ; <nl> break ; <nl> case SimpleOp : : Map : <nl> - gen ( MapSet , makeCatch ( ) , m_base , key , value ) ; <nl> + gen ( MapSet , makeCatch ( ) , m_base . value , key , value ) ; <nl> m_result = value ; <nl> break ; <nl> case SimpleOp : : Pair : <nl> case SimpleOp : : None : <nl> constrainBase ( DataTypeSpecific ) ; <nl> SSATmp * result = genStk ( SetElem , makeCatchSet ( ) , NoExtraData { } , <nl> - m_base , key , value ) ; <nl> + m_base . value , key , value ) ; <nl> auto t = result - > type ( ) ; <nl> if ( t = = Type : : Nullptr ) { <nl> / / Base is not a string . Result is always value . <nl> void HhbcTranslator : : MInstrTranslator : : emitSetElem ( ) { <nl> void HhbcTranslator : : MInstrTranslator : : emitSetOpElem ( ) { <nl> SetOpOp op = static_cast < SetOpOp > ( m_ni . imm [ 0 ] . u_OA ) ; <nl> m_result = genStk ( SetOpElem , makeCatch ( ) , SetOpData { op } , <nl> - m_base , getKey ( ) , getValue ( ) , genMisPtr ( ) ) ; <nl> + m_base . value , getKey ( ) , getValue ( ) , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitIncDecElem ( ) { <nl> IncDecOp op = static_cast < IncDecOp > ( m_ni . imm [ 0 ] . u_OA ) ; <nl> m_result = genStk ( IncDecElem , makeCatch ( ) , IncDecData { op } , <nl> - m_base , getKey ( ) , genMisPtr ( ) ) ; <nl> + m_base . value , getKey ( ) , genMisPtr ( ) ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitBindElem ( ) { <nl> auto const key = getKey ( ) ; <nl> auto const box = getValue ( ) ; <nl> genStk ( BindElem , makeCatch ( ) , NoExtraData { } , <nl> - m_base , key , box , genMisPtr ( ) ) ; <nl> + m_base . value , key , box , genMisPtr ( ) ) ; <nl> m_result = box ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitUnsetElem ( ) { <nl> auto const key = getKey ( ) ; <nl> <nl> - auto const baseType = m_baseType . strip ( ) ; <nl> + auto const baseType = m_base . type . strip ( ) ; <nl> constrainBase ( DataTypeSpecific ) ; <nl> if ( baseType < = Type : : Str ) { <nl> gen ( RaiseError , makeCatch ( ) , <nl> void HhbcTranslator : : MInstrTranslator : : emitUnsetElem ( ) { <nl> return ; <nl> } <nl> <nl> - genStk ( UnsetElem , makeCatch ( ) , NoExtraData { } , m_base , key ) ; <nl> + genStk ( UnsetElem , makeCatch ( ) , NoExtraData { } , m_base . value , key ) ; <nl> } <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitNotSuppNewElem ( ) { <nl> void HhbcTranslator : : MInstrTranslator : : emitVGetNewElem ( ) { <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitSetNewElem ( ) { <nl> SSATmp * value = getValue ( ) ; <nl> - if ( m_baseType < = Type : : PtrToArr ) { <nl> + if ( m_base . type < = Type : : PtrToArr ) { <nl> constrainBase ( DataTypeSpecific ) ; <nl> - gen ( SetNewElemArray , makeCatchSet ( ) , m_base , value ) ; <nl> + gen ( SetNewElemArray , makeCatchSet ( ) , m_base . value , value ) ; <nl> } else { <nl> - gen ( SetNewElem , makeCatchSet ( ) , m_base , value ) ; <nl> + gen ( SetNewElem , makeCatchSet ( ) , m_base . value , value ) ; <nl> } <nl> m_result = value ; <nl> } <nl> void HhbcTranslator : : MInstrTranslator : : emitIncDecNewElem ( ) { <nl> <nl> void HhbcTranslator : : MInstrTranslator : : emitBindNewElem ( ) { <nl> SSATmp * box = getValue ( ) ; <nl> - genStk ( BindNewElem , makeCatch ( ) , NoExtraData { } , m_base , box , genMisPtr ( ) ) ; <nl> + genStk ( BindNewElem , makeCatch ( ) , NoExtraData { } , m_base . value , box , <nl> + genMisPtr ( ) ) ; <nl> m_result = box ; <nl> } <nl> <nl>
Use a small anonymous struct for the base in MinstrTranslator
facebook/hhvm
e51861aa3a978d38af8767ecaf6ea1a6b58b70c1
2014-11-07T04:30:23Z
mmm a / libraries / DNSServer / examples / CaptivePortalAdvanced / handleHttp . ino <nl> ppp b / libraries / DNSServer / examples / CaptivePortalAdvanced / handleHttp . ino <nl> void handleWifi ( ) { <nl> Serial . println ( " scan done " ) ; <nl> if ( n > 0 ) { <nl> for ( int i = 0 ; i < n ; i + + ) { <nl> - server . sendContent ( String ( ) + " \ r \ n < tr > < td > SSID " + String ( WiFi . SSID ( i ) ) + String ( ( WiFi . encryptionType ( i ) = = ENC_TYPE_NONE ) ? " " : " * " ) + " ( " + WiFi . RSSI ( i ) + " ) < / td > < / tr > " ) ; <nl> + server . sendContent ( String ( ) + " \ r \ n < tr > < td > SSID " + WiFi . SSID ( i ) + String ( ( WiFi . encryptionType ( i ) = = ENC_TYPE_NONE ) ? " " : " * " ) + " ( " + WiFi . RSSI ( i ) + " ) < / td > < / tr > " ) ; <nl> } <nl> } else { <nl> server . sendContent ( String ( ) + " < tr > < td > No WLAN found < / td > < / tr > " ) ; <nl> mmm a / libraries / ESP8266WiFi / src / ESP8266WiFi . cpp <nl> ppp b / libraries / ESP8266WiFi / src / ESP8266WiFi . cpp <nl> void * ESP8266WiFiClass : : _getScanInfoByIndex ( int i ) <nl> return reinterpret_cast < bss_info * > ( ESP8266WiFiClass : : _scanResult ) + i ; <nl> } <nl> <nl> - const char * ESP8266WiFiClass : : SSID ( uint8_t i ) <nl> + String ESP8266WiFiClass : : SSID ( uint8_t i ) <nl> { <nl> struct bss_info * it = reinterpret_cast < struct bss_info * > ( _getScanInfoByIndex ( i ) ) ; <nl> if ( ! it ) <nl> - return 0 ; <nl> + return " " ; <nl> <nl> - return reinterpret_cast < const char * > ( it - > ssid ) ; <nl> + return String ( reinterpret_cast < const char * > ( it - > ssid ) ) ; <nl> } <nl> <nl> uint8_t * ESP8266WiFiClass : : BSSID ( uint8_t i ) <nl> mmm a / libraries / ESP8266WiFi / src / ESP8266WiFi . h <nl> ppp b / libraries / ESP8266WiFi / src / ESP8266WiFi . h <nl> class ESP8266WiFiClass <nl> * <nl> * return : ssid string of the specified item on the networks scanned list <nl> * / <nl> - const char * SSID ( uint8_t networkItem ) ; <nl> + String SSID ( uint8_t networkItem ) ; <nl> <nl> / * <nl> * Return the encryption type of the networks discovered during the scanNetworks <nl>
Merge pull request from pgollor / esp8266
esp8266/Arduino
b27a4d142fdba0ca3f7b7b69a132b6473eba2fae
2015-10-02T11:37:38Z
mmm a / cocos2dx / proj . linux / Makefile <nl> ppp b / cocos2dx / proj . linux / Makefile <nl> OBJECTS = . . / actions / CCAction . o \ <nl> . . / . . / extensions / CCBReader / CCLayerGradientLoader . o \ <nl> . . / . . / extensions / CCBReader / CCSpriteLoader . o \ <nl> . . / . . / extensions / CCBReader / CCLayerLoader . o \ <nl> - . . / . . / extensions / CCBReader / CCBAnimationManager . o \ <nl> - . . / . . / extensions / CCBReader / CCBKeyframe . o \ <nl> - . . / . . / extensions / CCBReader / CCBSequence . o \ <nl> - . . / . . / extensions / CCBReader / CCBSequenceProperty . o \ <nl> - . . / . . / extensions / CCBReader / CCBValue . o \ <nl> - . . / . . / extensions / CCBReader / CCData . o \ <nl> - . . / . . / extensions / CCBReader / CCNode + CCBRelativePositioning . o \ <nl> + . . / . . / extensions / CCBReader / CCBAnimationManager . o \ <nl> + . . / . . / extensions / CCBReader / CCBKeyframe . o \ <nl> + . . / . . / extensions / CCBReader / CCBSequence . o \ <nl> + . . / . . / extensions / CCBReader / CCBSequenceProperty . o \ <nl> + . . / . . / extensions / CCBReader / CCBValue . o \ <nl> + . . / . . / extensions / CCBReader / CCData . o \ <nl> + . . / . . / extensions / CCBReader / CCNode + CCBRelativePositioning . o \ <nl> . . / . . / extensions / GUI / CCScrollView / CCScrollView . o \ <nl> . . / . . / extensions / GUI / CCScrollView / CCSorting . o \ <nl> . . / . . / extensions / GUI / CCScrollView / CCTableView . o \ <nl> OBJECTS = . . / actions / CCAction . o \ <nl> . . / . . / extensions / GUI / CCControlExtension / CCControlSwitch . o \ <nl> . . / . . / extensions / GUI / CCControlExtension / CCControlUtils . o \ <nl> . . / . . / extensions / GUI / CCControlExtension / CCInvocation . o \ <nl> - . . / . . / extensions / GUI / CCControlExtension / CCMenuPassive . o \ <nl> . . / . . / extensions / GUI / CCControlExtension / CCScale9Sprite . o \ <nl> - . . / . . / extensions / GUI / CCControlExtension / CCSpacer . o \ <nl> + . . / . . / extensions / GUI / CCControlExtension / CCControlPotentiometer . cpp \ <nl> + . . / . . / extensions / GUI / CCControlExtension / CCControlStepper . cpp \ <nl> . . / . . / extensions / network / HttpClient . o \ <nl> . . / kazmath / src / aabb . o \ <nl> . . / kazmath / src / plane . o \ <nl> mmm a / extensions / Android . mk <nl> ppp b / extensions / Android . mk <nl> GUI / CCControlExtension / CCControlSlider . cpp \ <nl> GUI / CCControlExtension / CCControlSwitch . cpp \ <nl> GUI / CCControlExtension / CCControlUtils . cpp \ <nl> GUI / CCControlExtension / CCInvocation . cpp \ <nl> - GUI / CCControlExtension / CCMenuPassive . cpp \ <nl> GUI / CCControlExtension / CCScale9Sprite . cpp \ <nl> - GUI / CCControlExtension / CCSpacer . cpp \ <nl> + GUI / CCControlExtension / CCControlPotentiometer . cpp \ <nl> + GUI / CCControlExtension / CCControlStepper . cpp \ <nl> GUI / CCScrollView / CCScrollView . cpp \ <nl> GUI / CCScrollView / CCTableView . cpp \ <nl> GUI / CCScrollView / CCTableViewCell . cpp \ <nl> mmm a / extensions / ExtensionMacros . h <nl> ppp b / extensions / ExtensionMacros . h <nl> <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> + Copyright ( c ) 2012 cocos2d - x . org <nl> + <nl> + http : / / www . cocos2d - x . org <nl> + <nl> + Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + of this software and associated documentation files ( the " Software " ) , to deal <nl> + in the Software without restriction , including without limitation the rights <nl> + to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + copies of the Software , and to permit persons to whom the Software is <nl> + furnished to do so , subject to the following conditions : <nl> + <nl> + The above copyright notice and this permission notice shall be included in <nl> + all copies or substantial portions of the Software . <nl> + <nl> + THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + THE SOFTWARE . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> # ifndef __EXTENSIONMARCROS_H__ <nl> # define __EXTENSIONMARCROS_H__ <nl> <nl> mmm a / extensions / GUI / CCControlExtension / CCControl . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControl . cpp <nl> <nl> / * <nl> - * CCControl . m <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2011 Yannick Loriot . <nl> * http : / / yannickloriot . com <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> CCControl : : CCControl ( ) <nl> + : m_cOpacity ( 0 ) <nl> + , m_tColor ( ccBLACK ) <nl> + , m_bIsOpacityModifyRGB ( false ) <nl> + , m_nDefaultTouchPriority ( 0 ) <nl> + , m_eState ( CCControlStateNormal ) <nl> + , m_hasVisibleParents ( false ) <nl> + , m_bEnabled ( false ) <nl> + , m_bSelected ( false ) <nl> + , m_bHighlighted ( false ) <nl> + , m_pDispatchTable ( NULL ) <nl> { <nl> <nl> } <nl> bool CCControl : : init ( ) <nl> / / this - > setTouchEnabled ( true ) ; <nl> / / m_bIsTouchEnabled = true ; <nl> / / Initialise instance variables <nl> - m_nState = CCControlStateNormal ; <nl> - m_bEnabled = true ; <nl> - m_bSelected = false ; <nl> - m_bHighlighted = false ; <nl> + m_eState = CCControlStateNormal ; <nl> + setEnabled ( true ) ; <nl> + setSelected ( false ) ; <nl> + setHighlighted ( false ) ; <nl> <nl> / / Set the touch dispatcher priority by default to 1 <nl> - m_nDefaultTouchPriority = 1 ; <nl> + setDefaultTouchPriority ( 1 ) ; <nl> this - > setDefaultTouchPriority ( m_nDefaultTouchPriority ) ; <nl> / / Initialise the tables <nl> - dispatchTable = new CCDictionary ( ) ; <nl> - / / dispatchTable - > autorelease ( ) ; <nl> - / / dispatchTable_ = [ [ NSMutableDictionary alloc ] initWithCapacity : 1 ] ; <nl> + m_pDispatchTable = new CCDictionary ( ) ; <nl> + <nl> return true ; <nl> } <nl> else <nl> + { <nl> return false ; <nl> + } <nl> } <nl> <nl> CCControl : : ~ CCControl ( ) <nl> { <nl> - CC_SAFE_RELEASE ( dispatchTable ) ; <nl> + CC_SAFE_RELEASE ( m_pDispatchTable ) ; <nl> } <nl> <nl> / / Menu - Events <nl> void CCControl : : registerWithTouchDispatcher ( ) <nl> { <nl> - CCDirector : : sharedDirector ( ) - > getTouchDispatcher ( ) - > addTargetedDelegate ( this , kCCMenuHandlerPriority , true ) ; <nl> + CCDirector : : sharedDirector ( ) - > getTouchDispatcher ( ) - > addTargetedDelegate ( this , m_nDefaultTouchPriority , true ) ; <nl> } <nl> <nl> void CCControl : : onEnter ( ) <nl> { <nl> - / / CCTouchDispatcher : : sharedDispatcher ( ) - > addTargetedDelegate ( this , m_nDefaultTouchPriority , true ) ; <nl> CCLayer : : onEnter ( ) ; <nl> } <nl> <nl> void CCControl : : onExit ( ) <nl> { <nl> - / / CCTouchDispatcher : : sharedDispatcher ( ) - > removeDelegate ( this ) ; <nl> CCLayer : : onExit ( ) ; <nl> } <nl> <nl> void CCControl : : sendActionsForControlEvents ( CCControlEvent controlEvents ) <nl> { <nl> / / For each control events <nl> - for ( int i = 0 ; i < CONTROL_EVENT_TOTAL_NUMBER ; i + + ) <nl> + for ( int i = 0 ; i < kControlEventTotalNumber ; i + + ) <nl> { <nl> / / If the given controlEvents bitmask contains the curent event <nl> if ( ( controlEvents & ( 1 < < i ) ) ) <nl> { <nl> / / Call invocations <nl> / / < CCInvocation * > <nl> - CCArray * invocationList = CCControl : : dispatchListforControlEvent ( 1 < < i ) ; <nl> + CCArray * invocationList = this - > dispatchListforControlEvent ( 1 < < i ) ; <nl> CCObject * pObj = NULL ; <nl> CCARRAY_FOREACH ( invocationList , pObj ) <nl> { <nl> CCInvocation * invocation = ( CCInvocation * ) pObj ; <nl> invocation - > invoke ( this ) ; <nl> - } <nl> + } <nl> } <nl> } <nl> } <nl> void CCControl : : addTargetWithActionForControlEvents ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvents ) <nl> { <nl> / / For each control events <nl> - for ( int i = 0 ; i < CONTROL_EVENT_TOTAL_NUMBER ; i + + ) <nl> + for ( int i = 0 ; i < kControlEventTotalNumber ; i + + ) <nl> { <nl> / / If the given controlEvents bitmask contains the curent event <nl> if ( ( controlEvents & ( 1 < < i ) ) ) <nl> { <nl> - CCControl : : addTargetWithActionForControlEvent ( target , action , 1 < < i ) ; <nl> + this - > addTargetWithActionForControlEvent ( target , action , 1 < < i ) ; <nl> } <nl> } <nl> } <nl> void CCControl : : addTargetWithActionForControlEvents ( CCObject * target , SEL_CCCont <nl> * parameters , in that order . <nl> * When you call this method , target is not retained . <nl> * <nl> - * @ param target The target object — that is , the object to which the action <nl> + * @ param target The target object that is , the object to which the action <nl> * message is sent . It cannot be nil . The target is not retained . <nl> * @ param action A selector identifying an action message . It cannot be NULL . <nl> * @ param controlEvent A control event for which the action message is sent . <nl> void CCControl : : addTargetWithActionForControlEvents ( CCObject * target , SEL_CCCont <nl> void CCControl : : addTargetWithActionForControlEvent ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) <nl> { <nl> / / Create the invocation object <nl> - CCInvocation * invocation = new CCInvocation ( target , action , controlEvent ) ; <nl> - invocation - > autorelease ( ) ; <nl> + CCInvocation * invocation = CCInvocation : : create ( target , action , controlEvent ) ; <nl> + <nl> / / Add the invocation into the dispatch list for the given control event <nl> - CCArray * eventInvocationList = dispatchListforControlEvent ( controlEvent ) ; <nl> + CCArray * eventInvocationList = this - > dispatchListforControlEvent ( controlEvent ) ; <nl> eventInvocationList - > addObject ( invocation ) ; <nl> } <nl> <nl> void CCControl : : removeTargetWithActionForControlEvents ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvents ) <nl> { <nl> / / For each control events <nl> - for ( int i = 0 ; i < CONTROL_EVENT_TOTAL_NUMBER ; i + + ) <nl> + for ( int i = 0 ; i < kControlEventTotalNumber ; i + + ) <nl> { <nl> / / If the given controlEvents bitmask contains the curent event <nl> if ( ( controlEvents & ( 1 < < i ) ) ) <nl> { <nl> - removeTargetWithActionForControlEvent ( target , action , 1 < < i ) ; <nl> + this - > removeTargetWithActionForControlEvent ( target , action , 1 < < i ) ; <nl> } <nl> } <nl> } <nl> <nl> - / * * <nl> - * Removes a target and action for a particular event from an internal dispatch <nl> - * table . <nl> - * <nl> - * @ param target The target object — that is , the object to which the action <nl> - * message is sent . Pass nil to remove all targets paired with action and the <nl> - * specified control events . <nl> - * @ param action A selector identifying an action message . Pass NULL to remove <nl> - * all action messages paired with target . <nl> - * @ param controlEvent A control event for which the action message is sent . <nl> - * See " CCControlEvent " for constants . <nl> - * / <nl> void CCControl : : removeTargetWithActionForControlEvent ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) <nl> { <nl> / / Retrieve all invocations for the given control event <nl> / / < CCInvocation * > <nl> - CCArray * eventInvocationList = dispatchListforControlEvent ( controlEvent ) ; <nl> + CCArray * eventInvocationList = this - > dispatchListforControlEvent ( controlEvent ) ; <nl> <nl> / / remove all invocations if the target and action are null <nl> / / TODO : should the invocations be deleted , or just removed from the array ? Won ' t that cause issues if you add a single invocation for multiple events ? <nl> void CCControl : : removeTargetWithActionForControlEvent ( CCObject * target , SEL_CCCo <nl> { <nl> CCInvocation * invocation = ( CCInvocation * ) pObj ; <nl> bool shouldBeRemoved = true ; <nl> - if ( target ) <nl> - shouldBeRemoved = ( target = = invocation - > getTarget ( ) ) ; <nl> + if ( target ) <nl> + { <nl> + shouldBeRemoved = ( target = = invocation - > getTarget ( ) ) ; <nl> + } <nl> if ( action ) <nl> + { <nl> shouldBeRemoved = ( shouldBeRemoved & & ( action = = invocation - > getAction ( ) ) ) ; <nl> + } <nl> / / Remove the corresponding invocation object <nl> if ( shouldBeRemoved ) <nl> + { <nl> eventInvocationList - > removeObject ( invocation , bDeleteObjects ) ; <nl> + } <nl> } <nl> } <nl> } <nl> GLubyte CCControl : : getOpacity ( ) <nl> } <nl> <nl> <nl> - void CCControl : : setOpacityModifyRGB ( bool opacityModifyRGB ) <nl> + void CCControl : : setOpacityModifyRGB ( bool bOpacityModifyRGB ) <nl> { <nl> - m_bIsOpacityModifyRGB = opacityModifyRGB ; <nl> - CCObject * child ; <nl> + m_bIsOpacityModifyRGB = bOpacityModifyRGB ; <nl> + CCObject * child ; <nl> CCArray * children = getChildren ( ) ; <nl> CCARRAY_FOREACH ( children , child ) <nl> { <nl> CCRGBAProtocol * pNode = dynamic_cast < CCRGBAProtocol * > ( child ) ; <nl> if ( pNode ) <nl> { <nl> - pNode - > setOpacityModifyRGB ( opacityModifyRGB ) ; <nl> + pNode - > setOpacityModifyRGB ( bOpacityModifyRGB ) ; <nl> } <nl> } <nl> } <nl> bool CCControl : : isOpacityModifyRGB ( ) <nl> <nl> CCPoint CCControl : : getTouchLocation ( CCTouch * touch ) <nl> { <nl> - CCPoint touchLocation = touch - > getLocation ( ) ; ; / / Get the touch position <nl> - touchLocation = this - > getParent ( ) - > convertToNodeSpace ( touchLocation ) ; / / Convert to the node space of this class <nl> + CCPoint touchLocation = touch - > getLocation ( ) ; / / Get the touch position <nl> + touchLocation = this - > convertToNodeSpace ( touchLocation ) ; / / Convert to the node space of this class <nl> <nl> return touchLocation ; <nl> } <nl> <nl> bool CCControl : : isTouchInside ( CCTouch * touch ) <nl> { <nl> - CCPoint touchLocation = getTouchLocation ( touch ) ; <nl> + CCPoint touchLocation = touch - > getLocation ( ) ; / / Get the touch position <nl> + touchLocation = this - > getParent ( ) - > convertToNodeSpace ( touchLocation ) ; <nl> CCRect bBox = boundingBox ( ) ; <nl> return bBox . containsPoint ( touchLocation ) ; <nl> } <nl> <nl> CCArray * CCControl : : dispatchListforControlEvent ( CCControlEvent controlEvent ) <nl> { <nl> - CCArray * invocationList = ( CCArray * ) dispatchTable - > objectForKey ( controlEvent ) ; <nl> + CCArray * invocationList = ( CCArray * ) m_pDispatchTable - > objectForKey ( controlEvent ) ; <nl> <nl> / / If the invocation list does not exist for the dispatch table , we create it <nl> if ( invocationList = = NULL ) <nl> { <nl> invocationList = CCArray : : createWithCapacity ( 1 ) ; <nl> - dispatchTable - > setObject ( invocationList , controlEvent ) ; <nl> + m_pDispatchTable - > setObject ( invocationList , controlEvent ) ; <nl> } <nl> return invocationList ; <nl> } <nl> <nl> + void CCControl : : needsLayout ( ) <nl> + { <nl> + } <nl> + <nl> void CCControl : : setEnabled ( bool bEnabled ) <nl> { <nl> m_bEnabled = bEnabled ; <nl> + if ( m_bEnabled ) { <nl> + m_eState = CCControlStateNormal ; <nl> + } else { <nl> + m_eState = CCControlStateDisabled ; <nl> + } <nl> + <nl> + this - > needsLayout ( ) ; <nl> } <nl> <nl> bool CCControl : : isEnabled ( ) <nl> bool CCControl : : isEnabled ( ) <nl> void CCControl : : setSelected ( bool bSelected ) <nl> { <nl> m_bSelected = bSelected ; <nl> + this - > needsLayout ( ) ; <nl> } <nl> <nl> bool CCControl : : isSelected ( ) <nl> bool CCControl : : isSelected ( ) <nl> void CCControl : : setHighlighted ( bool bHighlighted ) <nl> { <nl> m_bHighlighted = bHighlighted ; <nl> + this - > needsLayout ( ) ; <nl> } <nl> <nl> bool CCControl : : isHighlighted ( ) <nl> bool CCControl : : isHighlighted ( ) <nl> return m_bHighlighted ; <nl> } <nl> <nl> + bool CCControl : : hasVisibleParents ( ) <nl> + { <nl> + CCNode * pParent = this - > getParent ( ) ; <nl> + for ( CCNode * c = pParent ; c ! = NULL ; c = c - > getParent ( ) ) <nl> + { <nl> + if ( ! c - > isVisible ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> NS_CC_EXT_END <nl> mmm a / extensions / GUI / CCControlExtension / CCControl . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControl . h <nl> <nl> / * <nl> - * CCControl . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2011 Yannick Loriot . <nl> * http : / / yannickloriot . com <nl> <nl> <nl> # include " CCInvocation . h " <nl> # include " CCControlUtils . h " <nl> - # include " layers_scenes_transitions_nodes / CCLayer . h " <nl> + # include " cocos2d . h " <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> class CCInvocation ; <nl> * / <nl> <nl> / * * Number of kinds of control event . * / <nl> - # define CONTROL_EVENT_TOTAL_NUMBER 9 <nl> + # define kControlEventTotalNumber 9 <nl> <nl> / * * Kinds of possible events for the control objects . * / <nl> enum <nl> typedef unsigned int CCControlEvent ; <nl> / * * The possible state for a control . * / <nl> enum <nl> { <nl> - CCControlStateNormal = 1 < < 0 , / / The normal , or default state of a control — that is , enabled but neither selected nor highlighted . <nl> + CCControlStateNormal = 1 < < 0 , / / The normal , or default state of a control ¡ ªthat is , enabled but neither selected nor highlighted . <nl> CCControlStateHighlighted = 1 < < 1 , / / Highlighted state of a control . A control enters this state when a touch down , drag inside or drag enter is performed . You can retrieve and set this value through the highlighted property . <nl> CCControlStateDisabled = 1 < < 2 , / / Disabled state of a control . This state indicates that the control is currently disabled . You can retrieve and set this value through the enabled property . <nl> - CCControlStateSelected = 1 < < 3 , / / Selected state of a control . This state indicates that the control is currently selected . You can retrieve and set this value through the selected property . <nl> - CCControlStateInitial = 1 < < 3 <nl> + CCControlStateSelected = 1 < < 3 / / Selected state of a control . This state indicates that the control is currently selected . You can retrieve and set this value through the selected property . <nl> } ; <nl> typedef unsigned int CCControlState ; <nl> <nl> class CCControl : public CCLayer , public CCRGBAProtocol <nl> CC_PROPERTY_PASS_BY_REF ( ccColor3B , m_tColor , Color ) ; <nl> bool m_bIsOpacityModifyRGB ; <nl> bool isOpacityModifyRGB ( ) ; <nl> - void setOpacityModifyRGB ( bool isOpacityModifyRGB ) ; <nl> + void setOpacityModifyRGB ( bool bOpacityModifyRGB ) ; <nl> <nl> / * * Changes the priority of the button . The lower the number , the higher the priority . * / <nl> CC_SYNTHESIZE ( int , m_nDefaultTouchPriority , DefaultTouchPriority ) ; <nl> / * * The current control state constant . * / <nl> - CC_SYNTHESIZE_READONLY ( CCControlState , m_nState , State ) ; <nl> + CC_SYNTHESIZE_READONLY ( CCControlState , m_eState , State ) ; <nl> + <nl> + / * * True if all of the controls parents are visible * / <nl> + protected : <nl> + bool m_hasVisibleParents ; <nl> <nl> public : <nl> / * * Tells whether the control is enabled . * / <nl> class CCControl : public CCLayer , public CCRGBAProtocol <nl> / * * A Boolean value that determines whether the control is highlighted . * / <nl> virtual void setHighlighted ( bool bHighlighted ) ; <nl> virtual bool isHighlighted ( ) ; <nl> + bool hasVisibleParents ( ) ; <nl> + / * * <nl> + * Updates the control layout using its current internal state . <nl> + * / <nl> + virtual void needsLayout ( ) ; <nl> <nl> protected : <nl> bool m_bEnabled ; <nl> bool m_bSelected ; <nl> bool m_bHighlighted ; <nl> <nl> - / / CCControlState , CCArray < CCInvocation * > <nl> - CCDictionary * dispatchTable ; <nl> - <nl> - <nl> + / * * <nl> + * Table of connection between the CCControlEvents and their associated <nl> + * target - actions pairs . For each CCButtonEvents a list of NSInvocation <nl> + * ( which contains the target - action pair ) is linked . <nl> + * / <nl> + CCDictionary * m_pDispatchTable ; <nl> <nl> public : <nl> CCControl ( ) ; <nl> class CCControl : public CCLayer , public CCRGBAProtocol <nl> * parameters , in that order . <nl> * When you call this method , target is not retained . <nl> * <nl> - * @ param target The target object — that is , the object to which the action <nl> + * @ param target The target object that is , the object to which the action <nl> * message is sent . It cannot be nil . The target is not retained . <nl> * @ param action A selector identifying an action message . It cannot be NULL . <nl> * @ param controlEvents A bitmask specifying the control events for which the <nl> class CCControl : public CCLayer , public CCRGBAProtocol <nl> * <nl> * @ param touch A CCTouch object that represents a touch . <nl> * <nl> - * @ return YES whether a touch is inside the receiver ’ s rect . <nl> + * @ return YES whether a touch is inside the receiver ¡ ¯ s rect . <nl> * / <nl> virtual bool isTouchInside ( CCTouch * touch ) ; <nl> <nl> <nl> protected : <nl> / * * <nl> - * Returns an CCInvocation object able to construct messages using a given <nl> - * target - action pair . ( The invocation may optionnaly include the sender and <nl> - * the event as parameters , in that order ) <nl> - * <nl> - * @ param target The target object . <nl> - * @ param action A selector identifying an action message . <nl> - * @ param controlEvent A control events for which the action message is sent . <nl> - * See " CCControlEvent " for constants . <nl> - * <nl> - * @ return an CCInvocation object able to construct messages using a given <nl> - * target - action pair . <nl> - * / <nl> + * Returns an CCInvocation object able to construct messages using a given <nl> + * target - action pair . ( The invocation may optionnaly include the sender and <nl> + * the event as parameters , in that order ) <nl> + * <nl> + * @ param target The target object . <nl> + * @ param action A selector identifying an action message . <nl> + * @ param controlEvent A control events for which the action message is sent . <nl> + * See " CCControlEvent " for constants . <nl> + * <nl> + * @ return an CCInvocation object able to construct messages using a given <nl> + * target - action pair . <nl> + * / <nl> CCInvocation * invocationWithTargetAndActionForControlEvent ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) ; <nl> <nl> <nl> class CCControl : public CCLayer , public CCRGBAProtocol <nl> * / <nl> / / < CCInvocation * > <nl> CCArray * dispatchListforControlEvent ( CCControlEvent controlEvent ) ; <nl> - public : <nl> + / * * <nl> + * Adds a target and action for a particular event to an internal dispatch <nl> + * table . <nl> + * The action message may optionnaly include the sender and the event as <nl> + * parameters , in that order . <nl> + * When you call this method , target is not retained . <nl> + * <nl> + * @ param target The target object ¡ ªthat is , the object to which the action <nl> + * message is sent . It cannot be nil . The target is not retained . <nl> + * @ param action A selector identifying an action message . It cannot be NULL . <nl> + * @ param controlEvent A control event for which the action message is sent . <nl> + * See " CCControlEvent " for constants . <nl> + * / <nl> void addTargetWithActionForControlEvent ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) ; <nl> + <nl> + / * * <nl> + * Removes a target and action for a particular event from an internal dispatch <nl> + * table . <nl> + * <nl> + * @ param target The target object ¡ ªthat is , the object to which the action <nl> + * message is sent . Pass nil to remove all targets paired with action and the <nl> + * specified control events . <nl> + * @ param action A selector identifying an action message . Pass NULL to remove <nl> + * all action messages paired with target . <nl> + * @ param controlEvent A control event for which the action message is sent . <nl> + * See " CCControlEvent " for constants . <nl> + * / <nl> void removeTargetWithActionForControlEvent ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) ; <nl> <nl> CREATE_FUNC ( CCControl ) ; <nl> mmm a / extensions / GUI / CCControlExtension / CCControlButton . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlButton . cpp <nl> <nl> / * <nl> - * CCControlButton . m <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2011 Yannick Loriot . <nl> * http : / / yannickloriot . com <nl> enum <nl> kZoomActionTag = 0xCCCB0001 , <nl> } ; <nl> <nl> + CCControlButton : : CCControlButton ( ) <nl> + : m_currentTitle ( NULL ) <nl> + , m_currentTitleColor ( ccWHITE ) <nl> + , m_doesAdjustBackgroundImage ( false ) <nl> + , m_titleLabel ( NULL ) <nl> + , m_backgroundSprite ( NULL ) <nl> + , m_zoomOnTouchDown ( false ) <nl> + , m_isPushed ( false ) <nl> + , m_bParentInited ( false ) <nl> + , m_titleDispatchTable ( NULL ) <nl> + , m_titleColorDispatchTable ( NULL ) <nl> + , m_titleLabelDispatchTable ( NULL ) <nl> + , m_backgroundSpriteDispatchTable ( NULL ) <nl> + , m_marginH ( CCControlButtonMarginLR ) <nl> + , m_marginV ( CCControlButtonMarginTB ) <nl> + { <nl> + <nl> + } <nl> + <nl> CCControlButton : : ~ CCControlButton ( ) <nl> { <nl> CC_SAFE_RELEASE ( m_backgroundSpriteDispatchTable ) ; <nl> CC_SAFE_RELEASE ( m_titleLabelDispatchTable ) ; <nl> CC_SAFE_RELEASE ( m_titleColorDispatchTable ) ; <nl> CC_SAFE_RELEASE ( m_titleDispatchTable ) ; <nl> + CC_SAFE_RELEASE ( m_backgroundSprite ) ; <nl> } <nl> <nl> / / initialisers <nl> bool CCControlButton : : init ( ) <nl> return this - > initWithLabelAndBackgroundSprite ( CCLabelTTF : : create ( " " , " Helvetica " , 12 ) , CCScale9Sprite : : create ( ) ) ; <nl> } <nl> <nl> - <nl> bool CCControlButton : : initWithLabelAndBackgroundSprite ( CCNode * node , CCScale9Sprite * backgroundSprite ) <nl> { <nl> if ( CCControl : : init ( ) ) <nl> { <nl> - assert ( node ! = NULL ) ; <nl> + CCAssert ( node ! = NULL , " Label must not be nil . " ) ; <nl> CCLabelProtocol * label = dynamic_cast < CCLabelProtocol * > ( node ) ; <nl> CCRGBAProtocol * rgbaLabel = dynamic_cast < CCRGBAProtocol * > ( node ) ; <nl> - assert ( label ! = NULL | | rgbaLabel ! = NULL | | backgroundSprite ! = NULL ) ; <nl> + CCAssert ( backgroundSprite ! = NULL , " Background sprite must not be nil . " ) ; <nl> + CCAssert ( label ! = NULL | | rgbaLabel ! = NULL | | backgroundSprite ! = NULL , " " ) ; <nl> <nl> + m_bParentInited = true ; <nl> + <nl> + / / Initialize the button state tables <nl> + this - > setTitleDispatchTable ( CCDictionary : : create ( ) ) ; <nl> + this - > setTitleColorDispatchTable ( CCDictionary : : create ( ) ) ; <nl> + this - > setTitleLabelDispatchTable ( CCDictionary : : create ( ) ) ; <nl> + this - > setBackgroundSpriteDispatchTable ( CCDictionary : : create ( ) ) ; <nl> + <nl> setTouchEnabled ( true ) ; <nl> - pushed = false ; <nl> + m_isPushed = false ; <nl> m_zoomOnTouchDown = true ; <nl> - m_nState = CCControlStateInitial ; <nl> + <nl> m_currentTitle = NULL ; <nl> <nl> / / Adjust the background image by default <nl> - m_adjustBackgroundImage = true ; <nl> - <nl> + setAdjustBackgroundImage ( true ) ; <nl> + setPreferredSize ( CCSizeZero ) ; <nl> / / Zooming button by default <nl> m_zoomOnTouchDown = true ; <nl> - <nl> + <nl> / / Set the default anchor point <nl> ignoreAnchorPointForPosition ( false ) ; <nl> setAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> <nl> / / Set the nodes <nl> - m_titleLabel = node ; <nl> - m_backgroundSprite = backgroundSprite ; <nl> - <nl> - <nl> - / / Initialize the button state tables <nl> - m_titleDispatchTable = new CCDictionary ( ) ; <nl> - / / m_titleDispatchTable - > autorelease ( ) ; <nl> - m_titleColorDispatchTable = new CCDictionary ( ) ; <nl> - / / m_titleColorDispatchTable - > autorelease ( ) ; <nl> - m_titleLabelDispatchTable = new CCDictionary ( ) ; <nl> - / / m_titleLabelDispatchTable - > autorelease ( ) ; <nl> - m_backgroundSpriteDispatchTable = new CCDictionary ( ) ; <nl> - / / m_backgroundSpriteDispatchTable - > autorelease ( ) ; <nl> + setTitleLabel ( node ) ; <nl> + setBackgroundSprite ( backgroundSprite ) ; <nl> <nl> / / Set the default color and opacity <nl> - setColor ( ccc3 ( 255 , 255 , 255 ) ) ; <nl> - setOpacity ( 255 ) ; <nl> + setColor ( ccc3 ( 255 . 0f , 255 . 0f , 255 . 0f ) ) ; <nl> + setOpacity ( 255 . 0f ) ; <nl> setOpacityModifyRGB ( true ) ; <nl> <nl> / / Initialize the dispatch table <nl> bool CCControlButton : : initWithLabelAndBackgroundSprite ( CCNode * node , CCScale9Spr <nl> setTitleLabelForState ( node , CCControlStateNormal ) ; <nl> setBackgroundSpriteForState ( backgroundSprite , CCControlStateNormal ) ; <nl> <nl> - m_nState = CCControlStateNormal ; <nl> - <nl> - / / default margins <nl> - m_marginH = 24 ; <nl> - m_marginV = 12 ; <nl> - <nl> - this - > m_labelAnchorPoint = CCPoint ( 0 . 5f , 0 . 5f ) ; <nl> + setLabelAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> <nl> / / Layout update <nl> needsLayout ( ) ; <nl> bool CCControlButton : : initWithLabelAndBackgroundSprite ( CCNode * node , CCScale9Spr <nl> } <nl> / / couldn ' t init the CCControl <nl> else <nl> + { <nl> return false ; <nl> + } <nl> } <nl> <nl> CCControlButton * CCControlButton : : buttonWithLabelAndBackgroundSprite ( CCNode * label , CCScale9Sprite * backgroundSprite ) <nl> void CCControlButton : : setPreferredSize ( CCSize size ) <nl> { <nl> if ( size . width = = 0 & & size . height = = 0 ) <nl> { <nl> - m_adjustBackgroundImage = true ; <nl> + m_doesAdjustBackgroundImage = true ; <nl> } <nl> else <nl> { <nl> - m_adjustBackgroundImage = false ; <nl> + m_doesAdjustBackgroundImage = false ; <nl> CCDictElement * item = NULL ; <nl> CCDICT_FOREACH ( m_backgroundSpriteDispatchTable , item ) <nl> { <nl> CCScale9Sprite * sprite = ( CCScale9Sprite * ) item - > getObject ( ) ; <nl> sprite - > setPreferredSize ( size ) ; <nl> } <nl> - <nl> - m_preferredSize = size ; <nl> } <nl> + <nl> + m_preferredSize = size ; <nl> needsLayout ( ) ; <nl> } <nl> <nl> CCSize CCControlButton : : getPreferredSize ( ) <nl> <nl> void CCControlButton : : setAdjustBackgroundImage ( bool adjustBackgroundImage ) <nl> { <nl> - m_adjustBackgroundImage = adjustBackgroundImage ; <nl> + m_doesAdjustBackgroundImage = adjustBackgroundImage ; <nl> needsLayout ( ) ; <nl> } <nl> <nl> - bool CCControlButton : : getAdjustBackgroundImage ( ) <nl> + bool CCControlButton : : doesAdjustBackgroundImage ( ) <nl> { <nl> - return m_adjustBackgroundImage ; <nl> + return m_doesAdjustBackgroundImage ; <nl> } <nl> <nl> CCPoint CCControlButton : : getLabelAnchorPoint ( ) <nl> CCPoint CCControlButton : : getLabelAnchorPoint ( ) <nl> void CCControlButton : : setLabelAnchorPoint ( CCPoint labelAnchorPoint ) <nl> { <nl> this - > m_labelAnchorPoint = labelAnchorPoint ; <nl> - <nl> - this - > m_titleLabel - > setAnchorPoint ( labelAnchorPoint ) ; <nl> + if ( m_titleLabel ! = NULL ) <nl> + { <nl> + this - > m_titleLabel - > setAnchorPoint ( labelAnchorPoint ) ; <nl> + } <nl> } <nl> <nl> CCString * CCControlButton : : getTitleForState ( CCControlState state ) <nl> { <nl> - CCString * title = ( CCString * ) m_titleDispatchTable - > objectForKey ( state ) ; <nl> - if ( title ) <nl> + if ( m_titleDispatchTable ! = NULL ) <nl> { <nl> - return title ; <nl> + CCString * title = ( CCString * ) m_titleDispatchTable - > objectForKey ( state ) ; <nl> + if ( title ) <nl> + { <nl> + return title ; <nl> + } <nl> + return ( CCString * ) m_titleDispatchTable - > objectForKey ( CCControlStateNormal ) ; <nl> } <nl> - return ( CCString * ) m_titleDispatchTable - > objectForKey ( CCControlStateNormal ) ; <nl> + return CCString : : create ( " " ) ; <nl> } <nl> <nl> void CCControlButton : : setTitleForState ( CCString * title , CCControlState state ) <nl> void CCControlButton : : setTitleForState ( CCString * title , CCControlState state ) <nl> <nl> const ccColor3B CCControlButton : : getTitleColorForState ( CCControlState state ) <nl> { <nl> - ccColor3B returnColor ; <nl> - CCColor3bObject * colorObject = ( CCColor3bObject * ) m_titleColorDispatchTable - > objectForKey ( state ) ; <nl> - if ( colorObject ) <nl> + ccColor3B returnColor = ccWHITE ; <nl> + do <nl> { <nl> - returnColor = colorObject - > value ; <nl> - return returnColor ; <nl> - } <nl> - colorObject = ( CCColor3bObject * ) m_titleColorDispatchTable - > objectForKey ( CCControlStateNormal ) ; <nl> - returnColor = colorObject - > value ; <nl> + CC_BREAK_IF ( NULL = = m_titleColorDispatchTable ) ; <nl> + CCColor3bObject * colorObject = ( CCColor3bObject * ) m_titleColorDispatchTable - > objectForKey ( state ) ; <nl> + if ( colorObject ) <nl> + { <nl> + returnColor = colorObject - > value ; <nl> + break ; <nl> + } <nl> + <nl> + colorObject = ( CCColor3bObject * ) m_titleColorDispatchTable - > objectForKey ( CCControlStateNormal ) ; <nl> + if ( colorObject ) <nl> + { <nl> + returnColor = colorObject - > value ; <nl> + } <nl> + } while ( 0 ) ; <nl> + <nl> return returnColor ; <nl> } <nl> <nl> void CCControlButton : : setTitleLabelForState ( CCNode * titleLabel , CCControlState s <nl> void CCControlButton : : setTitleTTFForState ( const char * fntFile , CCControlState state ) <nl> { <nl> CCString * title = this - > getTitleForState ( state ) ; <nl> - if ( ! title ) title = new CCString ( " " ) ; <nl> + if ( ! title ) <nl> + { <nl> + title = CCString : : create ( " " ) ; <nl> + } <nl> this - > setTitleLabelForState ( CCLabelTTF : : create ( title - > getCString ( ) , fntFile , 12 ) , state ) ; <nl> } <nl> <nl> float CCControlButton : : getTitleTTFSizeForState ( CCControlState state ) <nl> void CCControlButton : : setTitleBMFontForState ( const char * fntFile , CCControlState state ) <nl> { <nl> CCString * title = this - > getTitleForState ( state ) ; <nl> - if ( ! title ) title = new CCString ( " " ) ; <nl> + if ( ! title ) <nl> + { <nl> + title = CCString : : create ( " " ) ; <nl> + } <nl> this - > setTitleLabelForState ( CCLabelBMFont : : create ( title - > getCString ( ) , fntFile ) , state ) ; <nl> } <nl> <nl> CCScale9Sprite * CCControlButton : : getBackgroundSpriteForState ( CCControlState stat <nl> <nl> void CCControlButton : : setBackgroundSpriteForState ( CCScale9Sprite * sprite , CCControlState state ) <nl> { <nl> - CCScale9Sprite * previousSprite = ( CCScale9Sprite * ) m_backgroundSpriteDispatchTable - > objectForKey ( state ) ; <nl> - if ( previousSprite ) <nl> + CCSize oldPreferredSize = m_preferredSize ; <nl> + <nl> + CCScale9Sprite * previousBackgroundSprite = ( CCScale9Sprite * ) m_backgroundSpriteDispatchTable - > objectForKey ( state ) ; <nl> + if ( previousBackgroundSprite ) <nl> { <nl> - removeChild ( previousSprite , true ) ; <nl> + removeChild ( previousBackgroundSprite , true ) ; <nl> m_backgroundSpriteDispatchTable - > removeObjectForKey ( state ) ; <nl> } <nl> <nl> void CCControlButton : : setBackgroundSpriteForState ( CCScale9Sprite * sprite , CCCont <nl> <nl> if ( this - > m_preferredSize . width ! = 0 | | this - > m_preferredSize . height ! = 0 ) <nl> { <nl> + if ( oldPreferredSize . equals ( m_preferredSize ) ) <nl> + { <nl> + / / Force update of preferred size <nl> + sprite - > setPreferredSize ( CCSizeMake ( oldPreferredSize . width + 1 , oldPreferredSize . height + 1 ) ) ; <nl> + } <nl> + <nl> sprite - > setPreferredSize ( this - > m_preferredSize ) ; <nl> } <nl> <nl> void CCControlButton : : setBackgroundSpriteFrameForState ( CCSpriteFrame * spriteFra <nl> <nl> void CCControlButton : : needsLayout ( ) <nl> { <nl> + if ( ! m_bParentInited ) { <nl> + return ; <nl> + } <nl> / / Hide the background and the label <nl> - m_titleLabel - > setVisible ( false ) ; <nl> - m_backgroundSprite - > setVisible ( false ) ; <nl> - <nl> + if ( m_titleLabel ! = NULL ) { <nl> + m_titleLabel - > setVisible ( false ) ; <nl> + } <nl> + if ( m_backgroundSprite ) { <nl> + m_backgroundSprite - > setVisible ( false ) ; <nl> + } <nl> / / Update anchor of all labels <nl> this - > setLabelAnchorPoint ( this - > m_labelAnchorPoint ) ; <nl> <nl> / / Update the label to match with the current state <nl> - / / CC_SAFE_RELEASE ( m_currentTitle ) <nl> - <nl> - m_currentTitle = getTitleForState ( m_nState ) ; <nl> - m_currentTitleColor = getTitleColorForState ( m_nState ) ; <nl> + CC_SAFE_RELEASE ( m_currentTitle ) ; <nl> + m_currentTitle = getTitleForState ( m_eState ) ; <nl> + CC_SAFE_RETAIN ( m_currentTitle ) ; <nl> + <nl> + m_currentTitleColor = getTitleColorForState ( m_eState ) ; <nl> + <nl> + this - > setTitleLabel ( getTitleLabelForState ( m_eState ) ) ; <nl> <nl> - m_titleLabel = getTitleLabelForState ( m_nState ) ; <nl> - <nl> CCLabelProtocol * label = dynamic_cast < CCLabelProtocol * > ( m_titleLabel ) ; <nl> - if ( label ) <nl> + if ( label & & m_currentTitle ) <nl> + { <nl> label - > setString ( m_currentTitle - > getCString ( ) ) ; <nl> + } <nl> + <nl> CCRGBAProtocol * rgbaLabel = dynamic_cast < CCRGBAProtocol * > ( m_titleLabel ) ; <nl> if ( rgbaLabel ) <nl> + { <nl> rgbaLabel - > setColor ( m_currentTitleColor ) ; <nl> - m_titleLabel - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> - <nl> + } <nl> + if ( m_titleLabel ! = NULL ) <nl> + { <nl> + m_titleLabel - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> + } <nl> <nl> / / Update the background sprite <nl> - m_backgroundSprite = getBackgroundSpriteForState ( m_nState ) ; <nl> - m_backgroundSprite - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> - <nl> + this - > setBackgroundSprite ( this - > getBackgroundSpriteForState ( m_eState ) ) ; <nl> + if ( m_backgroundSprite ! = NULL ) <nl> + { <nl> + m_backgroundSprite - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> + } <nl> + <nl> / / Get the title label size <nl> - CCSize titleLabelSize = m_titleLabel - > boundingBox ( ) . size ; <nl> + CCSize titleLabelSize ; <nl> + if ( m_titleLabel ! = NULL ) <nl> + { <nl> + titleLabelSize = m_titleLabel - > boundingBox ( ) . size ; <nl> + } <nl> <nl> / / Adjust the background image if necessary <nl> - if ( m_adjustBackgroundImage ) <nl> + if ( m_doesAdjustBackgroundImage ) <nl> { <nl> / / Add the margins <nl> - m_backgroundSprite - > setContentSize ( CCSizeMake ( titleLabelSize . width + m_marginH * 2 , titleLabelSize . height + m_marginV * 2 ) ) ; <nl> + if ( m_backgroundSprite ! = NULL ) <nl> + { <nl> + m_backgroundSprite - > setContentSize ( CCSizeMake ( titleLabelSize . width + m_marginH * 2 , titleLabelSize . height + m_marginV * 2 ) ) ; <nl> + } <nl> } <nl> else <nl> { <nl> / / TODO : should this also have margins if one of the preferred sizes is relaxed ? <nl> - CCSize preferredSize = m_backgroundSprite - > getPreferredSize ( ) ; <nl> - if ( preferredSize . width < = 0 ) <nl> - { <nl> - preferredSize . width = titleLabelSize . width ; <nl> - } <nl> - if ( preferredSize . height < = 0 ) <nl> + if ( m_backgroundSprite ! = NULL ) <nl> { <nl> - preferredSize . height = titleLabelSize . height ; <nl> + CCSize preferredSize = m_backgroundSprite - > getPreferredSize ( ) ; <nl> + if ( preferredSize . width < = 0 ) <nl> + { <nl> + preferredSize . width = titleLabelSize . width ; <nl> + } <nl> + if ( preferredSize . height < = 0 ) <nl> + { <nl> + preferredSize . height = titleLabelSize . height ; <nl> + } <nl> + <nl> + m_backgroundSprite - > setContentSize ( preferredSize ) ; <nl> } <nl> - <nl> - m_backgroundSprite - > setContentSize ( preferredSize ) ; <nl> } <nl> <nl> / / Set the content size <nl> - <nl> - CCRect maxRect = CCControlUtils : : CCRectUnion ( m_titleLabel - > boundingBox ( ) , m_backgroundSprite - > boundingBox ( ) ) ; <nl> + CCRect rectTitle ; <nl> + if ( m_titleLabel ! = NULL ) <nl> + { <nl> + rectTitle = m_titleLabel - > boundingBox ( ) ; <nl> + } <nl> + CCRect rectBackground ; <nl> + if ( m_backgroundSprite ! = NULL ) <nl> + { <nl> + rectBackground = m_backgroundSprite - > boundingBox ( ) ; <nl> + } <nl> + <nl> + CCRect maxRect = CCControlUtils : : CCRectUnion ( rectTitle , rectBackground ) ; <nl> setContentSize ( CCSizeMake ( maxRect . size . width , maxRect . size . height ) ) ; <nl> <nl> - m_titleLabel - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> - m_backgroundSprite - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> - <nl> - / / Make visible the background and the label <nl> - m_titleLabel - > setVisible ( true ) ; <nl> - m_backgroundSprite - > setVisible ( true ) ; <nl> + if ( m_titleLabel ! = NULL ) <nl> + { <nl> + m_titleLabel - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> + / / Make visible the background and the label <nl> + m_titleLabel - > setVisible ( true ) ; <nl> + } <nl> + <nl> + if ( m_backgroundSprite ! = NULL ) <nl> + { <nl> + m_backgroundSprite - > setPosition ( ccp ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ) ; <nl> + m_backgroundSprite - > setVisible ( true ) ; <nl> + } <nl> } <nl> <nl> <nl> bool CCControlButton : : ccTouchBegan ( CCTouch * pTouch , CCEvent * pEvent ) <nl> return false ; <nl> } <nl> <nl> - m_nState = CCControlStateHighlighted ; <nl> - pushed = true ; <nl> + m_eState = CCControlStateHighlighted ; <nl> + m_isPushed = true ; <nl> this - > setHighlighted ( true ) ; <nl> sendActionsForControlEvents ( CCControlEventTouchDown ) ; <nl> return true ; <nl> bool CCControlButton : : ccTouchBegan ( CCTouch * pTouch , CCEvent * pEvent ) <nl> <nl> void CCControlButton : : ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) <nl> { <nl> - if ( ! m_bEnabled | | ! pushed | | m_bSelected ) <nl> + if ( ! isEnabled ( ) | | ! isPushed ( ) | | isSelected ( ) ) <nl> { <nl> - if ( m_bHighlighted ) <nl> + if ( isHighlighted ( ) ) <nl> { <nl> setHighlighted ( false ) ; <nl> } <nl> void CCControlButton : : ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) <nl> } <nl> <nl> bool isTouchMoveInside = isTouchInside ( pTouch ) ; <nl> - if ( isTouchMoveInside & & ! m_bHighlighted ) <nl> + if ( isTouchMoveInside & & ! isHighlighted ( ) ) <nl> { <nl> - m_nState = CCControlStateHighlighted ; <nl> + m_eState = CCControlStateHighlighted ; <nl> setHighlighted ( true ) ; <nl> sendActionsForControlEvents ( CCControlEventTouchDragEnter ) ; <nl> } <nl> - else if ( isTouchMoveInside & & m_bHighlighted ) <nl> + else if ( isTouchMoveInside & & isHighlighted ( ) ) <nl> { <nl> sendActionsForControlEvents ( CCControlEventTouchDragInside ) ; <nl> } <nl> - else if ( ! isTouchMoveInside & & m_bHighlighted ) <nl> + else if ( ! isTouchMoveInside & & isHighlighted ( ) ) <nl> { <nl> - m_nState = CCControlStateNormal ; <nl> + m_eState = CCControlStateNormal ; <nl> setHighlighted ( false ) ; <nl> <nl> sendActionsForControlEvents ( CCControlEventTouchDragExit ) ; <nl> } <nl> - else if ( ! isTouchMoveInside & & ! m_bHighlighted ) <nl> + else if ( ! isTouchMoveInside & & ! isHighlighted ( ) ) <nl> { <nl> sendActionsForControlEvents ( CCControlEventTouchDragOutside ) ; <nl> } <nl> } <nl> void CCControlButton : : ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) <nl> { <nl> - m_nState = CCControlStateNormal ; <nl> - pushed = false ; <nl> + m_eState = CCControlStateNormal ; <nl> + m_isPushed = false ; <nl> setHighlighted ( false ) ; <nl> <nl> <nl> GLubyte CCControlButton : : getOpacity ( ) <nl> <nl> void CCControlButton : : ccTouchCancelled ( CCTouch * pTouch , CCEvent * pEvent ) <nl> { <nl> - m_nState = CCControlStateNormal ; <nl> - pushed = false ; <nl> + m_eState = CCControlStateNormal ; <nl> + m_isPushed = false ; <nl> setHighlighted ( false ) ; <nl> sendActionsForControlEvents ( CCControlEventTouchCancel ) ; <nl> } <nl> mmm a / extensions / GUI / CCControlExtension / CCControlButton . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlButton . h <nl> <nl> / * <nl> - * CCControlButton . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2011 Yannick Loriot . All rights reserved . <nl> * http : / / yannickloriot . com <nl> <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> + / * Define the button margin for Left / Right edge * / <nl> + # define CCControlButtonMarginLR 8 / / px <nl> + / * Define the button margin for Top / Bottom edge * / <nl> + # define CCControlButtonMarginTB 2 / / px <nl> + <nl> + <nl> / * * <nl> * @ addtogroup GUI <nl> * @ { <nl> NS_CC_EXT_BEGIN <nl> class CCControlButton : public CCControl <nl> { <nl> public : <nl> + CCControlButton ( ) ; <nl> virtual ~ CCControlButton ( ) ; <nl> virtual void needsLayout ( void ) ; <nl> <nl> class CCControlButton : public CCControl <nl> / / CCRGBAProtocol <nl> / / bool m_bIsOpacityModifyRGB ; <nl> <nl> + / * * The current title that is displayed on the button . * / <nl> + CC_SYNTHESIZE_READONLY ( CCString * , m_currentTitle , CurrentTitle ) ; <nl> + <nl> + / * * The current color used to display the title . * / <nl> + CC_SYNTHESIZE_READONLY_PASS_BY_REF ( ccColor3B , m_currentTitleColor , CurrentTitleColor ) ; <nl> + <nl> / * * Adjust the background image . YES by default . If the property is set to NO , the <nl> background will use the prefered size of the background image . * / <nl> - CC_PROPERTY ( bool , m_adjustBackgroundImage , AdjustBackgroundImage ) ; <nl> + bool doesAdjustBackgroundImage ( ) ; <nl> + void setAdjustBackgroundImage ( bool adjustBackgroundImage ) ; <nl> + bool m_doesAdjustBackgroundImage ; <nl> <nl> - / * * Adjust the button zooming on touchdown . Default value is YES . * / <nl> - CC_PROPERTY ( bool , m_zoomOnTouchDown , ZoomOnTouchDown ) ; <nl> + / * * The current title label . * / <nl> + CC_SYNTHESIZE_RETAIN ( CCNode * , m_titleLabel , TitleLabel ) ; <nl> + <nl> + / * * The current background sprite . * / <nl> + CC_SYNTHESIZE_RETAIN ( CCScale9Sprite * , m_backgroundSprite , BackgroundSprite ) ; <nl> <nl> / * * The prefered size of the button , if label is larger it will be expanded . * / <nl> CC_PROPERTY ( CCSize , m_preferredSize , PreferredSize ) ; <nl> <nl> - CC_PROPERTY ( CCPoint , m_labelAnchorPoint , LabelAnchorPoint ) ; <nl> + / * * Adjust the button zooming on touchdown . Default value is YES . * / <nl> + CC_PROPERTY ( bool , m_zoomOnTouchDown , ZoomOnTouchDown ) ; <nl> <nl> - / * * The current title that is displayed on the button . * / <nl> - CC_SYNTHESIZE_READONLY ( CCString * , m_currentTitle , CurrentTitle ) ; <nl> - / * * The current color used to display the title . * / <nl> - CC_SYNTHESIZE_READONLY_PASS_BY_REF ( ccColor3B , m_currentTitleColor , CurrentTitleColor ) ; <nl> - / * * The current title label . * / <nl> - / / CC_PROPERTY ( CCNode * , m_titleLabel , TitleLabel ) ; <nl> - CCNode * m_titleLabel ; <nl> - / * * The current background sprite . * / <nl> - / / CC_PROPERTY ( CCScale9Sprite * , m_backgroundSprite , BackgroundSprite ) ; <nl> - CCScale9Sprite * m_backgroundSprite ; <nl> + CC_PROPERTY ( CCPoint , m_labelAnchorPoint , LabelAnchorPoint ) ; <nl> <nl> / * Override setter to affect a background sprite too * / <nl> - CC_PROPERTY ( GLubyte , m_cOpacity , Opacity ) ; <nl> + virtual GLubyte getOpacity ( void ) ; <nl> + virtual void setOpacity ( GLubyte var ) ; <nl> <nl> / * * Flag to know if the button is currently pushed . * / <nl> - CC_SYNTHESIZE_READONLY ( bool , pushed , IsPushed ) ; <nl> + protected : <nl> + bool m_isPushed ; <nl> + bool m_bParentInited ; <nl> + public : <nl> + bool isPushed ( ) { return m_isPushed ; } <nl> + <nl> / / < CCControlState , CCString * > <nl> - CCDictionary * m_titleDispatchTable ; <nl> + CC_SYNTHESIZE_RETAIN ( CCDictionary * , m_titleDispatchTable , TitleDispatchTable ) ; <nl> / / < CCControlState , CCColor3bObject * > <nl> - CCDictionary * m_titleColorDispatchTable ; <nl> + CC_SYNTHESIZE_RETAIN ( CCDictionary * , m_titleColorDispatchTable , TitleColorDispatchTable ) ; <nl> / / < CCControlState , CCNode * > <nl> - CCDictionary * m_titleLabelDispatchTable ; <nl> + CC_SYNTHESIZE_RETAIN ( CCDictionary * , m_titleLabelDispatchTable , TitleLabelDispatchTable ) ; <nl> / / < CCControlState , CCScale9Sprite * > <nl> - CCDictionary * m_backgroundSpriteDispatchTable ; <nl> + CC_SYNTHESIZE_RETAIN ( CCDictionary * , m_backgroundSpriteDispatchTable , BackgroundSpriteDispatchTable ) ; <nl> <nl> / * Define the button margin for Top / Bottom edge * / <nl> CC_SYNTHESIZE_READONLY ( int , m_marginV , VerticalMargin ) ; <nl> mmm a / extensions / GUI / CCControlExtension / CCControlColourPicker . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlColourPicker . cpp <nl> <nl> / * <nl> - * CCControlColourPicker . m <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> + CCControlColourPicker : : CCControlColourPicker ( ) <nl> + : m_colourPicker ( NULL ) <nl> + , m_huePicker ( NULL ) <nl> + , m_background ( NULL ) <nl> + { <nl> + <nl> + } <nl> + <nl> + CCControlColourPicker : : ~ CCControlColourPicker ( ) <nl> + { <nl> + if ( m_background ) <nl> + { <nl> + m_background - > removeFromParentAndCleanup ( true ) ; <nl> + } <nl> + <nl> + if ( m_huePicker ) <nl> + { <nl> + m_huePicker - > removeFromParentAndCleanup ( true ) ; <nl> + } <nl> + <nl> + if ( m_colourPicker ) <nl> + { <nl> + m_colourPicker - > removeFromParentAndCleanup ( true ) ; <nl> + } <nl> + <nl> + m_background = NULL ; <nl> + m_huePicker = NULL ; <nl> + m_colourPicker = NULL ; <nl> + } <nl> + <nl> bool CCControlColourPicker : : init ( ) <nl> { <nl> if ( CCControl : : init ( ) ) <nl> bool CCControlColourPicker : : init ( ) <nl> addChild ( spriteSheet ) ; <nl> <nl> / / MIPMAP <nl> - ccTexParams params = { GL_LINEAR_MIPMAP_LINEAR , GL_LINEAR , GL_REPEAT , GL_REPEAT } ; <nl> + / / ccTexParams params = { GL_LINEAR_MIPMAP_LINEAR , GL_LINEAR , GL_REPEAT , GL_REPEAT } ; <nl> spriteSheet - > getTexture ( ) - > setAliasTexParameters ( ) ; <nl> - spriteSheet - > getTexture ( ) - > setTexParameters ( & params ) ; <nl> - spriteSheet - > getTexture ( ) - > generateMipmap ( ) ; <nl> + / / spriteSheet - > getTexture ( ) - > setTexParameters ( & params ) ; <nl> + / / spriteSheet - > getTexture ( ) - > generateMipmap ( ) ; <nl> <nl> / / Init default color <nl> m_hsv . h = 0 ; <nl> bool CCControlColourPicker : : init ( ) <nl> <nl> CCPoint backgroundPointZero = ccpSub ( m_background - > getPosition ( ) , ccp ( m_background - > getContentSize ( ) . width / 2 , m_background - > getContentSize ( ) . height / 2 ) ) ; <nl> <nl> - / / Setup panels . currently hard - coded . . . <nl> + / / Setup panels <nl> float hueShift = 8 ; <nl> float colourShift = 28 ; <nl> <nl> - m_huePicker = CCControlHuePicker : : create ( spriteSheet , ccp ( backgroundPointZero . x + hueShift , backgroundPointZero . y + hueShift ) ) ; <nl> - m_colourPicker = CCControlSaturationBrightnessPicker : : create ( spriteSheet , ccp ( backgroundPointZero . x + colourShift , backgroundPointZero . y + colourShift ) ) ; <nl> + m_huePicker = new CCControlHuePicker ( ) ; <nl> + m_huePicker - > initWithTargetAndPos ( spriteSheet , ccp ( backgroundPointZero . x + hueShift , backgroundPointZero . y + hueShift ) ) ; <nl> + m_colourPicker = new CCControlSaturationBrightnessPicker ( ) ; <nl> + m_colourPicker - > initWithTargetAndPos ( spriteSheet , ccp ( backgroundPointZero . x + colourShift , backgroundPointZero . y + colourShift ) ) ; <nl> <nl> / / Setup events <nl> m_huePicker - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlColourPicker : : hueSliderValueChanged ) , CCControlEventValueChanged ) ; <nl> CCControlColourPicker * CCControlColourPicker : : create ( ) <nl> } <nl> <nl> <nl> - void CCControlColourPicker : : setColorValue ( const ccColor3B & colorValue ) <nl> + void CCControlColourPicker : : setColor ( const ccColor3B & color ) <nl> { <nl> - m_colorValue = colorValue ; <nl> + m_tColor = color ; <nl> <nl> RGBA rgba ; <nl> - rgba . r = colorValue . r / 255 . 0f ; <nl> - rgba . g = colorValue . g / 255 . 0f ; <nl> - rgba . b = colorValue . b / 255 . 0f ; <nl> + rgba . r = color . r / 255 . 0f ; <nl> + rgba . g = color . g / 255 . 0f ; <nl> + rgba . b = color . b / 255 . 0f ; <nl> rgba . a = 1 . 0f ; <nl> <nl> m_hsv = CCControlUtils : : HSVfromRGB ( rgba ) ; <nl> updateHueAndControlPicker ( ) ; <nl> } <nl> <nl> + void CCControlColourPicker : : setEnabled ( bool enabled ) <nl> + { <nl> + CCControl : : setEnabled ( enabled ) ; <nl> + if ( m_huePicker ! = NULL ) <nl> + { <nl> + m_huePicker - > setEnabled ( enabled ) ; <nl> + } <nl> + if ( m_colourPicker ) <nl> + { <nl> + m_colourPicker - > setEnabled ( enabled ) ; <nl> + } <nl> + } <nl> + <nl> + <nl> / / need two events to prevent an infinite loop ! ( can ' t update huePicker when the huePicker triggers the callback due to CCControlEventValueChanged ) <nl> void CCControlColourPicker : : updateControlPicker ( ) <nl> { <nl> void CCControlColourPicker : : hueSliderValueChanged ( CCObject * sender , CCControlEv <nl> <nl> / / Update the value <nl> RGBA rgb = CCControlUtils : : RGBfromHSV ( m_hsv ) ; <nl> - m_colorValue = ccc3 ( ( GLubyte ) ( rgb . r * 255 . 0f ) , ( GLubyte ) ( rgb . g * 255 . 0f ) , ( GLubyte ) ( rgb . b * 255 . 0f ) ) ; <nl> + m_tColor = ccc3 ( ( GLubyte ) ( rgb . r * 255 . 0f ) , ( GLubyte ) ( rgb . g * 255 . 0f ) , ( GLubyte ) ( rgb . b * 255 . 0f ) ) ; <nl> <nl> / / Send CCControl callback <nl> sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> void CCControlColourPicker : : colourSliderValueChanged ( CCObject * sender , CCContro <nl> <nl> / / Update the value <nl> RGBA rgb = CCControlUtils : : RGBfromHSV ( m_hsv ) ; <nl> - m_colorValue = ccc3 ( ( GLubyte ) ( rgb . r * 255 . 0f ) , ( GLubyte ) ( rgb . g * 255 . 0f ) , ( GLubyte ) ( rgb . b * 255 . 0f ) ) ; <nl> + m_tColor = ccc3 ( ( GLubyte ) ( rgb . r * 255 . 0f ) , ( GLubyte ) ( rgb . g * 255 . 0f ) , ( GLubyte ) ( rgb . b * 255 . 0f ) ) ; <nl> <nl> / / Send CCControl callback <nl> sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> mmm a / extensions / GUI / CCControlExtension / CCControlColourPicker . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlColourPicker . h <nl> <nl> / * <nl> - * CCControlColourPicker . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> NS_CC_EXT_BEGIN <nl> <nl> class CCControlColourPicker : public CCControl <nl> { <nl> - CC_SYNTHESIZE_READONLY_PASS_BY_REF ( ccColor3B , m_colorValue , ColorValue ) ; <nl> - virtual void setColorValue ( const ccColor3B & colorValue ) ; <nl> - <nl> + public : <nl> + CCControlColourPicker ( ) ; <nl> + virtual ~ CCControlColourPicker ( ) ; <nl> + virtual void setColor ( const ccColor3B & colorValue ) ; <nl> + virtual void setEnabled ( bool bEnabled ) ; <nl> protected : <nl> HSV m_hsv ; <nl> - CCControlSaturationBrightnessPicker * m_colourPicker ; <nl> - CCControlHuePicker * m_huePicker ; <nl> - <nl> - CC_SYNTHESIZE_READONLY ( CCSprite * , m_background , Background ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCControlSaturationBrightnessPicker * , m_colourPicker , colourPicker ) <nl> + CC_SYNTHESIZE_RETAIN ( CCControlHuePicker * , m_huePicker , HuePicker ) <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_background , Background ) <nl> <nl> public : <nl> / / @ deprecated : This interface will be deprecated sooner or later . <nl> mmm a / extensions / GUI / CCControlExtension / CCControlExtensions . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlExtensions . h <nl> <nl> - # ifndef __CCCONTROL_EXTENSIONS_H__ <nl> - # define __CCCONTROL_EXTENSIONS_H__ <nl> - <nl> - # include " CCControl . h " <nl> - # include " CCControlButton . h " <nl> - # include " CCControlColourPicker . h " <nl> - # include " CCControlHuePicker . h " <nl> - # include " CCControlSaturationBrightnessPicker . h " <nl> - # include " CCControlSlider . h " <nl> - # include " CCControlSwitch . h " <nl> - # include " CCMenuPassive . h " <nl> - # include " CCSpacer . h " <nl> - <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> + Copyright ( c ) 2012 cocos2d - x . org <nl> + <nl> + http : / / www . cocos2d - x . org <nl> + <nl> + Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + of this software and associated documentation files ( the " Software " ) , to deal <nl> + in the Software without restriction , including without limitation the rights <nl> + to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + copies of the Software , and to permit persons to whom the Software is <nl> + furnished to do so , subject to the following conditions : <nl> + <nl> + The above copyright notice and this permission notice shall be included in <nl> + all copies or substantial portions of the Software . <nl> + <nl> + THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + THE SOFTWARE . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + # ifndef __CCCONTROL_EXTENSIONS_H__ <nl> + # define __CCCONTROL_EXTENSIONS_H__ <nl> + <nl> + # include " CCScale9Sprite . h " <nl> + # include " CCControl . h " <nl> + # include " CCControlButton . h " <nl> + # include " CCControlColourPicker . h " <nl> + # include " CCControlPotentiometer . h " <nl> + # include " CCControlSlider . h " <nl> + # include " CCControlStepper . h " <nl> + # include " CCControlSwitch . h " <nl> + <nl> # endif <nl> \ No newline at end of file <nl> mmm a / extensions / GUI / CCControlExtension / CCControlHuePicker . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlHuePicker . cpp <nl> <nl> / * <nl> - * CCControlHuePicker . m <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> - CCControlHuePicker : : ~ CCControlHuePicker ( ) <nl> + CCControlHuePicker : : CCControlHuePicker ( ) <nl> + : m_hue ( 0 . 0f ) <nl> + , m_huePercentage ( 0 . 0f ) <nl> + , m_background ( NULL ) <nl> + , m_slider ( NULL ) <nl> { <nl> <nl> } <nl> <nl> + CCControlHuePicker : : ~ CCControlHuePicker ( ) <nl> + { <nl> + removeAllChildrenWithCleanup ( true ) ; <nl> + CC_SAFE_RELEASE ( m_background ) ; <nl> + CC_SAFE_RELEASE ( m_slider ) ; <nl> + } <nl> + <nl> CCControlHuePicker * CCControlHuePicker : : pickerWithTargetAndPos ( CCNode * target , CCPoint pos ) <nl> { <nl> return CCControlHuePicker : : create ( target , pos ) ; <nl> bool CCControlHuePicker : : initWithTargetAndPos ( CCNode * target , CCPoint pos ) <nl> { <nl> setTouchEnabled ( true ) ; <nl> / / Add background and slider sprites <nl> - m_background = CCControlUtils : : addSpriteToTargetWithPosAndAnchor ( " huePickerBackground . png " , target , pos , ccp ( 0 . 0f , 0 . 0f ) ) ; <nl> - m_slider = CCControlUtils : : addSpriteToTargetWithPosAndAnchor ( " colourPicker . png " , target , pos , ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> + this - > setBackground ( CCControlUtils : : addSpriteToTargetWithPosAndAnchor ( " huePickerBackground . png " , target , pos , ccp ( 0 . 0f , 0 . 0f ) ) ) ; <nl> + this - > setSlider ( CCControlUtils : : addSpriteToTargetWithPosAndAnchor ( " colourPicker . png " , target , pos , ccp ( 0 . 5f , 0 . 5f ) ) ) ; <nl> <nl> m_slider - > setPosition ( ccp ( pos . x , pos . y + m_background - > boundingBox ( ) . size . height * 0 . 5f ) ) ; <nl> m_startPos = pos ; <nl> bool CCControlHuePicker : : initWithTargetAndPos ( CCNode * target , CCPoint pos ) <nl> return true ; <nl> } <nl> else <nl> + { <nl> return false ; <nl> + } <nl> } <nl> <nl> void CCControlHuePicker : : setHue ( float hueValue ) <nl> { <nl> m_hue = hueValue ; <nl> - setHuePercentage ( m_hue / 360 . 0f ) ; <nl> + / / Set the position of the slider to the correct hue <nl> + / / We need to divide it by 360 as its taken as an angle in degrees <nl> + float huePercentage = hueValue / 360 . 0f ; <nl> + setHuePercentage ( huePercentage ) ; <nl> } <nl> <nl> void CCControlHuePicker : : setHuePercentage ( float hueValueInPercent ) <nl> void CCControlHuePicker : : setHuePercentage ( float hueValueInPercent ) <nl> <nl> } <nl> <nl> + void CCControlHuePicker : : setEnabled ( bool enabled ) <nl> + { <nl> + CCControl : : setEnabled ( enabled ) ; <nl> + if ( m_slider ! = NULL ) <nl> + { <nl> + m_slider - > setOpacity ( enabled ? 255 : 128 ) ; <nl> + } <nl> + } <nl> + <nl> void CCControlHuePicker : : updateSliderPosition ( CCPoint location ) <nl> { <nl> <nl> void CCControlHuePicker : : updateSliderPosition ( CCPoint location ) <nl> <nl> bool CCControlHuePicker : : checkSliderPosition ( CCPoint location ) <nl> { <nl> - / / check that the touch location is within the bounding rectangle before sending updates <nl> - if ( m_background - > boundingBox ( ) . containsPoint ( location ) ) <nl> - { <nl> + / / compute the distance between the current location and the center <nl> + double distance = sqrt ( pow ( location . x + 10 , 2 ) + pow ( location . y , 2 ) ) ; <nl> + <nl> + / / check that the touch location is within the circle <nl> + if ( 160 > distance & & distance > 118 ) <nl> + { <nl> updateSliderPosition ( location ) ; <nl> return true ; <nl> } <nl> bool CCControlHuePicker : : checkSliderPosition ( CCPoint location ) <nl> <nl> bool CCControlHuePicker : : ccTouchBegan ( CCTouch * touch , CCEvent * event ) <nl> { <nl> + if ( ! isEnabled ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> / / Get the touch location <nl> CCPoint touchLocation = getTouchLocation ( touch ) ; <nl> <nl> void CCControlHuePicker : : ccTouchMoved ( CCTouch * touch , CCEvent * event ) <nl> CCPoint touchLocation = getTouchLocation ( touch ) ; <nl> <nl> / / small modification : this allows changing of the colour , even if the touch leaves the bounding area <nl> - updateSliderPosition ( touchLocation ) ; <nl> - sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> + / / updateSliderPosition ( touchLocation ) ; <nl> + / / sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> / / Check the touch position on the slider <nl> - / / checkSliderPosition ( touchLocation ) ; <nl> + checkSliderPosition ( touchLocation ) ; <nl> } <nl> <nl> NS_CC_EXT_END <nl> mmm a / extensions / GUI / CCControlExtension / CCControlHuePicker . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlHuePicker . h <nl> <nl> / * <nl> - * CCControlHuePicker . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> class CCControlHuePicker : public CCControl <nl> <nl> <nl> / / not sure if these need to be there actually . I suppose someone might want to access the sprite ? <nl> - CC_SYNTHESIZE_READONLY ( CCSprite * , m_background , Background ) ; <nl> - CC_SYNTHESIZE_READONLY ( CCSprite * , m_slider , Slider ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_background , Background ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_slider , Slider ) ; <nl> CC_SYNTHESIZE_READONLY ( CCPoint , m_startPos , StartPos ) ; <nl> <nl> - public : <nl> + public : <nl> + CCControlHuePicker ( ) ; <nl> virtual ~ CCControlHuePicker ( ) ; <nl> virtual bool initWithTargetAndPos ( CCNode * target , CCPoint pos ) ; <nl> / / @ deprecated : This interface will be deprecated sooner or later . <nl> CC_DEPRECATED_ATTRIBUTE static CCControlHuePicker * pickerWithTargetAndPos ( CCNode * target , CCPoint pos ) ; <nl> static CCControlHuePicker * create ( CCNode * target , CCPoint pos ) ; <nl> + virtual void setEnabled ( bool enabled ) ; <nl> protected : <nl> void updateSliderPosition ( CCPoint location ) ; <nl> bool checkSliderPosition ( CCPoint location ) ; <nl> new file mode 100644 <nl> index 000000000000 . . 41c258e925d9 <nl> mmm / dev / null <nl> ppp b / extensions / GUI / CCControlExtension / CCControlPotentiometer . cpp <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> + * Copyright 2012 Yannick Loriot . All rights reserved . <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # include " CCControlPotentiometer . h " <nl> + # include " cocos2d . h " <nl> + <nl> + NS_CC_EXT_BEGIN <nl> + <nl> + CCControlPotentiometer : : CCControlPotentiometer ( ) <nl> + : m_fValue ( 0 . 0f ) <nl> + , m_fMinimumValue ( 0 . 0f ) <nl> + , m_fMaximumValue ( 0 . 0f ) <nl> + , m_pThumbSprite ( NULL ) <nl> + , m_pProgressTimer ( NULL ) <nl> + { <nl> + <nl> + } <nl> + <nl> + CCControlPotentiometer : : ~ CCControlPotentiometer ( ) <nl> + { <nl> + CC_SAFE_RELEASE ( m_pThumbSprite ) ; <nl> + CC_SAFE_RELEASE ( m_pProgressTimer ) ; <nl> + } <nl> + <nl> + CCControlPotentiometer * CCControlPotentiometer : : create ( const char * backgroundFile , const char * progressFile , const char * thumbFile ) <nl> + { <nl> + CCControlPotentiometer * pRet = new CCControlPotentiometer ( ) ; <nl> + if ( pRet ! = NULL ) <nl> + { <nl> + / / Prepare track for potentiometer <nl> + CCSprite * backgroundSprite = CCSprite : : create ( backgroundFile ) ; <nl> + <nl> + / / Prepare thumb for potentiometer <nl> + CCSprite * thumbSprite = CCSprite : : create ( thumbFile ) ; <nl> + <nl> + / / Prepare progress for potentiometer <nl> + CCProgressTimer * progressTimer = CCProgressTimer : : create ( CCSprite : : create ( progressFile ) ) ; <nl> + / / progressTimer . type = kCCProgressTimerTypeRadialCW ; <nl> + if ( pRet - > initWithTrackSprite_ProgressTimer_ThumbSprite ( backgroundSprite , progressTimer , thumbSprite ) ) <nl> + { <nl> + pRet - > autorelease ( ) ; <nl> + } <nl> + else <nl> + { <nl> + CC_SAFE_DELETE ( pRet ) ; <nl> + } <nl> + } <nl> + return pRet ; <nl> + } <nl> + <nl> + bool CCControlPotentiometer : : initWithTrackSprite_ProgressTimer_ThumbSprite ( CCSprite * trackSprite , CCProgressTimer * progressTimer , CCSprite * thumbSprite ) <nl> + { <nl> + if ( CCControl : : init ( ) ) <nl> + { <nl> + setTouchEnabled ( true ) ; <nl> + <nl> + setProgressTimer ( progressTimer ) ; <nl> + setThumbSprite ( thumbSprite ) ; <nl> + thumbSprite - > setPosition ( progressTimer - > getPosition ( ) ) ; <nl> + <nl> + addChild ( thumbSprite , 2 ) ; <nl> + addChild ( progressTimer , 1 ) ; <nl> + addChild ( trackSprite ) ; <nl> + <nl> + setContentSize ( trackSprite - > getContentSize ( ) ) ; <nl> + <nl> + / / Init default values <nl> + m_fMinimumValue = 0 . 0f ; <nl> + m_fMaximumValue = 1 . 0f ; <nl> + setValue ( m_fMinimumValue ) ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : setEnabled ( bool enabled ) <nl> + { <nl> + CCControl : : setEnabled ( enabled ) ; <nl> + if ( m_pThumbSprite ! = NULL ) <nl> + { <nl> + m_pThumbSprite - > setOpacity ( ( enabled ) ? 255 : 128 ) ; <nl> + } <nl> + } <nl> + <nl> + void CCControlPotentiometer : : setValue ( float value ) <nl> + { <nl> + / / set new value with sentinel <nl> + if ( value < m_fMinimumValue ) <nl> + { <nl> + value = m_fMinimumValue ; <nl> + } <nl> + <nl> + if ( value > m_fMaximumValue ) <nl> + { <nl> + value = m_fMaximumValue ; <nl> + } <nl> + <nl> + m_fValue = value ; <nl> + <nl> + / / Update thumb and progress position for new value <nl> + float percent = ( value - m_fMinimumValue ) / ( m_fMaximumValue - m_fMinimumValue ) ; <nl> + m_pProgressTimer - > setPercentage ( percent * 100 . 0f ) ; <nl> + m_pThumbSprite - > setRotation ( percent * 360 . 0f ) ; <nl> + <nl> + sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> + } <nl> + <nl> + float CCControlPotentiometer : : getValue ( ) <nl> + { <nl> + return m_fValue ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : setMinimumValue ( float minimumValue ) <nl> + { <nl> + m_fMinimumValue = minimumValue ; <nl> + <nl> + if ( m_fMinimumValue > = m_fMaximumValue ) <nl> + { <nl> + m_fMaximumValue = m_fMinimumValue + 1 . 0f ; <nl> + } <nl> + <nl> + setValue ( m_fMaximumValue ) ; <nl> + } <nl> + <nl> + float CCControlPotentiometer : : getMinimumValue ( ) <nl> + { <nl> + return m_fMinimumValue ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : setMaximumValue ( float maximumValue ) <nl> + { <nl> + m_fMaximumValue = maximumValue ; <nl> + <nl> + if ( m_fMaximumValue < = m_fMinimumValue ) <nl> + { <nl> + m_fMinimumValue = m_fMaximumValue - 1 . 0f ; <nl> + } <nl> + <nl> + setValue ( m_fMinimumValue ) ; <nl> + } <nl> + <nl> + float CCControlPotentiometer : : getMaximumValue ( ) <nl> + { <nl> + return m_fMaximumValue ; <nl> + } <nl> + <nl> + bool CCControlPotentiometer : : isTouchInside ( CCTouch * touch ) <nl> + { <nl> + CCPoint touchLocation = this - > getTouchLocation ( touch ) ; <nl> + <nl> + float distance = this - > distanceBetweenPointAndPoint ( m_pProgressTimer - > getPosition ( ) , touchLocation ) ; <nl> + <nl> + return distance < MIN ( getContentSize ( ) . width / 2 , getContentSize ( ) . height / 2 ) ; <nl> + } <nl> + <nl> + bool CCControlPotentiometer : : ccTouchBegan ( CCTouch * pTouch , CCEvent * pEvent ) <nl> + { <nl> + if ( ! this - > isTouchInside ( pTouch ) <nl> + | | ! this - > isEnabled ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + m_tPreviousLocation = this - > getTouchLocation ( pTouch ) ; <nl> + <nl> + this - > potentiometerBegan ( m_tPreviousLocation ) ; <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) <nl> + { <nl> + CCPoint location = this - > getTouchLocation ( pTouch ) ; <nl> + <nl> + this - > potentiometerMoved ( location ) ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) <nl> + { <nl> + this - > potentiometerEnded ( CCPointZero ) ; <nl> + } <nl> + <nl> + float CCControlPotentiometer : : distanceBetweenPointAndPoint ( CCPoint point1 , CCPoint point2 ) <nl> + { <nl> + float dx = point1 . x - point2 . x ; <nl> + float dy = point1 . y - point2 . y ; <nl> + return sqrt ( dx * dx + dy * dy ) ; <nl> + } <nl> + <nl> + float CCControlPotentiometer : : angleInDegreesBetweenLineFromPoint_toPoint_toLineFromPoint_toPoint ( <nl> + CCPoint beginLineA , <nl> + CCPoint endLineA , <nl> + CCPoint beginLineB , <nl> + CCPoint endLineB ) <nl> + { <nl> + float a = endLineA . x - beginLineA . x ; <nl> + float b = endLineA . y - beginLineA . y ; <nl> + float c = endLineB . x - beginLineB . x ; <nl> + float d = endLineB . y - beginLineB . y ; <nl> + <nl> + float atanA = atan2 ( a , b ) ; <nl> + float atanB = atan2 ( c , d ) ; <nl> + <nl> + / / convert radiants to degrees <nl> + return ( atanA - atanB ) * 180 / M_PI ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : potentiometerBegan ( CCPoint location ) <nl> + { <nl> + setSelected ( true ) ; <nl> + getThumbSprite ( ) - > setColor ( ccGRAY ) ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : potentiometerMoved ( CCPoint location ) <nl> + { <nl> + float angle = this - > angleInDegreesBetweenLineFromPoint_toPoint_toLineFromPoint_toPoint ( <nl> + m_pProgressTimer - > getPosition ( ) , <nl> + location , <nl> + m_pProgressTimer - > getPosition ( ) , <nl> + m_tPreviousLocation ) ; <nl> + <nl> + / / fix value , if the 12 o ' clock position is between location and previousLocation <nl> + if ( angle > 180 ) <nl> + { <nl> + angle - = 360 ; <nl> + } <nl> + else if ( angle < - 180 ) <nl> + { <nl> + angle + = 360 ; <nl> + } <nl> + <nl> + setValue ( m_fValue + angle / 360 . 0f * ( m_fMaximumValue - m_fMinimumValue ) ) ; <nl> + <nl> + m_tPreviousLocation = location ; <nl> + } <nl> + <nl> + void CCControlPotentiometer : : potentiometerEnded ( CCPoint location ) <nl> + { <nl> + getThumbSprite ( ) - > setColor ( ccWHITE ) ; <nl> + setSelected ( false ) ; <nl> + } <nl> + <nl> + NS_CC_EXT_END <nl> new file mode 100644 <nl> index 000000000000 . . 98a6d4d58c75 <nl> mmm / dev / null <nl> ppp b / extensions / GUI / CCControlExtension / CCControlPotentiometer . h <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> + * Copyright 2012 Yannick Loriot . All rights reserved . <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + # ifndef __CCCONTROLPOTENTIOMETER_H__ <nl> + # define __CCCONTROLPOTENTIOMETER_H__ <nl> + <nl> + # include " CCControl . h " <nl> + <nl> + NS_CC_EXT_BEGIN <nl> + <nl> + / * * <nl> + * @ addtogroup GUI <nl> + * @ { <nl> + * @ addtogroup control_extension <nl> + * @ { <nl> + * / <nl> + <nl> + / * * @ class CCControlPotentiometer Potentiometer control for Cocos2D . * / <nl> + class CCControlPotentiometer : public CCControl <nl> + { <nl> + public : <nl> + CCControlPotentiometer ( ) ; <nl> + virtual ~ CCControlPotentiometer ( ) ; <nl> + / * * <nl> + * Creates potentiometer with a track filename and a progress filename . <nl> + * / <nl> + static CCControlPotentiometer * create ( const char * backgroundFile , const char * progressFile , const char * thumbFile ) ; <nl> + <nl> + / * * <nl> + * Initializes a potentiometer with a track sprite and a progress bar . <nl> + * <nl> + * @ param trackSprite CCSprite , that is used as a background . <nl> + * @ param progressSprite CCProgressTimer , that is used as a progress bar . <nl> + * / <nl> + bool initWithTrackSprite_ProgressTimer_ThumbSprite ( CCSprite * trackSprite , CCProgressTimer * progressTimer , CCSprite * thumbSprite ) ; <nl> + void setValue ( float value ) ; <nl> + float getValue ( ) ; <nl> + <nl> + void setMinimumValue ( float minimumValue ) ; <nl> + float getMinimumValue ( ) ; <nl> + <nl> + void setMaximumValue ( float maximumValue ) ; <nl> + float getMaximumValue ( ) ; <nl> + <nl> + void setEnabled ( bool enabled ) ; <nl> + <nl> + virtual bool isTouchInside ( CCTouch * touch ) ; <nl> + <nl> + virtual bool ccTouchBegan ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> + virtual void ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> + virtual void ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> + <nl> + protected : <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_pThumbSprite , ThumbSprite ) <nl> + CC_SYNTHESIZE_RETAIN ( CCProgressTimer * , m_pProgressTimer , ProgressTimer ) <nl> + CC_SYNTHESIZE ( CCPoint , m_tPreviousLocation , PreviousLocation ) <nl> + / * * Contains the receiver⠀ ™ s current value . * / <nl> + float m_fValue ; <nl> + / * * Contains the minimum value of the receiver . <nl> + * The default value of this property is 0 . 0 . * / <nl> + float m_fMinimumValue ; <nl> + / * * Contains the maximum value of the receiver . <nl> + * The default value of this property is 1 . 0 . * / <nl> + float m_fMaximumValue ; <nl> + / * * Factorize the event dispath into these methods . * / <nl> + void potentiometerBegan ( CCPoint location ) ; <nl> + void potentiometerMoved ( CCPoint location ) ; <nl> + void potentiometerEnded ( CCPoint location ) ; <nl> + <nl> + / * * Returns the distance between the point1 and point2 . * / <nl> + float distanceBetweenPointAndPoint ( CCPoint point1 , CCPoint point2 ) ; <nl> + / * * Returns the angle in degree between line1 and line2 . * / <nl> + float angleInDegreesBetweenLineFromPoint_toPoint_toLineFromPoint_toPoint ( <nl> + CCPoint beginLineA , <nl> + CCPoint endLineA , <nl> + CCPoint beginLineB , <nl> + CCPoint endLineB ) ; <nl> + <nl> + } ; <nl> + <nl> + / / end of GUI group <nl> + / / / @ } <nl> + / / / @ } <nl> + <nl> + NS_CC_EXT_END <nl> + <nl> + # endif / * __CCCONTROLPOTENTIOMETER_H__ * / <nl> mmm a / extensions / GUI / CCControlExtension / CCControlSaturationBrightnessPicker . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlSaturationBrightnessPicker . cpp <nl> <nl> / * <nl> - * CCControlSaturationBrightnessPicker . m <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> + CCControlSaturationBrightnessPicker : : CCControlSaturationBrightnessPicker ( ) <nl> + : m_saturation ( 0 . 0f ) <nl> + , m_brightness ( 0 . 0f ) <nl> + , m_background ( NULL ) <nl> + , m_overlay ( NULL ) <nl> + , m_shadow ( NULL ) <nl> + , m_slider ( NULL ) <nl> + , boxPos ( 0 ) <nl> + , boxSize ( 0 ) <nl> + { <nl> + <nl> + } <nl> + <nl> CCControlSaturationBrightnessPicker : : ~ CCControlSaturationBrightnessPicker ( ) <nl> { <nl> + removeAllChildrenWithCleanup ( true ) ; <nl> <nl> + m_background = NULL ; <nl> + m_overlay = NULL ; <nl> + m_shadow = NULL ; <nl> + m_slider = NULL ; <nl> } <nl> <nl> bool CCControlSaturationBrightnessPicker : : initWithTargetAndPos ( CCNode * target , CCPoint pos ) <nl> bool CCControlSaturationBrightnessPicker : : initWithTargetAndPos ( CCNode * target , C <nl> <nl> m_startPos = pos ; / / starting position of the colour picker <nl> boxPos = 35 ; / / starting position of the virtual box area for picking a colour <nl> - boxSize = 150 ; / / the size ( width and height ) of the virtual box for picking a colour from <nl> + boxSize = m_background - > getContentSize ( ) . width / 2 ; ; / / the size ( width and height ) of the virtual box for picking a colour from <nl> return true ; <nl> } <nl> else <nl> + { <nl> return false ; <nl> + } <nl> } <nl> <nl> CCControlSaturationBrightnessPicker * CCControlSaturationBrightnessPicker : : pickerWithTargetAndPos ( CCNode * target , CCPoint pos ) <nl> CCControlSaturationBrightnessPicker * CCControlSaturationBrightnessPicker : : create <nl> return pRet ; <nl> } <nl> <nl> - <nl> + void CCControlSaturationBrightnessPicker : : setEnabled ( bool enabled ) <nl> + { <nl> + CCControl : : setEnabled ( enabled ) ; <nl> + if ( m_slider ! = NULL ) <nl> + { <nl> + m_slider - > setOpacity ( enabled ? 255 : 128 ) ; <nl> + } <nl> + } <nl> <nl> void CCControlSaturationBrightnessPicker : : updateWithHSV ( HSV hsv ) <nl> { <nl> bool CCControlSaturationBrightnessPicker : : checkSliderPosition ( CCPoint location ) <nl> float dist = sqrtf ( dx * dx + dy * dy ) ; <nl> <nl> / / check that the touch location is within the bounding rectangle before sending updates <nl> - if ( dist < = m_background - > boundingBox ( ) . size . width * . 5 ) <nl> + if ( dist < = m_background - > boundingBox ( ) . size . width * 0 . 5f ) <nl> { <nl> updateSliderPosition ( location ) ; <nl> sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> bool CCControlSaturationBrightnessPicker : : checkSliderPosition ( CCPoint location ) <nl> <nl> bool CCControlSaturationBrightnessPicker : : ccTouchBegan ( CCTouch * touch , CCEvent * event ) <nl> { <nl> + if ( ! isEnabled ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> / / Get the touch location <nl> CCPoint touchLocation = getTouchLocation ( touch ) ; <nl> <nl> void CCControlSaturationBrightnessPicker : : ccTouchMoved ( CCTouch * touch , CCEvent * <nl> CCPoint touchLocation = getTouchLocation ( touch ) ; <nl> <nl> / / small modification : this allows changing of the colour , even if the touch leaves the bounding area <nl> - updateSliderPosition ( touchLocation ) ; <nl> - sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> + / / updateSliderPosition ( touchLocation ) ; <nl> + / / sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> / / Check the touch position on the slider <nl> - / / checkSliderPosition ( touchLocation ) ; <nl> + checkSliderPosition ( touchLocation ) ; <nl> } <nl> <nl> NS_CC_EXT_END <nl> mmm a / extensions / GUI / CCControlExtension / CCControlSaturationBrightnessPicker . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlSaturationBrightnessPicker . h <nl> <nl> / * <nl> - * CCControlSaturationBrightnessPicker . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> NS_CC_EXT_BEGIN <nl> <nl> class CCControlSaturationBrightnessPicker : public CCControl <nl> { <nl> + / * * Contains the receiver ¡ ¯ s current saturation value . * / <nl> CC_SYNTHESIZE_READONLY ( float , m_saturation , Saturation ) ; <nl> + / * * Contains the receiver ¡ ¯ s current brightness value . * / <nl> CC_SYNTHESIZE_READONLY ( float , m_brightness , Brightness ) ; <nl> <nl> / / not sure if these need to be there actually . I suppose someone might want to access the sprite ? <nl> class CCControlSaturationBrightnessPicker : public CCControl <nl> int boxSize ; <nl> <nl> public : <nl> + CCControlSaturationBrightnessPicker ( ) ; <nl> virtual ~ CCControlSaturationBrightnessPicker ( ) ; <nl> virtual bool initWithTargetAndPos ( CCNode * target , CCPoint pos ) ; <nl> <nl> / / @ deprecated : This interface will be deprecated sooner or later . <nl> CC_DEPRECATED_ATTRIBUTE static CCControlSaturationBrightnessPicker * pickerWithTargetAndPos ( CCNode * target , CCPoint pos ) ; <nl> static CCControlSaturationBrightnessPicker * create ( CCNode * target , CCPoint pos ) ; <nl> + <nl> + virtual void setEnabled ( bool enabled ) ; <nl> virtual void updateWithHSV ( HSV hsv ) ; <nl> virtual void updateDraggerWithHSV ( HSV hsv ) ; <nl> <nl> mmm a / extensions / GUI / CCControlExtension / CCControlSlider . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlSlider . cpp <nl> <nl> / * <nl> - * CCControlSlider <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2011 Yannick Loriot . <nl> * http : / / yannickloriot . com <nl> <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> - CCControlSlider : : ~ CCControlSlider ( ) <nl> + CCControlSlider : : CCControlSlider ( ) <nl> + : m_value ( 0 . 0f ) <nl> + , m_minimumValue ( 0 . 0f ) <nl> + , m_maximumValue ( 0 . 0f ) <nl> + , m_minimumAllowedValue ( 0 . 0f ) <nl> + , m_maximumAllowedValue ( 0 . 0f ) <nl> + , m_thumbSprite ( NULL ) <nl> + , m_progressSprite ( NULL ) <nl> + , m_backgroundSprite ( NULL ) <nl> { <nl> <nl> } <nl> <nl> + CCControlSlider : : ~ CCControlSlider ( ) <nl> + { <nl> + CC_SAFE_RELEASE ( m_thumbSprite ) ; <nl> + CC_SAFE_RELEASE ( m_progressSprite ) ; <nl> + CC_SAFE_RELEASE ( m_backgroundSprite ) ; <nl> + } <nl> + <nl> CCControlSlider * CCControlSlider : : sliderWithFiles ( const char * bgFile , const char * progressFile , const char * thumbFile ) <nl> { <nl> return CCControlSlider : : create ( bgFile , progressFile , thumbFile ) ; <nl> CCControlSlider * CCControlSlider : : create ( const char * bgFile , const char * progres <nl> CCSprite * progressSprite = CCSprite : : create ( progressFile ) ; <nl> <nl> / / Prepare thumb ( menuItem ) for slider <nl> - CCSprite * thumbNormal = CCSprite : : create ( thumbFile ) ; <nl> - CCSprite * thumbSelected = CCSprite : : create ( thumbFile ) ; <nl> - thumbSelected - > setColor ( ccGRAY ) ; <nl> - <nl> - CCMenuItemSprite * thumbMenuItem = CCMenuItemSprite : : create ( thumbNormal , thumbSelected ) ; <nl> + CCSprite * thumbSprite = CCSprite : : create ( thumbFile ) ; <nl> <nl> - return CCControlSlider : : create ( backgroundSprite , progressSprite , thumbMenuItem ) ; <nl> + return CCControlSlider : : create ( backgroundSprite , progressSprite , thumbSprite ) ; <nl> } <nl> <nl> - CCControlSlider * CCControlSlider : : sliderWithSprites ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCMenuItem * thumbItem ) <nl> + CCControlSlider * CCControlSlider : : sliderWithSprites ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCSprite * thumbSprite ) <nl> { <nl> - return CCControlSlider : : create ( backgroundSprite , pogressSprite , thumbItem ) ; <nl> + return CCControlSlider : : create ( backgroundSprite , pogressSprite , thumbSprite ) ; <nl> } <nl> <nl> - CCControlSlider * CCControlSlider : : create ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCMenuItem * thumbItem ) <nl> + CCControlSlider * CCControlSlider : : create ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCSprite * thumbSprite ) <nl> { <nl> CCControlSlider * pRet = new CCControlSlider ( ) ; <nl> - pRet - > initWithSprites ( backgroundSprite , pogressSprite , thumbItem ) ; <nl> + pRet - > initWithSprites ( backgroundSprite , pogressSprite , thumbSprite ) ; <nl> pRet - > autorelease ( ) ; <nl> return pRet ; <nl> } <nl> <nl> - bool CCControlSlider : : initWithSprites ( CCSprite * backgroundSprite , CCSprite * progessSprite , CCMenuItem * thumbItem ) <nl> + bool CCControlSlider : : initWithSprites ( CCSprite * backgroundSprite , CCSprite * progressSprite , CCSprite * thumbSprite ) <nl> { <nl> if ( CCControl : : init ( ) ) <nl> { <nl> + CCAssert ( backgroundSprite , " Background sprite must be not nil " ) ; <nl> + CCAssert ( progressSprite , " Progress sprite must be not nil " ) ; <nl> + CCAssert ( thumbSprite , " Thumb sprite must be not nil " ) ; <nl> + <nl> ignoreAnchorPointForPosition ( false ) ; <nl> setTouchEnabled ( true ) ; <nl> <nl> - m_backgroundSprite = backgroundSprite ; <nl> - m_progressSprite = progessSprite ; <nl> - m_thumbItem = thumbItem ; <nl> + this - > setBackgroundSprite ( backgroundSprite ) ; <nl> + this - > setProgressSprite ( progressSprite ) ; <nl> + this - > setThumbSprite ( thumbSprite ) ; <nl> <nl> / / Defines the content size <nl> - CCRect maxRect = CCControlUtils : : CCRectUnion ( backgroundSprite - > boundingBox ( ) , thumbItem - > boundingBox ( ) ) ; <nl> - CCSize size = CCSizeMake ( maxRect . size . width + 2 * SLIDER_MARGIN_H , maxRect . size . height + 2 * SLIDER_MARGIN_V ) ; <nl> - setContentSize ( size ) ; <nl> - / / setContentSize ( CCSizeMake ( backgroundSprite - > getContentSize ( ) . width , thumbItem - > getContentSize ( ) . height ) ) ; <nl> + CCRect maxRect = CCControlUtils : : CCRectUnion ( backgroundSprite - > boundingBox ( ) , thumbSprite - > boundingBox ( ) ) ; <nl> + <nl> + setContentSize ( CCSizeMake ( maxRect . size . width , maxRect . size . height ) ) ; <nl> + <nl> / / Add the slider background <nl> m_backgroundSprite - > setAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> - m_backgroundSprite - > setPosition ( ccp ( size . width / 2 , size . height / 2 ) ) ; <nl> + m_backgroundSprite - > setPosition ( ccp ( this - > getContentSize ( ) . width / 2 , this - > getContentSize ( ) . height / 2 ) ) ; <nl> addChild ( m_backgroundSprite ) ; <nl> <nl> / / Add the progress bar <nl> m_progressSprite - > setAnchorPoint ( ccp ( 0 . 0f , 0 . 5f ) ) ; <nl> - m_progressSprite - > setPosition ( ccp ( 0 . 0f + SLIDER_MARGIN_H , size . height / 2 ) ) ; <nl> + m_progressSprite - > setPosition ( ccp ( 0 . 0f , this - > getContentSize ( ) . height / 2 ) ) ; <nl> addChild ( m_progressSprite ) ; <nl> <nl> / / Add the slider thumb <nl> - m_thumbItem - > setPosition ( ccp ( 0 + SLIDER_MARGIN_H , size . height / 2 ) ) ; <nl> - addChild ( m_thumbItem ) ; <nl> + m_thumbSprite - > setPosition ( ccp ( 0 . 0f , this - > getContentSize ( ) . height / 2 ) ) ; <nl> + addChild ( m_thumbSprite ) ; <nl> <nl> / / Init default values <nl> m_minimumValue = 0 . 0f ; <nl> m_maximumValue = 1 . 0f ; <nl> - m_snappingInterval = - 1 . 0f ; <nl> + <nl> setValue ( m_minimumValue ) ; <nl> return true ; <nl> } <nl> CCControlSlider * CCControlSlider : : create ( CCSprite * backgroundSprite , CCSprite * <nl> } <nl> <nl> <nl> + void CCControlSlider : : setEnabled ( bool enabled ) <nl> + { <nl> + CCControl : : setEnabled ( enabled ) ; <nl> + if ( m_thumbSprite ! = NULL ) <nl> + { <nl> + m_thumbSprite - > setOpacity ( ( enabled ) ? 255 : 128 ) ; <nl> + } <nl> + } <nl> + <nl> void CCControlSlider : : setValue ( float value ) <nl> { <nl> - / / clamp between the two bounds <nl> - value = MAX ( value , m_minimumValue ) ; <nl> - value = MIN ( value , m_maximumValue ) ; <nl> + / / set new value with sentinel <nl> + if ( value < m_minimumValue ) <nl> + { <nl> + value = m_minimumValue ; <nl> + } <nl> <nl> - / / if we ' re snapping <nl> - if ( m_snappingInterval > = 0 ) <nl> + if ( value > m_maximumValue ) <nl> { <nl> - / / int nTotal = ( int ) ( ceil ( m_maximumValue - m_minimumValue ) / m_snappingInterval ) ; <nl> - / / floor ( n + 0 . 5f ) = = round ( n ) <nl> - value = floor ( 0 . 5f + value / m_snappingInterval ) * m_snappingInterval ; <nl> + value = m_maximumValue ; <nl> } <nl> - m_value = value ; <nl> <nl> - / / Update thumb position for new value <nl> - float percent = ( m_value - m_minimumValue ) / ( m_maximumValue - m_minimumValue ) ; <nl> - CCPoint pos = m_thumbItem - > getPosition ( ) ; <nl> - pos . x = percent * m_backgroundSprite - > getContentSize ( ) . width + SLIDER_MARGIN_H ; <nl> - m_thumbItem - > setPosition ( pos ) ; <nl> - <nl> - / / Stretches content proportional to newLevel <nl> - CCRect textureRect = m_progressSprite - > getTextureRect ( ) ; <nl> - textureRect = CCRectMake ( textureRect . origin . x , textureRect . origin . y , percent * m_backgroundSprite - > getContentSize ( ) . width , textureRect . size . height ) ; <nl> - m_progressSprite - > setTextureRect ( textureRect , m_progressSprite - > isTextureRectRotated ( ) , textureRect . size ) ; <nl> - sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> + m_value = value ; <nl> + <nl> + this - > needsLayout ( ) ; <nl> + <nl> + this - > sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> } <nl> <nl> void CCControlSlider : : setMinimumValue ( float minimumValue ) <nl> CCControlSlider * CCControlSlider : : create ( CCSprite * backgroundSprite , CCSprite * <nl> m_minimumValue = minimumValue ; <nl> m_minimumAllowedValue = minimumValue ; <nl> if ( m_minimumValue > = m_maximumValue ) <nl> + { <nl> m_maximumValue = m_minimumValue + 1 . 0f ; <nl> + } <nl> setValue ( m_value ) ; <nl> } <nl> <nl> - void CCControlSlider : : setMaximumValue ( float maximumValue ) <nl> + void CCControlSlider : : setMaximumValue ( float maximumValue ) <nl> { <nl> m_maximumValue = maximumValue ; <nl> m_maximumAllowedValue = maximumValue ; <nl> - if ( m_maximumValue < = m_minimumValue ) <nl> + if ( m_maximumValue < = m_minimumValue ) <nl> + { <nl> m_minimumValue = m_maximumValue - 1 . 0f ; <nl> + } <nl> setValue ( m_value ) ; <nl> } <nl> <nl> - / / this is the same as CCControl : : getTouchLocation , but it returns the position relative to the position of this control <nl> - CCPoint CCControlSlider : : getTouchLocationInControl ( CCTouch * touch ) <nl> + bool CCControlSlider : : isTouchInside ( CCTouch * touch ) <nl> { <nl> - CCPoint touchLocation = touch - > getLocation ( ) ; ; / / Get the touch position <nl> - touchLocation = convertToNodeSpace ( touchLocation ) ; / / Convert to the node space of this class <nl> - <nl> - if ( touchLocation . x < 0 ) <nl> - { <nl> - touchLocation . x = 0 ; <nl> - } <nl> - else if ( touchLocation . x > m_backgroundSprite - > getContentSize ( ) . width + SLIDER_MARGIN_H ) <nl> - { <nl> - touchLocation . x = m_backgroundSprite - > getContentSize ( ) . width + SLIDER_MARGIN_H ; <nl> - } <nl> - return touchLocation ; <nl> - } <nl> - <nl> - bool CCControlSlider : : ccTouchBegan ( CCTouch * touch , CCEvent * pEvent ) <nl> + CCPoint touchLocation = touch - > getLocation ( ) ; <nl> + touchLocation = this - > getParent ( ) - > convertToNodeSpace ( touchLocation ) ; <nl> + <nl> + CCRect rect = this - > boundingBox ( ) ; <nl> + rect . size . width + = m_thumbSprite - > getContentSize ( ) . width ; <nl> + rect . origin . x - = m_thumbSprite - > getContentSize ( ) . width / 2 ; <nl> + <nl> + return rect . containsPoint ( touchLocation ) ; <nl> + } <nl> + <nl> + CCPoint CCControlSlider : : locationFromTouch ( CCTouch * touch ) <nl> + { <nl> + CCPoint touchLocation = touch - > getLocation ( ) ; / / Get the touch position <nl> + touchLocation = this - > convertToNodeSpace ( touchLocation ) ; / / Convert to the node space of this class <nl> + <nl> + if ( touchLocation . x < 0 ) <nl> { <nl> - if ( ! isTouchInside ( touch ) ) <nl> + touchLocation . x = 0 ; <nl> + } else if ( touchLocation . x > m_backgroundSprite - > getContentSize ( ) . width ) <nl> + { <nl> + touchLocation . x = m_backgroundSprite - > getContentSize ( ) . width ; <nl> + } <nl> + <nl> + return touchLocation ; <nl> + } <nl> + <nl> + <nl> + bool CCControlSlider : : ccTouchBegan ( CCTouch * touch , CCEvent * pEvent ) <nl> + { <nl> + if ( ! isTouchInside ( touch ) | | ! isEnabled ( ) ) <nl> return false ; <nl> <nl> - CCPoint location = getTouchLocationInControl ( touch ) ; <nl> + CCPoint location = locationFromTouch ( touch ) ; <nl> sliderBegan ( location ) ; <nl> return true ; <nl> } <nl> <nl> void CCControlSlider : : ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) <nl> { <nl> - CCPoint location = getTouchLocationInControl ( pTouch ) ; <nl> + CCPoint location = locationFromTouch ( pTouch ) ; <nl> sliderMoved ( location ) ; <nl> } <nl> <nl> void CCControlSlider : : ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) <nl> { <nl> - CCPoint location = getTouchLocationInControl ( pTouch ) ; <nl> sliderEnded ( CCPointZero ) ; <nl> } <nl> <nl> + void CCControlSlider : : needsLayout ( ) <nl> + { <nl> + if ( NULL = = m_thumbSprite | | NULL = = m_backgroundSprite | | NULL = = m_progressSprite ) <nl> + { <nl> + return ; <nl> + } <nl> + / / Update thumb position for new value <nl> + float percent = ( m_value - m_minimumValue ) / ( m_maximumValue - m_minimumValue ) ; <nl> + <nl> + CCPoint pos = m_thumbSprite - > getPosition ( ) ; <nl> + pos . x = percent * m_backgroundSprite - > getContentSize ( ) . width ; <nl> + m_thumbSprite - > setPosition ( pos ) ; <nl> + <nl> + / / Stretches content proportional to newLevel <nl> + CCRect textureRect = m_progressSprite - > getTextureRect ( ) ; <nl> + textureRect = CCRectMake ( textureRect . origin . x , textureRect . origin . y , pos . x , textureRect . size . height ) ; <nl> + m_progressSprite - > setTextureRect ( textureRect , m_progressSprite - > isTextureRectRotated ( ) , textureRect . size ) ; <nl> + } <nl> + <nl> void CCControlSlider : : sliderBegan ( CCPoint location ) <nl> { <nl> - m_thumbItem - > selected ( ) ; <nl> + this - > setSelected ( true ) ; <nl> + this - > getThumbSprite ( ) - > setColor ( ccGRAY ) ; <nl> setValue ( valueForLocation ( location ) ) ; <nl> } <nl> <nl> void CCControlSlider : : sliderMoved ( CCPoint location ) <nl> <nl> void CCControlSlider : : sliderEnded ( CCPoint location ) <nl> { <nl> - if ( m_thumbItem - > isSelected ( ) ) <nl> + if ( this - > isSelected ( ) ) <nl> { <nl> - m_thumbItem - > unselected ( ) ; <nl> - setValue ( valueForLocation ( m_thumbItem - > getPosition ( ) ) ) ; <nl> + setValue ( valueForLocation ( m_thumbSprite - > getPosition ( ) ) ) ; <nl> } <nl> + this - > getThumbSprite ( ) - > setColor ( ccWHITE ) ; <nl> + this - > setSelected ( false ) ; <nl> } <nl> <nl> float CCControlSlider : : valueForLocation ( CCPoint location ) <nl> { <nl> - float percent = ( location . x - SLIDER_MARGIN_H ) / m_backgroundSprite - > getContentSize ( ) . width ; <nl> + float percent = location . x / m_backgroundSprite - > getContentSize ( ) . width ; <nl> return MAX ( MIN ( m_minimumValue + percent * ( m_maximumValue - m_minimumValue ) , m_maximumAllowedValue ) , m_minimumAllowedValue ) ; <nl> } <nl> <nl> mmm a / extensions / GUI / CCControlExtension / CCControlSlider . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlSlider . h <nl> <nl> / * <nl> - * CCControlSlider <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2011 Yannick Loriot . All rights reserved . <nl> * http : / / yannickloriot . com <nl> <nl> <nl> # include " CCControl . h " <nl> # include " CCInvocation . h " <nl> - # include " sprite_nodes / CCSprite . h " <nl> - # include " menu_nodes / CCMenuItem . h " <nl> - <nl> - # define SLIDER_MARGIN_H 24 <nl> - # define SLIDER_MARGIN_V 8 <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> NS_CC_EXT_BEGIN <nl> class CCControlSlider : public CCControl <nl> { <nl> / / maunally put in the setters <nl> + / * * Contains the receiver ¡ ¯ s current value . * / <nl> CC_SYNTHESIZE_READONLY ( float , m_value , Value ) ; <nl> virtual void setValue ( float val ) ; <nl> + / * * Contains the minimum value of the receiver . <nl> + * The default value of this property is 0 . 0 . * / <nl> CC_SYNTHESIZE_READONLY ( float , m_minimumValue , MinimumValue ) ; <nl> virtual void setMinimumValue ( float val ) ; <nl> + / * * Contains the maximum value of the receiver . <nl> + * The default value of this property is 1 . 0 . * / <nl> CC_SYNTHESIZE_READONLY ( float , m_maximumValue , MaximumValue ) ; <nl> virtual void setMaximumValue ( float val ) ; <nl> - <nl> + virtual void setEnabled ( bool enabled ) ; <nl> + virtual bool isTouchInside ( CCTouch * touch ) ; <nl> + CCPoint locationFromTouch ( CCTouch * touch ) ; <nl> + <nl> CC_SYNTHESIZE ( float , m_minimumAllowedValue , MinimumAllowedValue ) ; <nl> CC_SYNTHESIZE ( float , m_maximumAllowedValue , MaximumAllowedValue ) ; <nl> - <nl> - <nl> - / / interval to snap to <nl> - CC_SYNTHESIZE ( float , m_snappingInterval , SnappingInterval ) ; <nl> <nl> / / maybe this should be read - only <nl> - CC_SYNTHESIZE_READONLY ( CCMenuItem * , m_thumbItem , ThumbItem ) ; <nl> - CC_SYNTHESIZE_READONLY ( CCSprite * , m_progressSprite , ProgressSprite ) ; <nl> - CC_SYNTHESIZE_READONLY ( CCSprite * , m_backgroundSprite , BackgroundSprite ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_thumbSprite , ThumbSprite ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_progressSprite , ProgressSprite ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_backgroundSprite , BackgroundSprite ) ; <nl> <nl> public : <nl> - <nl> + CCControlSlider ( ) ; <nl> virtual ~ CCControlSlider ( ) ; <nl> <nl> / * * <nl> class CCControlSlider : public CCControl <nl> * <nl> * @ param backgroundSprite CCSprite , that is used as a background . <nl> * @ param progressSprite CCSprite , that is used as a progress bar . <nl> - * @ param thumbItem CCMenuItem , that is used as a thumb . <nl> + * @ param thumbItem CCSprite , that is used as a thumb . <nl> * / <nl> - virtual bool initWithSprites ( CCSprite * backgroundSprite , CCSprite * progessSprite , CCMenuItem * thumbItem ) ; <nl> + virtual bool initWithSprites ( CCSprite * backgroundSprite , CCSprite * progressSprite , CCSprite * thumbSprite ) ; <nl> <nl> <nl> / * * <nl> class CCControlSlider : public CCControl <nl> * @ deprecated : This interface will be deprecated sooner or later . <nl> * @ see initWithBackgroundSprite : progressSprite : thumbMenuItem : <nl> * / <nl> - CC_DEPRECATED_ATTRIBUTE static CCControlSlider * sliderWithSprites ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCMenuItem * thumbItem ) ; <nl> + CC_DEPRECATED_ATTRIBUTE static CCControlSlider * sliderWithSprites ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCSprite * thumbSprite ) ; <nl> <nl> <nl> / * * <nl> class CCControlSlider : public CCControl <nl> * <nl> * @ see initWithBackgroundSprite : progressSprite : thumbMenuItem : <nl> * / <nl> - static CCControlSlider * create ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCMenuItem * thumbItem ) ; <nl> - <nl> + static CCControlSlider * create ( CCSprite * backgroundSprite , CCSprite * pogressSprite , CCSprite * thumbSprite ) ; <nl> <nl> + virtual void needsLayout ( ) ; <nl> protected : <nl> void sliderBegan ( CCPoint location ) ; <nl> void sliderMoved ( CCPoint location ) ; <nl> void sliderEnded ( CCPoint location ) ; <nl> <nl> - virtual CCPoint getTouchLocationInControl ( CCTouch * touch ) ; <nl> - <nl> virtual bool ccTouchBegan ( CCTouch * touch , CCEvent * pEvent ) ; <nl> virtual void ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> virtual void ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> <nl> - <nl> - <nl> / * * Returns the value for the given location . * / <nl> float valueForLocation ( CCPoint location ) ; <nl> } ; <nl> new file mode 100644 <nl> index 000000000000 . . a6a0db21086b <nl> mmm / dev / null <nl> ppp b / extensions / GUI / CCControlExtension / CCControlStepper . cpp <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> + * Copyright 2012 Yannick Loriot . All rights reserved . <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT falseT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND falseNINFRINGEMENT . IN false EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # include " CCControlStepper . h " <nl> + <nl> + NS_CC_EXT_BEGIN <nl> + <nl> + # define CCControlStepperLabelColorEnabled ccc3 ( 55 , 55 , 55 ) <nl> + # define CCControlStepperLabelColorDisabled ccc3 ( 147 , 147 , 147 ) <nl> + <nl> + # define CCControlStepperLabelFont " CourierNewPSMT " <nl> + <nl> + <nl> + # define kAutorepeatDeltaTime 0 . 15f <nl> + # define kAutorepeatIncreaseTimeIncrement 12 <nl> + <nl> + CCControlStepper : : CCControlStepper ( ) <nl> + : m_dValue ( 0 . 0 ) <nl> + , m_bContinuous ( false ) <nl> + , m_bAutorepeat ( false ) <nl> + , m_bWraps ( false ) <nl> + , m_dMinimumValue ( 0 . 0 ) <nl> + , m_dMaximumValue ( 0 . 0 ) <nl> + , m_dStepValue ( 0 . 0 ) <nl> + , m_pMinusSprite ( NULL ) <nl> + , m_pPlusSprite ( NULL ) <nl> + , m_pMinusLabel ( NULL ) <nl> + , m_pPlusLabel ( NULL ) <nl> + , m_bTouchInsideFlag ( false ) <nl> + , m_eTouchedPart ( kCCControlStepperPartNone ) <nl> + , m_nAutorepeatCount ( 0 ) <nl> + { <nl> + <nl> + } <nl> + <nl> + CCControlStepper : : ~ CCControlStepper ( ) <nl> + { <nl> + unscheduleAllSelectors ( ) ; <nl> + <nl> + CC_SAFE_RELEASE ( m_pMinusSprite ) ; <nl> + CC_SAFE_RELEASE ( m_pPlusSprite ) ; <nl> + CC_SAFE_RELEASE ( m_pMinusLabel ) ; <nl> + CC_SAFE_RELEASE ( m_pPlusLabel ) ; <nl> + } <nl> + <nl> + bool CCControlStepper : : initWithMinusSpriteAndPlusSprite ( CCSprite * minusSprite , CCSprite * plusSprite ) <nl> + { <nl> + if ( CCControl : : init ( ) ) <nl> + { <nl> + CCAssert ( minusSprite , " Minus sprite must be not nil " ) ; <nl> + CCAssert ( plusSprite , " Plus sprite must be not nil " ) ; <nl> + <nl> + setTouchEnabled ( true ) ; <nl> + <nl> + / / Set the default values <nl> + m_bAutorepeat = true ; <nl> + m_bContinuous = true ; <nl> + m_dMinimumValue = 0 ; <nl> + m_dMaximumValue = 100 ; <nl> + m_dValue = 0 ; <nl> + m_dStepValue = 1 ; <nl> + m_bWraps = false ; <nl> + this - > ignoreAnchorPointForPosition ( false ) ; <nl> + <nl> + / / Add the minus components <nl> + this - > setMinusSprite ( minusSprite ) ; <nl> + m_pMinusSprite - > setPosition ( ccp ( minusSprite - > getContentSize ( ) . width / 2 , minusSprite - > getContentSize ( ) . height / 2 ) ) ; <nl> + this - > addChild ( m_pMinusSprite ) ; <nl> + <nl> + this - > setMinusLabel ( CCLabelTTF : : create ( " - " , CCControlStepperLabelFont , 40 ) ) ; <nl> + m_pMinusLabel - > setColor ( CCControlStepperLabelColorDisabled ) ; <nl> + m_pMinusLabel - > setPosition ( CCPointMake ( m_pMinusSprite - > getContentSize ( ) . width / 2 , m_pMinusSprite - > getContentSize ( ) . height / 2 ) ) ; <nl> + m_pMinusSprite - > addChild ( m_pMinusLabel ) ; <nl> + <nl> + / / Add the plus components <nl> + this - > setPlusSprite ( plusSprite ) ; <nl> + m_pPlusSprite - > setPosition ( ccp ( minusSprite - > getContentSize ( ) . width + plusSprite - > getContentSize ( ) . width / 2 , <nl> + minusSprite - > getContentSize ( ) . height / 2 ) ) ; <nl> + this - > addChild ( m_pPlusSprite ) ; <nl> + <nl> + this - > setPlusLabel ( CCLabelTTF : : create ( " + " , CCControlStepperLabelFont , 40 ) ) ; <nl> + m_pPlusLabel - > setColor ( CCControlStepperLabelColorEnabled ) ; <nl> + m_pPlusLabel - > setPosition ( CCPointMake ( m_pPlusSprite - > getContentSize ( ) . width / 2 , m_pPlusSprite - > getContentSize ( ) . height / 2 ) ) ; <nl> + m_pPlusSprite - > addChild ( m_pPlusLabel ) ; <nl> + <nl> + / / Defines the content size <nl> + CCRect maxRect = CCControlUtils : : CCRectUnion ( m_pMinusSprite - > boundingBox ( ) , m_pPlusSprite - > boundingBox ( ) ) ; <nl> + this - > setContentSize ( CCSizeMake ( m_pMinusSprite - > getContentSize ( ) . width + m_pPlusSprite - > getContentSize ( ) . height , maxRect . size . height ) ) ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + CCControlStepper * CCControlStepper : : create ( CCSprite * minusSprite , CCSprite * plusSprite ) <nl> + { <nl> + CCControlStepper * pRet = new CCControlStepper ( ) ; <nl> + if ( pRet ! = NULL & & pRet - > initWithMinusSpriteAndPlusSprite ( minusSprite , plusSprite ) ) <nl> + { <nl> + pRet - > autorelease ( ) ; <nl> + } <nl> + else <nl> + { <nl> + CC_SAFE_DELETE ( pRet ) ; <nl> + } <nl> + return pRet ; <nl> + } <nl> + <nl> + / / # pragma mark Properties <nl> + <nl> + void CCControlStepper : : setWraps ( bool wraps ) <nl> + { <nl> + m_bWraps = wraps ; <nl> + <nl> + if ( m_bWraps ) <nl> + { <nl> + m_pMinusLabel - > setColor ( CCControlStepperLabelColorEnabled ) ; <nl> + m_pPlusLabel - > setColor ( CCControlStepperLabelColorEnabled ) ; <nl> + } <nl> + <nl> + this - > setValue ( m_dValue ) ; <nl> + } <nl> + <nl> + void CCControlStepper : : setMinimumValue ( double minimumValue ) <nl> + { <nl> + if ( minimumValue > = m_dMaximumValue ) <nl> + { <nl> + CCAssert ( 0 , " Must be numerically less than maximumValue . " ) ; <nl> + } <nl> + <nl> + m_dMinimumValue = minimumValue ; <nl> + this - > setValue ( m_dValue ) ; <nl> + } <nl> + <nl> + void CCControlStepper : : setMaximumValue ( double maximumValue ) <nl> + { <nl> + if ( maximumValue < = m_dMinimumValue ) <nl> + { <nl> + CCAssert ( 0 , " Must be numerically greater than minimumValue . " ) ; <nl> + } <nl> + <nl> + m_dMaximumValue = maximumValue ; <nl> + this - > setValue ( m_dValue ) ; <nl> + } <nl> + <nl> + void CCControlStepper : : setValue ( double value ) <nl> + { <nl> + this - > setValueWithSendingEvent ( value , true ) ; <nl> + } <nl> + <nl> + double CCControlStepper : : getValue ( ) <nl> + { <nl> + return m_dValue ; <nl> + } <nl> + <nl> + void CCControlStepper : : setStepValue ( double stepValue ) <nl> + { <nl> + if ( stepValue < = 0 ) <nl> + { <nl> + CCAssert ( 0 , " Must be numerically greater than 0 . " ) ; <nl> + } <nl> + <nl> + m_dStepValue = stepValue ; <nl> + } <nl> + <nl> + bool CCControlStepper : : isContinuous ( ) <nl> + { <nl> + return m_bContinuous ; <nl> + } <nl> + / / # pragma mark - <nl> + / / # pragma mark CCControlStepper Public Methods <nl> + <nl> + void CCControlStepper : : setValueWithSendingEvent ( double value , bool send ) <nl> + { <nl> + if ( value < m_dMinimumValue ) <nl> + { <nl> + value = m_bWraps ? m_dMaximumValue : m_dMinimumValue ; <nl> + } else if ( value > m_dMaximumValue ) <nl> + { <nl> + value = m_bWraps ? m_dMinimumValue : m_dMaximumValue ; <nl> + } <nl> + <nl> + m_dValue = value ; <nl> + <nl> + if ( ! m_bWraps ) <nl> + { <nl> + m_pMinusLabel - > setColor ( ( value = = m_dMinimumValue ) ? CCControlStepperLabelColorDisabled : CCControlStepperLabelColorEnabled ) ; <nl> + m_pPlusLabel - > setColor ( ( value = = m_dMaximumValue ) ? CCControlStepperLabelColorDisabled : CCControlStepperLabelColorEnabled ) ; <nl> + } <nl> + <nl> + if ( send ) <nl> + { <nl> + this - > sendActionsForControlEvents ( CCControlEventValueChanged ) ; <nl> + } <nl> + } <nl> + <nl> + void CCControlStepper : : startAutorepeat ( ) <nl> + { <nl> + m_nAutorepeatCount = - 1 ; <nl> + <nl> + this - > schedule ( schedule_selector ( CCControlStepper : : update ) , kAutorepeatDeltaTime , kCCRepeatForever , kAutorepeatDeltaTime * 3 ) ; <nl> + } <nl> + <nl> + / * * Stop the autorepeat . * / <nl> + void CCControlStepper : : stopAutorepeat ( ) <nl> + { <nl> + this - > unschedule ( schedule_selector ( CCControlStepper : : update ) ) ; <nl> + } <nl> + <nl> + void CCControlStepper : : update ( float dt ) <nl> + { <nl> + m_nAutorepeatCount + + ; <nl> + <nl> + if ( ( m_nAutorepeatCount < kAutorepeatIncreaseTimeIncrement ) & & ( m_nAutorepeatCount % 3 ) ! = 0 ) <nl> + return ; <nl> + <nl> + if ( m_eTouchedPart = = kCCControlStepperPartMinus ) <nl> + { <nl> + this - > setValueWithSendingEvent ( m_dValue - m_dStepValue , m_bContinuous ) ; <nl> + } else if ( m_eTouchedPart = = kCCControlStepperPartPlus ) <nl> + { <nl> + this - > setValueWithSendingEvent ( m_dValue + m_dStepValue , m_bContinuous ) ; <nl> + } <nl> + } <nl> + <nl> + / / # pragma mark CCControlStepper Private Methods <nl> + <nl> + void CCControlStepper : : updateLayoutUsingTouchLocation ( CCPoint location ) <nl> + { <nl> + if ( location . x < m_pMinusSprite - > getContentSize ( ) . width <nl> + & & m_dValue > m_dMinimumValue ) <nl> + { <nl> + m_eTouchedPart = kCCControlStepperPartMinus ; <nl> + <nl> + m_pMinusSprite - > setColor ( ccGRAY ) ; <nl> + m_pPlusSprite - > setColor ( ccWHITE ) ; <nl> + } else if ( location . x > = m_pMinusSprite - > getContentSize ( ) . width <nl> + & & m_dValue < m_dMaximumValue ) <nl> + { <nl> + m_eTouchedPart = kCCControlStepperPartPlus ; <nl> + <nl> + m_pMinusSprite - > setColor ( ccWHITE ) ; <nl> + m_pPlusSprite - > setColor ( ccGRAY ) ; <nl> + } else <nl> + { <nl> + m_eTouchedPart = kCCControlStepperPartNone ; <nl> + <nl> + m_pMinusSprite - > setColor ( ccWHITE ) ; <nl> + m_pPlusSprite - > setColor ( ccWHITE ) ; <nl> + } <nl> + } <nl> + <nl> + <nl> + bool CCControlStepper : : ccTouchBegan ( CCTouch * pTouch , CCEvent * pEvent ) <nl> + { <nl> + if ( ! this - > isTouchInside ( pTouch ) <nl> + | | ! this - > isEnabled ( ) ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + CCPoint location = this - > getTouchLocation ( pTouch ) ; <nl> + this - > updateLayoutUsingTouchLocation ( location ) ; <nl> + <nl> + m_bTouchInsideFlag = true ; <nl> + <nl> + if ( m_bAutorepeat ) <nl> + { <nl> + this - > startAutorepeat ( ) ; <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + void CCControlStepper : : ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) <nl> + { <nl> + if ( this - > isTouchInside ( pTouch ) ) <nl> + { <nl> + CCPoint location = this - > getTouchLocation ( pTouch ) ; <nl> + this - > updateLayoutUsingTouchLocation ( location ) ; <nl> + <nl> + if ( ! m_bTouchInsideFlag ) <nl> + { <nl> + m_bTouchInsideFlag = true ; <nl> + <nl> + if ( m_bAutorepeat ) <nl> + { <nl> + this - > startAutorepeat ( ) ; <nl> + } <nl> + } <nl> + } else <nl> + { <nl> + m_bTouchInsideFlag = false ; <nl> + <nl> + m_eTouchedPart = kCCControlStepperPartNone ; <nl> + <nl> + m_pMinusSprite - > setColor ( ccWHITE ) ; <nl> + m_pPlusSprite - > setColor ( ccWHITE ) ; <nl> + <nl> + if ( m_bAutorepeat ) <nl> + { <nl> + this - > stopAutorepeat ( ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + void CCControlStepper : : ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) <nl> + { <nl> + m_pMinusSprite - > setColor ( ccWHITE ) ; <nl> + m_pPlusSprite - > setColor ( ccWHITE ) ; <nl> + <nl> + if ( m_bAutorepeat ) <nl> + { <nl> + this - > stopAutorepeat ( ) ; <nl> + } <nl> + <nl> + if ( this - > isTouchInside ( pTouch ) ) <nl> + { <nl> + CCPoint location = this - > getTouchLocation ( pTouch ) ; <nl> + <nl> + this - > setValue ( m_dValue + ( ( location . x < m_pMinusSprite - > getContentSize ( ) . width ) ? ( 0 . 0 - m_dStepValue ) : m_dStepValue ) ) ; <nl> + } <nl> + } <nl> + <nl> + NS_CC_EXT_END <nl> new file mode 100644 <nl> index 000000000000 . . 01e763286af3 <nl> mmm / dev / null <nl> ppp b / extensions / GUI / CCControlExtension / CCControlStepper . h <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> + * Copyright 2012 Yannick Loriot . All rights reserved . <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # ifndef __CCCONTROLSTEPPER_H__ <nl> + # define __CCCONTROLSTEPPER_H__ <nl> + <nl> + # include " CCControl . h " <nl> + <nl> + NS_CC_EXT_BEGIN <nl> + <nl> + / * * <nl> + * @ addtogroup GUI <nl> + * @ { <nl> + * @ addtogroup control_extension <nl> + * @ { <nl> + * / <nl> + <nl> + typedef enum <nl> + { <nl> + kCCControlStepperPartMinus , <nl> + kCCControlStepperPartPlus , <nl> + kCCControlStepperPartNone , <nl> + } CCControlStepperPart ; <nl> + <nl> + class CCControlStepper : public CCControl <nl> + { <nl> + public : <nl> + CCControlStepper ( ) ; <nl> + virtual ~ CCControlStepper ( ) ; <nl> + <nl> + bool initWithMinusSpriteAndPlusSprite ( CCSprite * minusSprite , CCSprite * plusSprite ) ; <nl> + static CCControlStepper * create ( CCSprite * minusSprite , CCSprite * plusSprite ) ; <nl> + virtual void setWraps ( bool wraps ) ; <nl> + virtual void setMinimumValue ( double minimumValue ) ; <nl> + virtual void setMaximumValue ( double maximumValue ) ; <nl> + virtual void setValue ( double value ) ; <nl> + virtual double getValue ( ) ; <nl> + virtual void setStepValue ( double stepValue ) ; <nl> + virtual void setValueWithSendingEvent ( double value , bool send ) ; <nl> + virtual bool isContinuous ( ) ; <nl> + void update ( float dt ) ; <nl> + <nl> + / / events <nl> + virtual bool ccTouchBegan ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> + virtual void ccTouchMoved ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> + virtual void ccTouchEnded ( CCTouch * pTouch , CCEvent * pEvent ) ; <nl> + <nl> + protected : <nl> + / / Weak links to children <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_pMinusSprite , MinusSprite ) <nl> + CC_SYNTHESIZE_RETAIN ( CCSprite * , m_pPlusSprite , PlusSprite ) <nl> + CC_SYNTHESIZE_RETAIN ( CCLabelTTF * , m_pMinusLabel , MinusLabel ) <nl> + CC_SYNTHESIZE_RETAIN ( CCLabelTTF * , m_pPlusLabel , PlusLabel ) <nl> + <nl> + / * * Update the layout of the stepper with the given touch location . * / <nl> + void updateLayoutUsingTouchLocation ( CCPoint location ) ; <nl> + <nl> + / * * Set the numeric value of the stepper . If send is true , the CCControlEventValueChanged is sent . * / <nl> + void setValue ( double value , bool send ) ; <nl> + <nl> + / * * Start the autorepeat increment / decrement . * / <nl> + void startAutorepeat ( ) ; <nl> + <nl> + / * * Stop the autorepeat . * / <nl> + void stopAutorepeat ( ) ; <nl> + <nl> + / * * The numeric value of the stepper . * / <nl> + double m_dValue ; <nl> + / * * The continuous vs . noncontinuous state of the stepper . * / <nl> + bool m_bContinuous ; <nl> + / * * The automatic vs . nonautomatic repeat state of the stepper . * / <nl> + bool m_bAutorepeat ; <nl> + / * * The wrap vs . no - wrap state of the stepper . * / <nl> + bool m_bWraps ; <nl> + / * * The lowest possible numeric value for the stepper . * / <nl> + double m_dMinimumValue ; <nl> + / * * The highest possible numeric value for the stepper . * / <nl> + double m_dMaximumValue ; <nl> + / * * The step , or increment , value for the stepper . * / <nl> + double m_dStepValue ; <nl> + bool m_bTouchInsideFlag ; <nl> + CCControlStepperPart m_eTouchedPart ; <nl> + int m_nAutorepeatCount ; <nl> + } ; <nl> + <nl> + / / end of GUI group <nl> + / / / @ } <nl> + / / / @ } <nl> + <nl> + NS_CC_EXT_END <nl> + <nl> + # endif / * __CCCONTROLSTEPPER_H__ * / <nl> mmm a / extensions / GUI / CCControlExtension / CCControlSwitch . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlSwitch . cpp <nl> <nl> / * <nl> - * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> * Copyright 2012 Yannick Loriot . All rights reserved . <nl> * http : / / yannickloriot . com <nl> * <nl> float CCControlSwitchSprite : : offSideWidth ( ) <nl> / / CCControlSwitch <nl> <nl> CCControlSwitch : : CCControlSwitch ( ) <nl> + : m_pSwitchSprite ( NULL ) <nl> + , m_fInitialTouchXPosition ( 0 . 0f ) <nl> + , m_bMoved ( false ) <nl> + , m_bOn ( false ) <nl> { <nl> <nl> } <nl> void CCControlSwitch : : setOn ( bool isOn , bool animated ) <nl> void CCControlSwitch : : setEnabled ( bool enabled ) <nl> { <nl> m_bEnabled = enabled ; <nl> - <nl> - m_pSwitchSprite - > setOpacity ( ( enabled ) ? 255 : 128 ) ; <nl> + if ( m_pSwitchSprite ! = NULL ) <nl> + { <nl> + m_pSwitchSprite - > setOpacity ( ( enabled ) ? 255 : 128 ) ; <nl> + } <nl> } <nl> <nl> CCPoint CCControlSwitch : : locationFromTouch ( CCTouch * pTouch ) <nl> mmm a / extensions / GUI / CCControlExtension / CCControlSwitch . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlSwitch . h <nl> <nl> / * <nl> - * CCControlSwitch . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> * <nl> * Copyright 2012 Yannick Loriot . All rights reserved . <nl> * http : / / yannickloriot . com <nl> mmm a / extensions / GUI / CCControlExtension / CCControlUtils . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCControlUtils . cpp <nl> <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> + Copyright ( c ) 2012 cocos2d - x . org <nl> + <nl> + http : / / www . cocos2d - x . org <nl> + <nl> + Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + of this software and associated documentation files ( the " Software " ) , to deal <nl> + in the Software without restriction , including without limitation the rights <nl> + to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + copies of the Software , and to permit persons to whom the Software is <nl> + furnished to do so , subject to the following conditions : <nl> + <nl> + The above copyright notice and this permission notice shall be included in <nl> + all copies or substantial portions of the Software . <nl> + <nl> + THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + THE SOFTWARE . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> # include " CCControlUtils . h " <nl> # include " support / CCPointExtension . h " <nl> <nl> mmm a / extensions / GUI / CCControlExtension / CCControlUtils . h <nl> ppp b / extensions / GUI / CCControlExtension / CCControlUtils . h <nl> <nl> / * <nl> - * ColourUtils . h <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> * <nl> * Copyright 2012 Stewart Hamilton - Arrandale . <nl> * http : / / creativewax . co . uk <nl> mmm a / extensions / GUI / CCControlExtension / CCInvocation . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCInvocation . cpp <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * <nl> + * Converted to c + + / cocos2d - x by Angus C <nl> + * / <nl> + <nl> # include " CCInvocation . h " <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> + CCInvocation * CCInvocation : : create ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) <nl> + { <nl> + CCInvocation * pRet = new CCInvocation ( target , action , controlEvent ) ; <nl> + if ( pRet ! = NULL ) <nl> + { <nl> + pRet - > autorelease ( ) ; <nl> + } <nl> + return pRet ; <nl> + } <nl> + <nl> CCInvocation : : CCInvocation ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) <nl> { <nl> m_target = target ; <nl> mmm a / extensions / GUI / CCControlExtension / CCInvocation . h <nl> ppp b / extensions / GUI / CCControlExtension / CCInvocation . h <nl> <nl> - / * <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * http : / / www . cocos2d - x . org <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * <nl> + * Converted to c + + / cocos2d - x by Angus C <nl> + * / <nl> + / * <nl> * <nl> * Helper class to store targets and selectors ( and eventually , params ? ) in the same CCMutableArray . Basically a very crude form of a NSInvocation <nl> * / <nl> class CCInvocation : public CCObject <nl> CC_SYNTHESIZE_READONLY ( CCControlEvent , m_controlEvent , ControlEvent ) ; <nl> <nl> public : <nl> + static CCInvocation * create ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) ; <nl> CCInvocation ( CCObject * target , SEL_CCControlHandler action , CCControlEvent controlEvent ) ; <nl> <nl> void invoke ( CCObject * sender ) ; <nl> deleted file mode 100644 <nl> index 24592b9403b8 . . 000000000000 <nl> mmm a / extensions / GUI / CCControlExtension / CCMenuPassive . cpp <nl> ppp / dev / null <nl> <nl> - # include " CCMenuPassive . h " <nl> - # include " CCDirector . h " <nl> - # include " support / CCPointExtension . h " <nl> - # include " menu_nodes / CCMenuItem . h " <nl> - # include < vector > <nl> - <nl> - using namespace std ; <nl> - <nl> - NS_CC_EXT_BEGIN <nl> - <nl> - enum <nl> - { <nl> - kDefaultPadding = 5 , <nl> - } ; <nl> - <nl> - / / <nl> - / / CCMenu <nl> - / / <nl> - CCMenuPassive * CCMenuPassive : : node ( ) <nl> - { <nl> - return CCMenuPassive : : create ( ) ; <nl> - } <nl> - <nl> - CCMenuPassive * CCMenuPassive : : create ( ) <nl> - { <nl> - return create ( NULL , NULL ) ; <nl> - } <nl> - <nl> - CCMenuPassive * CCMenuPassive : : menuWithItems ( CCNode * item , . . . ) <nl> - { <nl> - va_list args ; <nl> - va_start ( args , item ) ; <nl> - CCMenuPassive * pRet = new CCMenuPassive ( ) ; <nl> - if ( pRet & & pRet - > initWithItems ( item , args ) ) <nl> - { <nl> - pRet - > autorelease ( ) ; <nl> - va_end ( args ) ; <nl> - return pRet ; <nl> - } <nl> - va_end ( args ) ; <nl> - CC_SAFE_DELETE ( pRet ) ; <nl> - return NULL ; <nl> - } <nl> - <nl> - CCMenuPassive * CCMenuPassive : : create ( CCNode * item , . . . ) <nl> - { <nl> - va_list args ; <nl> - va_start ( args , item ) ; <nl> - CCMenuPassive * pRet = new CCMenuPassive ( ) ; <nl> - if ( pRet & & pRet - > initWithItems ( item , args ) ) <nl> - { <nl> - pRet - > autorelease ( ) ; <nl> - va_end ( args ) ; <nl> - return pRet ; <nl> - } <nl> - va_end ( args ) ; <nl> - CC_SAFE_DELETE ( pRet ) ; <nl> - return NULL ; <nl> - } <nl> - <nl> - CCMenuPassive * CCMenuPassive : : menuWithItem ( CCNode * item ) <nl> - { <nl> - return CCMenuPassive : : createWithItem ( item ) ; <nl> - } <nl> - <nl> - CCMenuPassive * CCMenuPassive : : createWithItem ( CCNode * item ) <nl> - { <nl> - return create ( item , NULL ) ; <nl> - } <nl> - <nl> - bool CCMenuPassive : : initWithItems ( CCNode * item , va_list args ) <nl> - { <nl> - if ( CCLayer : : init ( ) ) <nl> - { <nl> - / / this - > m_bIsTouchEnabled = false ; <nl> - <nl> - / / menu in the center of the screen <nl> - CCSize s = CCDirector : : sharedDirector ( ) - > getWinSize ( ) ; <nl> - <nl> - / / Set the default anchor point <nl> - ignoreAnchorPointForPosition ( true ) ; <nl> - setAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> - this - > setContentSize ( s ) ; <nl> - <nl> - setPosition ( ccp ( s . width / 2 , s . height / 2 ) ) ; <nl> - <nl> - int z = 0 ; <nl> - <nl> - if ( item ) <nl> - { <nl> - this - > addChild ( item , z ) ; <nl> - CCMenuItem * i = va_arg ( args , CCMenuItem * ) ; <nl> - while ( i ) <nl> - { <nl> - z + + ; <nl> - this - > addChild ( i , z ) ; <nl> - i = va_arg ( args , CCMenuItem * ) ; <nl> - } <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> - <nl> - return false ; <nl> - } <nl> - <nl> - <nl> - / / Menu - Alignment <nl> - void CCMenuPassive : : alignItemsVertically ( ) <nl> - { <nl> - this - > alignItemsVerticallyWithPadding ( kDefaultPadding ) ; <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsVerticallyWithPadding ( float padding ) <nl> - { <nl> - float height = - padding ; <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - height + = pChild - > getContentSize ( ) . height * pChild - > getScaleY ( ) + padding ; <nl> - } <nl> - } <nl> - } <nl> - float width = 0 ; <nl> - float y = height / 2 . 0f ; <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - width = max ( width , pChild - > getContentSize ( ) . width ) ; <nl> - pChild - > setPosition ( ccp ( 0 , y - pChild - > getContentSize ( ) . height * pChild - > getScaleY ( ) / 2 . 0f ) ) ; <nl> - y - = pChild - > getContentSize ( ) . height * pChild - > getScaleY ( ) + padding ; <nl> - } <nl> - } <nl> - } <nl> - setContentSize ( CCSizeMake ( width , height ) ) ; <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsHorizontally ( void ) <nl> - { <nl> - this - > alignItemsHorizontallyWithPadding ( kDefaultPadding ) ; <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsHorizontallyWithPadding ( float padding ) <nl> - { <nl> - <nl> - float width = - padding ; <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - width + = pChild - > getContentSize ( ) . width * pChild - > getScaleX ( ) + padding ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - float height = 0 ; <nl> - float x = - width / 2 . 0f ; <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - height = max ( height , pChild - > getContentSize ( ) . height ) ; <nl> - pChild - > setPosition ( ccp ( x + pChild - > getContentSize ( ) . width * pChild - > getScaleX ( ) / 2 . 0f , 0 ) ) ; <nl> - x + = pChild - > getContentSize ( ) . width * pChild - > getScaleX ( ) + padding ; <nl> - } <nl> - } <nl> - } <nl> - setContentSize ( CCSizeMake ( width , height ) ) ; <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsInColumns ( unsigned int columns , . . . ) <nl> - { <nl> - va_list args ; <nl> - va_start ( args , columns ) ; <nl> - <nl> - this - > alignItemsInColumns ( columns , args ) ; <nl> - <nl> - va_end ( args ) ; <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsInColumns ( unsigned int columns , va_list args ) <nl> - { <nl> - vector < unsigned int > rows ; <nl> - while ( columns ) <nl> - { <nl> - rows . push_back ( columns ) ; <nl> - columns = va_arg ( args , unsigned int ) ; <nl> - } <nl> - <nl> - int height = - 5 ; <nl> - unsigned int row = 0 ; <nl> - unsigned int rowHeight = 0 ; <nl> - unsigned int columnsOccupied = 0 ; <nl> - unsigned int rowColumns ; <nl> - <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - CCAssert ( row < rows . size ( ) , " " ) ; <nl> - <nl> - rowColumns = rows [ row ] ; <nl> - / / can not have zero columns on a row <nl> - CCAssert ( rowColumns , " " ) ; <nl> - <nl> - float tmp = pChild - > getContentSize ( ) . height ; <nl> - rowHeight = ( unsigned int ) ( ( rowHeight > = tmp | | isnan ( tmp ) ) ? rowHeight : tmp ) ; <nl> - <nl> - + + columnsOccupied ; <nl> - if ( columnsOccupied > = rowColumns ) <nl> - { <nl> - height + = rowHeight + 5 ; <nl> - <nl> - columnsOccupied = 0 ; <nl> - rowHeight = 0 ; <nl> - + + row ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / check if too many rows / columns for available menu items <nl> - CCAssert ( ! columnsOccupied , " " ) ; <nl> - <nl> - CCSize winSize = CCDirector : : sharedDirector ( ) - > getWinSize ( ) ; <nl> - <nl> - row = 0 ; <nl> - rowHeight = 0 ; <nl> - rowColumns = 0 ; <nl> - float w = 0 . 0 ; <nl> - float x = 0 . 0 ; <nl> - float y = ( float ) ( height / 2 ) ; <nl> - <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - if ( rowColumns = = 0 ) <nl> - { <nl> - rowColumns = rows [ row ] ; <nl> - w = winSize . width / ( 1 + rowColumns ) ; <nl> - x = w ; <nl> - } <nl> - <nl> - float tmp = pChild - > getContentSize ( ) . height ; <nl> - rowHeight = ( unsigned int ) ( ( rowHeight > = tmp | | isnan ( tmp ) ) ? rowHeight : tmp ) ; <nl> - <nl> - pChild - > setPosition ( ccp ( x - winSize . width / 2 , <nl> - y - pChild - > getContentSize ( ) . height / 2 ) ) ; <nl> - <nl> - x + = w ; <nl> - + + columnsOccupied ; <nl> - <nl> - if ( columnsOccupied > = rowColumns ) <nl> - { <nl> - y - = rowHeight + 5 ; <nl> - <nl> - columnsOccupied = 0 ; <nl> - rowColumns = 0 ; <nl> - rowHeight = 0 ; <nl> - + + row ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsInRows ( unsigned int rows , . . . ) <nl> - { <nl> - va_list args ; <nl> - va_start ( args , rows ) ; <nl> - <nl> - this - > alignItemsInRows ( rows , args ) ; <nl> - <nl> - va_end ( args ) ; <nl> - } <nl> - <nl> - void CCMenuPassive : : alignItemsInRows ( unsigned int rows , va_list args ) <nl> - { <nl> - vector < unsigned int > columns ; <nl> - while ( rows ) <nl> - { <nl> - columns . push_back ( rows ) ; <nl> - rows = va_arg ( args , unsigned int ) ; <nl> - } <nl> - <nl> - vector < unsigned int > columnWidths ; <nl> - vector < unsigned int > columnHeights ; <nl> - <nl> - int width = - 10 ; <nl> - int columnHeight = - 5 ; <nl> - unsigned int column = 0 ; <nl> - unsigned int columnWidth = 0 ; <nl> - unsigned int rowsOccupied = 0 ; <nl> - unsigned int columnRows ; <nl> - <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - / / check if too many menu items for the amount of rows / columns <nl> - CCAssert ( column < columns . size ( ) , " " ) ; <nl> - <nl> - columnRows = columns [ column ] ; <nl> - / / can ' t have zero rows on a column <nl> - CCAssert ( columnRows , " " ) ; <nl> - <nl> - / / columnWidth = fmaxf ( columnWidth , [ item contentSize ] . width ) ; <nl> - float tmp = pChild - > getContentSize ( ) . width ; <nl> - columnWidth = ( unsigned int ) ( ( columnWidth > = tmp | | isnan ( tmp ) ) ? columnWidth : tmp ) ; <nl> - <nl> - columnHeight + = ( int ) ( pChild - > getContentSize ( ) . height + 5 ) ; <nl> - + + rowsOccupied ; <nl> - <nl> - if ( rowsOccupied > = columnRows ) <nl> - { <nl> - columnWidths . push_back ( columnWidth ) ; <nl> - columnHeights . push_back ( columnHeight ) ; <nl> - width + = columnWidth + 10 ; <nl> - <nl> - rowsOccupied = 0 ; <nl> - columnWidth = 0 ; <nl> - columnHeight = - 5 ; <nl> - + + column ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / check if too many rows / columns for available menu items . <nl> - CCAssert ( ! rowsOccupied , " " ) ; <nl> - <nl> - CCSize winSize = CCDirector : : sharedDirector ( ) - > getWinSize ( ) ; <nl> - <nl> - column = 0 ; <nl> - columnWidth = 0 ; <nl> - columnRows = 0 ; <nl> - float x = ( float ) ( - width / 2 ) ; <nl> - float y = 0 . 0 ; <nl> - <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - if ( columnRows = = 0 ) <nl> - { <nl> - columnRows = columns [ column ] ; <nl> - y = ( float ) columnHeights [ column ] ; <nl> - } <nl> - <nl> - / / columnWidth = fmaxf ( columnWidth , [ item contentSize ] . width ) ; <nl> - float tmp = pChild - > getContentSize ( ) . width ; <nl> - columnWidth = ( unsigned int ) ( ( columnWidth > = tmp | | isnan ( tmp ) ) ? columnWidth : tmp ) ; <nl> - <nl> - pChild - > setPosition ( ccp ( x + columnWidths [ column ] / 2 , <nl> - y - winSize . height / 2 ) ) ; <nl> - <nl> - y - = pChild - > getContentSize ( ) . height + 10 ; <nl> - + + rowsOccupied ; <nl> - <nl> - if ( rowsOccupied > = columnRows ) <nl> - { <nl> - x + = columnWidth + 5 ; <nl> - rowsOccupied = 0 ; <nl> - columnRows = 0 ; <nl> - columnWidth = 0 ; <nl> - + + column ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / Opacity Protocol <nl> - <nl> - / * * Override synthesized setOpacity to recurse items * / <nl> - void CCMenuPassive : : setOpacity ( GLubyte var ) <nl> - { <nl> - m_cOpacity = var ; <nl> - <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - CCRGBAProtocol * pRGBAProtocol = dynamic_cast < CCRGBAProtocol * > ( pChild ) ; <nl> - if ( pRGBAProtocol ) <nl> - { <nl> - pRGBAProtocol - > setOpacity ( m_cOpacity ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - GLubyte CCMenuPassive : : getOpacity ( void ) <nl> - { <nl> - return m_cOpacity ; <nl> - } <nl> - <nl> - void CCMenuPassive : : setColor ( const ccColor3B & var ) <nl> - { <nl> - m_tColor = var ; <nl> - <nl> - if ( m_pChildren & & m_pChildren - > count ( ) > 0 ) <nl> - { <nl> - CCObject * pObject = NULL ; <nl> - CCARRAY_FOREACH ( m_pChildren , pObject ) <nl> - { <nl> - CCNode * pChild = dynamic_cast < CCNode * > ( pObject ) ; <nl> - if ( pChild ) <nl> - { <nl> - CCRGBAProtocol * pRGBAProtocol = dynamic_cast < CCRGBAProtocol * > ( pChild ) ; <nl> - if ( pRGBAProtocol ) <nl> - { <nl> - pRGBAProtocol - > setColor ( m_tColor ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - const ccColor3B & CCMenuPassive : : getColor ( void ) <nl> - { <nl> - return m_tColor ; <nl> - } <nl> - <nl> - NS_CC_EXT_END <nl> deleted file mode 100644 <nl> index c72591019f20 . . 000000000000 <nl> mmm a / extensions / GUI / CCControlExtension / CCMenuPassive . h <nl> ppp / dev / null <nl> <nl> - / * <nl> - * <nl> - * A menu that does not send any events , it ' s simply a passive container ( lets the contents do their own thing ) of CCNodes <nl> - * / <nl> - # ifndef __CCMENU_PASSIVE_H__ <nl> - # define __CCMENU_PASSIVE_H__ <nl> - <nl> - # include " CCControl . h " <nl> - <nl> - NS_CC_EXT_BEGIN <nl> - <nl> - / * * <nl> - * @ addtogroup GUI <nl> - * @ { <nl> - * @ addtogroup control_extension <nl> - * @ { <nl> - * / <nl> - <nl> - class CCMenuPassive : public CCLayer , public CCRGBAProtocol <nl> - { <nl> - / * * Color : conforms with CCRGBAProtocol protocol * / <nl> - CC_PROPERTY_PASS_BY_REF ( ccColor3B , m_tColor , Color ) ; <nl> - / * * Opacity : conforms with CCRGBAProtocol protocol * / <nl> - CC_PROPERTY ( GLubyte , m_cOpacity , Opacity ) ; <nl> - <nl> - public : <nl> - / * * creates an empty CCMenu <nl> - @ deprecated : This interface will be deprecated sooner or later . <nl> - * / <nl> - CC_DEPRECATED_ATTRIBUTE static CCMenuPassive * node ( ) ; <nl> - <nl> - / * * creates a CCMenu with it ' s items <nl> - @ deprecated : This interface will be deprecated sooner or later . <nl> - * / <nl> - CC_DEPRECATED_ATTRIBUTE static CCMenuPassive * menuWithItems ( CCNode * item , . . . ) ; <nl> - <nl> - / * * creates a CCMenu with it ' s item , then use addChild ( ) to add <nl> - * other items . It is used for script , it can ' t init with undetermined <nl> - * number of variables . <nl> - @ deprecated : This interface will be deprecated sooner or later . <nl> - * / <nl> - CC_DEPRECATED_ATTRIBUTE static CCMenuPassive * menuWithItem ( CCNode * item ) ; <nl> - <nl> - / * * creates an empty CCMenu * / <nl> - static CCMenuPassive * create ( ) ; <nl> - <nl> - / * * creates a CCMenu with it ' s items * / <nl> - static CCMenuPassive * create ( CCNode * item , . . . ) ; <nl> - <nl> - / * * creates a CCMenu with it ' s item , then use addChild ( ) to add <nl> - * other items . It is used for script , it can ' t init with undetermined <nl> - * number of variables . <nl> - * / <nl> - static CCMenuPassive * createWithItem ( CCNode * item ) ; <nl> - <nl> - / * * initializes a CCMenu with it ' s items * / <nl> - bool initWithItems ( CCNode * item , va_list args ) ; <nl> - <nl> - / * * align items vertically * / <nl> - void alignItemsVertically ( ) ; <nl> - / * * align items vertically with padding <nl> - @ since v0 . 7 . 2 <nl> - * / <nl> - void alignItemsVerticallyWithPadding ( float padding ) ; <nl> - <nl> - / * * align items horizontally * / <nl> - void alignItemsHorizontally ( ) ; <nl> - / * * align items horizontally with padding <nl> - @ since v0 . 7 . 2 <nl> - * / <nl> - void alignItemsHorizontallyWithPadding ( float padding ) ; <nl> - <nl> - / * * align items in rows of columns * / <nl> - void alignItemsInColumns ( unsigned int columns , . . . ) ; <nl> - void alignItemsInColumns ( unsigned int columns , va_list args ) ; <nl> - <nl> - / * * align items in columns of rows * / <nl> - void alignItemsInRows ( unsigned int rows , . . . ) ; <nl> - void alignItemsInRows ( unsigned int rows , va_list args ) ; <nl> - <nl> - / / RGBA protocol <nl> - virtual void setOpacityModifyRGB ( bool bValue ) { CC_UNUSED_PARAM ( bValue ) ; } <nl> - virtual bool isOpacityModifyRGB ( void ) { return false ; } <nl> - } ; <nl> - <nl> - / / end of GUI group <nl> - / / / @ } <nl> - / / / @ } <nl> - <nl> - NS_CC_EXT_END <nl> - <nl> - # endif <nl> \ No newline at end of file <nl> mmm a / extensions / GUI / CCControlExtension / CCScale9Sprite . cpp <nl> ppp b / extensions / GUI / CCControlExtension / CCScale9Sprite . cpp <nl> <nl> - / / <nl> - / / CCScale9Sprite . cpp <nl> - / / PlantCaring <nl> - / / <nl> - / / Created by Jung Sang - Taik on 12 . 3 . 16 . . <nl> - / / Copyright ( c ) 2012 Neofect . All rights reserved . <nl> - / / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> + Copyright ( c ) 2012 cocos2d - x . org <nl> + <nl> + http : / / www . cocos2d - x . org <nl> + <nl> + Created by Jung Sang - Taik on 12 . 3 . 16 . . <nl> + Copyright ( c ) 2012 Neofect . All rights reserved . <nl> + <nl> + Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + of this software and associated documentation files ( the " Software " ) , to deal <nl> + in the Software without restriction , including without limitation the rights <nl> + to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + copies of the Software , and to permit persons to whom the Software is <nl> + furnished to do so , subject to the following conditions : <nl> + <nl> + The above copyright notice and this permission notice shall be included in <nl> + all copies or substantial portions of the Software . <nl> + <nl> + THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + THE SOFTWARE . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> # include " CCScale9Sprite . h " <nl> - # include " sprite_nodes / CCSpriteBatchNode . h " <nl> - # include " sprite_nodes / CCSpriteFrame . h " <nl> - # include " sprite_nodes / CCSpriteFrameCache . h " <nl> - # include " sprite_nodes / CCSprite . h " <nl> - # include " support / CCPointExtension . h " <nl> <nl> NS_CC_EXT_BEGIN <nl> <nl> + enum positions <nl> + { <nl> + pCentre = 0 , <nl> + pTop , <nl> + pLeft , <nl> + pRight , <nl> + pBottom , <nl> + pTopRight , <nl> + pTopLeft , <nl> + pBottomRight , <nl> + pBottomLeft <nl> + } ; <nl> + <nl> CCScale9Sprite : : CCScale9Sprite ( ) <nl> : m_insetLeft ( 0 ) <nl> , m_insetTop ( 0 ) <nl> , m_insetRight ( 0 ) <nl> , m_insetBottom ( 0 ) <nl> + , m_cOpacity ( 0 ) <nl> + , m_bSpritesGenerated ( false ) <nl> + , m_bSpriteFrameRotated ( false ) <nl> + , m_positionsAreDirty ( false ) <nl> + , scale9Image ( NULL ) <nl> + , topLeft ( NULL ) <nl> + , top ( NULL ) <nl> + , topRight ( NULL ) <nl> + , left ( NULL ) <nl> + , centre ( NULL ) <nl> + , right ( NULL ) <nl> + , bottomLeft ( NULL ) <nl> + , bottom ( NULL ) <nl> + , bottomRight ( NULL ) <nl> + , m_bIsOpacityModifyRGB ( false ) <nl> { <nl> <nl> } <nl> <nl> CCScale9Sprite : : ~ CCScale9Sprite ( ) <nl> { <nl> - <nl> + CC_SAFE_RELEASE ( topLeft ) ; <nl> + CC_SAFE_RELEASE ( top ) ; <nl> + CC_SAFE_RELEASE ( topRight ) ; <nl> + CC_SAFE_RELEASE ( left ) ; <nl> + CC_SAFE_RELEASE ( centre ) ; <nl> + CC_SAFE_RELEASE ( right ) ; <nl> + CC_SAFE_RELEASE ( bottomLeft ) ; <nl> + CC_SAFE_RELEASE ( bottom ) ; <nl> + CC_SAFE_RELEASE ( bottomRight ) ; <nl> + CC_SAFE_RELEASE ( scale9Image ) ; <nl> } <nl> <nl> bool CCScale9Sprite : : init ( ) <nl> bool CCScale9Sprite : : init ( ) <nl> } <nl> <nl> bool CCScale9Sprite : : initWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , CCRect capInsets ) <nl> + { <nl> + return this - > initWithBatchNode ( batchnode , rect , false , capInsets ) ; <nl> + } <nl> + <nl> + bool CCScale9Sprite : : initWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , bool rotated , CCRect capInsets ) <nl> { <nl> if ( batchnode ) <nl> { <nl> - this - > updateWithBatchNode ( batchnode , rect , capInsets ) ; <nl> + this - > updateWithBatchNode ( batchnode , rect , rotated , capInsets ) ; <nl> this - > setAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> } <nl> this - > m_positionsAreDirty = true ; <nl> bool CCScale9Sprite : : initWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect <nl> return true ; <nl> } <nl> <nl> - bool CCScale9Sprite : : updateWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , CCRect capInsets ) <nl> + bool CCScale9Sprite : : updateWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , bool rotated , CCRect capInsets ) <nl> { <nl> + GLubyte opacity = m_cOpacity ; <nl> + ccColor3B color = m_tColor ; <nl> + <nl> / / Release old sprites <nl> this - > removeAllChildrenWithCleanup ( true ) ; <nl> <nl> - / / TODO Is this needed ? <nl> - / * <nl> - if ( this - > topLeft ! = NULL ) <nl> - { <nl> - CC_SAFE_RELEASE ( this - > topLeft ) ; <nl> - CC_SAFE_RELEASE ( this - > top ) ; <nl> - CC_SAFE_RELEASE ( this - > topRight ) ; <nl> - CC_SAFE_RELEASE ( this - > left ) ; <nl> - CC_SAFE_RELEASE ( this - > centre ) ; <nl> - CC_SAFE_RELEASE ( this - > right ) ; <nl> - CC_SAFE_RELEASE ( this - > bottomLeft ) ; <nl> - CC_SAFE_RELEASE ( this - > bottom ) ; <nl> - CC_SAFE_RELEASE ( this - > bottomRight ) ; <nl> - } <nl> - * / <nl> + CC_SAFE_RELEASE ( this - > centre ) ; <nl> + CC_SAFE_RELEASE ( this - > top ) ; <nl> + CC_SAFE_RELEASE ( this - > topLeft ) ; <nl> + CC_SAFE_RELEASE ( this - > topRight ) ; <nl> + CC_SAFE_RELEASE ( this - > left ) ; <nl> + CC_SAFE_RELEASE ( this - > right ) ; <nl> + CC_SAFE_RELEASE ( this - > bottomLeft ) ; <nl> + CC_SAFE_RELEASE ( this - > bottom ) ; <nl> + CC_SAFE_RELEASE ( this - > bottomRight ) ; <nl> + <nl> <nl> if ( this - > scale9Image ! = batchnode ) <nl> { <nl> - / / TODO Is this needed ? <nl> - / * <nl> - if ( this - > scale9Image ! = NULL ) <nl> - { <nl> - CC_SAFE_RELEASE ( this - > scale9Image ) ; <nl> - } <nl> - * / <nl> - scale9Image = batchnode ; / / TODO No retain on purpose ? <nl> + CC_SAFE_RELEASE ( this - > scale9Image ) ; <nl> + scale9Image = batchnode ; <nl> + CC_SAFE_RETAIN ( scale9Image ) ; <nl> } <nl> <nl> scale9Image - > removeAllChildrenWithCleanup ( true ) ; <nl> bool CCScale9Sprite : : updateWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect re <nl> m_preferredSize = m_originalSize ; <nl> m_capInsetsInternal = capInsets ; <nl> <nl> - / / If there is no specified center region <nl> - if ( m_capInsetsInternal . equals ( CCRectZero ) ) <nl> - { <nl> - / / Apply the 3x3 grid format <nl> - m_capInsetsInternal = CCRectMake ( <nl> - rect . origin . x + m_originalSize . width / 3 , <nl> - rect . origin . y + m_originalSize . height / 3 , <nl> - m_originalSize . width / 3 , <nl> - m_originalSize . height / 3 ) ; <nl> - } <nl> - <nl> / / Get the image edges <nl> float l = rect . origin . x ; <nl> float t = rect . origin . y ; <nl> float h = rect . size . height ; <nl> float w = rect . size . width ; <nl> <nl> + / / If there is no specified center region <nl> + if ( m_capInsetsInternal . equals ( CCRectZero ) ) <nl> + { <nl> + / / Apply the 3x3 grid format <nl> + if ( rotated ) <nl> + { <nl> + m_capInsetsInternal = CCRectMake ( l + h / 3 , t + w / 3 , w / 3 , h / 3 ) ; <nl> + } <nl> + else <nl> + { <nl> + m_capInsetsInternal = CCRectMake ( l + w / 3 , t + h / 3 , w / 3 , h / 3 ) ; <nl> + } <nl> + } <nl> + <nl> / / <nl> / / Set up the image <nl> / / <nl> - <nl> - / / Centre <nl> - centre = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , m_capInsetsInternal ) ; <nl> - scale9Image - > addChild ( centre , 0 , pCentre ) ; <nl> - <nl> - / / Top <nl> - top = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x , <nl> - t , <nl> - m_capInsetsInternal . size . width , <nl> - m_capInsetsInternal . origin . y - t ) ) ; <nl> - scale9Image - > addChild ( top , 1 , pTop ) ; <nl> - <nl> - / / Bottom <nl> - bottom = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x , <nl> - m_capInsetsInternal . origin . y + m_capInsetsInternal . size . height , <nl> - m_capInsetsInternal . size . width , <nl> - h - ( m_capInsetsInternal . origin . y - t + m_capInsetsInternal . size . height ) ) ) ; <nl> - scale9Image - > addChild ( bottom , 1 , pBottom ) ; <nl> - <nl> - / / Left <nl> - left = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> - l , <nl> - m_capInsetsInternal . origin . y , <nl> - m_capInsetsInternal . origin . x - l , <nl> - m_capInsetsInternal . size . height ) ) ; <nl> - scale9Image - > addChild ( left , 1 , pLeft ) ; <nl> - <nl> - / / Right <nl> - right = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> - m_capInsetsInternal . origin . x + m_capInsetsInternal . size . width , <nl> - m_capInsetsInternal . origin . y , <nl> - w - ( m_capInsetsInternal . origin . x - l + m_capInsetsInternal . size . width ) , <nl> - m_capInsetsInternal . size . height ) ) ; <nl> - scale9Image - > addChild ( right , 1 , pRight ) ; <nl> - <nl> - / / Top left <nl> - topLeft = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> - l , <nl> - t , <nl> - m_capInsetsInternal . origin . x - l , <nl> - m_capInsetsInternal . origin . y - t ) ) ; <nl> - <nl> - scale9Image - > addChild ( topLeft , 2 , pTopLeft ) ; <nl> - <nl> - / / Top right <nl> - topRight = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> - m_capInsetsInternal . origin . x + m_capInsetsInternal . size . width , <nl> + if ( rotated ) <nl> + { <nl> + / / Sprite frame is rotated <nl> + <nl> + / / Centre <nl> + centre = new CCSprite ( ) ; <nl> + centre - > initWithTexture ( scale9Image - > getTexture ( ) , m_capInsetsInternal , true ) ; <nl> + scale9Image - > addChild ( centre , 0 , pCentre ) ; <nl> + <nl> + / / Bottom <nl> + bottom = new CCSprite ( ) ; <nl> + bottom - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( l , <nl> + m_capInsetsInternal . origin . y , <nl> + m_capInsetsInternal . size . width , <nl> + m_capInsetsInternal . origin . x - l ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( bottom , 1 , pBottom ) ; <nl> + <nl> + / / Top <nl> + top = new CCSprite ( ) ; <nl> + top - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x + m_capInsetsInternal . size . height , <nl> + m_capInsetsInternal . origin . y , <nl> + m_capInsetsInternal . size . width , <nl> + h - m_capInsetsInternal . size . height - ( m_capInsetsInternal . origin . x - l ) ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( top , 1 , pTop ) ; <nl> + <nl> + / / Right <nl> + right = new CCSprite ( ) ; <nl> + right - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x , <nl> + m_capInsetsInternal . origin . y + m_capInsetsInternal . size . width , <nl> + w - ( m_capInsetsInternal . origin . y - t ) - m_capInsetsInternal . size . width , <nl> + m_capInsetsInternal . size . height ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( right , 1 , pRight ) ; <nl> + <nl> + / / Left <nl> + left = new CCSprite ( ) ; <nl> + left - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x , <nl> t , <nl> - w - ( m_capInsetsInternal . origin . x - l + m_capInsetsInternal . size . width ) , <nl> - m_capInsetsInternal . origin . y - t ) ) ; <nl> - <nl> - scale9Image - > addChild ( topRight , 2 , pTopRight ) ; <nl> - <nl> - / / Bottom left <nl> - bottomLeft = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> - l , <nl> + m_capInsetsInternal . origin . y - t , <nl> + m_capInsetsInternal . size . height ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( left , 1 , pLeft ) ; <nl> + <nl> + / / Top right <nl> + topRight = new CCSprite ( ) ; <nl> + topRight - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x + m_capInsetsInternal . size . height , <nl> + m_capInsetsInternal . origin . y + m_capInsetsInternal . size . width , <nl> + w - ( m_capInsetsInternal . origin . y - t ) - m_capInsetsInternal . size . width , <nl> + h - m_capInsetsInternal . size . height - ( m_capInsetsInternal . origin . x - l ) ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( topRight , 2 , pTopRight ) ; <nl> + <nl> + / / Top left <nl> + topLeft = new CCSprite ( ) ; <nl> + topLeft - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x + m_capInsetsInternal . size . height , <nl> + t , <nl> + m_capInsetsInternal . origin . y - t , <nl> + h - m_capInsetsInternal . size . height - ( m_capInsetsInternal . origin . x - l ) ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( topLeft , 2 , pTopLeft ) ; <nl> + <nl> + / / Bottom right <nl> + bottomRight = new CCSprite ( ) ; <nl> + bottomRight - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( l , <nl> + m_capInsetsInternal . origin . y + m_capInsetsInternal . size . width , <nl> + w - ( m_capInsetsInternal . origin . y - t ) - m_capInsetsInternal . size . width , <nl> + m_capInsetsInternal . origin . x - l ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( bottomRight , 2 , pBottomRight ) ; <nl> + <nl> + / / Bottom left <nl> + bottomLeft = new CCSprite ( ) ; <nl> + bottomLeft - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( l , <nl> + t , <nl> + m_capInsetsInternal . origin . y - t , <nl> + m_capInsetsInternal . origin . x - l ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( bottomLeft , 2 , pBottomLeft ) ; <nl> + } <nl> + else <nl> + { <nl> + / / Sprite frame is not rotated <nl> + / / Centre <nl> + centre = new CCSprite ( ) ; <nl> + centre - > initWithTexture ( scale9Image - > getTexture ( ) , m_capInsetsInternal , rotated ) ; <nl> + scale9Image - > addChild ( centre , 0 , pCentre ) ; <nl> + <nl> + / / Top <nl> + top = new CCSprite ( ) ; <nl> + top - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x , <nl> + t , <nl> + m_capInsetsInternal . size . width , <nl> + m_capInsetsInternal . origin . y - t ) , <nl> + rotated <nl> + ) ; <nl> + scale9Image - > addChild ( top , 1 , pTop ) ; <nl> + <nl> + / / Bottom <nl> + bottom = new CCSprite ( ) ; <nl> + bottom - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( m_capInsetsInternal . origin . x , <nl> m_capInsetsInternal . origin . y + m_capInsetsInternal . size . height , <nl> - m_capInsetsInternal . origin . x - l , <nl> - h - ( m_capInsetsInternal . origin . y - t + m_capInsetsInternal . size . height ) ) ) ; <nl> - scale9Image - > addChild ( bottomLeft , 2 , pBottomLeft ) ; <nl> - <nl> - / / Bottom right <nl> - bottomRight = CCSprite : : createWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> - m_capInsetsInternal . origin . x + m_capInsetsInternal . size . width , <nl> - m_capInsetsInternal . origin . y + m_capInsetsInternal . size . height , <nl> - w - ( m_capInsetsInternal . origin . x - l + m_capInsetsInternal . size . width ) , <nl> - h - ( m_capInsetsInternal . origin . y - t + m_capInsetsInternal . size . height ) ) ) ; <nl> - scale9Image - > addChild ( bottomRight , 2 , pBottomRight ) ; <nl> - <nl> + m_capInsetsInternal . size . width , <nl> + h - ( m_capInsetsInternal . origin . y - t + m_capInsetsInternal . size . height ) ) , <nl> + rotated ) ; <nl> + scale9Image - > addChild ( bottom , 1 , pBottom ) ; <nl> + <nl> + / / Left <nl> + left = new CCSprite ( ) ; <nl> + left - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> + l , <nl> + m_capInsetsInternal . origin . y , <nl> + m_capInsetsInternal . origin . x - l , <nl> + m_capInsetsInternal . size . height ) , <nl> + rotated ) ; <nl> + scale9Image - > addChild ( left , 1 , pLeft ) ; <nl> + <nl> + / / Right <nl> + right = new CCSprite ( ) ; <nl> + right - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> + m_capInsetsInternal . origin . x + m_capInsetsInternal . size . width , <nl> + m_capInsetsInternal . origin . y , <nl> + w - ( m_capInsetsInternal . origin . x - l + m_capInsetsInternal . size . width ) , <nl> + m_capInsetsInternal . size . height ) , <nl> + rotated ) ; <nl> + scale9Image - > addChild ( right , 1 , pRight ) ; <nl> + <nl> + / / Top left <nl> + topLeft = new CCSprite ( ) ; <nl> + topLeft - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> + l , <nl> + t , <nl> + m_capInsetsInternal . origin . x - l , <nl> + m_capInsetsInternal . origin . y - t ) , <nl> + rotated ) ; <nl> + <nl> + scale9Image - > addChild ( topLeft , 2 , pTopLeft ) ; <nl> + <nl> + / / Top right <nl> + topRight = new CCSprite ( ) ; <nl> + topRight - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> + m_capInsetsInternal . origin . x + m_capInsetsInternal . size . width , <nl> + t , <nl> + w - ( m_capInsetsInternal . origin . x - l + m_capInsetsInternal . size . width ) , <nl> + m_capInsetsInternal . origin . y - t ) , <nl> + rotated ) ; <nl> + <nl> + scale9Image - > addChild ( topRight , 2 , pTopRight ) ; <nl> + <nl> + / / Bottom left <nl> + bottomLeft = new CCSprite ( ) ; <nl> + bottomLeft - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> + l , <nl> + m_capInsetsInternal . origin . y + m_capInsetsInternal . size . height , <nl> + m_capInsetsInternal . origin . x - l , <nl> + h - ( m_capInsetsInternal . origin . y - t + m_capInsetsInternal . size . height ) ) , <nl> + rotated ) ; <nl> + scale9Image - > addChild ( bottomLeft , 2 , pBottomLeft ) ; <nl> + <nl> + / / Bottom right <nl> + bottomRight = new CCSprite ( ) ; <nl> + bottomRight - > initWithTexture ( scale9Image - > getTexture ( ) , CCRectMake ( <nl> + m_capInsetsInternal . origin . x + m_capInsetsInternal . size . width , <nl> + m_capInsetsInternal . origin . y + m_capInsetsInternal . size . height , <nl> + w - ( m_capInsetsInternal . origin . x - l + m_capInsetsInternal . size . width ) , <nl> + h - ( m_capInsetsInternal . origin . y - t + m_capInsetsInternal . size . height ) ) , <nl> + rotated ) ; <nl> + scale9Image - > addChild ( bottomRight , 2 , pBottomRight ) ; <nl> + } <nl> <nl> this - > setContentSize ( rect . size ) ; <nl> this - > addChild ( scale9Image ) ; <nl> <nl> + if ( m_bSpritesGenerated ) <nl> + { <nl> + / / Restore color and opacity <nl> + this - > setOpacity ( opacity ) ; <nl> + this - > setColor ( color ) ; <nl> + } <nl> + m_bSpritesGenerated = true ; <nl> + <nl> return true ; <nl> } <nl> <nl> void CCScale9Sprite : : updatePositions ( ) <nl> <nl> float sizableWidth = size . width - topLeft - > getContentSize ( ) . width - topRight - > getContentSize ( ) . width ; <nl> float sizableHeight = size . height - topLeft - > getContentSize ( ) . height - bottomRight - > getContentSize ( ) . height ; <nl> + <nl> float horizontalScale = sizableWidth / centre - > getContentSize ( ) . width ; <nl> float verticalScale = sizableHeight / centre - > getContentSize ( ) . height ; <nl> + <nl> centre - > setScaleX ( horizontalScale ) ; <nl> centre - > setScaleY ( verticalScale ) ; <nl> + <nl> float rescaledWidth = centre - > getContentSize ( ) . width * horizontalScale ; <nl> float rescaledHeight = centre - > getContentSize ( ) . height * verticalScale ; <nl> <nl> CCScale9Sprite * CCScale9Sprite : : create ( const char * file , CCRect rect , CCRect ca <nl> <nl> bool CCScale9Sprite : : initWithFile ( const char * file , CCRect rect ) <nl> { <nl> + CCAssert ( file ! = NULL , " Invalid file for sprite " ) ; <nl> bool pReturn = this - > initWithFile ( file , rect , CCRectZero ) ; <nl> return pReturn ; <nl> } <nl> bool CCScale9Sprite : : initWithSpriteFrame ( CCSpriteFrame * spriteFrame , CCRect capI <nl> CCAssert ( spriteFrame ! = NULL , " Sprite frame must be not nil " ) ; <nl> <nl> CCSpriteBatchNode * batchnode = CCSpriteBatchNode : : createWithTexture ( spriteFrame - > getTexture ( ) , 9 ) ; <nl> - bool pReturn = this - > initWithBatchNode ( batchnode , spriteFrame - > getRect ( ) , capInsets ) ; <nl> + bool pReturn = this - > initWithBatchNode ( batchnode , spriteFrame - > getRect ( ) , spriteFrame - > isRotated ( ) , capInsets ) ; <nl> return pReturn ; <nl> } <nl> <nl> CCScale9Sprite * CCScale9Sprite : : createWithSpriteFrame ( CCSpriteFrame * spriteFrame <nl> } <nl> bool CCScale9Sprite : : initWithSpriteFrame ( CCSpriteFrame * spriteFrame ) <nl> { <nl> + CCAssert ( spriteFrame ! = NULL , " Invalid spriteFrame for sprite " ) ; <nl> bool pReturn = this - > initWithSpriteFrame ( spriteFrame , CCRectZero ) ; <nl> return pReturn ; <nl> } <nl> void CCScale9Sprite : : setOpacity ( GLubyte var ) <nl> { <nl> pNode - > setOpacity ( m_cOpacity ) ; <nl> } <nl> - / / CCNode * pNode = ( CCNode * ) child ; <nl> - / / if ( pNode ) <nl> - / / { <nl> - / / CCRGBAProtocol * pRGBAProtocol = ( CCRGBAProtocol * ) pNode ; <nl> - / / if ( pRGBAProtocol ) <nl> - / / { <nl> - / / pRGBAProtocol - > setOpacity ( m_cOpacity ) ; <nl> - / / } <nl> - / / } <nl> } <nl> } <nl> } <nl> CCSize CCScale9Sprite : : getPreferredSize ( ) <nl> void CCScale9Sprite : : setCapInsets ( CCRect capInsets ) <nl> { <nl> CCSize contentSize = this - > m_tContentSize ; <nl> - this - > updateWithBatchNode ( this - > scale9Image , this - > m_spriteRect , capInsets ) ; <nl> + this - > updateWithBatchNode ( this - > scale9Image , this - > m_spriteRect , m_bSpriteFrameRotated , capInsets ) ; <nl> this - > setContentSize ( contentSize ) ; <nl> } <nl> <nl> void CCScale9Sprite : : updateCapInset ( ) <nl> } <nl> else <nl> { <nl> - insets = CCRectMake ( this - > m_insetLeft , <nl> - this - > m_insetTop , <nl> - this - > m_spriteRect . size . width - this - > m_insetLeft - this - > m_insetRight , <nl> - this - > m_spriteRect . size . height - this - > m_insetTop - this - > m_insetBottom ) ; <nl> + if ( m_bSpriteFrameRotated ) <nl> + { <nl> + insets = CCRectMake ( m_spriteRect . origin . x + m_insetBottom , <nl> + m_spriteRect . origin . y + m_insetLeft , <nl> + m_spriteRect . size . width - m_insetRight - m_insetLeft , <nl> + m_spriteRect . size . height - m_insetTop - m_insetBottom ) ; <nl> + } <nl> + else <nl> + { <nl> + insets = CCRectMake ( m_spriteRect . origin . x + m_insetLeft , <nl> + m_spriteRect . origin . y + m_insetTop , <nl> + m_spriteRect . size . width - m_insetLeft - m_insetRight , <nl> + m_spriteRect . size . height - m_insetTop - m_insetBottom ) ; <nl> + } <nl> } <nl> this - > setCapInsets ( insets ) ; <nl> } <nl> void CCScale9Sprite : : setOpacityModifyRGB ( bool var ) <nl> { <nl> pNode - > setOpacityModifyRGB ( m_bIsOpacityModifyRGB ) ; <nl> } <nl> - / / CCNode * pNode = ( CCNode * ) child ; <nl> - / / if ( pNode ) <nl> - / / { <nl> - / / CCRGBAProtocol * pRGBAProtocol = ( CCRGBAProtocol * ) pNode ; <nl> - / / if ( pRGBAProtocol ) <nl> - / / { <nl> - / / pRGBAProtocol - > setOpacityModifyRGB ( m_bIsOpacityModifyRGB ) ; <nl> - / / } <nl> - / / } <nl> } <nl> } <nl> } <nl> bool CCScale9Sprite : : isOpacityModifyRGB ( ) <nl> void CCScale9Sprite : : setSpriteFrame ( CCSpriteFrame * spriteFrame ) <nl> { <nl> CCSpriteBatchNode * batchnode = CCSpriteBatchNode : : createWithTexture ( spriteFrame - > getTexture ( ) , 9 ) ; <nl> - this - > updateWithBatchNode ( batchnode , spriteFrame - > getRect ( ) , CCRectZero ) ; <nl> + this - > updateWithBatchNode ( batchnode , spriteFrame - > getRect ( ) , spriteFrame - > isRotated ( ) , CCRectZero ) ; <nl> <nl> / / Reset insets <nl> this - > m_insetLeft = 0 ; <nl> mmm a / extensions / GUI / CCControlExtension / CCScale9Sprite . h <nl> ppp b / extensions / GUI / CCControlExtension / CCScale9Sprite . h <nl> <nl> - / / <nl> - / / CCScale9Sprite . h <nl> - / / PlantCaring <nl> - / / <nl> - / / Created by Jung Sang - Taik on 12 . 3 . 16 . . <nl> - / / Copyright ( c ) 2012 Neofect . All rights reserved . <nl> - / / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> + Copyright ( c ) 2012 cocos2d - x . org <nl> + <nl> + http : / / www . cocos2d - x . org <nl> + <nl> + Created by Jung Sang - Taik on 12 . 3 . 16 . . <nl> + Copyright ( c ) 2012 Neofect . All rights reserved . <nl> + <nl> + Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + of this software and associated documentation files ( the " Software " ) , to deal <nl> + in the Software without restriction , including without limitation the rights <nl> + to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + copies of the Software , and to permit persons to whom the Software is <nl> + furnished to do so , subject to the following conditions : <nl> + <nl> + The above copyright notice and this permission notice shall be included in <nl> + all copies or substantial portions of the Software . <nl> + <nl> + THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + THE SOFTWARE . <nl> + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> # ifndef __CCScale9Sprite_H__ <nl> # define __CCScale9Sprite_H__ <nl> <nl> - # include " base_nodes / CCNode . h " <nl> - # include " CCProtocols . h " <nl> + # include " cocos2d . h " <nl> # include " ExtensionMacros . h " <nl> <nl> - <nl> - namespace cocos2d { class CCSprite ; } <nl> - namespace cocos2d { class CCSpriteBatchNode ; } <nl> - namespace cocos2d { class CCSpriteFrame ; } <nl> - <nl> NS_CC_EXT_BEGIN <nl> <nl> - enum positions <nl> - { <nl> - pCentre = 0 , <nl> - pTop , <nl> - pLeft , <nl> - pRight , <nl> - pBottom , <nl> - pTopRight , <nl> - pTopLeft , <nl> - pBottomRight , <nl> - pBottomLeft <nl> - } ; <nl> - <nl> / * * <nl> * @ addtogroup GUI <nl> * @ { <nl> class CCScale9Sprite : public CCNode , public CCRGBAProtocol <nl> <nl> public : <nl> / * * Original sprite ' s size . * / <nl> - CC_SYNTHESIZE ( CCSize , m_originalSize , OriginalSize ) ; <nl> + CC_SYNTHESIZE_READONLY ( CCSize , m_originalSize , OriginalSize ) ; <nl> / * * Prefered sprite ' s size . By default the prefered size is the original size . * / <nl> <nl> / / if the preferredSize component is given as - 1 , it is ignored <nl> class CCScale9Sprite : public CCNode , public CCRGBAProtocol <nl> * On a non - resizeable sprite , this property is set to CGRectZero ; the sprite <nl> * does not use end caps and the entire sprite is subject to stretching . <nl> * / <nl> - <nl> - / * * Opacity : conforms to CCRGBAProtocol protocol * / <nl> - CC_PROPERTY ( GLubyte , m_cOpacity , Opacity ) <nl> - / * * Color : conforms to CCRGBAProtocol protocol * / <nl> - CC_PROPERTY_PASS_BY_REF ( ccColor3B , m_tColor , Color ) <nl> CC_PROPERTY ( CCRect , m_capInsets , CapInsets ) ; <nl> + / * * Sets the left side inset * / <nl> CC_PROPERTY ( float , m_insetLeft , InsetLeft ) ; <nl> + / * * Sets the top side inset * / <nl> CC_PROPERTY ( float , m_insetTop , InsetTop ) ; <nl> + / * * Sets the right side inset * / <nl> CC_PROPERTY ( float , m_insetRight , InsetRight ) ; <nl> + / * * Sets the bottom side inset * / <nl> CC_PROPERTY ( float , m_insetBottom , InsetBottom ) ; <nl> - <nl> + <nl> + / * * Opacity : conforms to CCRGBAProtocol protocol * / <nl> + CC_PROPERTY ( GLubyte , m_cOpacity , Opacity ) <nl> + / * * Color : conforms to CCRGBAProtocol protocol * / <nl> + CC_PROPERTY_PASS_BY_REF ( ccColor3B , m_tColor , Color ) <nl> + <nl> protected : <nl> + bool m_bSpritesGenerated ; <nl> CCRect m_spriteRect ; <nl> + bool m_bSpriteFrameRotated ; <nl> CCRect m_capInsetsInternal ; <nl> bool m_positionsAreDirty ; <nl> <nl> class CCScale9Sprite : public CCNode , public CCRGBAProtocol <nl> <nl> virtual bool init ( ) ; <nl> <nl> + virtual bool initWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , bool rotated , CCRect capInsets ) ; <nl> virtual bool initWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , CCRect capInsets ) ; <nl> / * * <nl> * Initializes a 9 - slice sprite with a texture file , a delimitation zone and <nl> class CCScale9Sprite : public CCNode , public CCRGBAProtocol <nl> * @ see initWithFile : rect : <nl> @ deprecated : This interface will be deprecated sooner or later . <nl> * / <nl> - static CCScale9Sprite * spriteWithFile ( const char * file , CCRect rect ) ; <nl> + CC_DEPRECATED_ATTRIBUTE static CCScale9Sprite * spriteWithFile ( const char * file , CCRect rect ) ; <nl> <nl> / * * <nl> * Creates a 9 - slice sprite with a texture file and a delimitation zone . The <nl> class CCScale9Sprite : public CCNode , public CCRGBAProtocol <nl> * / <nl> virtual bool isOpacityModifyRGB ( void ) ; <nl> <nl> - virtual bool updateWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , CCRect capInsets ) ; <nl> + virtual bool updateWithBatchNode ( CCSpriteBatchNode * batchnode , CCRect rect , bool rotated , CCRect capInsets ) ; <nl> <nl> virtual void setSpriteFrame ( CCSpriteFrame * spriteFrame ) ; <nl> } ; <nl> deleted file mode 100644 <nl> index 931866dc2613 . . 000000000000 <nl> mmm a / extensions / GUI / CCControlExtension / CCSpacer . cpp <nl> ppp / dev / null <nl> <nl> - # include " CCSpacer . h " <nl> - <nl> - NS_CC_EXT_BEGIN <nl> - <nl> - CCSpacer * CCSpacer : : verticalSpacer ( float space ) <nl> - { <nl> - CCSpacer * pRet = new CCSpacer ( ) ; <nl> - pRet - > init ( ) ; <nl> - pRet - > setContentSize ( CCSizeMake ( 0 , space ) ) ; <nl> - pRet - > autorelease ( ) ; <nl> - return pRet ; <nl> - } <nl> - <nl> - CCSpacer * CCSpacer : : horizontalSpacer ( float space ) <nl> - { <nl> - CCSpacer * pRet = new CCSpacer ( ) ; <nl> - pRet - > init ( ) ; <nl> - pRet - > setContentSize ( CCSizeMake ( space , 0 ) ) ; <nl> - pRet - > autorelease ( ) ; <nl> - return pRet ; <nl> - } <nl> - <nl> - NS_CC_EXT_END <nl> deleted file mode 100644 <nl> index c3dfbd0c34ee . . 000000000000 <nl> mmm a / extensions / GUI / CCControlExtension / CCSpacer . h <nl> ppp / dev / null <nl> <nl> - # ifndef __CCSPACER_H__ <nl> - # define __CCSPACER_H__ <nl> - <nl> - # include " layers_scenes_transitions_nodes / CCLayer . h " <nl> - # include " ExtensionMacros . h " <nl> - <nl> - NS_CC_EXT_BEGIN <nl> - <nl> - / * * <nl> - * @ addtogroup GUI <nl> - * @ { <nl> - * @ addtogroup control_extension <nl> - * @ { <nl> - * / <nl> - <nl> - class CCSpacer : public CCLayer <nl> - { <nl> - public : <nl> - static CCSpacer * verticalSpacer ( float space ) ; <nl> - static CCSpacer * horizontalSpacer ( float space ) ; <nl> - } ; <nl> - <nl> - / / end of GUI group <nl> - / / / @ } <nl> - / / / @ } <nl> - <nl> - NS_CC_EXT_END <nl> - <nl> - # endif <nl> \ No newline at end of file <nl> mmm a / extensions / proj . win32 / libExtensions . vcproj <nl> ppp b / extensions / proj . win32 / libExtensions . vcproj <nl> <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlPotentiometer . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlPotentiometer . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSlider . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSlider . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSwitch . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSlider . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSwitch . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSlider . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlUtils . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlStepper . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCControlUtils . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlStepper . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCInvocation . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSwitch . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCInvocation . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlSwitch . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCMenuPassive . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlUtils . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCMenuPassive . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCControlUtils . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCInvocation . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCInvocation . h " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCSpacer . cpp " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . cpp " <nl> > <nl> < / File > <nl> < File <nl> - RelativePath = " . . \ GUI \ CCControlExtension \ CCSpacer . h " <nl> + RelativePath = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . h " <nl> > <nl> < / File > <nl> < / Filter > <nl> mmm a / extensions / proj . win32 / libExtensions . vcxproj <nl> ppp b / extensions / proj . win32 / libExtensions . vcxproj <nl> <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlButton . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlColourPicker . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlHuePicker . cpp " / > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlPotentiometer . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSlider . cpp " / > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlStepper . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSwitch . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlUtils . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCInvocation . cpp " / > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCMenuPassive . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . cpp " / > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCSpacer . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCScrollView \ CCScrollView . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCScrollView \ CCSorting . cpp " / > <nl> < ClCompile Include = " . . \ GUI \ CCScrollView \ CCTableView . cpp " / > <nl> <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlColourPicker . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlExtensions . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlHuePicker . h " / > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlPotentiometer . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSlider . h " / > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlStepper . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSwitch . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlUtils . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCInvocation . h " / > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCMenuPassive . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . h " / > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCSpacer . h " / > <nl> < ClInclude Include = " . . \ GUI \ CCScrollView \ CCScrollView . h " / > <nl> < ClInclude Include = " . . \ cocos - ext . h " / > <nl> < ClInclude Include = " . . \ ExtensionMacros . h " / > <nl> mmm a / extensions / proj . win32 / libExtensions . vcxproj . filters <nl> ppp b / extensions / proj . win32 / libExtensions . vcxproj . filters <nl> <nl> < / Filter > <nl> < / ItemGroup > <nl> < ItemGroup > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControl . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlButton . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlColourPicker . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlHuePicker . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSlider . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSwitch . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlUtils . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCInvocation . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCMenuPassive . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> - < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCSpacer . cpp " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClCompile > <nl> < ClCompile Include = " . . \ GUI \ CCScrollView \ CCScrollView . cpp " > <nl> < Filter > GUI \ CCScrollView < / Filter > <nl> < / ClCompile > <nl> <nl> < ClCompile Include = " . . \ CCBReader \ CCSpriteLoader . cpp " > <nl> < Filter > CCBReader < / Filter > <nl> < / ClCompile > <nl> - < / ItemGroup > <nl> - < ItemGroup > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControl . h " > <nl> - < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlButton . h " > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlColourPicker . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlColourPicker . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlHuePicker . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlExtensions . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlPotentiometer . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlHuePicker . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSlider . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSlider . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlStepper . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSwitch . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlSwitch . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlUtils . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlUtils . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCInvocation . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCInvocation . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCMenuPassive . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControl . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> - < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCSpacer . h " > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ GUI \ CCControlExtension \ CCControlButton . cpp " > <nl> < Filter > GUI \ CCControlExtension < / Filter > <nl> - < / ClInclude > <nl> + < / ClCompile > <nl> + < / ItemGroup > <nl> + < ItemGroup > <nl> < ClInclude Include = " . . \ GUI \ CCScrollView \ CCScrollView . h " > <nl> < Filter > GUI \ CCScrollView < / Filter > <nl> < / ClInclude > <nl> <nl> < ClInclude Include = " . . \ CCBReader \ CCSpriteLoader . h " > <nl> < Filter > CCBReader < / Filter > <nl> < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlButton . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlColourPicker . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlExtensions . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlHuePicker . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlPotentiometer . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSaturationBrightnessPicker . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSlider . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlStepper . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlSwitch . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControlUtils . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCInvocation . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCScale9Sprite . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ GUI \ CCControlExtension \ CCControl . h " > <nl> + < Filter > GUI \ CCControlExtension < / Filter > <nl> + < / ClInclude > <nl> < / ItemGroup > <nl> < / Project > <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 000000000000 . . bcd4f4d25422 <nl> mmm / dev / null <nl> ppp b / licenses / LICENSE_CCControlExtension . txt <nl> <nl> + / * <nl> + * <nl> + * Copyright 2012 Yannick Loriot . <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> \ No newline at end of file <nl> mmm a / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlButtonTest / CCControlButtonTest . cpp <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlButtonTest / CCControlButtonTest . cpp <nl> bool CCControlButtonTest_Event : : init ( ) <nl> addChild ( background ) ; <nl> <nl> / / Sets up event handlers <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDownAction ) , CCControlEventTouchDown ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragInsideAction ) , CCControlEventTouchDragInside ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragOutsideAction ) , CCControlEventTouchDragOutside ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragEnterAction ) , CCControlEventTouchDragEnter ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragExitAction ) , CCControlEventTouchDragExit ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchUpInsideAction ) , CCControlEventTouchUpInside ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchUpOutsideAction ) , CCControlEventTouchUpOutside ) ; <nl> - controlButton - > addTargetWithActionForControlEvent ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchCancelAction ) , CCControlEventTouchCancel ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDownAction ) , CCControlEventTouchDown ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragInsideAction ) , CCControlEventTouchDragInside ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragOutsideAction ) , CCControlEventTouchDragOutside ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragEnterAction ) , CCControlEventTouchDragEnter ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchDragExitAction ) , CCControlEventTouchDragExit ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchUpInsideAction ) , CCControlEventTouchUpInside ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchUpOutsideAction ) , CCControlEventTouchUpOutside ) ; <nl> + controlButton - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlButtonTest_Event : : touchCancelAction ) , CCControlEventTouchCancel ) ; <nl> return true ; <nl> } <nl> return false ; <nl> mmm a / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlColourPicker / CCControlColourPickerTest . cpp <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlColourPicker / CCControlColourPickerTest . cpp <nl> CCControlColourPickerTest : : ~ CCControlColourPickerTest ( ) <nl> void CCControlColourPickerTest : : colourValueChanged ( CCObject * sender , CCControlEvent controlEvent ) <nl> { <nl> CCControlColourPicker * pPicker = ( CCControlColourPicker * ) sender ; <nl> - m_pColorLabel - > setString ( CCString : : createWithFormat ( " # % 02X % 02X % 02X " , pPicker - > getColorValue ( ) . r , pPicker - > getColorValue ( ) . g , pPicker - > getColorValue ( ) . b ) - > getCString ( ) ) ; <nl> + m_pColorLabel - > setString ( CCString : : createWithFormat ( " # % 02X % 02X % 02X " , pPicker - > getColor ( ) . r , pPicker - > getColor ( ) . g , pPicker - > getColor ( ) . b ) - > getCString ( ) ) ; <nl> } <nl> <nl> <nl> new file mode 100644 <nl> index 000000000000 . . e9df102d65c4 <nl> mmm / dev / null <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlPotentiometerTest / CCControlPotentiometerTest . cpp <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * Copyright ( c ) 2012 Yannick Loriot <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # include " CCControlPotentiometerTest . h " <nl> + <nl> + CCControlPotentiometerTest : : CCControlPotentiometerTest ( ) <nl> + : m_pDisplayValueLabel ( NULL ) <nl> + { <nl> + <nl> + } <nl> + <nl> + CCControlPotentiometerTest : : ~ CCControlPotentiometerTest ( ) <nl> + { <nl> + CC_SAFE_RELEASE ( m_pDisplayValueLabel ) ; <nl> + } <nl> + <nl> + bool CCControlPotentiometerTest : : init ( ) <nl> + { <nl> + if ( CCControlScene : : init ( ) ) <nl> + { <nl> + CCSize screenSize = CCDirector : : sharedDirector ( ) - > getWinSize ( ) ; <nl> + <nl> + CCNode * layer = CCNode : : create ( ) ; <nl> + layer - > setPosition ( ccp ( screenSize . width / 2 , screenSize . height / 2 ) ) ; <nl> + this - > addChild ( layer , 1 ) ; <nl> + <nl> + double layer_width = 0 ; <nl> + <nl> + / / Add the black background for the text <nl> + CCScale9Sprite * background = CCScale9Sprite : : create ( " extensions / buttonBackground . png " ) ; <nl> + background - > setContentSize ( CCSizeMake ( 80 , 50 ) ) ; <nl> + background - > setPosition ( ccp ( layer_width + background - > getContentSize ( ) . width / 2 . 0f , 0 ) ) ; <nl> + layer - > addChild ( background ) ; <nl> + <nl> + layer_width + = background - > getContentSize ( ) . width ; <nl> + <nl> + this - > setDisplayValueLabel ( CCLabelTTF : : create ( " " , " HelveticaNeue - Bold " , 30 ) ) ; <nl> + <nl> + m_pDisplayValueLabel - > setPosition ( background - > getPosition ( ) ) ; <nl> + layer - > addChild ( m_pDisplayValueLabel ) ; <nl> + <nl> + / / Add the slider <nl> + CCControlPotentiometer * potentiometer = CCControlPotentiometer : : create ( " extensions / potentiometerTrack . png " <nl> + , " extensions / potentiometerProgress . png " <nl> + , " extensions / potentiometerButton . png " ) ; <nl> + potentiometer - > setPosition ( ccp ( layer_width + 10 + potentiometer - > getContentSize ( ) . width / 2 , 0 ) ) ; <nl> + <nl> + / / When the value of the slider will change , the given selector will be call <nl> + potentiometer - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlPotentiometerTest : : valueChanged ) , CCControlEventValueChanged ) ; <nl> + <nl> + layer - > addChild ( potentiometer ) ; <nl> + <nl> + layer_width + = potentiometer - > getContentSize ( ) . width ; <nl> + <nl> + / / Set the layer size <nl> + layer - > setContentSize ( CCSizeMake ( layer_width , 0 ) ) ; <nl> + layer - > setAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> + <nl> + / / Update the value label <nl> + this - > valueChanged ( potentiometer , CCControlEventValueChanged ) ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + void CCControlPotentiometerTest : : valueChanged ( CCObject * sender , CCControlEvent controlEvent ) <nl> + { <nl> + CCControlPotentiometer * pControl = ( CCControlPotentiometer * ) sender ; <nl> + / / Change value of label . <nl> + m_pDisplayValueLabel - > setString ( CCString : : createWithFormat ( " % . 02f " , pControl - > getValue ( ) ) - > getCString ( ) ) ; <nl> + } <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . b76f327d15a5 <nl> mmm / dev / null <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlPotentiometerTest / CCControlPotentiometerTest . h <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * Copyright ( c ) 2012 Yannick Loriot <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # ifndef __CCCONTROLPOTENTIOMETERTEST_H__ <nl> + # define __CCCONTROLPOTENTIOMETERTEST_H__ <nl> + <nl> + # include " . . / CCControlScene . h " <nl> + <nl> + class CCControlPotentiometerTest : public CCControlScene <nl> + { <nl> + public : <nl> + CCControlPotentiometerTest ( ) ; <nl> + virtual ~ CCControlPotentiometerTest ( ) ; <nl> + bool init ( ) ; <nl> + CC_SYNTHESIZE_RETAIN ( CCLabelTTF * , m_pDisplayValueLabel , DisplayValueLabel ) <nl> + <nl> + void valueChanged ( CCObject * sender , CCControlEvent controlEvent ) ; <nl> + <nl> + CONTROL_SCENE_CREATE_FUNC ( CCControlPotentiometerTest ) <nl> + } ; <nl> + <nl> + <nl> + # endif / * __CCCONTROLPOTENTIOMETERTEST_H__ * / <nl> + <nl> mmm a / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlSceneManager . cpp <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlSceneManager . cpp <nl> <nl> # include " CCControlColourPicker / CCControlColourPickerTest . h " <nl> # include " CCControlSliderTest / CCControlSliderTest . h " <nl> # include " CCControlSwitchTest / CCControlSwitchTest . h " <nl> + # include " CCControlPotentiometerTest / CCControlPotentiometerTest . h " <nl> + # include " CCControlStepperTest / CCControlStepperTest . h " <nl> <nl> USING_NS_CC ; <nl> <nl> enum <nl> kCCControlButtonTest_HelloVariableSize , <nl> kCCControlButtonTest_Event , <nl> kCCControlButtonTest_Styling , <nl> + kCCControlPotentiometerTest , <nl> + kCCControlStepperTest , <nl> kCCControlTestMax <nl> } ; <nl> <nl> static const char * s_testArray [ ] = { <nl> " ControlSwitchTest " , <nl> " ControlButtonTest_HelloVariableSize " , <nl> " ControlButtonTest_Event " , <nl> - " ControlButtonTest_Styling " <nl> + " ControlButtonTest_Styling " , <nl> + " ControlPotentiometerTest " , <nl> + " CCControlStepperTest " <nl> } ; <nl> <nl> static CCControlSceneManager * sharedInstance = NULL ; <nl> CCScene * CCControlSceneManager : : currentControlScene ( ) <nl> case kCCControlButtonTest_HelloVariableSize : return CCControlButtonTest_HelloVariableSize : : sceneWithTitle ( s_testArray [ m_nCurrentControlSceneId ] ) ; <nl> case kCCControlButtonTest_Event : return CCControlButtonTest_Event : : sceneWithTitle ( s_testArray [ m_nCurrentControlSceneId ] ) ; <nl> case kCCControlButtonTest_Styling : return CCControlButtonTest_Styling : : sceneWithTitle ( s_testArray [ m_nCurrentControlSceneId ] ) ; <nl> + case kCCControlPotentiometerTest : return CCControlPotentiometerTest : : sceneWithTitle ( s_testArray [ m_nCurrentControlSceneId ] ) ; <nl> + case kCCControlStepperTest : return CCControlStepperTest : : sceneWithTitle ( s_testArray [ m_nCurrentControlSceneId ] ) ; <nl> } <nl> return NULL ; <nl> } <nl> new file mode 100644 <nl> index 000000000000 . . 90b77c832707 <nl> mmm / dev / null <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlStepperTest / CCControlStepperTest . cpp <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * Copyright ( c ) 2012 Yannick Loriot <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # include " CCControlStepperTest . h " <nl> + <nl> + CCControlStepperTest : : CCControlStepperTest ( ) <nl> + : m_pDisplayValueLabel ( NULL ) <nl> + { <nl> + <nl> + } <nl> + <nl> + CCControlStepperTest : : ~ CCControlStepperTest ( ) <nl> + { <nl> + CC_SAFE_RELEASE ( m_pDisplayValueLabel ) ; <nl> + } <nl> + <nl> + bool CCControlStepperTest : : init ( ) <nl> + { <nl> + if ( CCControlScene : : init ( ) ) <nl> + { <nl> + CCSize screenSize = CCDirector : : sharedDirector ( ) - > getWinSize ( ) ; <nl> + <nl> + CCNode * layer = CCNode : : create ( ) ; <nl> + layer - > setPosition ( ccp ( screenSize . width / 2 , screenSize . height / 2 ) ) ; <nl> + this - > addChild ( layer , 1 ) ; <nl> + <nl> + double layer_width = 0 ; <nl> + <nl> + / / Add the black background for the text <nl> + CCScale9Sprite * background = CCScale9Sprite : : create ( " extensions / buttonBackground . png " ) ; <nl> + background - > setContentSize ( CCSizeMake ( 100 , 50 ) ) ; <nl> + background - > setPosition ( ccp ( layer_width + background - > getContentSize ( ) . width / 2 . 0f , 0 ) ) ; <nl> + layer - > addChild ( background ) ; <nl> + <nl> + this - > setDisplayValueLabel ( CCLabelTTF : : create ( " 0 " , " HelveticaNeue - Bold " , 30 ) ) ; <nl> + <nl> + m_pDisplayValueLabel - > setPosition ( background - > getPosition ( ) ) ; <nl> + layer - > addChild ( m_pDisplayValueLabel ) ; <nl> + <nl> + layer_width + = background - > getContentSize ( ) . width ; <nl> + <nl> + CCControlStepper * stepper = this - > makeControlStepper ( ) ; <nl> + stepper - > setPosition ( ccp ( layer_width + 10 + stepper - > getContentSize ( ) . width / 2 , 0 ) ) ; <nl> + stepper - > addTargetWithActionForControlEvents ( this , cccontrol_selector ( CCControlStepperTest : : valueChanged ) , CCControlEventValueChanged ) ; <nl> + layer - > addChild ( stepper ) ; <nl> + <nl> + layer_width + = stepper - > getContentSize ( ) . width ; <nl> + <nl> + / / Set the layer size <nl> + layer - > setContentSize ( CCSizeMake ( layer_width , 0 ) ) ; <nl> + layer - > setAnchorPoint ( ccp ( 0 . 5f , 0 . 5f ) ) ; <nl> + <nl> + / / Update the value label <nl> + this - > valueChanged ( stepper , CCControlEventValueChanged ) ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + CCControlStepper * CCControlStepperTest : : makeControlStepper ( ) <nl> + { <nl> + CCSprite * minusSprite = CCSprite : : create ( " extensions / stepper - minus . png " ) ; <nl> + CCSprite * plusSprite = CCSprite : : create ( " extensions / stepper - plus . png " ) ; <nl> + <nl> + return CCControlStepper : : create ( minusSprite , plusSprite ) ; <nl> + } <nl> + <nl> + void CCControlStepperTest : : valueChanged ( CCObject * sender , CCControlEvent controlEvent ) <nl> + { <nl> + CCControlStepper * pControl = ( CCControlStepper * ) sender ; <nl> + / / Change value of label . <nl> + m_pDisplayValueLabel - > setString ( CCString : : createWithFormat ( " % 0 . 02f " , ( float ) pControl - > getValue ( ) ) - > getCString ( ) ) ; <nl> + } <nl> + <nl> new file mode 100644 <nl> index 000000000000 . . 174917fa739b <nl> mmm / dev / null <nl> ppp b / samples / TestCpp / Classes / ExtensionsTest / ControlExtensionTest / CCControlStepperTest / CCControlStepperTest . h <nl> <nl> + / * <nl> + * Copyright ( c ) 2012 cocos2d - x . org <nl> + * Copyright ( c ) 2012 Yannick Loriot <nl> + * http : / / yannickloriot . com <nl> + * <nl> + * Permission is hereby granted , free of charge , to any person obtaining a copy <nl> + * of this software and associated documentation files ( the " Software " ) , to deal <nl> + * in the Software without restriction , including without limitation the rights <nl> + * to use , copy , modify , merge , publish , distribute , sublicense , and / or sell <nl> + * copies of the Software , and to permit persons to whom the Software is <nl> + * furnished to do so , subject to the following conditions : <nl> + * <nl> + * The above copyright notice and this permission notice shall be included in <nl> + * all copies or substantial portions of the Software . <nl> + * <nl> + * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR <nl> + * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , <nl> + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE <nl> + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER <nl> + * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , <nl> + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <nl> + * THE SOFTWARE . <nl> + * <nl> + * / <nl> + <nl> + # ifndef __CCCONTROLSTEPPERTEST_H__ <nl> + # define __CCCONTROLSTEPPERTEST_H__ <nl> + <nl> + # include " . . / CCControlScene . h " <nl> + <nl> + class CCControlStepperTest : public CCControlScene <nl> + { <nl> + public : <nl> + CCControlStepperTest ( ) ; <nl> + virtual ~ CCControlStepperTest ( ) ; <nl> + bool init ( ) ; <nl> + / * * Creates and returns a new ControlStepper . * / <nl> + CCControlStepper * makeControlStepper ( ) ; <nl> + <nl> + / * * Callback for the change value . * / <nl> + void valueChanged ( CCObject * sender , CCControlEvent controlEvent ) ; <nl> + protected : <nl> + CC_SYNTHESIZE_RETAIN ( CCLabelTTF * , m_pDisplayValueLabel , DisplayValueLabel ) <nl> + CONTROL_SCENE_CREATE_FUNC ( CCControlStepperTest ) <nl> + } ; <nl> + <nl> + # endif / * __CCCONTROLSTEPPERTEST_H__ * / <nl> + <nl> mmm a / samples / TestCpp / proj . win32 / TestCpp . vcproj <nl> ppp b / samples / TestCpp / proj . win32 / TestCpp . vcproj <nl> <nl> > <nl> < / File > <nl> < / Filter > <nl> + < Filter <nl> + Name = " CCControlPotentiometerTest " <nl> + > <nl> + < File <nl> + RelativePath = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest \ CCControlPotentiometerTest . cpp " <nl> + > <nl> + < / File > <nl> + < File <nl> + RelativePath = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest \ CCControlPotentiometerTest . h " <nl> + > <nl> + < / File > <nl> + < / Filter > <nl> + < Filter <nl> + Name = " CCControlStepperTest " <nl> + > <nl> + < File <nl> + RelativePath = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest \ CCControlStepperTest . cpp " <nl> + > <nl> + < / File > <nl> + < File <nl> + RelativePath = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest \ CCControlStepperTest . h " <nl> + > <nl> + < / File > <nl> + < / Filter > <nl> < / Filter > <nl> < Filter <nl> Name = " NotificationCenterTest " <nl> mmm a / samples / TestCpp / proj . win32 / TestCpp . vcxproj <nl> ppp b / samples / TestCpp / proj . win32 / TestCpp . vcxproj <nl> <nl> < / ItemDefinitionGroup > <nl> < ItemGroup > <nl> < ClCompile Include = " . . \ Classes \ ExtensionsTest \ CocosBuilderTest \ AnimationsTest \ AnimationsTestLayer . cpp " / > <nl> + < ClCompile Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest \ CCControlPotentiometerTest . cpp " / > <nl> + < ClCompile Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest \ CCControlStepperTest . cpp " / > <nl> < ClCompile Include = " . . \ Classes \ ExtensionsTest \ NetworkTest \ HttpClientTest . cpp " / > <nl> < ClCompile Include = " . . \ Classes \ ExtensionsTest \ TableViewTest \ CustomTableViewCell . cpp " / > <nl> < ClCompile Include = " . . \ Classes \ ExtensionsTest \ TableViewTest \ TableViewTestScene . cpp " / > <nl> <nl> < ItemGroup > <nl> < ClInclude Include = " . . \ Classes \ ExtensionsTest \ CocosBuilderTest \ AnimationsTest \ AnimationsLayerLoader . h " / > <nl> < ClInclude Include = " . . \ Classes \ ExtensionsTest \ CocosBuilderTest \ AnimationsTest \ AnimationsTestLayer . h " / > <nl> + < ClInclude Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest \ CCControlPotentiometerTest . h " / > <nl> + < ClInclude Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest \ CCControlStepperTest . h " / > <nl> < ClInclude Include = " . . \ Classes \ ExtensionsTest \ NetworkTest \ HttpClientTest . h " / > <nl> < ClInclude Include = " . . \ Classes \ ExtensionsTest \ TableViewTest \ CustomTableViewCell . h " / > <nl> < ClInclude Include = " . . \ Classes \ ExtensionsTest \ TableViewTest \ TableViewTestScene . h " / > <nl> mmm a / samples / TestCpp / proj . win32 / TestCpp . vcxproj . filters <nl> ppp b / samples / TestCpp / proj . win32 / TestCpp . vcxproj . filters <nl> <nl> < Filter Include = " Classes \ ExtensionsTest \ AnimationsTest " > <nl> < UniqueIdentifier > { e8752620 - 8414 - 4f43 - a572 - 5fa82650f223 } < / UniqueIdentifier > <nl> < / Filter > <nl> + < Filter Include = " Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest " > <nl> + < UniqueIdentifier > { 08850f9d - e7e5 - 4bca - ae90 - cf8df391479f } < / UniqueIdentifier > <nl> + < / Filter > <nl> + < Filter Include = " Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest " > <nl> + < UniqueIdentifier > { 7e809230 - 9bb5 - 45bb - a26c - b5cdd1390914 } < / UniqueIdentifier > <nl> + < / Filter > <nl> < / ItemGroup > <nl> < ItemGroup > <nl> < ClCompile Include = " main . cpp " > <nl> <nl> < ClCompile Include = " . . \ Classes \ ExtensionsTest \ CocosBuilderTest \ AnimationsTest \ AnimationsTestLayer . cpp " > <nl> < Filter > Classes \ ExtensionsTest \ AnimationsTest < / Filter > <nl> < / ClCompile > <nl> + < ClCompile Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest \ CCControlPotentiometerTest . cpp " > <nl> + < Filter > Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest < / Filter > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest \ CCControlStepperTest . cpp " > <nl> + < Filter > Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest < / Filter > <nl> + < / ClCompile > <nl> < / ItemGroup > <nl> < ItemGroup > <nl> < ClInclude Include = " main . h " > <nl> <nl> < ClInclude Include = " . . \ Classes \ ExtensionsTest \ CocosBuilderTest \ AnimationsTest \ AnimationsTestLayer . h " > <nl> < Filter > Classes \ ExtensionsTest \ AnimationsTest < / Filter > <nl> < / ClInclude > <nl> + < ClInclude Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest \ CCControlPotentiometerTest . h " > <nl> + < Filter > Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlPotentiometerTest < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " . . \ Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest \ CCControlStepperTest . h " > <nl> + < Filter > Classes \ ExtensionsTest \ ControlExtensionTest \ CCControlStepperTest < / Filter > <nl> + < / ClInclude > <nl> < / ItemGroup > <nl> < / Project > <nl> \ No newline at end of file <nl>
Merge pull request from dumganhar / iss1483_sync_cccontrol
cocos2d/cocos2d-x
3e442d161fd2c0785890a5d8df4e80821038edd9
2012-09-25T09:30:30Z
mmm a / src / config / args . hpp <nl> ppp b / src / config / args . hpp <nl> <nl> / / transactions will be throttled . <nl> # define DEFAULT_UNSAVED_DATA_LIMIT GIGABYTE <nl> <nl> - / / How many times the page replacement algorithm tries to find an eligible page before giving up <nl> - # define PAGE_REPL_NUM_TRIES 3 <nl> + / / The unsaved data limit cannot exceed this fraction of the max cache size <nl> + # define MAX_UNSAVED_DATA_LIMIT_FRACTION 0 . 9 <nl> + <nl> + / / How many times the page replacement algorithm tries to find an eligible page before giving up . <nl> + / / Note that ( MAX_UNSAVED_DATA_LIMIT_FRACTION * * PAGE_REPL_NUM_TRIES ) is the probability that the <nl> + / / page replacement algorithm will succeed on a given try , and if that probability is less than 1 / 2 <nl> + / / then the page replacement algorithm will on average be unable to evict pages from the cache . <nl> + # define PAGE_REPL_NUM_TRIES 10 <nl> <nl> / / How large can the key be , in bytes ? This value needs to fit in a byte . <nl> # define MAX_KEY_SIZE 250 <nl> mmm a / src / config / cmd_args . cc <nl> ppp b / src / config / cmd_args . cc <nl> cmd_config_t parse_cmd_args ( int argc , char * argv [ ] ) { <nl> / * Sanity - check the input * / <nl> <nl> if ( config . store_dynamic_config . cache . max_dirty_size > <nl> - config . store_dynamic_config . cache . max_size / 2 ) { <nl> + config . store_dynamic_config . cache . max_size * MAX_UNSAVED_DATA_LIMIT_FRACTION ) { <nl> <nl> / * The page replacement algorithm won ' t work properly if the number of dirty bufs <nl> is allowed to be more than about half of the total number of bufs . * / <nl> config . store_dynamic_config . cache . max_dirty_size = <nl> - config . store_dynamic_config . cache . max_size / 2 ; <nl> + config . store_dynamic_config . cache . max_size * MAX_UNSAVED_DATA_LIMIT_FRACTION ; <nl> } <nl> <nl> if ( config . store_dynamic_config . cache . wait_for_flush = = true & & <nl>
Raised the max unsaved data limit fraction from 0 . 5 to 0 . 9 to give the user more flexibility .
rethinkdb/rethinkdb
383cd3412796fee042283fc6aae2e5f6ce3a0be6
2011-01-07T01:27:41Z
mmm a / tensorflow / python / data / ops / dataset_ops . py <nl> ppp b / tensorflow / python / data / ops / dataset_ops . py <nl> def from_tensors ( tensors ) : <nl> Note that if ` tensors ` contains a NumPy array , and eager execution is not <nl> enabled , the values will be embedded in the graph as one or more <nl> ` tf . constant ` operations . For large datasets ( > 1 GB ) , this can waste <nl> - memory and run into byte limits of graph serialization . If tensors contains <nl> - one or more large NumPy arrays , consider the alternative described in <nl> - [ this guide ] ( https : / / tensorflow . org / guide / datasets # consuming_numpy_arrays ) . <nl> + memory and run into byte limits of graph serialization . If ` tensors ` <nl> + contains one or more large NumPy arrays , consider the alternative described <nl> + in [ this guide ] ( https : / / tensorflow . org / guide / datasets # consuming_numpy_arrays ) . <nl> <nl> Args : <nl> tensors : A nested structure of tensors . <nl> def from_tensor_slices ( tensors ) : <nl> Note that if ` tensors ` contains a NumPy array , and eager execution is not <nl> enabled , the values will be embedded in the graph as one or more <nl> ` tf . constant ` operations . For large datasets ( > 1 GB ) , this can waste <nl> - memory and run into byte limits of graph serialization . If tensors contains <nl> - one or more large NumPy arrays , consider the alternative described in <nl> - [ this guide ] ( https : / / tensorflow . org / guide / datasets # consuming_numpy_arrays ) . <nl> + memory and run into byte limits of graph serialization . If ` tensors ` <nl> + contains one or more large NumPy arrays , consider the alternative described <nl> + in [ this guide ] ( https : / / tensorflow . org / guide / datasets # consuming_numpy_arrays ) . <nl> <nl> Args : <nl> tensors : A nested structure of tensors , each having the same size in the <nl> def range ( * args ) : <nl> ` ` ` <nl> <nl> Args : <nl> - * args : follow same semantics as python ' s xrange . <nl> + * args : follows the same semantics as python ' s xrange . <nl> len ( args ) = = 1 - > start = 0 , stop = args [ 0 ] , step = 1 <nl> len ( args ) = = 2 - > start = args [ 0 ] , stop = args [ 1 ] , step = 1 <nl> len ( args ) = = 3 - > start = args [ 0 ] , stop = args [ 1 , stop = args [ 2 ] <nl> def shard ( self , num_shards , index ) : <nl> <nl> Raises : <nl> ValueError : if ` num_shards ` or ` index ` are illegal values . Note : error <nl> - checking is done on a best - effort basis , and aren ' t guaranteed to be <nl> - caught upon dataset creation . ( e . g . providing in a placeholder tensor <nl> - bypasses the early checking , and will instead result in an error during <nl> - a session . run call . ) <nl> + checking is done on a best - effort basis , and errors aren ' t guaranteed <nl> + to be caught upon dataset creation . ( e . g . providing in a placeholder <nl> + tensor bypasses the early checking , and will instead result in an error <nl> + during a session . run call . ) <nl> " " " <nl> num_shards = ops . convert_to_tensor ( <nl> num_shards , name = " num_shards " , dtype = dtypes . int64 ) <nl> def batch ( self , batch_size , drop_remainder = False ) : <nl> batch_size : A ` tf . int64 ` scalar ` tf . Tensor ` , representing the number of <nl> consecutive elements of this dataset to combine in a single batch . <nl> drop_remainder : ( Optional . ) A ` tf . bool ` scalar ` tf . Tensor ` , representing <nl> - whether the last batch should be dropped in the case its has fewer than <nl> + whether the last batch should be dropped in the case it has fewer than <nl> ` batch_size ` elements ; the default behavior is not to drop the smaller <nl> batch . <nl> <nl> def padded_batch ( self , <nl> respective components . Defaults are ` 0 ` for numeric types and <nl> the empty string for string types . <nl> drop_remainder : ( Optional . ) A ` tf . bool ` scalar ` tf . Tensor ` , representing <nl> - whether the last batch should be dropped in the case its has fewer than <nl> + whether the last batch should be dropped in the case it has fewer than <nl> ` batch_size ` elements ; the default behavior is not to drop the smaller <nl> batch . <nl> <nl> def make_one_shot_iterator ( self ) : <nl> class Options ( object ) : <nl> " " " Represents options for tf . data . Dataset . <nl> <nl> - An ` Options ` object can be for instance used to control which static <nl> + An ` Options ` object can be , for instance , used to control which static <nl> optimizations to apply or whether to use performance modeling to dynamically <nl> tune the parallelism of operations such as ` tf . data . Dataset . map ` or <nl> ` tf . data . Dataset . interleave ` . <nl> mmm a / tensorflow / python / data / ops / readers . py <nl> ppp b / tensorflow / python / data / ops / readers . py <nl> class TFRecordDatasetV2 ( dataset_ops . DatasetV2 ) : <nl> <nl> def __init__ ( self , filenames , compression_type = None , buffer_size = None , <nl> num_parallel_reads = None ) : <nl> - " " " Creates a ` TFRecordDataset ` to read for one or more TFRecord files . <nl> + " " " Creates a ` TFRecordDataset ` to read one or more TFRecord files . <nl> <nl> NOTE : The ` num_parallel_reads ` argument can be used to improve performance <nl> when reading from a remote filesystem . <nl>
fixed grammar in dataset_ops and readers
tensorflow/tensorflow
b7bc8650cd673e2b12ed2a9b5a81d8074cee1e2a
2018-11-20T00:08:25Z
mmm a / src / compiler / statement / method_statement . cpp <nl> ppp b / src / compiler / statement / method_statement . cpp <nl> class TryingGotoFixer { <nl> new GotoStatement ( <nl> c - > getScope ( ) , c - > getLocation ( ) , lab ) ) ) ; <nl> StatementListPtr newBody ( new StatementList ( <nl> - body - > getScope ( ) , body - > getLocation ( ) ) ) ; <nl> + c - > getScope ( ) , c - > getLocation ( ) ) ) ; <nl> newBody - > addElement ( StatementPtr ( <nl> new LabelStatement ( <nl> - body - > getScope ( ) , body - > getLocation ( ) , <nl> + c - > getScope ( ) , c - > getLocation ( ) , <nl> lab ) ) ) ; <nl> - newBody - > addElement ( body ) ; <nl> + if ( body ) newBody - > addElement ( body ) ; <nl> if ( i + 1 < n ) { <nl> newBody - > addElement ( <nl> StatementPtr ( new GotoStatement ( <nl> - body - > getScope ( ) , body - > getLocation ( ) , <nl> + c - > getScope ( ) , c - > getLocation ( ) , <nl> afterLab ) ) ) ; <nl> } <nl> sl - > addElement ( newBody ) ; <nl>
[ Fix ] Dont crash re - writing empty catch statements
facebook/hhvm
2b03ffa7f3fa77632930d27fd56d2ae2b6089bec
2011-08-19T23:21:01Z
mmm a / hphp / hack / src / client / clientLsp . ml <nl> ppp b / hphp / hack / src / client / clientLsp . ml <nl> let handle_event <nl> & & c . method_ = " workspace / didChangeWatchedFiles " - > <nl> let open DidChangeWatchedFiles in <nl> let notification = parse_didChangeWatchedFiles c . params in <nl> - let changes = notification . changes <nl> - | > List . filter ~ f : ( fun change - > <nl> - let path = lsp_uri_to_path change . uri in <nl> - FindUtils . file_filter path <nl> - ) <nl> - in <nl> - List . iter changes ~ f : ( fun change - > <nl> + List . iter notification . changes ~ f : ( fun change - > <nl> let path = lsp_uri_to_path change . uri in <nl> - let path = Relative_path . strip_root_if_possible path in <nl> - match path with <nl> - | Some path - > <nl> - let relative_path = Relative_path . from_root path in <nl> - ClientIdeService . notify_file_changed ide_service relative_path <nl> - | None - > <nl> - ( ) <nl> + let path = Path . make path in <nl> + ClientIdeService . notify_file_changed ide_service path <nl> ) ; <nl> Lwt . return_unit <nl> <nl> mmm a / hphp / hack / src / utils / sys / path . ml <nl> ppp b / hphp / hack / src / utils / sys / path . ml <nl> <nl> * <nl> * ) <nl> <nl> + open Reordered_argument_collections <nl> include Sys <nl> <nl> - type t = string <nl> + module S = struct <nl> + type t = string <nl> + let compare = Pervasives . compare <nl> + let to_string x = x <nl> + end <nl> + type t = S . t <nl> <nl> let dummy_path : t = " " <nl> <nl> let path_of_slash_escaped_string str = <nl> consume next_i <nl> in consume 0 ; <nl> make ( Buffer . contents buf ) <nl> + <nl> + module Set = Reordered_argument_set ( Set . Make ( S ) ) <nl> mmm a / hphp / hack / src / utils / sys / path . mli <nl> ppp b / hphp / hack / src / utils / sys / path . mli <nl> <nl> * <nl> * ) <nl> <nl> + open Reordered_argument_collections <nl> <nl> - type t = private string <nl> + module S : sig <nl> + type t = private string <nl> + val compare : t - > t - > int <nl> + val to_string : t - > string <nl> + end <nl> + type t = S . t <nl> <nl> val dummy_path : t <nl> val make : string - > t <nl> val cat : t - > string <nl> <nl> val slash_escaped_string_of_path : t - > string <nl> val path_of_slash_escaped_string : string - > t <nl> + <nl> + module Set : module type of Reordered_argument_set ( Set . Make ( S ) ) <nl>
Use separate queues for processing file change events and for responding to IDE queries
facebook/hhvm
43fb22d24348d0def2db70c1a7214aa6c4cf7ede
2019-06-12T03:15:13Z
mmm a / hphp / hack / src / heap / hh_shared . c <nl> ppp b / hphp / hack / src / heap / hh_shared . c <nl> static void memfd_reserve ( char * mem , size_t sz ) { <nl> <nl> static void memfd_reserve ( char * mem , size_t sz ) { <nl> off_t offset = ( off_t ) ( mem - shared_mem ) ; <nl> - if ( posix_fallocate ( memfd , offset , sz ) ) { <nl> + int err ; <nl> + do { <nl> + err = posix_fallocate ( memfd , offset , sz ) ; <nl> + } while ( err = = EINTR ) ; <nl> + if ( err ) { <nl> raise_out_of_shared_memory ( ) ; <nl> } <nl> } <nl>
Handle EINTR in posix_fallocate call
facebook/hhvm
34a061184677558c2c690dc928238e6b59fdb295
2019-11-08T19:23:27Z
mmm a / cmake / OpenCVDetectCUDA . cmake <nl> ppp b / cmake / OpenCVDetectCUDA . cmake <nl> if ( CUDA_FOUND ) <nl> message ( STATUS " CUDA detected : " $ { CUDA_VERSION } ) <nl> <nl> if ( CARMA ) <nl> - set ( CUDA_ARCH_BIN " 3 . 0 " CACHE STRING " Specify ' real ' GPU architectures to build binaries for , BIN ( PTX ) format is supported " ) <nl> + set ( CUDA_ARCH_BIN " 2 . 1 ( 2 . 0 ) 3 . 0 " CACHE STRING " Specify ' real ' GPU architectures to build binaries for , BIN ( PTX ) format is supported " ) <nl> set ( CUDA_ARCH_PTX " 3 . 0 " CACHE STRING " Specify ' virtual ' PTX architectures to build PTX intermediate code for " ) <nl> else ( ) <nl> set ( CUDA_ARCH_BIN " 1 . 1 1 . 2 1 . 3 2 . 0 2 . 1 ( 2 . 0 ) 3 . 0 " CACHE STRING " Specify ' real ' GPU architectures to build binaries for , BIN ( PTX ) format is supported " ) <nl> mmm a / modules / gpu / app / nv_perf_test / main . cpp <nl> ppp b / modules / gpu / app / nv_perf_test / main . cpp <nl> int main ( int argc , char * argv [ ] ) <nl> <nl> DEF_PARAM_TEST_1 ( Image , std : : string ) ; <nl> <nl> - PERF_TEST_P ( Image , HoughLinesP , <nl> - testing : : Values ( std : : string ( " im1_1280x800 . jpg " ) ) ) <nl> + GPU_PERF_TEST_P ( Image , HoughLinesP , testing : : Values ( std : : string ( " im1_1280x800 . jpg " ) ) ) <nl> { <nl> declare . time ( 30 . 0 ) ; <nl> <nl> std : : string fileName = GetParam ( ) ; <nl> <nl> - const double rho = 1 . 0 ; <nl> - const double theta = 1 . 0 ; <nl> + const float rho = 1 . f ; <nl> + const float theta = 1 . f ; <nl> const int threshold = 40 ; <nl> const int minLineLenght = 20 ; <nl> const int maxLineGap = 5 ; <nl> PERF_TEST_P ( Image , HoughLinesP , <nl> <nl> DEF_PARAM_TEST ( Image_Depth , std : : string , perf : : MatDepth ) ; <nl> <nl> - PERF_TEST_P ( Image_Depth , GoodFeaturesToTrack , <nl> - testing : : Combine ( <nl> + GPU_PERF_TEST_P ( Image_Depth , GoodFeaturesToTrack , <nl> + testing : : Combine ( <nl> testing : : Values ( std : : string ( " im1_1280x800 . jpg " ) ) , <nl> testing : : Values ( CV_8U , CV_16U ) <nl> ) ) <nl> typedef std : : pair < std : : string , std : : string > string_pair ; <nl> <nl> DEF_PARAM_TEST ( ImagePair_Depth_GraySource , string_pair , perf : : MatDepth , bool ) ; <nl> <nl> - PERF_TEST_P ( ImagePair_Depth_GraySource , OpticalFlowPyrLKSparse , <nl> - testing : : Combine ( <nl> - testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> - testing : : Values ( CV_8U , CV_16U ) , <nl> - testing : : Bool ( ) <nl> - ) ) <nl> + GPU_PERF_TEST_P ( ImagePair_Depth_GraySource , OpticalFlowPyrLKSparse , <nl> + testing : : Combine ( <nl> + testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> + testing : : Values ( CV_8U , CV_16U ) , <nl> + testing : : Bool ( ) <nl> + ) ) <nl> { <nl> declare . time ( 60 ) ; <nl> <nl> PERF_TEST_P ( ImagePair_Depth_GraySource , OpticalFlowPyrLKSparse , <nl> <nl> DEF_PARAM_TEST ( ImagePair_Depth , string_pair , perf : : MatDepth ) ; <nl> <nl> - PERF_TEST_P ( ImagePair_Depth , OpticalFlowFarneback , <nl> - testing : : Combine ( <nl> - testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> - testing : : Values ( CV_8U , CV_16U ) <nl> - ) ) <nl> + GPU_PERF_TEST_P ( ImagePair_Depth , OpticalFlowFarneback , <nl> + testing : : Combine ( <nl> + testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> + testing : : Values ( CV_8U , CV_16U ) <nl> + ) ) <nl> { <nl> declare . time ( 500 ) ; <nl> <nl> void calcOpticalFlowBM ( const cv : : Mat & prev , const cv : : Mat & curr , <nl> <nl> DEF_PARAM_TEST ( ImagePair_BlockSize_ShiftSize_MaxRange , string_pair , cv : : Size , cv : : Size , cv : : Size ) ; <nl> <nl> - PERF_TEST_P ( ImagePair_BlockSize_ShiftSize_MaxRange , OpticalFlowBM , <nl> - testing : : Combine ( <nl> - testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> - testing : : Values ( cv : : Size ( 16 , 16 ) ) , <nl> - testing : : Values ( cv : : Size ( 2 , 2 ) ) , <nl> - testing : : Values ( cv : : Size ( 16 , 16 ) ) <nl> - ) ) <nl> + GPU_PERF_TEST_P ( ImagePair_BlockSize_ShiftSize_MaxRange , OpticalFlowBM , <nl> + testing : : Combine ( <nl> + testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> + testing : : Values ( cv : : Size ( 16 , 16 ) ) , <nl> + testing : : Values ( cv : : Size ( 2 , 2 ) ) , <nl> + testing : : Values ( cv : : Size ( 16 , 16 ) ) <nl> + ) ) <nl> { <nl> - declare . time ( 1000 ) ; <nl> + declare . time ( 3000 ) ; <nl> <nl> const string_pair fileNames = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> const cv : : Size block_size = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> PERF_TEST_P ( ImagePair_BlockSize_ShiftSize_MaxRange , OpticalFlowBM , <nl> SANITY_CHECK ( 0 ) ; <nl> } <nl> <nl> - PERF_TEST_P ( ImagePair_BlockSize_ShiftSize_MaxRange , FastOpticalFlowBM , <nl> - testing : : Combine ( <nl> - testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> - testing : : Values ( cv : : Size ( 16 , 16 ) ) , <nl> - testing : : Values ( cv : : Size ( 1 , 1 ) ) , <nl> - testing : : Values ( cv : : Size ( 16 , 16 ) ) <nl> - ) ) <nl> + GPU_PERF_TEST_P ( ImagePair_BlockSize_ShiftSize_MaxRange , FastOpticalFlowBM , <nl> + testing : : Combine ( <nl> + testing : : Values ( string_pair ( " im1_1280x800 . jpg " , " im2_1280x800 . jpg " ) ) , <nl> + testing : : Values ( cv : : Size ( 16 , 16 ) ) , <nl> + testing : : Values ( cv : : Size ( 1 , 1 ) ) , <nl> + testing : : Values ( cv : : Size ( 16 , 16 ) ) <nl> + ) ) <nl> { <nl> - declare . time ( 1000 ) ; <nl> + declare . time ( 3000 ) ; <nl> <nl> const string_pair fileNames = std : : tr1 : : get < 0 > ( GetParam ( ) ) ; <nl> const cv : : Size block_size = std : : tr1 : : get < 1 > ( GetParam ( ) ) ; <nl> mmm a / modules / gpu / perf / perf_imgproc . cpp <nl> ppp b / modules / gpu / perf / perf_imgproc . cpp <nl> PERF_TEST_P ( Image , ImgProc_HoughLinesP , testing : : Values ( " cv / shared / pic5 . png " , " s <nl> <nl> std : : string fileName = getDataPath ( GetParam ( ) ) ; <nl> <nl> - const float rho = 1 . f ; <nl> - const float theta = float ( CV_PI ) / 180 . f ; <nl> + const float rho = 1 . 0f ; <nl> + const float theta = static_cast < float > ( CV_PI / 180 . 0 ) ; <nl> const int threshold = 100 ; <nl> const int minLineLenght = 50 ; <nl> const int maxLineGap = 5 ; <nl> mmm a / modules / gpu / perf / perf_softcascade . cpp <nl> ppp b / modules / gpu / perf / perf_softcascade . cpp <nl> <nl> # include " perf_precomp . hpp " <nl> <nl> - # define GPU_PERF_TEST_P ( fixture , name , params ) \ <nl> + # define PERF_TEST_P1 ( fixture , name , params ) \ <nl> class fixture # # _ # # name : public fixture { \ <nl> public : \ <nl> fixture # # _ # # name ( ) { } \ <nl> namespace { <nl> typedef std : : tr1 : : tuple < std : : string , std : : string > fixture_t ; <nl> typedef perf : : TestBaseWithParam < fixture_t > SCascadeTest ; <nl> <nl> - GPU_PERF_TEST_P ( SCascadeTest , detect , <nl> + PERF_TEST_P1 ( SCascadeTest , detect , <nl> testing : : Combine ( <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / sc_cvpr_2012_to_opencv . xml " ) ) , <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / bahnhof / image_00000000_0 . png " ) ) ) ) <nl> static cv : : Rect getFromTable ( int idx ) <nl> typedef std : : tr1 : : tuple < std : : string , std : : string , int > roi_fixture_t ; <nl> typedef perf : : TestBaseWithParam < roi_fixture_t > SCascadeTestRoi ; <nl> <nl> - GPU_PERF_TEST_P ( SCascadeTestRoi , detectInRoi , <nl> + PERF_TEST_P1 ( SCascadeTestRoi , detectInRoi , <nl> testing : : Combine ( <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / sc_cvpr_2012_to_opencv . xml " ) ) , <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / bahnhof / image_00000000_0 . png " ) ) , <nl> RUN_GPU ( SCascadeTestRoi , detectInRoi ) <nl> NO_CPU ( SCascadeTestRoi , detectInRoi ) <nl> <nl> <nl> - GPU_PERF_TEST_P ( SCascadeTestRoi , detectEachRoi , <nl> + PERF_TEST_P1 ( SCascadeTestRoi , detectEachRoi , <nl> testing : : Combine ( <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / sc_cvpr_2012_to_opencv . xml " ) ) , <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / bahnhof / image_00000000_0 . png " ) ) , <nl> RUN_GPU ( SCascadeTestRoi , detectEachRoi ) <nl> <nl> NO_CPU ( SCascadeTestRoi , detectEachRoi ) <nl> <nl> - GPU_PERF_TEST_P ( SCascadeTest , detectOnIntegral , <nl> + PERF_TEST_P1 ( SCascadeTest , detectOnIntegral , <nl> testing : : Combine ( <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / sc_cvpr_2012_to_opencv . xml " ) ) , <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / integrals . xml " ) ) ) ) <nl> RUN_GPU ( SCascadeTest , detectOnIntegral ) <nl> <nl> NO_CPU ( SCascadeTest , detectOnIntegral ) <nl> <nl> - GPU_PERF_TEST_P ( SCascadeTest , detectStream , <nl> + PERF_TEST_P1 ( SCascadeTest , detectStream , <nl> testing : : Combine ( <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / sc_cvpr_2012_to_opencv . xml " ) ) , <nl> testing : : Values ( std : : string ( " cv / cascadeandhog / bahnhof / image_00000000_0 . png " ) ) ) ) <nl> mmm a / modules / gpu / src / cuda / optflowbm . cu <nl> ppp b / modules / gpu / src / cuda / optflowbm . cu <nl> namespace optflowbm_fast <nl> { <nl> } <nl> <nl> - __device__ void initSums_BruteForce ( int i , int j , int * dist_sums , PtrStepi & col_sums , PtrStepi & up_col_sums ) const <nl> + __device__ __forceinline__ void initSums_BruteForce ( int i , int j , int * dist_sums , PtrStepi & col_sums , PtrStepi & up_col_sums ) const <nl> { <nl> for ( int index = threadIdx . x ; index < search_window * search_window ; index + = STRIDE ) <nl> { <nl> namespace optflowbm_fast <nl> } <nl> } <nl> <nl> - __device__ void shiftRight_FirstRow ( int i , int j , int first , int * dist_sums , PtrStepi & col_sums , PtrStepi & up_col_sums ) const <nl> + __device__ __forceinline__ void shiftRight_FirstRow ( int i , int j , int first , int * dist_sums , PtrStepi & col_sums , PtrStepi & up_col_sums ) const <nl> { <nl> for ( int index = threadIdx . x ; index < search_window * search_window ; index + = STRIDE ) <nl> { <nl> namespace optflowbm_fast <nl> } <nl> } <nl> <nl> - __device__ void shiftRight_UpSums ( int i , int j , int first , int * dist_sums , PtrStepi & col_sums , PtrStepi & up_col_sums ) const <nl> + __device__ __forceinline__ void shiftRight_UpSums ( int i , int j , int first , int * dist_sums , PtrStepi & col_sums , PtrStepi & up_col_sums ) const <nl> { <nl> int ay = i ; <nl> int ax = j + block_radius ; <nl> namespace optflowbm_fast <nl> } <nl> } <nl> <nl> - __device__ void convolve_window ( int i , int j , const int * dist_sums , float & velx , float & vely ) const <nl> + __device__ __forceinline__ void convolve_window ( int i , int j , const int * dist_sums , float & velx , float & vely ) const <nl> { <nl> int bestDist = numeric_limits < int > : : max ( ) ; <nl> int bestInd = - 1 ; <nl> namespace optflowbm_fast <nl> } <nl> } <nl> <nl> - __device__ void operator ( ) ( PtrStepf velx , PtrStepf vely ) const <nl> + __device__ __forceinline__ void operator ( ) ( PtrStepf velx , PtrStepf vely ) const <nl> { <nl> int tbx = blockIdx . x * TILE_COLS ; <nl> int tby = blockIdx . y * TILE_ROWS ; <nl> mmm a / modules / gpu / src / softcascade . cpp <nl> ppp b / modules / gpu / src / softcascade . cpp <nl> struct cv : : gpu : : SCascade : : Fields <nl> int dcs = 0 ; <nl> for ( int sc = 0 ; sc < totals ; + + sc ) <nl> { <nl> - int width = : : std : : max ( 0 . 0f , fw - ( origObjWidth * scale ) ) ; <nl> - int height = : : std : : max ( 0 . 0f , fh - ( origObjHeight * scale ) ) ; <nl> + int width = ( int ) : : std : : max ( 0 . 0f , fw - ( origObjWidth * scale ) ) ; <nl> + int height = ( int ) : : std : : max ( 0 . 0f , fh - ( origObjHeight * scale ) ) ; <nl> <nl> float logScale = : : log ( scale ) ; <nl> int fit = fitOctave ( voctaves , logScale ) ; <nl> cv : : gpu : : SCascade : : ~ SCascade ( ) { delete fields ; } <nl> bool cv : : gpu : : SCascade : : load ( const FileNode & fn ) <nl> { <nl> if ( fields ) delete fields ; <nl> - fields = Fields : : parseCascade ( fn , minScale , maxScale , scales , flags ) ; <nl> + fields = Fields : : parseCascade ( fn , ( float ) minScale , ( float ) maxScale , scales , flags ) ; <nl> return fields ! = 0 ; <nl> } <nl> <nl> void cv : : gpu : : SCascade : : detect ( InputArray _image , InputArray _rois , OutputArray <nl> { <nl> flds . update ( image . rows , image . cols , flds . shrinkage ) ; <nl> <nl> - if ( flds . check ( minScale , maxScale , scales ) ) <nl> + if ( flds . check ( ( float ) minScale , ( float ) maxScale , scales ) ) <nl> flds . createLevels ( image . rows , image . cols ) ; <nl> <nl> flds . preprocessor - > apply ( image , flds . shrunk ) ; <nl> cv : : Ptr < cv : : gpu : : ChannelsProcessor > cv : : gpu : : ChannelsProcessor : : create ( const int <nl> cv : : gpu : : ChannelsProcessor : : ChannelsProcessor ( ) { } <nl> cv : : gpu : : ChannelsProcessor : : ~ ChannelsProcessor ( ) { } <nl> <nl> - # endif <nl> \ No newline at end of file <nl> + # endif <nl> mmm a / modules / ts / include / opencv2 / ts / ts_perf . hpp <nl> ppp b / modules / ts / include / opencv2 / ts / ts_perf . hpp <nl> CV_EXPORTS void PrintTo ( const Size & sz , : : std : : ostream * os ) ; <nl> INSTANTIATE_TEST_CASE_P ( / * none * / , fixture # # _ # # name , params ) ; \ <nl> void fixture # # _ # # name : : PerfTestBody ( ) <nl> <nl> + # define GPU_PERF_TEST_P ( fixture , name , params ) \ <nl> + class fixture # # _ # # name : public fixture { \ <nl> + public : \ <nl> + fixture # # _ # # name ( ) { } \ <nl> + protected : \ <nl> + virtual void PerfTestBody ( ) ; \ <nl> + } ; \ <nl> + TEST_P ( fixture # # _ # # name , name / * perf * / ) \ <nl> + { \ <nl> + try { RunPerfTestBody ( ) ; } \ <nl> + catch ( . . . ) { cv : : gpu : : resetDevice ( ) ; throw ; } \ <nl> + } \ <nl> + INSTANTIATE_TEST_CASE_P ( / * none * / , fixture # # _ # # name , params ) ; \ <nl> + void fixture # # _ # # name : : PerfTestBody ( ) <nl> + <nl> <nl> # define CV_PERF_TEST_MAIN ( testsuitname , . . . ) \ <nl> int main ( int argc , char * * argv ) \ <nl> mmm a / samples / gpu / softcascade . cpp <nl> ppp b / samples / gpu / softcascade . cpp <nl> int main ( int argc , char * * argv ) <nl> <nl> std : : cout < < " working . . . " < < std : : endl ; <nl> cv : : imshow ( " Soft Cascade demo " , result ) ; <nl> - cv : : waitKey ( 10 ) ; <nl> + if ( 27 = = cv : : waitKey ( 10 ) ) <nl> + break ; <nl> } <nl> <nl> return 0 ; <nl>
merge CUDA dev branch
opencv/opencv
45191dd6a57b3d5bb17b662bc4535c8cf248a520
2012-12-29T15:44:38Z