�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �~   �� ���P*P*��9� ~�E~�E~��U~�>���")07=CJQX_fmt{������������������� !'.5<CJQX_fmtz������������������� &-4;AHOV]dkry������������������� &-4:AGNU\cjqx������������������#*18?FMT[ahov}������������������� &-4:AGNU\cjqx~������������������$*18?FMT[bipw~������������������#*18?FMT[bipv}������������������#*18?FMT[bipw~������������������     # * 1 8 ? F L S Z a h o u { � � � � � � � � � � � � � � � � � � �     & - 4 ; B I P W ] d j q x  � � � � � � � � � � � � � � � � � �     # * 1 8 ? F M T Y ` g n t { � � � � � � � � � � � � � � � � � � �     $ + 2 9 @ G N U \ c j p w ~ � � � � � � � � � � � � � � � � � �     # * 1 8 ? D K R Y ` g n u | � � � � � � � � � � � � � � � � � � �  #)07>ELRX_flsy�������������������� &-4;BIPW^dkry������������������� #*18?ELSZahov|������������������� &-4;BINU\cipw~������������������ &-4;AHOV]dkry�������������������")07>ELSZahov}�������������������")06=DKRY`gnu{������������������� !(/6=DKRY_fmt{�������������������  '.5<CJQX_elsz������������������� %,3:AHOU[bipw~������������������� &-4:@FLSZahov}������������������� !(.5<BIOU[bipw~������������������ $+18?FMT[bipw~������447640349605805268564557647226483051894082561299296011682702473542641549773570323343295154978814517485290253928753982860297896471342748543662742087748203774412074931279945277347637892203684150427135626983275294977060202512161362341540964424711205322551513995323677619013175647026791328690477072917141425431957558276033180322562055113427925481245109596243312043824061483941311300565856324278165664423519947371858118513784149195204690529690014319390439709353750303471592299962212270639001256151614311466627475251590135996081605594643903194720774530223944640511878885380661516861716478943039907153238443865485482691349151251891231145916279391157737195232041171597156192433081123481503396509252231042505022011338117012439498402030725218214654217011443807137755813616374117000164252437406032423595185798237497413752855235540341916726040165663884667933596605037155515088496486321217619123761735586025262705544469212416277988756224853651351331283622189286726560205150534333624201515860966572671784417381693502645834372305256593734513193391394241186598130040926169326210312912342672283077399502158419741744929537856344732468471405049602421178610323341804584367053220208296325036372442385792396164953046839062586153438459212653779921832218164485731835924370174201132130433644345119480611616727521260765890222305603153326232351311793505388700982903235133362267346323403835760557164323805004233345441964732534449884003658149472100950119393878329269503351562395597424069322307062161898473404302352125235866056085953188926652197272729461612957985943612909601421328621385515220832153183707151383408811263131519428155907824613245503094298351546018575550149200135232002502635443129435391353245926394625873480336730375611102049134393755912515654143721582563822657299404441089280462297895848548553643365477577224821822943475456098161756795529468340287139131041061320374351711945431751565240790818511353786111124646258634039640005039758262871732189625691548252670640149441495591195581249655385622302368901154920311538539238697356002624790431787261213675713910473229074424031632830452775404065357614853441564172942210111589721423645119340476424638751446180063415307112954583859839535509955204701396699114193156310746026619492424143389584474652158698731196643490538561129888619813790924869031723665561745618173351077905645378371602637678864905299207347134496082259450469696359883115974055399112342082338070514585810134867915719283848162402962815158598859549897474805622376096718507944724825353571785166016147093355227448134919245954891054292054130169113627291302463329520972585253936451076272501905610681016934212631971325923421365024204552579707015051726335573157530231704940400808304271489068213882041083694705610609020551948481418458179789751737578090742668330823232566254492452444378330938871597691420834051173301113270446150837208652883306420043660737595023323557948661996335379525286299821977465971677250225515124823973052497974135310352333518316325321581859544875216612703019519885954820387488831722004959318391071774792418390043718894193635122132492571039767363456774420131641352063718729448408321434538230245212339862043378095520997734171393616791949575526204024389897328915293807736380069742632935205403735831536941747174193764431197012511351594055108550503129245043323173516216066663537456580082825129645886364378647542881431895180181392343529801468588563098660757421211187396191224082373727269107174190051279394810282554709376496769530590655931867562354633960699947804682525443941912863392636693138828237307092761400408135242975085723090331919218297187264121073146022108241486857791119393395510639209475422369564986396480376821318824418740312740040454551726348833419984796753723938114521111134755284366042216632031414444457163883191445479892188805142587669327238999843246840329928036410745170493295075390311440140315231845524973220646463941259696833146145563362268609858037797144124577424596967528447214780534346691186664819211786121234283976151098917081545921997459824357082693196764313542152481614156714385536552484412879461220491180631736887004844106942705589538049829153702403394569736715139276135944420577513830082753418877131686741240260543431365091056174599125674861117385661478564535499219922311146008625923150586276418444353984132766033908382718884370861104091912078036200375590142431636545658003469147245464833894847428239218840383283444429666298031429296041046215440918946125011063139351537718133315062161693219496521858748438724731039490448827449838732565484532617600440670882002205222850934555199952469744754074387422964340084435906786555179743385783421814304632719122614075406240673373276260518533462285199713302360265749796890178883545977874753451430017411179595612592629742110151315904614596413511016554600903865507543896252758812458653057841340825159035484601094393877623768542802723608955690026217271033083209289525462783693612330289585696322746166178882057991285331226289577189044913713965491981524116813832903224098360052542301444255388534198410982085299758212077953768646227951592582772965718414278104488036038451734816662936483735636168457656229858775974212370228547116258435220430173768835312168266623925915609489653356729085656546733715964598498114400897574611817951138215714225241793186255210945249354509876482887748703372748831173863484250171135461751353660553717320507127956546004721092208278235182013509315618566852482596077967420947846212193240681628463629040995892104153834744438481356813160789348517311012472603434161111504716890142692411791811180782111181628252312946194281023438697232902283464844220458037650584166432851311362706324500293217394535242627434165654149557056945291363968368191074348113731689379255110931748916939015363460240296478859750863011130191285082463191593773157371214751098485900081424227171923530249015506376357867325806802198944235716677316121524001323858183527433183091179242370317279333023846031641581920524255668757073923251912140607529508173575927116496266358323099912293051422661114716332819005494519334013304935647947850747294534183928335074002413512457446030233035470286954083367570196227135581018895574108375891858391931831929203817099815937061600237117652761851776393258720333424733568190015200515526869115520188497007832920804452405136501215128629192621686349852560136042036875463724938445352766321521547646065286203984156520047308785835791571000459735433415081623242744371250775039829084485373320302438598736277580406985827039324021241892532503214125484248811314493767144757350429519957644768386513996036157427007805355106294487619526249160327804811375003504246168625362830573413891560245151443314401468478107751508469191181643421601683819515204365523105638758264344362977334330353033165942666587854015698161678270290675540690838886235321708957238253998361198371823160168562312843955694716241985650421772468366576251135854094970311341639605897353783044923765773786^?� �H^���h� �� �% `�� � 6�8�9�@\IHL�R��������} ��w�-QHY"m-{ �\�9�x�2�B��� �qO�v$w�Ή1��2h������2�� I���ِ<���������5�r�>�m�J%r(S*UE&F�IZ�sfyQ��� � � � �$ �* �0 h6 07 L9 �< �= �e �g �n � � � �� � S� �� �I �J�Qsg~��p�����3��W����)�D�h����������j�E���H ��N�P�+�&*^034�6[=�S��d�U��w\�c�2�n��"o27�9G+S�[�a�k�t��}�� � n y �J $L ,S �X � j� �� )2!�S!UY!�"�!"�#"�&"�)"GN"�N"]"*s"JS$jZ$�[$Vu$hv$8y$�$��$ܩ$�$��$�$5%+ &,&\"&�<)pH)U^)�_)�`)-d)Re)�s)Zv)5�*��*��+��+/�+m�+�),z8,}E,�V,�,�,��,��,��,��,��,{�,}�,�-�@-�b-�e-��-��-��-�-��-��-_�-�-�.j.�.�.C.B).6.�I.�v0=�0��0�0H�0ٯ0��0�0��0d�0�1p"1�&1�@1��3YP4�U4ra4�w4`�4��4��4v�4P�4ڡ4��4�44�4��4��4�5�5)5G5�5�Y5�^5e5�i5Wo5��5c�5��5�6<)68,6�H6�O6 S6<]6^6�a6�d68f6�m6?�6�6��6��6�6��6A�6h�6�6 �6a;:�A:2B:�F:�K:�O:�Q:�Z: `:�r:,]<�`<�j<�l<��<u�<��<4 =�'=[9=�D=d=�e=�n=��=�=؍=��=��=g�= �=V�=$> >�%> A>7F>�O>�T>�>��>+�>�> ??lD?�^?�h?k?�u?�v?/�?^�?Y�?ئ?O�?V�Bk�BA�E�ES�E��E�EмE��E}�Ef�F��F�G�#G^&G�.G�5Gr6G\9G��GiaH�sHN�H��H��H �HQ�H�HF�HW�H��H@tI�}I��I��I�I}�IV�IT�I��I�IW�I�8J O�?O�iO�qO֗O�P� P� P�>R�AR�1S9:S�?S�JS�LS�S��SK�S�S��S|�S��S��S �S �S0T�@T3KTST�"U=U*{U��U�V�V(*Vw0V�6V�BVCVmEV�RVjV�jVolV8�V4�Vf�V��V�V�V�:W�BW�JWQ�X5�Y��Y��Y��Y��Y��Y��Y@�Y�ZMZ�8Z�8Z"VZ�iZ�qZӈZߟZ��Z��Z��Z5�Z [� [e[�[�[��[��[j�[R�[w�[��[�\�\�\a\}\t"\q:\W?\,P\�s\G�\�\p�\R�\8�\�]O]d*]*K]6M]�f]�v]�w]��]�]��]}�]N�]�]��]��],�]��]��]�^^#^%^�/^�1^n?^�C^cF^s^^�p^dq^�q^�r^�s^e~^��^��^��^��^��^��_<�_$�_i�_j`2,`}K`�M`�O`�Q`�T`k`�k`��`�_a�b`�b��bTc�c�cg�f��f��fg[g�gl-g9.g�6g:g�>gdg�lgY�gX�g��gj�g��gΓg��gâgάg�hh#`h(eh�qhnsh�h��h�h��h_�h��h�i7i:i Dijfi�xim}i�i6�i>�iؘiO�iL�i��i� jj�jHjq j-"j�#j^6jF;j�Bj�Cj~Ij�Qj�ejijWqjuj�}jU�j�j �j?�j��j�k`SkUk�gkajk�vk|�k��k5�k��kql�l�l�l3!l%@lIlm|l�}lm�l��lk�l��l��lK�l��m�m��m��m��mV�m[�mA�m�n.jnHnn'snDynj�nJ�nǐnk�nN�n$�n}�n��n��n��n��n��nK�n<�n�o#o&!o�&o0Zo�^o�eo�o�o��o �o$�o��o��o��o"�o%�o �o��o��op p�p�p�=pIp�Qp�ip��p�pe�pu�p��pd�p�p1�p��p�p��p�qRq�[q�_q�`qQ�q��qr�NraSrger#nr�r$�r�rV�rT�r��rs�OsVs�Ws"[s�]s�`s�esӉsr�sn�s�s��su�s/ tW1t�@t�AtZt�Zt�]titמtw�t�t[u�u�u.uj6u�9uW@u�Yu [u�\uQ�u��u��uΝu�u�u��u$�u=�u��u��u��u��u�v� v v�Nv�Yv;avgv�v$�v��v��v��w��wk�w�w��w��w��w �wo�w_mxBux�x��xv�x9�x+�xn�x��x>�x}yy�#|Q'|.*|�4|�7|��|��|��|��|��|��|��|� }� }�}20}�9}[G}1J}�R}tU}�V}[u}Ð}P�}p�}M�}}�}y�}� ~1019.cpp #include #include using namespace std; int main(void) { int n, x; cin >> n; x = n / 3600; cout << x << ":"; n -= x * 3600; x = n / 60; cout << x << ":"; n -= x * 60; cout << n << endl; return 0; } #include "ir_exp_const.hpp" #include "../mappers/generic/ir_exp_mapper.hpp" namespace splicpp { void ir_exp_const::map(ir_exp_mapper& t) const { t.map(std::static_pointer_cast(shared_from_this())); } void ir_exp_const::print(std::ostream& s, const uint) const { s << "CONST(" << i << ")"; } } // Author: #include #include #include "polynomial_solver.h" #include "polynomial_sampler.h" using namespace p4; int main(int argc, char** argv) { const size_t num_nodes = 10000; std::vector times = {0}; // Equality bounds paramater order is: // 1) Dimension index // 2) Node index // 3) Derivative index // 4) Value std::vector equality_bounds = { NodeEqualityBound(0,0,0,0), NodeEqualityBound(0,0,1,0), NodeEqualityBound(0,0,2,0), }; for(size_t node_idx = 1; node_idx < num_nodes; ++node_idx) { times.push_back(node_idx); equality_bounds.push_back(NodeEqualityBound(0,node_idx,0,node_idx)); } PolynomialSolver::Options solver_options; solver_options.num_dimensions = 1; solver_options.polynomial_order = 7; solver_options.continuity_order = 4; solver_options.derivative_order = 4; solver_options.osqp_settings.polish = true; // Polish the solution, getting the best answer possible solver_options.osqp_settings.verbose = true; // Suppress the printout PolynomialSolver solver(solver_options); const PolynomialSolver::Solution solution = solver.Run(times, equality_bounds,{},{}); return EXIT_SUCCESS; } #pragma once #include namespace AllegroFlare { class PickingBuffer { private: ALLEGRO_BITMAP *surface_render; int w, h; int depth; ALLEGRO_BITMAP *create_new_surface(int w, int h, int depth); static int decode_id(ALLEGRO_COLOR color); static ALLEGRO_COLOR encode_id(int id); public: static const int ID_MAX = 16777216; PickingBuffer(int w=1, int h=1, int depth=0); ~PickingBuffer(); void initialize(); void clear_surface(); ALLEGRO_BITMAP *get_surface_render(); int get_surface_width(); int get_surface_height(); int get_id(int x, int y); }; } 0 /***************************************************************************** * * Freescale Confidential Proprietary * * Copyright (c) 2014 Freescale Semiconductor; * All Rights Reserved * ***************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include #include #include typedef unsigned int REG32; #include "apex_642cl_motion_comp_map.h" #if ((1 == APEX_SIM_ISS) || (1 == APEX_SIM_NATIVE)) #include #endif void mce_hal_program_linkedlist(int lApexID, unsigned int chNo, unsigned int linkedListAddr) { volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); lpMceRegisters->Ch[chNo].LinkedList.as32BitValue = (linkedListAddr | 0x01); } void mce_hal_program_nonseq_linkedlist(int lApexID, unsigned int chNo, unsigned int linkedListAddr) { volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); lpMceRegisters->Ch[chNo].LinkedList.as32BitValue = (linkedListAddr | 0x03); } void mce_hal_enable_ch(int lApexID, unsigned int chNo) { volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); #if (!((1 == APEX_SIM_ISS) || (1 == APEX_SIM_NATIVE))) lpMceRegisters->ChEnable.as32BitValue = (1 << chNo); #else MceChStep(lApexID, chNo); #endif } void mce_hal_wait_polling(int lApexID, unsigned int chNo) { volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); while(lpMceRegisters->ChEnable.as32BitValue & (1 << chNo)) ; } #if !defined(__chess__) && !defined(__clang__) //THIS FUNCTION IS ONLY FOR HOST USE (i.e. do not use on the APU)!!!! int mce_hal_wait_ch_enable_timeout(int lApexID, unsigned int chNo, int timeoutInUs) { int retVal = 0; volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); uint64_t timeoutProbe = RET_TICKS; while(lpMceRegisters->ChEnable.as32BitValue & (1 << chNo)) { if (CONVERT_TICKS_TO_US(RET_TICKS - timeoutProbe) >= timeoutInUs) { lpMceRegisters->ChClear.as32BitValue = (1 << chNo); retVal = 1; break; } _wait_cc(10); //prevent overly aggressive polling } lpMceRegisters->Icr.as32BitValue = (1 << chNo); return retVal; } #endif //!defined(__chess__) && !defined(__clang__) void mce_hal_clear_int(int lApexID, unsigned int chNo) { volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); #if (!((1 == APEX_SIM_ISS) || (1 == APEX_SIM_NATIVE))) lpMceRegisters->Icr.as32BitValue = (1 << chNo); #else lpMceRegisters->Isr.as32BitValue &= (~(1 << chNo)); #endif } void mce_hal_clear_ch(int lApexID, unsigned int chNo) { volatile APEX_642CL_MOTION_COMP_DCR *const lpMceRegisters = (APEX_642CL_MOTION_COMP_DCR*)ReturnVirtualHwPtr(lApexID, HW_REG_MODMA); lpMceRegisters->ChClear.as32BitValue = (1 << chNo); }// 剑指 Offer 03. 数组中重复的数字 // 21/12/25 HashTable #include struct Solution { int findRepeatNumber(vector &nums) { std::bitset<100000> counts; for (auto &&n : nums) { if (counts.test(n)) { return n; } else { counts.set(n); } } return -1; } }; // 22/03/06 参考书中,交换排序检测重复,T=O(N) struct Solution { int findRepeatNumber(vector &nums) { for (int i = 0; i < nums.size(); ) { if (nums[i] == i) { i++; } else { int x = nums[i]; if (nums[x] == x) { return x; } else { swap(nums[x], nums[i]); } } } return -1; } }; cedricga91/framework // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* Variable.cc (C) 2000-2022 */ /* */ /* Classe gérant une variable. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #ifndef ARCANE_VARIABLE_CC #define ARCANE_VARIABLE_CC /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/utils/List.h" #include "arcane/utils/FatalErrorException.h" #include "arcane/utils/OStringStream.h" #include "arcane/utils/Iterator.h" #include "arcane/utils/Iostream.h" #include "arcane/utils/String.h" #include "arcane/utils/ITraceMng.h" #include "arcane/utils/PlatformUtils.h" #include "arcane/utils/IStackTraceService.h" #include "arcane/utils/MemoryAccessInfo.h" #include "arcane/utils/NotImplementedException.h" #include "arcane/utils/ScopedPtr.h" #include "arcane/utils/StringBuilder.h" #include "arcane/ItemGroupObserver.h" #include "arcane/expr/Expression.h" #include "arcane/VariableExpressionImpl.h" #include "arcane/Variable.h" #include "arcane/VarRefEnumerator.h" #include "arcane/IVariableAccessor.h" #include "arcane/ItemGroup.h" #include "arcane/IMesh.h" #include "arcane/IItemFamily.h" #include "arcane/ISubDomain.h" #include "arcane/VariableInfo.h" #include "arcane/ISerializer.h" #include "arcane/VariableBuildInfo.h" #include "arcane/VariableComputeFunction.h" #include "arcane/CommonVariables.h" #include "arcane/Observable.h" #include "arcane/IVariableMng.h" #include "arcane/IDataReader.h" #include "arcane/IDataWriter.h" #include "arcane/IParallelMng.h" #include "arcane/VariableDependInfo.h" #include "arcane/IParallelReplication.h" #include "arcane/VariableMetaData.h" #include "arcane/IMeshMng.h" #include "arcane/MeshHandle.h" #include #include /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arcane { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* * \brief Partie privée d'une variable. */ class VariablePrivate { public: VariablePrivate(const VariableBuildInfo& v,const VariableInfo& vi); ~VariablePrivate(){} public: static Int64 modified_time_global_value; public: ISubDomain* m_sub_domain = nullptr; IDataFactoryMng* m_data_factory_mng = nullptr; MeshHandle m_mesh_handle; //!< Maillage (peut être nul) Ref m_data; //!< Données de la variable ItemGroup m_item_group; //!< Groupe d'entité sur lequel est associé la variable IItemFamily* m_item_family = nullptr; //!< Familly d'entité (peut être nul) VariableInfo m_infos; //!< Infos caractéristiques de la variable int m_property; //!< Propriétés de la variable bool m_is_partial; //!< Vrai si la variable est partielle bool m_need_property_update; bool m_is_used; //!< Etat d'utilisation de la variable bool m_has_valid_data; //!< Vrai si les données sont valide Real m_last_update_time; //!< Temps physique de la dernière mise à jour VariableRef* m_first_reference = nullptr; //! Première référence sur la variable Integer m_nb_reference; UniqueArray m_depends; //!< Liste des dépendances de cette variable Int64 m_modified_time; //!< Tag de la dernière modification ScopedPtrT m_compute_function; //!< Fonction de calcul AutoDetachObservable m_write_observable; //!< Observable en écriture AutoDetachObservable m_read_observable; //!< Observable en lecture AutoDetachObservable m_on_size_changed_observable; //!< Observable en redimensionnement std::map m_tags; //!< Liste des tags bool m_has_recursive_depend; //!< Vrai si les dépendances sont récursives bool m_want_shrink = false; public: /*! * \brief Sérialise le `hashid`. * * Lors de la désérialisation, vérifie que le `hashid` est correctement * et si ce n'est pas le cas renvoie une exception. */ void serializeHashId(ISerializer* sbuf) { switch(sbuf->mode()){ case ISerializer::ModeReserve: sbuf->reserveSpan(DT_Byte,HASHID_SIZE); break; case ISerializer::ModePut: sbuf->putSpan(Span(m_hash_id,HASHID_SIZE)); break; case ISerializer::ModeGet: { Byte read_hash_id_buf[HASHID_SIZE]; Span read_span(read_hash_id_buf,HASHID_SIZE); sbuf->getSpan(read_span); Span ref_span(m_hash_id,HASHID_SIZE); if (ref_span!=Span(read_span)) ARCANE_FATAL("Bad hashid for variable name='{0}'\n" " expected_hash_id='{1}'\n" " hash_id ='{2}'\n" " This may be due to incoherence in variable list (order) between ranks" " during serialization", m_infos.fullName(),String(ref_span),String(read_span)); } break; } } private: static const int HASHID_SIZE = 64; /*! * \brief hash de la variable pour vérifier la cohérence de la sérialisation. * * Les 16 premiers octets sont le hash du nom au format hexadécimal (issu d'un Int64) * et les suivants sont le nom complet (fullName()), éventuellement tronqué, de la variable. * Les éventuels caractères restants sont des '~'. */ Byte m_hash_id[HASHID_SIZE]; void _setHashId() { constexpr Int64 hashid_hexa_length = 16; constexpr Int64 name_length = HASHID_SIZE - hashid_hexa_length; Span hash_id(m_hash_id,HASHID_SIZE); hash_id.fill('~'); const String& full_name = m_infos.fullName(); Int64 hash_value = IntegerHashFunctionT::hashfunc(full_name.view()); Convert::toHexaString(hash_value,hash_id); Span bytes = full_name.bytes(); if (bytes.size()>name_length) bytes = bytes.subspan(0,name_length); auto hash_id2 = hash_id.subspan(hashid_hexa_length,name_length); hash_id2.copy(bytes); } }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Int64 VariablePrivate::modified_time_global_value = 1; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Int64 IVariable:: incrementModifiedTime() { //TODO: Utiliser version atomique. Int64 v = VariablePrivate::modified_time_global_value; ++VariablePrivate::modified_time_global_value; return v; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ VariablePrivate:: VariablePrivate(const VariableBuildInfo& v,const VariableInfo& vi) : m_sub_domain(v._subDomain()) , m_data_factory_mng(v.dataFactoryMng()) , m_mesh_handle(v.meshHandle()) , m_item_family(nullptr) , m_infos(vi) , m_property(v.property()) , m_is_partial(vi.isPartial()) , m_need_property_update(false) , m_is_used(false) , m_has_valid_data(false) , m_last_update_time(0.0) , m_first_reference(nullptr) , m_nb_reference(0) , m_modified_time(0) , m_has_recursive_depend(true) { _setHashId(); m_infos.setDefaultItemGroupName(); // Pour test uniquement if (!platform::getEnvironmentVariable("ARCANE_NO_RECURSIVE_DEPEND").null()) m_has_recursive_depend = false; // Pour teste de libération mémoire. { String str = platform::getEnvironmentVariable("ARCANE_VARIABLE_SHRINK_MEMORY"); if (str=="1") m_want_shrink = true; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ //! Observer des évènements sur ItemGroup sous-jacent. class ItemGroupPartialVariableObserver : public IItemGroupObserver { public: ItemGroupPartialVariableObserver(IVariable * var) : m_var(var) { ARCANE_ASSERT((m_var),("Variable pointer null")); if(var->itemGroup().isAllItems()) ARCANE_FATAL("No observer should be attached on all items group"); } ~ItemGroupPartialVariableObserver() {} void executeExtend(const Int32ConstArrayView * info) { const Int32ConstArrayView & new_ids = *info; if (new_ids.empty()) return; ItemGroup group = m_var->itemGroup(); SharedPtrT id_to_index = group.localIdToIndex(); const Integer old_size = id_to_index->size(); const Integer group_size = group.size(); if (group_size != (old_size+new_ids.size())) ARCANE_FATAL("Inconsitent extended size"); m_var->resizeFromGroup(); //id_to_index->update(); } void executeReduce(const Int32ConstArrayView * info) { // contient la liste des localids des items supprimés dans l'ancien groupe const Int32ConstArrayView & removed_lids = *info; if (removed_lids.empty()) return; ItemGroup group = m_var->itemGroup(); SharedPtrT id_to_index = group.localIdToIndex(); const Integer old_size = id_to_index->size(); const Integer group_size = group.size(); if (group_size != (old_size-removed_lids.size())) ARCANE_FATAL("Inconsitent reduced size {0} vs {1}",group_size,old_size); ItemVectorView view = group.view(); Int32UniqueArray source, destination; source.reserve(group_size); destination.reserve(group_size); for(Integer i=0,index=0,removed_index=0; ikeyLocalId(i) == removed_lids[removed_index]) { ++removed_index; } else { ARCANE_ASSERT((id_to_index->keyLocalId(i) == view[index].localId()), ("Inconsistent key (pos=%d,key=%d) vs (pos=%d,key=%d)", i,id_to_index->keyLocalId(i),index,view[index].localId())); if (i != index) { destination.add(index); source.add(i); } ++index; } } m_var->copyItemsValues(source,destination); m_var->resizeFromGroup(); } void executeCompact(const Int32ConstArrayView* info) { const Int32ConstArrayView & ids = *info; if (ids.empty()) return; ItemGroup group = m_var->itemGroup(); SharedPtrT id_to_index = group.localIdToIndex(); m_var->compact(*info); //id_to_index->compact(info); } void executeInvalidate() { ItemGroup group = m_var->itemGroup(); SharedPtrT id_to_index = group.localIdToIndex(); m_var->resizeFromGroup(); //id_to_index->update(); } bool needInfo() const { return true; } private: IVariable* m_var; }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Variable:: Variable(const VariableBuildInfo& v,const VariableInfo& vi) : TraceAccessor(v.traceMng()) , m_p(new VariablePrivate(v,vi)) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Variable:: ~Variable() { //NOTE: si la variable possède un groupe, c'est le IVariableMng // qui supprime la référence de cette variable sur le groupe delete m_p; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ bool Variable:: _hasReference() const { return m_p->m_first_reference; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: addVariableRef(VariableRef* ref) { _checkSetProperty(ref); ++m_p->m_nb_reference; ref->setNextReference(m_p->m_first_reference); if (m_p->m_first_reference){ VariableRef* _list = m_p->m_first_reference; if (_list->previousReference()) _list->previousReference()->setNextReference(ref); _list->setPreviousReference(ref); } else{ ref->setPreviousReference(0); } m_p->m_first_reference = ref; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: removeVariableRef(VariableRef* ref) { { VariableRef* tmp = ref; if (tmp->previousReference()) tmp->previousReference()->setNextReference(tmp->nextReference()); if (tmp->nextReference()) tmp->nextReference()->setPreviousReference(tmp->previousReference()); if (m_p->m_first_reference==tmp) m_p->m_first_reference = m_p->m_first_reference->nextReference(); } // La référence peut être utilisée par la suite donc il ne faut pas oublier // de supprimer le précédent et le suivant. ref->setNextReference(0); ref->setPreviousReference(0); --m_p->m_nb_reference; _checkSetProperty(ref); // Lorsqu'il n'y a plus de références sur cette variable, le signale au // gestionnaire de variable, sauf s'il s'agit d'une variable persistante if (!_hasReference()){ bool is_persistant = property() & IVariable::PPersistant; if (!is_persistant){ //m_p->m_trace->info() << " REF PROPERTY name=" << name() << " " << ref->referenceProperty(); _removeMeshReference(); ISubDomain* sd = m_p->m_sub_domain; IVariableMng* vm = sd->variableMng(); vm->removeVariable(this); } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ VariableRef* Variable:: firstReference() const { return m_p->m_first_reference; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _checkSetProperty(VariableRef* ref) { // Garantie que la propriété est correctement mise à jour avec la valeur // de la seule référence. if (!_hasReference()){ m_p->m_property = ref->referenceProperty(); m_p->m_need_property_update = false; } else m_p->m_need_property_update = true; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer Variable:: nbReference() const { return m_p->m_nb_reference; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ISubDomain* Variable:: subDomain() { return m_p->m_sub_domain; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ const String& Variable:: name() const { return m_p->m_infos.localName(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ const String& Variable:: fullName() const { return m_p->m_infos.fullName(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ const String& Variable:: itemFamilyName() const { return m_p->m_infos.itemFamilyName(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ const String& Variable:: itemGroupName() const { return m_p->m_infos.itemGroupName(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ const String& Variable:: meshName() const { return m_p->m_infos.meshName(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ eDataType Variable:: dataType() const { return m_p->m_infos.dataType(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Expression Variable:: expression() { return Expression(new VariableExpressionImpl(this)); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \todo traiter le cas PSubDomainPrivate. */ int Variable:: property() const { if (!m_p->m_need_property_update) return m_p->m_property; // Les propriétés de la variable dépendent de ce que chaque // référence souhaite et il faut les remettre à jour lorsque ces // dernières changent. // Par exemple, si toutes les références sont PNoDump et qu'une seule // ne l'est pas, la variable ne doit pas l'être. m_p->m_need_property_update = false; bool want_dump = false; bool want_sync = false; bool want_replica_sync = false; bool sub_domain_depend = false; bool execution_depend = false; bool want_private = false; bool want_restore = false; bool want_notemporary = false; bool want_exchange = false; bool want_persistant = false; int property = 0; for( VarRefEnumerator i(this); i.hasNext(); ++i ){ VariableRef* vref = *i; int p = vref->referenceProperty(); if ( ! (p & IVariable::PNoDump) ) want_dump = true; if ( ! (p & IVariable::PNoNeedSync) ) want_sync = true; if ( ! (p & IVariable::PNoReplicaSync) ) want_replica_sync = true; if ( (p & IVariable::PSubDomainDepend) ) sub_domain_depend = true; if ( (p & IVariable::PExecutionDepend) ) execution_depend = true; if ( (p & IVariable::PPersistant) ) want_persistant = true; if ( (p & IVariable::PPrivate) ) want_private = true; if ( ! (p & IVariable::PNoRestore) ) want_restore = true; if ( ! (p & IVariable::PNoExchange) ) want_exchange = true; if ( ! (p & IVariable::PTemporary) ) want_notemporary = true; } if (!want_dump) property |= IVariable::PNoDump; if (!want_sync) property |= IVariable::PNoNeedSync; if (!want_replica_sync) property |= IVariable::PNoReplicaSync; if (sub_domain_depend) property |= IVariable::PSubDomainDepend; if (execution_depend) property |= IVariable::PExecutionDepend; if (want_private) property |= IVariable::PPrivate; if (want_persistant) property |= IVariable::PPersistant; if (!want_restore) property |= IVariable::PNoRestore; if (!want_exchange) property |= IVariable::PNoExchange; if (!want_notemporary) property |= IVariable::PTemporary; m_p->m_property = property; return m_p->m_property; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: notifyReferencePropertyChanged() { m_p->m_need_property_update = true; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: setUsed(bool is_used) { if (m_p->m_is_used==is_used) return; m_p->m_is_used = is_used; eItemKind ik = itemKind(); if (m_p->m_is_used){ if (m_p->m_item_group.null() && ik!=IK_Unknown){ _checkSetItemFamily(); _checkSetItemGroup(); // Attention à ne pas reinitialiser les valeurs lorsque ces dernières // sont valides, ce qui est le cas par exemple après une protection. if (!m_p->m_has_valid_data){ resizeFromGroup(); // Historiquement on remplissait dans tous les cas la variable avec le // constructeur par défaut // de la donnée en appelant systématiquement fillDefautt(). Cependant, // ce n'était pas le comportement souhaité qui doit être celui défini par // getGlobalDataInitialisationPolicy() (dans DataTypes.h). // On ne le fait maintenant que si le mode d'initialisation est égal // à DIP_Legacy. Ce mode doit à terme disparaître. if (getGlobalDataInitialisationPolicy()==DIP_Legacy) m_p->m_data->fillDefault(); m_p->m_has_valid_data = true; } } } else{ _removeMeshReference(); if (ik==IK_Unknown) resize(0); else resizeFromGroup(); // Indique que les valeurs ne sont plus valides m_p->m_has_valid_data = false; } for( VarRefEnumerator i(this); i.hasNext(); ++i ){ VariableRef* ref = *i; ref->internalSetUsed(m_p->m_is_used); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _removeMeshReference() { IItemFamily* family = m_p->m_item_family; if (family) family->removeVariable(this); if (isPartial()) m_p->m_item_group.internal()->detachObserver(this); m_p->m_item_group = ItemGroup(); m_p->m_item_family = 0; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ bool Variable:: isUsed() const { return m_p->m_is_used; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace { String _buildVariableFullType(const IVariable* var) { StringBuilder full_type_b; full_type_b = dataTypeName(var->dataType()); full_type_b += "."; full_type_b += itemKindName(var->itemKind()); full_type_b += "."; full_type_b += var->dimension(); full_type_b += "."; full_type_b += var->multiTag(); if (var->isPartial()) full_type_b += ".Partial"; return full_type_b.toString(); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ VariableMetaData* Variable:: createMetaData() const { auto vmd = new VariableMetaData(name(),meshName(),itemFamilyName(), itemGroupName(),isPartial()); vmd->setFullType(_buildVariableFullType(this)); vmd->setMultiTag(String::fromNumber(multiTag())); vmd->setProperty(property()); return vmd; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: syncReferences() { //cout << "** SYNC REFERENCE N=" << m_p->m_nb_reference << " F=" << m_p->m_first_reference << '\n'; for( VarRefEnumerator i(this); i.hasNext(); ++i ){ VariableRef* ref = *i; //cout << "** SYNC REFERENCE V=" << ref << '\n'; ref->updateFromInternal(); } // Il faut le faire après la mise à jour des références // car les observateurs peuvent lire les valeurs via une référence onSizeChangedObservable()->notifyAllObservers(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer Variable:: checkIfSync(int max_print) { ARCANE_UNUSED(max_print); return 0; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer Variable:: checkIfSameOnAllReplica(Integer max_print) { //TODO: regarder si la variable est utilisée. IMesh* mesh = this->mesh(); IParallelMng* pm = (mesh) ? mesh->parallelMng() : subDomain()->parallelMng(); IParallelReplication* pr = pm->replication(); if (!pr->hasReplication()) return 0; return _checkIfSameOnAllReplica(pr->replicaParallelMng(),max_print); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IMesh* Variable:: mesh() const { if (m_p->m_mesh_handle.hasMesh()) return m_p->m_mesh_handle.mesh(); return nullptr; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ MeshHandle Variable:: meshHandle() const { return m_p->m_mesh_handle; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ItemGroup Variable:: itemGroup() const { return m_p->m_item_group; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ eItemKind Variable:: itemKind() const { return m_p->m_infos.itemKind(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer Variable:: dimension() const { return m_p->m_infos.dimension(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer Variable:: multiTag() const { return m_p->m_infos.multiTag(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ bool Variable:: isPartial() const { return m_p->m_is_partial; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IItemFamily* Variable:: itemFamily() const { return m_p->m_item_family; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _setData(const Ref& data) { m_p->m_data = data; if (!data.get()){ ARCANE_FATAL("Invalid data: name={0} datatype={1} dimension={2} multitag={3}", m_p->m_infos.fullName(),m_p->m_infos.dataType(), m_p->m_infos.dimension(),m_p->m_infos.multiTag()); } data->setName(m_p->m_infos.localName()); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _setValidData(bool valid_data) { m_p->m_has_valid_data = valid_data; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _setProperty(int property) { m_p->m_property |= property; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IDataFactoryMng* Variable:: dataFactoryMng() const { return m_p->m_data_factory_mng; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: serialize(ISerializer* sbuffer,Int32ConstArrayView ids,IDataOperation* operation) { debug(Trace::High) << "Serialize (partial) variable name=" << fullName(); m_p->serializeHashId(sbuffer); m_p->m_data->serialize(sbuffer,ids,operation); // En mode lecture, les données sont modifiées if (sbuffer->mode()==ISerializer::ModeGet) syncReferences(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: serialize(ISerializer* sbuffer,IDataOperation* operation) { debug(Trace::High) << "Serialize (full) variable name=" << fullName(); m_p->serializeHashId(sbuffer); m_p->m_data->serialize(sbuffer,operation); // En mode lecture, les données sont modifiées if (sbuffer->mode()==ISerializer::ModeGet) syncReferences(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: resize(Integer new_size) { eItemKind ik = itemKind(); if (ik!=IK_Unknown){ ARCANE_FATAL("This call is invalid for item variable. Use resizeFromGroup() instead"); } _internalResize(new_size,0); syncReferences(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: resizeFromGroup() { eItemKind ik = itemKind(); if (ik==IK_Unknown) return; Integer new_size = 0; IItemFamily* family = m_p->m_item_family; if (family){ if (m_p->m_item_group.isAllItems()) new_size = m_p->m_item_family->maxLocalId(); else new_size = m_p->m_item_group.size(); } else{ ItemGroup group = m_p->m_item_group; if (!group.null()){ ARCANE_FATAL("Variable '{0}' has group but no family",fullName()); } } debug(Trace::High) << "Variable::resizeFromGroup() var='" << fullName() << "' with " << new_size << " items " << " this=" << this; _internalResize(new_size,new_size/20); syncReferences(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _checkSetItemFamily() { if (m_p->m_item_family || !m_p->m_item_group.null()) return; if (m_p->m_mesh_handle.isNull()) m_p->m_mesh_handle = m_p->m_sub_domain->meshMng()->findMeshHandle(m_p->m_infos.meshName()); IMesh* mesh = m_p->m_mesh_handle.mesh(); if (!mesh) ARCANE_FATAL("No mesh named '{0}' exists for variable '{1}'",m_p->m_infos.meshName(),name()); eItemKind ik = itemKind(); IItemFamily* family = 0; const String& family_name = m_p->m_infos.itemFamilyName(); if (ik==IK_Particle || ik==IK_DoF){ if (family_name.null()){ ARCANE_FATAL("family name not specified for variable {0}",name()); } family = mesh->findItemFamily(ik,family_name,true); } else{ family = mesh->itemFamily(ik); } if (family && family->itemKind()!=itemKind()) ARCANE_FATAL("Bad family kind '{0}' '{1}'",family->itemKind(),itemKind()); if (family && family->name()!=itemFamilyName()) ARCANE_FATAL("Incoherent family name. var={0} from_type={1} given={2}", name(),family->name(),itemFamilyName()); if (!family) ARCANE_FATAL("Family not found"); if (isPartial() && !family->hasUniqueIdMap()) ARCANE_FATAL("Cannot have partial variable for a family without unique id map"); m_p->m_item_family = family; debug(Trace::High) << "Variable::setItemFamily() name=" << name() << " family=" << family << " familyname='" << family_name << "'"; family->addVariable(this); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: _checkSetItemGroup() { if (!m_p->m_item_group.null()) return; const String& group_name = m_p->m_infos.itemGroupName(); //info() << " CHECK SET GROUP var=" << name() << " group=" << group_name; if (group_name.null()){ m_p->m_item_group = m_p->m_item_family->allItems(); } else m_p->m_item_group = m_p->m_item_family->findGroup(group_name,true); ItemGroupImpl * internal = m_p->m_item_group.internal(); // (HP) TODO: faut il garder ce controle hérité de l'ancienne implémentation de addVariable if (internal->parent() && (mesh()->parallelMng()->isParallel() && internal->isOwn())) ARCANE_FATAL("Cannot add variable ({0}) on a own group (name={1})", fullName(),internal->name()); if (isPartial()) { debug(Trace::High) << "Attach ItemGroupPartialVariableObserver from " << fullName() << " to " << m_p->m_item_group.name(); internal->attachObserver(this,new ItemGroupPartialVariableObserver(this)); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IObservable* Variable:: writeObservable() { return &(m_p->m_write_observable); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IObservable* Variable:: readObservable() { return &(m_p->m_read_observable); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IObservable* Variable:: onSizeChangedObservable() { return &(m_p->m_on_size_changed_observable); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: update() { update(DPT_PreviousTime); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: update(Real wanted_time) { if (m_p->m_last_update_timem_depends.size(); km_depends[k]; if (vdi.dependType()==DPT_PreviousTime) vdi.variable()->update(wanted_time); } } if (m_p->m_has_recursive_depend){ for( Integer k=0,n=m_p->m_depends.size(); km_depends[k]; if (vdi.dependType()==DPT_CurrentTime) vdi.variable()->update(m_p->m_last_update_time); } } bool need_update = false; Int64 modified_time = m_p->m_modified_time; for( Integer k=0,n=m_p->m_depends.size(); km_depends[k]; Int64 mt = vdi.variable()->modifiedTime(); if (mt>modified_time){ need_update = true; break; } } if (need_update){ IVariableComputeFunction* cf = m_p->m_compute_function.get(); //msg->info() << "Need Compute For Variable <" << name() << "> " << cf; if (cf){ //msg->info() << "Compute For Variable <" << name() << ">"; cf->execute(); } else{ ARCANE_FATAL("No compute function for variable '{0}'",fullName()); } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: setUpToDate() { m_p->m_last_update_time = subDomain()->commonVariables().globalTime(); m_p->m_modified_time = IVariable::incrementModifiedTime(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Int64 Variable:: modifiedTime() { return m_p->m_modified_time; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: addDepend(IVariable* var,eDependType dt) { m_p->m_depends.add(VariableDependInfo(var,dt,TraceInfo())); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: addDepend(IVariable* var,eDependType dt,const TraceInfo& tinfo) { m_p->m_depends.add(VariableDependInfo(var,dt,tinfo)); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: removeDepend(IVariable* var) { ARCANE_UNUSED(var); throw NotImplementedException(A_FUNCINFO); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: setComputeFunction(IVariableComputeFunction* v) { m_p->m_compute_function = v; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IVariableComputeFunction* Variable:: computeFunction() { return m_p->m_compute_function.get(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: dependInfos(Array& infos) { for( Integer k=0,n=m_p->m_depends.size(); km_depends[k]; infos.add(vdi); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: addTag(const String& tagname,const String& tagvalue) { m_p->m_tags[tagname] = tagvalue; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: removeTag(const String& tagname) { m_p->m_tags.erase(tagname); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ bool Variable:: hasTag(const String& tagname) { return m_p->m_tags.find(tagname)!=m_p->m_tags.end(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ String Variable:: tagValue(const String& tagname) { std::map::const_iterator i = m_p->m_tags.find(tagname); if (i==m_p->m_tags.end()) return String(); return i->second; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: notifyEndRead() { setUpToDate(); syncReferences(); readObservable()->notifyAllObservers(); _setValidData(true); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: notifyBeginWrite() { writeObservable()->notifyAllObservers(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: read(IDataReader* reader) { reader->read(this,data()); notifyEndRead(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: write(IDataWriter* writer) { notifyBeginWrite(); writer->write(this,data()); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void Variable:: changeGroupIds(Int32ConstArrayView old_to_new_ids) { ARCANE_UNUSED(old_to_new_ids); // pH: default implementation since this method is not yet official } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Vérifie qu'il est possible d'échanger les valeurs de l'instance * avec celle de \a rhs. * * Cette méthode étant appelée par une classe dérivée, on est sur que \a rhs * est du même type C++ que l'instance et donc il n'y a pas besoin de * vérifier par exemple que les dimensions ou le type des données sont les * mêmes. Pour que l'échange soit valide, il faut que le maillage, la famille * et le groupe soit les mêmes. Pour cela, il suffit de vérifier que le * groupe est le même. */ void Variable:: _checkSwapIsValid(Variable* rhs) { if (!m_p->m_is_used) ARCANE_FATAL("Can not swap variable values for unused variable (instance)"); if (!rhs->m_p->m_is_used) ARCANE_FATAL("Can not swap variable values for unused variable (argument)"); if (isPartial() || rhs->isPartial()) ARCANE_FATAL("Can not swap variable values for partial variables"); if (itemGroup()!=rhs->itemGroup()) ARCANE_FATAL("Can not swap variable values for variables from different groups"); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ bool Variable:: _wantShrink() const { return m_p->m_want_shrink; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #endif src/passes/transform/transform2combview.cpp #include "coreir.h" #include "coreir/passes/transform/transform2combview.h" #include "coreir/passes/analysis/createcombview.h" using namespace std; using namespace CoreIR; namespace { struct Helper { Context* c; map selects; Type* type = nullptr; Helper(Context* c) : c(c) {} ~Helper() { for (auto h : selects) { delete h.second; } } Type* getType() { if (type) return type; assert(selects.size()>0); if (isNumber(selects.begin()->first)) { int max = -1; set nums; Type* elemtype = selects.begin()->second->getType(); for (auto spair : selects) { assert(isNumber(spair.first)); Type* checktype = spair.second->getType(); assert(checktype == elemtype); int i = stoi(spair.first); nums.insert(i); if (i>max) max = i; } for (int i=0; i<=max; ++i) { assert(nums.count(i)>0); } this->type = c->Array(max+1,elemtype); return this->type; } else { //Is a record RecordParams rps; for (auto spair : selects) { rps.push_back({spair.first,spair.second->getType()}); } this->type = c->Record(rps); return this->type; } } void addPath(SelectPath path,Type* t) { if (path.size()==0) { this->type = t; return; } string sel = path.front(); assert(t->canSel(sel)); if (selects.count(sel)==0) { selects[sel] = new Helper(c); } path.pop_front(); selects[sel]->addPath(path,t->sel(sel)); } }; RecordType* createType(Context* c,RecordType* mtype,set& paths) { Helper* h = new Helper(c); for (auto path : paths) { assert(mtype->canSel(path)); h->addPath(path,mtype); } RecordType* ret = cast(h->getType()); delete h; return ret; } void connect(ModuleDef* def, SelectPath path, string ptname, string iname) { SelectPath ptpath = path; ptpath.push_front("in"); ptpath.push_front(ptname); SelectPath snkpath = path; snkpath.push_front(iname); def->connect(ptpath,snkpath); } } string Passes::Transform2CombView::ID = "transform2combview"; bool Passes::Transform2CombView::runOnInstanceGraphNode(InstanceGraphNode& node) { Context* c = getContext(); Module* m = node.getModule(); if (node.getInstanceList().size() == 0) { return false; } RecordType* mtype = m->getType(); Namespace* ns = m->getNamespace(); auto combview = getAnalysisPass(); string mname = m->getLongName(); string mname_src = mname+"_src"; string mname_snk = mname+"_snk"; string mname_comb = mname+"_comb"; if (combview->hasSrc(m)) { //cout << "HEREsrc" << endl; RecordType* srctype = createType(c,mtype,combview->getSrc(m)); auto newmod = ns->newModuleDecl(mname_src,srctype); newmod->getMetaData()["original"] = m->getRefName(); } if (combview->hasSnk(m)) { //cout << "HEREsnk" << endl; RecordType* snktype = createType(c,mtype,combview->getSnk(m)); auto newmod = ns->newModuleDecl(mname_snk,snktype); newmod->getMetaData()["original"] = m->getRefName(); } if (combview->hasComb(m)) { //cout << "HEREcomb " << mname_comb << endl; set combset = combview->getComb(m).inputs; set combouts = combview->getComb(m).outputs; combset.insert(combouts.begin(),combouts.end()); RecordType* combtype = createType(c,mtype,combset); auto newmod = ns->newModuleDecl(mname_comb,combtype); newmod->getMetaData()["original"] = m->getRefName(); } for (auto inst : node.getInstanceList()) { ModuleDef* def = inst->getContainer(); string ptname = "_pt" + getContext()->getUnique(); auto pt = addPassthrough(inst,ptname); string iname = inst->getInstname(); string iname_src = iname + "_src"; string iname_snk = iname + "_snk"; string iname_comb = iname + "_comb"; //inst is now freed def->removeInstance(inst); //Add new instances if (combview->hasSrc(m)) { auto newinst = def->addInstance(iname_src,ns->getModule(mname_src)); newinst->getMetaData()["srcsnkcomb"] = "src"; newinst->getMetaData()["original"] = iname; } if (combview->hasSnk(m)) { auto newinst = def->addInstance(iname_snk,ns->getModule(mname_snk)); newinst->getMetaData()["srcsnkcomb"] = "snk"; newinst->getMetaData()["original"] = iname; } if (combview->hasComb(m)) { auto newinst = def->addInstance(iname_comb,ns->getModule(mname_comb)); newinst->getMetaData()["srcsnkcomb"] = "comb"; newinst->getMetaData()["original"] = iname; } //Src for (auto path : combview->getSrc(m)) { connect(def,path,ptname,iname_src); } //Snk for (auto path : combview->getSnk(m)) { connect(def,path,ptname,iname_snk); } //Comb inputs for (auto path : combview->getComb(m).inputs) { connect(def,path,ptname,iname_comb); } //Comb outputs for (auto path : combview->getComb(m).outputs) { connect(def,path,ptname,iname_comb); } //inline passthrough inlineInstance(pt); } return true; } FindDlg.cpp1-10 /****************************************************************************** ** (C) ** ** MODULE: FINDDLG.CPP ** COMPONENT: The Application ** DESCRIPTION: CFindDlg class definition. ** ******************************************************************************* */ #include "Common.hpp" #include "FindDlg.hpp" /****************************************************************************** ** Method: Default constructor. ** ** Description: . ** ** Parameters: None. ** ** Returns: Nothing. ** ******************************************************************************* */ CFindDlg::CFindDlg() : CDialog(IDD_FIND) { DEFINE_CTRL_TABLE CTRL(IDC_TEXT, &m_ebText) END_CTRL_TABLE // DEFINE_CTRLMSG_TABLE // END_CTRLMSG_TABLE } /****************************************************************************** ** Method: OnInitDialog() ** ** Description: Initialise the dialog. ** ** Parameters: None. ** ** Returns: Nothing. ** ******************************************************************************* */ void CFindDlg::OnInitDialog() { // Initialise controls. m_ebText.Text(m_strText); } /****************************************************************************** ** Method: OnOk() ** ** Description: The OK button was pressed. ** ** Parameters: None. ** ** Returns: true or false. ** ******************************************************************************* */ bool CFindDlg::OnOk() { // Validate settings. if (m_ebText.TextLength() == 0) { AlertMsg(TXT("Please enter the text to find.")); m_ebText.Focus(); return false; } // Get new settings. m_strText = m_ebText.Text(); return true; } main/xmloff/inc/XMLChartPropertySetMapper.hxx100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _XMLOFF_CHARTPROPERTYSETMAPPER_HXX_ #define _XMLOFF_CHARTPROPERTYSETMAPPER_HXX_ #include #include #include #include #include namespace rtl { class OUString; } extern const XMLPropertyMapEntry aXMLChartPropMap[]; class SvXMLExport; // ---------------------------------------- class XMLChartPropHdlFactory : public XMLPropertyHandlerFactory { private: const XMLPropertyHandler* GetShapePropertyHandler( sal_Int32 nType ) const; public: virtual ~XMLChartPropHdlFactory(); virtual const XMLPropertyHandler* GetPropertyHandler( sal_Int32 nType ) const; }; // ---------------------------------------- class XMLChartPropertySetMapper : public XMLPropertySetMapper { public: XMLChartPropertySetMapper(); ~XMLChartPropertySetMapper(); }; // ---------------------------------------- class XMLChartExportPropertyMapper : public SvXMLExportPropertyMapper { private: const rtl::OUString msTrue; const rtl::OUString msFalse; bool mbAdaptPercentage; SvXMLExport& mrExport; protected: virtual void ContextFilter( ::std::vector< XMLPropertyState >& rProperties, ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > rPropSet ) const; private: /// this method is called for every item that has the MID_FLAG_ELEMENT_EXPORT flag set virtual void handleElementItem( SvXMLExport& rExport, const XMLPropertyState& rProperty, sal_uInt16 nFlags, const ::std::vector< XMLPropertyState > *pProperties = 0, sal_uInt32 nIdx = 0 ) const; /// this method is called for every item that has the MID_FLAG_SPECIAL_ITEM_EXPORT flag set virtual void handleSpecialItem( SvXMLAttributeList& rAttrList, const XMLPropertyState& rProperty, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap, const ::std::vector< XMLPropertyState > *pProperties = 0, sal_uInt32 nIdx = 0 ) const; public: XMLChartExportPropertyMapper( const UniReference< XMLPropertySetMapper >& rMapper, SvXMLExport& rExport ); virtual ~XMLChartExportPropertyMapper(); void setAdaptPercentage( bool bNewValue ); }; // ---------------------------------------- class XMLChartImportPropertyMapper : public SvXMLImportPropertyMapper { private: SvXMLImport& mrImport; public: XMLChartImportPropertyMapper( const UniReference< XMLPropertySetMapper >& rMapper, const SvXMLImport& rImport ); virtual ~XMLChartImportPropertyMapper(); virtual sal_Bool handleSpecialItem( XMLPropertyState& rProperty, ::std::vector< XMLPropertyState >& rProperties, const ::rtl::OUString& rValue, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const; virtual void finished( ::std::vector< XMLPropertyState >& rProperties, sal_Int32 nStartIndex, sal_Int32 nEndIndex ) const; }; #endif // _XMLOFF_CHARTPROPERTYSETMAPPER_HXX_ #include "transit_time.hpp" using namespace stransit; using namespace std::literals; time_hm::time_hm(std::chrono::hours hours, std::chrono::minutes minutes) : m_hours(hours), m_minutes(minutes) {} std::string time_hm::to_string() const { return ""s + std::to_string(m_hours.count()) + "h" + std::to_string(m_minutes.count()) + "min"; } std::chrono::minutes time_hm::difference_to(const stransit::time_hm &other) const { std::chrono::hours h_diff = other.m_hours - m_hours; std::chrono::minutes m_diff = other.m_minutes - m_minutes; if (h_diff > 0h || (h_diff == 0h && m_diff >= 0min)) { std::chrono::minutes minute_h_diff(h_diff); minute_h_diff += m_diff; return minute_h_diff; } else { std::chrono::minutes minute_h_diff(24h + h_diff); minute_h_diff += m_diff; return minute_h_diff; } } time_hm time_hm::add(const time_hm& other) const { int total_minutes = other.m_minutes.count() + m_minutes.count(); int excess_minutes_in_hours = total_minutes / 60; int total_hours = excess_minutes_in_hours + other.m_hours.count() + m_hours.count(); return {std::chrono::hours(total_hours % 24), std::chrono::minutes(total_minutes % 60)}; } time_hm time_hm::add(const std::chrono::minutes& other) const { return add({0h, other}); } std::chrono::minutes time_hm::compare(const time_hm& other) const { std::chrono::hours hour_diff = m_hours - other.m_hours; std::chrono::minutes min_diff = m_minutes - other.m_minutes; return hour_diff + min_diff; } Code/Components/Services/ingest/current/ingestpipeline/calcuvwtask/CalcUVWTask.cc /// @file CalcUVWTask.cc /// /// @copyright (c) 2010 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author <> // Include own header file first #include "CalcUVWTask.h" // Include package level header file #include "askap_cpingest.h" // System includes #include #include // ASKAPsoft includes #include "askap/AskapLogging.h" #include "askap/AskapError.h" #include "Common/ParameterSet.h" #include "casacore/casa/Arrays/Matrix.h" #include "casacore/casa/Arrays/MatrixMath.h" #include "casacore/measures/Measures.h" #include "casacore/measures/Measures/MeasConvert.h" #include "casacore/measures/Measures/MCEpoch.h" #include "casacore/measures/Measures/MDirection.h" #include "casacore/measures/Measures/MEpoch.h" #include "casacore/measures/Measures/MeasFrame.h" #include "casacore/measures/Measures/MCDirection.h" #include "casacore/casa/Quanta/MVAngle.h" #include "casacore/scimath/Mathematics/RigidVector.h" #include "cpcommon/VisChunk.h" #include "casacore/measures/Measures/UVWMachine.h" // Local package includes #include "configuration/Configuration.h" // Includes all configuration attributes too ASKAP_LOGGER(logger, ".CalcUVWTask"); using namespace casa; using namespace askap; using namespace askap::cp::common; using namespace askap::cp::ingest; CalcUVWTask::CalcUVWTask(const LOFAR::ParameterSet& parset, const Configuration& config) { ASKAPLOG_DEBUG_STR(logger, "Constructor"); createPositionMatrix(config); if (config.feedInfoDefined()) { ASKAPLOG_INFO_STR(logger, "Use static beam offset information in favour of the dynamic one!"); setupBeamOffsets(config); } } CalcUVWTask::~CalcUVWTask() { ASKAPLOG_DEBUG_STR(logger, "Destructor"); } void CalcUVWTask::process(VisChunk::ShPtr& chunk) { ASKAPASSERT(chunk); if (chunk->beamOffsets().nelements() > 0) { ASKAPLOG_INFO_STR(logger, "Use dynamic beam offset information, overriding existing arrangement if present"); setupBeamOffsets(chunk->beamOffsets()); } for (casa::uInt row = 0; row < chunk->nRow(); ++row) { calcForRow(chunk, row); } } /// @brief obtain phase centre for a given beam /// @details This method encapsulates common operations to obtain the direction /// of the phase centre for an (off-axis) beam by shifting dish pointing centre /// @param[in] dishPointing pointing centre for the whole dish /// @param[in] beam beam index to work /// @return direction measure for the phase centre casa::MDirection CalcUVWTask::phaseCentre(const casa::MDirection &dishPointing, const casa::uInt beam) const { // Current phase center casa::MDirection fpc(dishPointing); ASKAPCHECK(beam < itsBeamOffset.size(), "Beam index (" << beam << ") is invalid"); // Shift per beam offsets const RigidVector offset = itsBeamOffset(beam); fpc.shift(-offset(0), offset(1), True); return fpc; } /// @brief obtain gast for the given epoch /// @param[in] epoch UTC epoch to convert to GAST /// @return gast in radians modulo 2pi double CalcUVWTask::calcGAST(const casa::MVEpoch &epoch) { // Determine Greenwich Apparent Sidereal Time MEpoch epUT1(epoch, MEpoch::UTC); MEpoch::Ref refGAST(MEpoch::GAST); MEpoch::Convert epGAST(epUT1, refGAST); const double gast = epGAST().get("d").getValue("d"); return (gast - Int(gast)) * C::_2pi; // Into Radians } void CalcUVWTask::calcForRow(VisChunk::ShPtr chunk, const casa::uInt row) { const casa::uInt ant1 = chunk->antenna1()(row); const casa::uInt ant2 = chunk->antenna2()(row); const casa::uInt nAnt = nAntennas(); ASKAPCHECK(ant1 < nAnt, "Antenna index (" << ant1 << ") is invalid"); ASKAPCHECK(ant2 < nAnt, "Antenna index (" << ant2 << ") is invalid"); ASKAPDEBUGASSERT(nAnt > 0); /* // reference point, could've used one of the antennas const casa::MPosition mroPos(casa::MVPosition(casa::Quantity(370.81, "m"), casa::Quantity(116.6310372795, "deg"), casa::Quantity(-26.6991531922, "deg")), casa::MPosition::Ref(casa::MPosition::WGS84)); */ const casa::MPosition mroPos(casa::MVPosition(antXYZ(0)), casa::MPosition::ITRF); // Determine Greenwich Apparent Sidereal Time //const double gast = calcGAST(chunk->time()); casa::MeasFrame frame(casa::MEpoch(chunk->time(), casa::MEpoch::UTC), mroPos); // phase center for a given beam const casa::MDirection fpc = casa::MDirection::Convert(phaseCentre(chunk->phaseCentre()(row),chunk->beam1()(row)), casa::MDirection::Ref(casa::MDirection::TOPO, frame))(); /* const double ra = fpc.getAngle().getValue()(0); const double dec = fpc.getAngle().getValue()(1); */ const casa::MDirection hadec = casa::MDirection::Convert(phaseCentre(chunk->phaseCentre()(row), chunk->beam1()(row)), casa::MDirection::Ref(casa::MDirection::HADEC, frame))(); const double H0 = hadec.getValue().getLong() - mroPos.getValue().getLong(); const double dec = hadec.getValue().getLat(); // Transformation from antenna position difference (ant2-ant1) to uvw //const double H0 = gast - ra; const double sH0 = sin(H0); const double cH0 = cos(H0); const double sd = sin(dec); const double cd = cos(dec); Matrix trans(3, 3, 0); trans(0, 0) = -sH0; trans(0, 1) = -cH0; trans(1, 0) = sd * cH0; trans(1, 1) = -sd * sH0; trans(1, 2) = -cd; trans(2, 0) = -cd * cH0; trans(2, 1) = cd * sH0; trans(2, 2) = -sd; // Rotate antennas to correct frame /* // there is no need to calculate uvw per antenna here as we recalculate it per row // caching it per row and beam would be the optimal approach in terms of the number of // operations, but we leave such implementation for some time in the future Matrix antUVW(3, nAnt); for (uInt i = 0; i < nAnt; ++i) { antUVW.column(i) = casa::product(trans, antXYZ(i)); } double x1 = antUVW(0, ant1), y1 = antUVW(1, ant1), z1 = antUVW(2, ant1); double x2 = antUVW(0, ant2), y2 = antUVW(1, ant2), z2 = antUVW(2, ant2); Vector uvwvec(3); uvwvec(0) = x2 - x1; uvwvec(1) = y2 - y1; uvwvec(2) = z2 - z1; */ const Vector baseline = antXYZ(ant2) - antXYZ(ant1); ASKAPDEBUGASSERT(baseline.nelements() == 3); Vector uvwvec = casa::product(trans,baseline); ASKAPDEBUGASSERT(uvwvec.nelements() == 3); // do the conversion to J2000 in a quick and dirty way for now // some optimisation and caching of rotation matrix are definitely possible here // but cache class in accessors needs to be adapted first. // commented out hadec-based transformation, see ADESCOM-342 and ASKAPSDP-3033 //casa::UVWMachine uvm(casa::MDirection::Ref(casa::MDirection::J2000), hadec, frame); casa::UVWMachine uvm(casa::MDirection::Ref(casa::MDirection::J2000), fpc); uvm.convertUVW(uvwvec); ASKAPDEBUGASSERT(uvwvec.nelements() == 3); /* // code for cross-check with UVWs already in the buffer (e.g. received with metadata or // calculated earlier in the processing chain. // note, now it doesn't quite match as we using the frame related to each // particular antenna rather than antenna 0. This gives about 0.1mm error casa::Vector diff = uvwvec.copy(); diff(0) -= chunk->uvw()(row)(0); diff(1) -= chunk->uvw()(row)(1); diff(2) -= chunk->uvw()(row)(2); //ASKAPCHECK(sqrt(diff[0]*diff[0]+diff[1]*diff[1]+diff[2]*diff[2]) < 1e-6, // "Mismatch in UVW for row="<uvw()(row)); if (sqrt(diff[0]*diff[0]+diff[1]*diff[1]+diff[2]*diff[2]) > 1e-6) { ASKAPLOG_WARN_STR(logger, "Mismatch in UVW for row="<uvw()(row)); if (norm(uvwvec)>1e-6 && norm(chunk->uvw()(row).vector())>1e-6) { const double cosAng = innerProduct(uvwvec,chunk->uvw()(row).vector())/norm(uvwvec)/norm(chunk->uvw()(row).vector()); ASKAPLOG_WARN_STR(logger, "UVW mismatch angle for row "<uvw()(row).vector())<<" "<uvw()(row) = uvwvec; } /// @brief obtain ITRF coordinates of a given antenna /// @details /// @param[in] ant antenna index /// @return 3-element vector with X,Y and Z casa::Vector CalcUVWTask::antXYZ(const casa::uInt ant) const { return itsAntXYZ.column(ant); } void CalcUVWTask::createPositionMatrix(const Configuration& config) { const std::vector antennas = config.antennas(); const size_t nAnt = antennas.size(); itsAntXYZ = casa::Matrix(3, nAnt); for (size_t i = 0; i < nAnt; ++i) { itsAntXYZ(0, i) = antennas.at(i).position()(0); // x itsAntXYZ(1, i) = antennas.at(i).position()(1); // y itsAntXYZ(2, i) = antennas.at(i).position()(2); // z } } void CalcUVWTask::setupBeamOffsets(const casa::Matrix& offsets) { if (itsBeamOffset.nelements() != offsets.ncolumn()) { itsBeamOffset.resize(offsets.ncolumn()); ASKAPASSERT(offsets.nrow() == 2u); for (uInt beam = 0; beam < itsBeamOffset.nelements(); ++beam) { itsBeamOffset(beam)(0) = offsets(0, beam); itsBeamOffset(beam)(1) = offsets(1, beam); } } } void CalcUVWTask::setupBeamOffsets(const Configuration& config) { const FeedConfig& feedConfig = config.feed(); const uInt nFeeds = feedConfig.nFeeds(); itsBeamOffset.resize(nFeeds); for (uInt feed = 0; feed < nFeeds; feed++) { itsBeamOffset(feed)(0) = feedConfig.offsetX(feed).getValue("rad"); itsBeamOffset(feed)(1) = feedConfig.offsetY(feed).getValue("rad"); } } 1-10 #ifndef __SIAR_FUNCTIONS_H__ #define __SIAR_FUNCTIONS_H__ #include // template T sgn(T value) { // return (value > static_cast(0.0)?static_cast(1.0):((value < static_cast(0.0))?static_cast(-1.0):0.0); // } template class DeadZone { public: DeadZone (T pos_dead, T neg_dead):_pos_dead(pos_dead),_neg_dead(neg_dead){} DeadZone (T pos_dead = 1.0):_pos_dead(pos_dead),_neg_dead(-pos_dead){} inline double apply(T value) const { T ret_val = 0.0; if (value > static_cast(0.0) && value > _pos_dead) { ret_val = value; } else if (value < static_cast(0.0) && value < _neg_dead) { ret_val = value; } return ret_val; } double _pos_dead, _neg_dead; }; template class Saturate { public: Saturate (T low, T high):_low(low), _high(high) {} Saturate (T high = 1.0):_low(-high), _high(high) {} inline T apply(T value) const { T ret_val = (value > _high)?_high:value; return (ret_val < _low)?_low:value; } inline T getWidth() const { return _high - _low; } double _low,_high; }; inline uint16_t from_two_bytes(uint8_t b1, uint8_t b2) { uint16_t ret_val = b1; ret_val = ret_val << 8; return ret_val + b2; } inline int16_t from_two_bytes_signed(uint8_t b1, uint8_t b2) { uint16_t aux = from_two_bytes(b1, b2); int16_t ret = aux; if (aux > 32767) { ret = -65536 + aux; } return ret; } #endif#include "load_data.h" #include namespace NCatboostCuda { void TDataProviderBuilder::StartNextBlock(ui32 blockSize) { Cursor = DataProvider.Targets.size(); const auto newDataSize = Cursor + blockSize; DataProvider.Targets.resize(newDataSize); DataProvider.Weights.resize(newDataSize, 1.0); DataProvider.QueryIds.resize(newDataSize); DataProvider.SubgroupIds.resize(newDataSize); DataProvider.Timestamp.resize(newDataSize); for (ui32 i = Cursor; i < DataProvider.QueryIds.size(); ++i) { DataProvider.QueryIds[i] = TGroupId(i); DataProvider.SubgroupIds[i] = i; } for (auto& baseline : DataProvider.Baseline) { baseline.resize(newDataSize); } for (ui32 featureId = 0; featureId < FeatureBlobs.size(); ++featureId) { if (IgnoreFeatures.count(featureId) == 0) { FeatureBlobs[featureId].resize(newDataSize * GetBytesPerFeature(featureId)); } } DataProvider.DocIds.resize(newDataSize); } static inline bool HasQueryIds(const TVector& qids) { for (ui32 i = 0; i < qids.size(); ++i) { if (qids[i] != TGroupId(i)) { return true; } } return false; } template static inline TVector MakeOrderedLine(const TVector& source, const TVector& order) { CB_ENSURE(source.size() == sizeof(T) * order.size(), "Error: size should be consistent " << source.size() << " " << order.size() << " " << sizeof(T)); TVector line(order.size()); for (size_t i = 0; i < order.size(); ++i) { const T* rawSourcePtr = reinterpret_cast(source.data()); line[i] = rawSourcePtr[order[i]]; } return line; } void TDataProviderBuilder::Finish() { CB_ENSURE(!IsDone, "Error: can't finish more than once"); DataProvider.Features.reserve(FeatureBlobs.size()); DataProvider.Order.resize(DataProvider.Targets.size()); std::iota(DataProvider.Order.begin(), DataProvider.Order.end(), 0); if (!AreEqualTo(DataProvider.Timestamp, 0)) { ShuffleFlag = false; DataProvider.Order = CreateOrderByKey(DataProvider.Timestamp); } bool hasQueryIds = HasQueryIds(DataProvider.QueryIds); if (!hasQueryIds) { DataProvider.QueryIds.resize(0); } //TODO(noxoomo): it's not safe here, if we change order with shuffle everything'll go wrong if (Pairs.size()) { //they are local, so we don't need shuffle CB_ENSURE(hasQueryIds, "Error: for GPU pairwise learning you should provide query id column. Query ids will be used to split data between devices and for dynamic boosting learning scheme."); DataProvider.FillQueryPairs(Pairs); } if (ShuffleFlag) { if (hasQueryIds) { //should not change order inside query for pairs consistency QueryConsistentShuffle(Seed, 1, DataProvider.QueryIds, &DataProvider.Order); } else { Shuffle(Seed, 1, DataProvider.Targets.size(), &DataProvider.Order); } DataProvider.SetShuffleSeed(Seed); } if (ShuffleFlag || !DataProvider.Timestamp.empty()) { DataProvider.ApplyOrderToMetaColumns(); } TVector featureNames; featureNames.resize(FeatureBlobs.size()); TAdaptiveLock lock; NPar::TLocalExecutor executor; executor.RunAdditionalThreads(BuildThreads - 1); TVector featureColumns(FeatureBlobs.size()); if (!IsTest) { RegisterFeaturesInFeatureManager(featureColumns); } NPar::ParallelFor(executor, 0, static_cast(FeatureBlobs.size()), [&](ui32 featureId) { auto featureName = GetFeatureName(featureId); featureNames[featureId] = featureName; if (FeatureBlobs[featureId].size() == 0) { return; } EFeatureValuesType featureValuesType = FeatureTypes[featureId]; if (featureValuesType == EFeatureValuesType::Categorical) { CB_ENSURE(featureValuesType == EFeatureValuesType::Categorical, "Wrong type " << featureValuesType); auto line = MakeOrderedLine(FeatureBlobs[featureId], DataProvider.Order); static_assert(sizeof(float) == sizeof(ui32), "Error: float size should be equal to ui32 size"); const bool shouldSkip = IsTest && (CatFeaturesPerfectHashHelper.GetUniqueValues(featureId) == 0); if (!shouldSkip) { auto data = CatFeaturesPerfectHashHelper.UpdatePerfectHashAndBinarize(featureId, ~line, line.size()); const ui32 uniqueValues = CatFeaturesPerfectHashHelper.GetUniqueValues(featureId); if (uniqueValues > 1) { auto compressedData = CompressVector(~data, line.size(), IntLog2(uniqueValues)); featureColumns[featureId] = MakeHolder(featureId, line.size(), std::move(compressedData), uniqueValues, featureName); } } } else if (featureValuesType == EFeatureValuesType::BinarizedFloat) { const TVector& borders = Borders.at(featureId); const ENanMode nanMode = NanModes.at(featureId); if (borders.ysize() == 0) { MATRIXNET_DEBUG_LOG << "Float Feature #" << featureId << " is empty" << Endl; return; } TVector binarizedData = MakeOrderedLine(FeatureBlobs[featureId], DataProvider.Order); const int binCount = static_cast(borders.size() + 1 + (ENanMode::Forbidden != nanMode)); auto compressedLine = CompressVector(binarizedData, IntLog2(binCount)); featureColumns[featureId] = MakeHolder(featureId, DataProvider.Order.size(), nanMode, borders, std::move(compressedLine), featureName); with_lock (lock) { FeaturesManager.SetOrCheckNanMode(*featureColumns[featureId], nanMode); } } else { CB_ENSURE(featureValuesType == EFeatureValuesType::Float, "Wrong feature values type (" << featureValuesType << ") for feature #" << featureId); TVector line(DataProvider.Order.size()); for (ui32 i = 0; i < DataProvider.Order.size(); ++i) { const float* floatFeatureSource = reinterpret_cast(FeatureBlobs[featureId].data()); line[i] = floatFeatureSource[DataProvider.Order[i]]; } auto floatFeature = MakeHolder(featureId, std::move(line), featureName); TVector& borders = Borders[featureId]; auto& nanMode = NanModes[featureId]; { TGuard guard(lock); nanMode = FeaturesManager.GetOrComputeNanMode(*floatFeature); } if (FeaturesManager.HasFloatFeatureBorders(*floatFeature)) { borders = FeaturesManager.GetFloatFeatureBorders(*floatFeature); } if (borders.empty() && !IsTest) { const auto& floatValues = floatFeature->GetValues(); NCatboostOptions::TBinarizationOptions config = FeaturesManager.GetFloatFeatureBinarization(); config.NanMode = nanMode; borders = BuildBorders(floatValues, floatFeature->GetId(), config); } if (borders.ysize() == 0) { MATRIXNET_DEBUG_LOG << "Float Feature #" << featureId << " is empty" << Endl; return; } auto binarizedData = BinarizeLine(floatFeature->GetValues().data(), floatFeature->GetValues().size(), nanMode, borders); const int binCount = static_cast(borders.size() + 1 + (ENanMode::Forbidden != nanMode)); auto compressedLine = CompressVector(binarizedData, IntLog2(binCount)); featureColumns[featureId] = MakeHolder(featureId, floatFeature->GetValues().size(), nanMode, borders, std::move(compressedLine), featureName); } //Free memory { auto emptyVec = TVector(); FeatureBlobs[featureId].swap(emptyVec); } }); for (ui32 featureId = 0; featureId < featureColumns.size(); ++featureId) { if (FeatureTypes[featureId] == EFeatureValuesType::Categorical) { if (featureColumns[featureId] == nullptr && (!IsTest)) { MATRIXNET_DEBUG_LOG << "Cat Feature #" << featureId << " is empty" << Endl; } } else if (featureColumns[featureId] != nullptr) { if (!FeaturesManager.HasFloatFeatureBordersForDataProviderFeature(featureId)) { FeaturesManager.SetFloatFeatureBordersForDataProviderId(featureId, std::move(Borders[featureId])); } } if (featureColumns[featureId] != nullptr) { DataProvider.Features.push_back(std::move(featureColumns[featureId])); } } DataProvider.BuildIndicesRemap(); if (!IsTest) { TOnCpuGridBuilderFactory gridBuilderFactory; FeaturesManager.SetTargetBorders(TBordersBuilder(gridBuilderFactory, DataProvider.GetTargets())(FeaturesManager.GetTargetBinarizationDescription())); } DataProvider.FeatureNames = featureNames; if (ClassesWeights.size()) { Reweight(DataProvider.Targets, ClassesWeights, &DataProvider.Weights); } IsDone = true; } void TDataProviderBuilder::WriteBinarizedFeatureToBlobImpl(ui32 localIdx, ui32 featureId, ui8 feature) { Y_ASSERT(IgnoreFeatures.count(featureId) == 0); Y_ASSERT(FeatureTypes[featureId] == EFeatureValuesType::BinarizedFloat); ui8* featureColumn = FeatureBlobs[featureId].data(); featureColumn[GetLineIdx(localIdx)] = feature; } void TDataProviderBuilder::WriteFloatOrCatFeatureToBlobImpl(ui32 localIdx, ui32 featureId, float feature) { Y_ASSERT(IgnoreFeatures.count(featureId) == 0); Y_ASSERT(FeatureTypes[featureId] == EFeatureValuesType::Float || FeatureTypes[featureId] == EFeatureValuesType::Categorical); auto* featureColumn = reinterpret_cast(FeatureBlobs[featureId].data()); featureColumn[GetLineIdx(localIdx)] = feature; } void TDataProviderBuilder::Start(const TPoolMetaInfo& poolMetaInfo, int docCount, const TVector& catFeatureIds) { DataProvider.Features.clear(); DataProvider.Baseline.clear(); DataProvider.Baseline.resize(poolMetaInfo.BaselineCount); Cursor = 0; IsDone = false; FeatureBlobs.clear(); FeatureBlobs.resize(poolMetaInfo.FeatureCount); FeatureTypes.resize(poolMetaInfo.FeatureCount, EFeatureValuesType::Float); for (int catFeature : catFeatureIds) { FeatureTypes[catFeature] = EFeatureValuesType::Categorical; } Borders.resize(poolMetaInfo.FeatureCount); NanModes.resize(poolMetaInfo.FeatureCount); for (size_t i = 0; i < BinarizedFeaturesMetaInfo.BinarizedFeatureIds.size(); ++i) { const size_t binarizedFeatureId = static_cast(BinarizedFeaturesMetaInfo.BinarizedFeatureIds[i]); const TVector& borders = BinarizedFeaturesMetaInfo.Borders.at(i); CB_ENSURE(binarizedFeatureId < poolMetaInfo.FeatureCount, "Error: binarized feature " << binarizedFeatureId << " is out of range"); FeatureTypes[binarizedFeatureId] = EFeatureValuesType::BinarizedFloat; NanModes[binarizedFeatureId] = BinarizedFeaturesMetaInfo.NanModes.at(i); Borders[binarizedFeatureId] = borders; } for (ui32 i = 0; i < poolMetaInfo.FeatureCount; ++i) { if (!IgnoreFeatures.has(i)) { ui32 bytesPerFeature = GetBytesPerFeature(i); FeatureBlobs[i].reserve(docCount * bytesPerFeature); } } DataProvider.CatFeatureIds = TSet(catFeatureIds.begin(), catFeatureIds.end()); } } // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/input_method/ibus_controller.h" #if defined(HAVE_IBUS) #include #endif #include // for std::reverse. #include #include // for std::strcmp. #include #include #include #include #include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "chrome/browser/chromeos/input_method/input_method_engine.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/input_method/input_method_util.h" #include "chrome/browser/chromeos/input_method/input_method_whitelist.h" #include "chrome/browser/chromeos/input_method/input_methods.h" namespace chromeos { namespace input_method { #if defined(HAVE_IBUS) const char kPanelObjectKey[] = "panel-object"; namespace { // Also defined in chrome/browser/chromeos/language_preferences.h (Chrome tree). const char kGeneralSectionName[] = "general"; const char kPreloadEnginesConfigName[] = "preload_engines"; // The list of input method property keys that we don't handle. const char* kInputMethodPropertyKeysBlacklist[] = { "setup", // menu for showing setup dialog used in anthy and hangul. "chewing_settings_prop", // menu for showing setup dialog used in chewing. "status", // used in m17n. }; const char* Or(const char* str1, const char* str2) { return str1 ? str1 : str2; } // Returns true if |key| is blacklisted. bool PropertyKeyIsBlacklisted(const char* key) { for (size_t i = 0; i < arraysize(kInputMethodPropertyKeysBlacklist); ++i) { if (!std::strcmp(key, kInputMethodPropertyKeysBlacklist[i])) { return true; } } return false; } // Returns IBusInputContext for |input_context_path|. NULL on errors. IBusInputContext* GetInputContext( const std::string& input_context_path, IBusBus* ibus) { GDBusConnection* connection = ibus_bus_get_connection(ibus); if (!connection) { LOG(ERROR) << "IBusConnection is null"; return NULL; } // This function does not issue an IBus IPC. IBusInputContext* context = ibus_input_context_get_input_context( input_context_path.c_str(), connection); if (!context) { LOG(ERROR) << "IBusInputContext is null: " << input_context_path; } return context; } // Returns true if |prop| has children. bool PropertyHasChildren(IBusProperty* prop) { return prop && prop->sub_props && ibus_prop_list_get(prop->sub_props, 0); } // This function is called by and FlattenProperty() and converts IBus // representation of a property, |ibus_prop|, to our own and push_back the // result to |out_prop_list|. This function returns true on success, and // returns false if sanity checks for |ibus_prop| fail. bool ConvertProperty(IBusProperty* ibus_prop, int selection_item_id, InputMethodPropertyList* out_prop_list) { DCHECK(ibus_prop); DCHECK(ibus_prop->key); DCHECK(out_prop_list); // Sanity checks. const bool has_sub_props = PropertyHasChildren(ibus_prop); if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) { LOG(ERROR) << "The property has sub properties, " << "but the type of the property is not PROP_TYPE_MENU"; return false; } if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) { // This is usually not an error. ibus-daemon sometimes sends empty props. VLOG(1) << "Property list is empty"; return false; } if (ibus_prop->type == PROP_TYPE_SEPARATOR || ibus_prop->type == PROP_TYPE_MENU) { // This is not an error, but we don't push an item for these types. return true; } const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO); selection_item_id = is_selection_item ? selection_item_id : InputMethodProperty::kInvalidSelectionItemId; bool is_selection_item_checked = false; if (ibus_prop->state == PROP_STATE_INCONSISTENT) { LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, " << "which is not supported."; } else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) { LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is " << "PROP_TYPE_RADIO."; } else { is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED); } if (!ibus_prop->key) { LOG(ERROR) << "key is NULL"; } if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) { LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key=" << Or(ibus_prop->key, ""); } if (ibus_prop->label && (!ibus_prop->label->text)) { LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key=" << Or(ibus_prop->key, ""); } // This label will be localized on Chrome side. // See src/chrome/browser/chromeos/status/language_menu_l10n_util.h. std::string label = ((ibus_prop->tooltip && ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : ""); if (label.empty()) { // Usually tooltips are more descriptive than labels. label = (ibus_prop->label && ibus_prop->label->text) ? ibus_prop->label->text : ""; } if (label.empty()) { // ibus-pinyin has a property whose label and tooltip are empty. Fall back // to the key. label = Or(ibus_prop->key, ""); } out_prop_list->push_back(InputMethodProperty(ibus_prop->key, label, is_selection_item, is_selection_item_checked, selection_item_id)); return true; } // Converts |ibus_prop| to |out_prop_list|. Please note that |ibus_prop| // may or may not have children. See the comment for FlattenPropertyList // for details. Returns true if no error is found. // TODO(yusukes): Write unittest. bool FlattenProperty(IBusProperty* ibus_prop, InputMethodPropertyList* out_prop_list) { DCHECK(ibus_prop); DCHECK(out_prop_list); int selection_item_id = -1; std::stack > prop_stack; prop_stack.push(std::make_pair(ibus_prop, selection_item_id)); while (!prop_stack.empty()) { IBusProperty* prop = prop_stack.top().first; const int current_selection_item_id = prop_stack.top().second; prop_stack.pop(); // Filter out unnecessary properties. if (PropertyKeyIsBlacklisted(prop->key)) { continue; } // Convert |prop| to InputMethodProperty and push it to |out_prop_list|. if (!ConvertProperty(prop, current_selection_item_id, out_prop_list)) { return false; } // Process childrens iteratively (if any). Push all sub properties to the // stack. if (PropertyHasChildren(prop)) { ++selection_item_id; for (int i = 0;; ++i) { IBusProperty* sub_prop = ibus_prop_list_get(prop->sub_props, i); if (!sub_prop) { break; } prop_stack.push(std::make_pair(sub_prop, selection_item_id)); } ++selection_item_id; } } std::reverse(out_prop_list->begin(), out_prop_list->end()); return true; } // Converts IBus representation of a property list, |ibus_prop_list| to our // own. This function also flatten the original list (actually it's a tree). // Returns true if no error is found. The conversion to our own type is // necessary since our language switcher in Chrome tree don't (or can't) know // IBus types. Here is an example: // // ====================================================================== // Input: // // --- Item-1 // |- Item-2 // |- SubMenuRoot --- Item-3-1 // | |- Item-3-2 // | |- Item-3-3 // |- Item-4 // // (Note: Item-3-X is a selection item since they're on a sub menu.) // // Output: // // Item-1, Item-2, Item-3-1, Item-3-2, Item-3-3, Item-4 // (Note: SubMenuRoot does not appear in the output.) // ====================================================================== // TODO(yusukes): Write unittest. bool FlattenPropertyList( IBusPropList* ibus_prop_list, InputMethodPropertyList* out_prop_list) { DCHECK(ibus_prop_list); DCHECK(out_prop_list); IBusProperty* fake_root_prop = ibus_property_new("Dummy.Key", PROP_TYPE_MENU, NULL, /* label */ "", /* icon */ NULL, /* tooltip */ FALSE, /* sensitive */ FALSE, /* visible */ PROP_STATE_UNCHECKED, ibus_prop_list); g_return_val_if_fail(fake_root_prop, false); // Increase the ref count so it won't get deleted when |fake_root_prop| // is deleted. g_object_ref(ibus_prop_list); const bool result = FlattenProperty(fake_root_prop, out_prop_list); g_object_unref(fake_root_prop); return result; } // Debug print function. const char* PropTypeToString(int prop_type) { switch (static_cast(prop_type)) { case PROP_TYPE_NORMAL: return "NORMAL"; case PROP_TYPE_TOGGLE: return "TOGGLE"; case PROP_TYPE_RADIO: return "RADIO"; case PROP_TYPE_MENU: return "MENU"; case PROP_TYPE_SEPARATOR: return "SEPARATOR"; } return "UNKNOWN"; } // Debug print function. const char* PropStateToString(int prop_state) { switch (static_cast(prop_state)) { case PROP_STATE_UNCHECKED: return "UNCHECKED"; case PROP_STATE_CHECKED: return "CHECKED"; case PROP_STATE_INCONSISTENT: return "INCONSISTENT"; } return "UNKNOWN"; } // Debug print function. std::string Spacer(int n) { return std::string(n, ' '); } std::string PrintPropList(IBusPropList *prop_list, int tree_level); // Debug print function. std::string PrintProp(IBusProperty *prop, int tree_level) { if (!prop) { return ""; } std::stringstream stream; stream << Spacer(tree_level) << "=========================" << std::endl; stream << Spacer(tree_level) << "key: " << Or(prop->key, "") << std::endl; stream << Spacer(tree_level) << "icon: " << Or(prop->icon, "") << std::endl; stream << Spacer(tree_level) << "label: " << ((prop->label && prop->label->text) ? prop->label->text : "") << std::endl; stream << Spacer(tree_level) << "tooptip: " << ((prop->tooltip && prop->tooltip->text) ? prop->tooltip->text : "") << std::endl; stream << Spacer(tree_level) << "sensitive: " << (prop->sensitive ? "YES" : "NO") << std::endl; stream << Spacer(tree_level) << "visible: " << (prop->visible ? "YES" : "NO") << std::endl; stream << Spacer(tree_level) << "type: " << PropTypeToString(prop->type) << std::endl; stream << Spacer(tree_level) << "state: " << PropStateToString(prop->state) << std::endl; stream << Spacer(tree_level) << "sub_props: " << (PropertyHasChildren(prop) ? "" : "") << std::endl; stream << PrintPropList(prop->sub_props, tree_level + 1); stream << Spacer(tree_level) << "=========================" << std::endl; return stream.str(); } // Debug print function. std::string PrintPropList(IBusPropList *prop_list, int tree_level) { if (!prop_list) { return ""; } std::stringstream stream; for (int i = 0;; ++i) { IBusProperty* prop = ibus_prop_list_get(prop_list, i); if (!prop) { break; } stream << PrintProp(prop, tree_level); } return stream.str(); } } // namespace // The real implementation of the IBusController. class IBusControllerImpl : public IBusController { public: IBusControllerImpl() : ibus_(NULL), ibus_config_(NULL) { } ~IBusControllerImpl() { // Disconnect signals so the handler functions will not be called with // |this| which is already freed. if (ibus_) { g_signal_handlers_disconnect_by_func( ibus_, reinterpret_cast(G_CALLBACK(IBusBusConnectedThunk)), this); g_signal_handlers_disconnect_by_func( ibus_, reinterpret_cast(G_CALLBACK(IBusBusDisconnectedThunk)), this); g_signal_handlers_disconnect_by_func( ibus_, reinterpret_cast(G_CALLBACK(IBusBusNameOwnerChangedThunk)), this); // Disconnect signals for the panel service as well. IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (ibus_panel_service) { g_signal_handlers_disconnect_by_func( ibus_panel_service, reinterpret_cast(G_CALLBACK(FocusInThunk)), this); g_signal_handlers_disconnect_by_func( ibus_panel_service, reinterpret_cast(G_CALLBACK(RegisterPropertiesThunk)), this); g_signal_handlers_disconnect_by_func( ibus_panel_service, reinterpret_cast(G_CALLBACK(UpdatePropertyThunk)), this); } } } virtual void Connect() { MaybeRestoreConnections(); } // IBusController override. virtual bool StopInputMethodProcess() { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive"; return false; } // Ask IBus to exit *asynchronously*. ibus_bus_exit_async(ibus_, FALSE /* do not restart */, -1 /* timeout */, NULL /* cancellable */, NULL /* callback */, NULL /* user_data */); if (ibus_config_) { // Release |ibus_config_| unconditionally to make sure next // IBusConnectionsAreAlive() call will return false. g_object_unref(ibus_config_); ibus_config_ = NULL; } return true; } // IBusController override. virtual void SetImePropertyActivated(const std::string& key, bool activated) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive"; return; } if (key.empty()) { return; } if (input_context_path_.empty()) { LOG(ERROR) << "Input context is unknown"; return; } IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } // Activate the property *asynchronously*. ibus_input_context_property_activate( context, key.c_str(), (activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED)); // We don't have to call ibus_proxy_destroy(context) explicitly here, // i.e. we can just call g_object_unref(context), since g_object_unref can // trigger both dispose, which is overridden by src/ibusproxy.c, and // finalize functions. For details, see // http://library.gnome.org/devel/gobject/stable/gobject-memory.html g_object_unref(context); } // IBusController override. virtual bool ChangeInputMethod(const std::string& name) { DCHECK(!InputMethodUtil::IsKeyboardLayout(name)); if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "ChangeInputMethod: IBus connection is not alive"; return false; } if (name.empty()) { return false; } if (!InputMethodIdIsWhitelisted(name) && name.find(kExtensionImePrefix) != 0) { return false; } // Clear all input method properties unconditionally. // // When switching to another input method and no text area is focused, // RegisterProperties signal for the new input method will NOT be sent // until a text area is focused. Therefore, we have to clear the old input // method properties here to keep the input method switcher status // consistent. DoRegisterProperties(NULL); // Change the global engine *asynchronously*. ibus_bus_set_global_engine_async(ibus_, name.c_str(), -1, // use the default ibus timeout NULL, // cancellable NULL, // callback NULL); // user_data UpdateUI(name.c_str()); return true; } // IBusController override. virtual bool SetInputMethodConfig(const std::string& section, const std::string& config_name, const InputMethodConfigValue& value) { // See comments in GetImeConfig() where ibus_config_get_value() is used. if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "SetInputMethodConfig: IBus connection is not alive"; return false; } bool is_preload_engines = false; // Sanity check: do not preload unknown/unsupported input methods. std::vector string_list; if ((value.type == InputMethodConfigValue::kValueTypeStringList) && (section == kGeneralSectionName) && (config_name == kPreloadEnginesConfigName)) { FilterInputMethods(value.string_list_value, &string_list); if (string_list.empty()) { return true; } is_preload_engines = true; } else { string_list = value.string_list_value; } // Convert the type of |value| from our structure to GVariant. GVariant* variant = NULL; switch (value.type) { case InputMethodConfigValue::kValueTypeString: variant = g_variant_new_string(value.string_value.c_str()); break; case InputMethodConfigValue::kValueTypeInt: variant = g_variant_new_int32(value.int_value); break; case InputMethodConfigValue::kValueTypeBool: variant = g_variant_new_boolean(value.bool_value); break; case InputMethodConfigValue::kValueTypeStringList: GVariantBuilder variant_builder; g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as")); DCHECK(!string_list.empty()); const size_t size = string_list.size(); // don't use string_list_value. for (size_t i = 0; i < size; ++i) { g_variant_builder_add(&variant_builder, "s", string_list[i].c_str()); } variant = g_variant_builder_end(&variant_builder); break; } if (!variant) { LOG(ERROR) << "SetInputMethodConfig: variant is NULL"; return false; } DCHECK(g_variant_is_floating(variant)); // Set an ibus configuration value *asynchronously*. ibus_config_set_value_async(ibus_config_, section.c_str(), config_name.c_str(), variant, -1, // use the default ibus timeout NULL, // cancellable SetInputMethodConfigCallback, g_object_ref(ibus_config_)); // Since |variant| is floating, ibus_config_set_value_async consumes // (takes ownership of) the variable. if (is_preload_engines) { VLOG(1) << "SetInputMethodConfig: " << section << "/" << config_name << ": " << value.ToString(); } return true; } // IBusController override. virtual void SendHandwritingStroke(const HandwritingStroke& stroke) { if (stroke.size() < 2) { LOG(WARNING) << "Empty stroke data or a single dot is passed."; return; } IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } const size_t raw_stroke_size = stroke.size() * 2; scoped_array raw_stroke(new double[raw_stroke_size]); for (size_t n = 0; n < stroke.size(); ++n) { raw_stroke[n * 2] = stroke[n].first; // x raw_stroke[n * 2 + 1] = stroke[n].second; // y } ibus_input_context_process_hand_writing_event( context, raw_stroke.get(), raw_stroke_size); g_object_unref(context); } // IBusController override. virtual void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); } virtual bool InputMethodIdIsWhitelisted(const std::string& input_method_id) { return whitelist_.InputMethodIdIsWhitelisted(input_method_id); } virtual bool XkbLayoutIsSupported(const std::string& xkb_layout) { return whitelist_.XkbLayoutIsSupported(xkb_layout); } virtual InputMethodDescriptor CreateInputMethodDescriptor( const std::string& id, const std::string& name, const std::string& raw_layout, const std::string& language_code) { return InputMethodDescriptor(whitelist_, id, name, raw_layout, language_code); } // IBusController override. virtual void AddObserver(Observer* observer) { observers_.AddObserver(observer); } // IBusController override. virtual void RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } private: // Functions that end with Thunk are used to deal with glib callbacks. // // Note that we cannot use CHROMEG_CALLBACK_0() here as we'll define // IBusBusConnected() inline. If we are to define the function outside // of the class definition, we should use CHROMEG_CALLBACK_0() here. // // CHROMEG_CALLBACK_0(Impl, // void, IBusBusConnected, IBusBus*); static void IBusBusConnectedThunk(IBusBus* sender, gpointer userdata) { return reinterpret_cast(userdata) ->IBusBusConnected(sender); } static void IBusBusDisconnectedThunk(IBusBus* sender, gpointer userdata) { return reinterpret_cast(userdata) ->IBusBusDisconnected(sender); } static void IBusBusNameOwnerChangedThunk(IBusBus* sender, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer userdata) { return reinterpret_cast(userdata) ->IBusBusNameOwnerChanged(sender, name, old_name, new_name); } static void FocusInThunk(IBusPanelService* sender, const gchar* input_context_path, gpointer userdata) { return reinterpret_cast(userdata) ->FocusIn(sender, input_context_path); } static void RegisterPropertiesThunk(IBusPanelService* sender, IBusPropList* prop_list, gpointer userdata) { return reinterpret_cast(userdata) ->RegisterProperties(sender, prop_list); } static void UpdatePropertyThunk(IBusPanelService* sender, IBusProperty* ibus_prop, gpointer userdata) { return reinterpret_cast(userdata) ->UpdateProperty(sender, ibus_prop); } // Checks if |ibus_| and |ibus_config_| connections are alive. bool IBusConnectionsAreAlive() { return ibus_ && ibus_bus_is_connected(ibus_) && ibus_config_; } // Restores connections to ibus-daemon and ibus-memconf if they are not ready. // If both |ibus_| and |ibus_config_| become ready, the function sends a // notification to Chrome. void MaybeRestoreConnections() { if (IBusConnectionsAreAlive()) { return; } MaybeCreateIBus(); MaybeRestoreIBusConfig(); if (IBusConnectionsAreAlive()) { ConnectPanelServiceSignals(); VLOG(1) << "Notifying Chrome that IBus is ready."; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(true)); } } // Creates IBusBus object if it's not created yet. void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); // Establish IBus connection between ibus-daemon to retrieve the list of // available input method engines, change the current input method engine, // and so on. ibus_ = ibus_bus_new(); // Check the IBus connection status. if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } // Register callback functions for IBusBus signals. ConnectIBusSignals(); // Ask libibus to watch the NameOwnerChanged signal *asynchronously*. ibus_bus_set_watch_dbus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { VLOG(1) << "IBus connection is ready."; } } // Creates IBusConfig object if it's not created yet AND |ibus_| connection // is ready. void MaybeRestoreIBusConfig() { if (!ibus_) { return; } // Destroy the current |ibus_config_| object. No-op if it's NULL. MaybeDestroyIBusConfig(); if (!ibus_config_) { GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_); if (!ibus_connection) { VLOG(1) << "Couldn't create an ibus config object since " << "IBus connection is not ready."; return; } const gboolean disconnected = g_dbus_connection_is_closed(ibus_connection); if (disconnected) { // |ibus_| object is not NULL, but the connection between ibus-daemon // is not yet established. In this case, we don't create |ibus_config_| // object. LOG(ERROR) << "Couldn't create an ibus config object since " << "IBus connection is closed."; return; } // If memconf is not successfully started yet, ibus_config_new() will // return NULL. Otherwise, it returns a transfer-none and non-floating // object. ibus_config_new() sometimes issues a D-Bus *synchronous* IPC // to check if the org.freedesktop.IBus.Config service is available. ibus_config_ = ibus_config_new(ibus_connection, NULL /* do not cancel the operation */, NULL /* do not get error information */); if (!ibus_config_) { LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?"; return; } // TODO(yusukes): g_object_weak_ref might be better since it allows // libcros to detect the delivery of the "destroy" glib signal the // |ibus_config_| object. g_object_ref(ibus_config_); VLOG(1) << "ibus_config_ is ready."; } } // Destroys IBusConfig object if |ibus_| connection is not ready. This // function does nothing if |ibus_config_| is NULL or |ibus_| connection is // still alive. Note that the IBusConfig object can't be used when |ibus_| // connection is not ready. void MaybeDestroyIBusConfig() { if (!ibus_) { LOG(ERROR) << "MaybeDestroyIBusConfig: ibus_ is NULL"; return; } if (ibus_config_ && !ibus_bus_is_connected(ibus_)) { g_object_unref(ibus_config_); ibus_config_ = NULL; } } // Handles "RegisterProperties" signal from chromeos_input_method_ui. void DoRegisterProperties(IBusPropList* ibus_prop_list) { VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); InputMethodPropertyList prop_list; // our representation. if (ibus_prop_list) { // You can call // LOG(INFO) << "\n" << PrintPropList(ibus_prop_list, 0); // here to dump |ibus_prop_list|. if (!FlattenPropertyList(ibus_prop_list, &prop_list)) { // Clear properties on errors. DoRegisterProperties(NULL); return; } } VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); // Notify the change. FOR_EACH_OBSERVER(Observer, observers_, OnRegisterImeProperties(prop_list)); } // Retrieves input method status and notifies them to the UI. // |current_global_engine_id| is the current global engine id such as "mozc" // and "xkb:us::eng". If the id is unknown, an empty string "" can be passed. // Warning: you can call this function only from ibus callback functions // like FocusIn(). See http://crosbug.com/5217#c9 for details. void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const InputMethodsInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kInputMethods); ++i) { if (kInputMethods[i].input_method_id == std::string(current_global_engine_id)) { engine_info = &kInputMethods[i]; break; } } InputMethodDescriptor current_input_method; if (engine_info) { current_input_method = CreateInputMethodDescriptor( engine_info->input_method_id, "", engine_info->xkb_layout_id, engine_info->language_code); } else { if (!InputMethodManager::GetInstance()->GetExtraDescriptor( current_global_engine_id, ¤t_input_method)) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } } VLOG(1) << "Updating the UI. ID:" << current_input_method.id() << ", keyboard_layout:" << current_input_method.keyboard_layout(); // Notify the change to update UI. FOR_EACH_OBSERVER(Observer, observers_, OnCurrentInputMethodChanged(current_input_method)); } // Installs gobject signal handlers to |ibus_|. void ConnectIBusSignals() { if (!ibus_) { return; } // We use g_signal_connect_after here since the callback should be called // *after* the IBusBusDisconnectedCallback in chromeos_input_method_ui.cc // is called. chromeos_input_method_ui.cc attaches the panel service object // to |ibus_|, and the callback in this file use the attached object. g_signal_connect_after(ibus_, "connected", G_CALLBACK(IBusBusConnectedThunk), this); g_signal_connect(ibus_, "disconnected", G_CALLBACK(IBusBusDisconnectedThunk), this); g_signal_connect(ibus_, "name-owner-changed", G_CALLBACK(IBusBusNameOwnerChangedThunk), this); } // Installs gobject signal handlers to the panel service. void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } // We don't _ref() or _weak_ref() the panel service object, since we're not // interested in the life time of the object. g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInThunk), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesThunk), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyThunk), this); } // Handles "connected" signal from ibus-daemon. void IBusBusConnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is recovered."; MaybeRestoreConnections(); } // Handles "disconnected" signal from ibus-daemon. void IBusBusDisconnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is terminated."; // ibus-daemon might be terminated. Since |ibus_| object will automatically // connect to the daemon if it restarts, we don't have to set NULL on ibus_. // Call MaybeDestroyIBusConfig() to set |ibus_config_| to NULL temporarily. MaybeDestroyIBusConfig(); VLOG(1) << "Notifying Chrome that IBus is terminated."; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(false)); } // Handles "name-owner-changed" signal from ibus-daemon. The signal is sent // to libcros when an IBus component such as ibus-memconf, ibus-engine-*, .. // is started. void IBusBusNameOwnerChanged(IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); VLOG(1) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { // Not a signal for ibus-memconf. return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { // ibus-memconf died? LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; // TODO(yusukes): it might be nice to set |ibus_config_| to NULL and call // |OnConnectionChange| with false here to allow Chrome to // recover all input method configurations when ibus-memconf is // automatically restarted by ibus-daemon. Though ibus-memconf is pretty // stable and unlikely crashes. return; } VLOG(1) << "IBus config daemon is started. Recovering ibus_config_"; // Try to recover |ibus_config_|. If the |ibus_config_| object is // successfully created, |OnConnectionChange| will be called to // notify Chrome that IBus is ready. MaybeRestoreConnections(); } // Handles "FocusIn" signal from chromeos_input_method_ui. void FocusIn(IBusPanelService* panel, const gchar* input_context_path) { if (!input_context_path) { LOG(ERROR) << "NULL context passed"; } else { VLOG(1) << "FocusIn: " << input_context_path; } // Remember the current ic path. input_context_path_ = Or(input_context_path, ""); } // Handles "RegisterProperties" signal from chromeos_input_method_ui. void RegisterProperties(IBusPanelService* panel, IBusPropList* prop_list) { DoRegisterProperties(prop_list); } // Handles "UpdateProperty" signal from chromeos_input_method_ui. void UpdateProperty(IBusPanelService* panel, IBusProperty* ibus_prop) { VLOG(1) << "UpdateProperty"; DCHECK(ibus_prop); // You can call // LOG(INFO) << "\n" << PrintProp(ibus_prop, 0); // here to dump |ibus_prop|. InputMethodPropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { // Don't update the UI on errors. LOG(ERROR) << "Malformed properties are detected"; return; } // Notify the change. if (!prop_list.empty()) { FOR_EACH_OBSERVER(Observer, observers_, OnUpdateImeProperty(prop_list)); } } // Removes input methods that are not whitelisted from // |requested_input_methods| and stores them on |out_filtered_input_methods|. // TODO(yusukes): Write unittest. void FilterInputMethods( const std::vector& requested_input_methods, std::vector* out_filtered_input_methods) { out_filtered_input_methods->clear(); for (size_t i = 0; i < requested_input_methods.size(); ++i) { const std::string& input_method = requested_input_methods[i]; if (whitelist_.InputMethodIdIsWhitelisted(input_method.c_str())) { if (!InputMethodUtil::IsKeyboardLayout(input_method)) { out_filtered_input_methods->push_back(input_method); } } else { LOG(ERROR) << "Unsupported input method: " << input_method; } } } // Frees input method names in |engines| and the list itself. Please make sure // that |engines| points the head of the list. void FreeInputMethodNames(GList* engines) { if (engines) { for (GList* cursor = engines; cursor; cursor = g_list_next(cursor)) { g_object_unref(IBUS_ENGINE_DESC(cursor->data)); } g_list_free(engines); } } // Copies input method names in |engines| to |out|. // TODO(yusukes): Write unittest. void AddInputMethodNames(const GList* engines, InputMethodDescriptors* out) { DCHECK(out); for (; engines; engines = g_list_next(engines)) { IBusEngineDesc* engine_desc = IBUS_ENGINE_DESC(engines->data); const gchar* name = ibus_engine_desc_get_name(engine_desc); const gchar* layout = ibus_engine_desc_get_layout(engine_desc); const gchar* language = ibus_engine_desc_get_language(engine_desc); if (whitelist_.InputMethodIdIsWhitelisted(name)) { out->push_back(CreateInputMethodDescriptor(name, "", layout, language)); VLOG(1) << name << " (preloaded)"; } } } // A callback function that will be called when ibus_config_set_value_async() // request is finished. static void SetInputMethodConfigCallback(GObject* source_object, GAsyncResult* res, gpointer user_data) { IBusConfig* config = IBUS_CONFIG(user_data); g_return_if_fail(config); GError* error = NULL; const gboolean result = ibus_config_set_value_async_finish(config, res, &error); if (!result) { std::string message = "(unknown error)"; if (error && error->message) { message = error->message; } LOG(ERROR) << "ibus_config_set_value_async failed: " << message; } if (error) { g_error_free(error); } g_object_unref(config); } // Connection to the ibus-daemon via IBus API. These objects are used to // call ibus-daemon's API (e.g. activate input methods, set config, ...) IBusBus* ibus_; IBusConfig* ibus_config_; // Current input context path. std::string input_context_path_; ObserverList observers_; // An object which knows all valid input method and layout IDs. InputMethodWhitelist whitelist_; DISALLOW_COPY_AND_ASSIGN(IBusControllerImpl); }; #endif // defined(HAVE_IBUS) // The stub implementation is used if IBus is not present. // // Note that this class is intentionally built even if HAVE_IBUS is // defined so that we can easily tell build breakage when we change the // IBusControllerImpl but forget to update the stub implementation. class IBusControllerStubImpl : public IBusController { public: IBusControllerStubImpl() { } virtual void Connect() { }; virtual void AddObserver(Observer* observer) { } virtual void RemoveObserver(Observer* observer) { } virtual bool StopInputMethodProcess() { return true; } virtual bool ChangeInputMethod(const std::string& name) { return true; } virtual void SetImePropertyActivated(const std::string& key, bool activated) { } virtual bool SetInputMethodConfig(const std::string& section, const std::string& config_name, const InputMethodConfigValue& value) { return true; } virtual void SendHandwritingStroke(const HandwritingStroke& stroke) { } virtual void CancelHandwriting(int n_strokes) { } // This is for ibus_controller_unittest.cc. Since the test is usually compiled // without HAVE_IBUS, we have to provide the same implementation as // IBusControllerImpl to test the whitelist class. virtual bool InputMethodIdIsWhitelisted(const std::string& input_method_id) { return whitelist_.InputMethodIdIsWhitelisted(input_method_id); } // See the comment above. We have to keep the implementation the same as // IBusControllerImpl. virtual bool XkbLayoutIsSupported(const std::string& xkb_layout) { return whitelist_.XkbLayoutIsSupported(xkb_layout); } // See the comment above. We have to keep the implementation the same as // IBusControllerImpl. virtual InputMethodDescriptor CreateInputMethodDescriptor( const std::string& id, const std::string& name, const std::string& raw_layout, const std::string& language_code) { return InputMethodDescriptor(whitelist_, id, name, raw_layout, language_code); } private: InputMethodWhitelist whitelist_; DISALLOW_COPY_AND_ASSIGN(IBusControllerStubImpl); }; IBusController* IBusController::Create() { #if defined(HAVE_IBUS) return new IBusControllerImpl; #else return new IBusControllerStubImpl; #endif } IBusController::~IBusController() { } } // namespace input_method } // namespace chromeos openharmony-gitee-mirror/ace_ace_engine /* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frameworks/bridge/common/dom/dom_swiper.h" #include "base/utils/linear_map.h" #include "base/utils/utils.h" #include "core/components/common/properties/color.h" #include "frameworks/bridge/common/utils/utils.h" namespace OHOS::Ace::Framework { namespace { constexpr double MAX_OPACITY = 255.0; const std::string DISPLAY_COMPOSED_NAME = "SwiperDisplayChild"; std::string GetDisplayComposedId(const RefPtr& child) { return "display" + std::to_string(child->GetNodeId()); } } // namespace DOMSwiper::DOMSwiper(NodeId nodeId, const std::string& nodeName) : DOMNode(nodeId, nodeName) { swiperChild_ = AceType::MakeRefPtr(std::list>()); } void DOMSwiper::InitializeStyle() { if (declaration_) { declaration_->InitializeStyle(); } } void DOMSwiper::OnChildNodeAdded(const RefPtr& child, int32_t slot) { ACE_DCHECK(child); auto display = AceType::MakeRefPtr(child->GetRootComponent()); display->SetOpacity(MAX_OPACITY); swiperChild_->InsertChild( slot, AceType::MakeRefPtr(GetDisplayComposedId(child), DISPLAY_COMPOSED_NAME, display)); } void DOMSwiper::OnChildNodeRemoved(const RefPtr& child) { ACE_DCHECK(child); swiperChild_->RemoveChildByComposedId(GetDisplayComposedId(child)); } void DOMSwiper::PrepareSpecializedComponent() { swiperChild_->SetShow(GetDisplay() == DisplayType::NO_SETTING || GetDisplay() == DisplayType::FLEX); swiperChild_->SetDeclaration(AceType::DynamicCast(declaration_)); swiperChild_->SetTextDirection(IsRightToLeft() ? TextDirection::RTL : TextDirection::LTR); for (const auto& item : swiperChild_->GetChildren()) { auto composedDisplay = AceType::DynamicCast(item); if (composedDisplay) { composedDisplay->MarkNeedUpdate(); } } } void DOMSwiper::AdjustSpecialParamInLiteMode() { auto declaration = AceType::DynamicCast(declaration_); if (declaration) { declaration->SetShowIndicator(false); } } } // namespace OHOS::Ace::Framework // ******************************************************************** // Copyright (c) 2019 // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files(the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and / or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ******************************************************************** #include "Engine/App/Application.h" #include "Engine/App/Program.h" #include "Core/Concurrent/TaskScheduler.h" #include "Core/Memory/AtomicSmartPointer.h" #include "Core/Utility/SmartCallback.h" #include "Core/Utility/Log.h" #include "Runtime/Async/PromiseImpl.h" using namespace lf; void OnResolve() { gSysLog.Info(LogMessage("Promise Resolved!")); } void OnError(const String& error) { gSysLog.Error(LogMessage("Promise Error! Error=") << error); } class PromiseApp : public Application { DECLARE_CLASS(PromiseApp, Application); public: using MyPromiseType = PromiseImpl, TCallback>; void RunPromise() { auto promise = MyPromiseType([](Promise* self) { self->Resolve(); // self->Reject("Rejected!"); }) .Then(OnResolve) .Then([]() { gSysLog.Info(LogMessage("On Lambda Resolved! ThreadId=") << GetPlatformThreadId()); }) .Catch(OnError) .Catch([](const String& error) { gSysLog.Error(LogMessage("On Lambda Error! Error=") << error); }) .Execute(); gSysLog.Info(LogMessage("Waiting for promise to complete!")); // promise->Wait(); // // promise->SetState(Promise::PROMISE_NULL); // GetAsync().ExecutePromise(promise); // promise->LazyWait(); (promise); // SleepCallingThread(2500); LF_DEBUG_BREAK; } void OnStart() override { gSysLog.Info(LogMessage("Tada")); RunPromise(); } }; DEFINE_CLASS(PromiseApp) { NO_REFLECTION; } test/socket/basic_socket_ut.hpp /** * @file : basic_socket_ut.hpp * @author : Ken.Matsushima <> * @date : 2015 * @desciption : a stub of boost::asio::socket for unit testing */ #ifndef BOOST_ASIO_BASIC_SOCKET_HPP #define BOOST_ASIO_BASIC_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) //#include //#include //#include //#include //#include //#include //#include //#include // //#include namespace boost { namespace asio { template class basic_socket : public basic_io_object, public socket_base { public: typedef typename SocketService::native_handle_type native_type; typedef typename SocketService::native_handle_type native_handle_type; typedef Protocol protocol_type; typedef typename Protocol::endpoint endpoint_type; typedef basic_socket lowest_layer_type; explicit basic_socket(boost::asio::io_service& io_service) : basic_io_object(io_service) { } basic_socket(boost::asio::io_service& io_service, const protocol_type& protocol) : basic_io_object(io_service) { } basic_socket(boost::asio::io_service& io_service, const endpoint_type& endpoint) : basic_io_object(io_service) { } basic_socket(boost::asio::io_service& io_service, const protocol_type& protocol, const native_handle_type& native_socket) : basic_io_object(io_service) { } #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) basic_socket(basic_socket&& other) : basic_io_object( BOOST_ASIO_MOVE_CAST(basic_socket)(other)) { } basic_socket& operator=(basic_socket&& other) { return *this; } template friend class basic_socket; template basic_socket(basic_socket&& other, typename enable_if::value>::type* = 0) : basic_io_object(other.get_io_service()) { } template typename enable_if::value, basic_socket>::type& operator=( basic_socket&& other) { return *this; } #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) lowest_layer_type& lowest_layer() { return *this; } const lowest_layer_type& lowest_layer() const { return *this; } void open(const protocol_type& protocol = protocol_type()) { } boost::system::error_code open(const protocol_type& protocol, boost::system::error_code& ec) { boost::syste::error_code er; return er; } void assign(const protocol_type& protocol, const native_handle_type& native_socket) { } boost::system::error_code assign(const protocol_type& protocol, const native_handle_type& native_socket, boost::system::error_code& ec) { boost::syste::error_code er; return er; } bool is_open() const { return true; } void close() { } boost::system::error_code close(boost::system::error_code& ec) { boost::syste::error_code er; return er; } native_type native() { return this->get_service().native_handle(this->get_implementation()); } native_handle_type native_handle() { return this->get_service().native_handle(this->get_implementation()); } #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif void cancel() { } #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif boost::system::error_code cancel(boost::system::error_code& ec) { boost::syste::error_code er; return er; } bool at_mark() const { return true; } bool at_mark(boost::system::error_code& ec) const { return true; } std::size_t available() const { return 0; } std::size_t available(boost::system::error_code& ec) const { return 0; } void bind(const endpoint_type& endpoint) { } boost::system::error_code bind(const endpoint_type& endpoint, boost::system::error_code& ec) { boost::syste::error_code er; return er; } void connect(const endpoint_type& peer_endpoint) { } boost::system::error_code connect(const endpoint_type& peer_endpoint, boost::system::error_code& ec) { boost::syste::error_code er; return er; } template BOOST_ASIO_INITFN_RESULT_TYPE(ConnectHandler, void (boost::system::error_code)) async_connect(const endpoint_type& peer_endpoint, BOOST_ASIO_MOVE_ARG(ConnectHandler) handler) { template void set_option(const SettableSocketOption& option) { } template boost::system::error_code set_option(const SettableSocketOption& option, boost::system::error_code& ec) { boost::syste::error_code er; return er; } template void get_option(GettableSocketOption& option) const { } template boost::system::error_code get_option(GettableSocketOption& option, boost::system::error_code& ec) const { boost::syste::error_code er; return er; } template void io_control(IoControlCommand& command) { } template boost::system::error_code io_control(IoControlCommand& command, boost::system::error_code& ec) { boost::syste::error_code er; return er; } bool non_blocking() const { return true; } void non_blocking(bool mode) { } boost::system::error_code non_blocking( bool mode, boost::system::error_code& ec) { boost::syste::error_code er; return er; } bool native_non_blocking() const { return true; } void native_non_blocking(bool mode) { } boost::system::error_code native_non_blocking( bool mode, boost::system::error_code& ec) { boost::syste::error_code er; return er; } endpoint_type m_local_endpoint; endpoint_type local_endpoint() const { return m_local_endpoint; } endpoint_type local_endpoint(boost::system::error_code& ec) const { return m_local_endpoint; } endpoint_type m_remote_endpoint; endpoint_type remote_endpoint() const { return m_remote_endpoint; } endpoint_type remote_endpoint(boost::system::error_code& ec) const { return m_remote_endpoint; } void shutdown(shutdown_type what) { } boost::system::error_code shutdown(shutdown_type what, boost::system::error_code& ec) { boost::syste::error_code er; return er; } protected: ~basic_socket() { } }; } // namespace asio } // namespace boost // #include #endif // BOOST_ASIO_BASIC_SOCKET_HPP abaire/xbdm_gdb_bridge #include "rdcp_request.h" static constexpr uint8_t kTerminator[] = {'\r', '\n'}; static constexpr long kTerminatorLen = sizeof(kTerminator) / sizeof(kTerminator[0]); RDCPRequest::operator std::vector() const { std::vector ret; ret.reserve(command_.size() + data_.size() + kTerminatorLen); ret.assign(command_.begin(), command_.end()); ret.insert(ret.end(), data_.begin(), data_.end()); ret.insert(ret.end(), kTerminator, kTerminator + kTerminatorLen); return ret; } std::ostream &operator<<(std::ostream &os, RDCPRequest const &r) { return os << r.command_ << " " << r.data_.size(); } 洛谷/普及-/P1097.cc #include using namespace std; int main() { map a; //把它看成数组 set b; int n,i,q; cin>>n; for(i=1; i<=n; i++) { scanf("%d",&q); a[q]++; b.insert(q); } for(set::iterator it=b.begin(); it!=b.end(); it++) //迭代器 printf("%d %d\n",*it,a[*it]); } #include #include #include #include #include #include #include "Student_info.h" #include "Ptr.h" #include "compare_Core_ptrs.h" using std::streamsize; using std::setprecision; using std::cout; using std::cin; using std::endl; using std::vector; using std::string; using std::sort; using std::max; using std::domain_error; int main() { vector< Ptr > students; // store Ptrs, not objects Ptr record; // temporary must be a Ptr as well char ch; string::size_type maxlen = 0; // read and store the data while (cin >> ch) { if (ch == 'U') record = new Core; // allocate a Core object else record = new Grad; // allocate a Grad object record->read(cin); // virtual call maxlen = max(maxlen, record->name().size()); // dereference students.push_back(record); } // pass the version of compare that works on Ptrs sort(students.begin(), students.end(), compare_Core_ptrs); // write the names and grades for (vector< Ptr >::size_type i = 0; i != students.size(); ++i) { // students[i] is a pointer that we dereference to call the functions cout << students[i]->name() << string(maxlen + 1 - students[i]->name().size(), ' '); try { double final_grade = students[i]->grade(); streamsize prec = cout.precision(); cout << setprecision(3) << final_grade << setprecision(prec) << endl; } catch (domain_error e) { cout << e.what() << endl; } } return 0; }#include #include #include #include #include #include "index_set.hpp" #include "jobs.hpp" #include "cache.hpp" namespace NP { // use pointers as a primitive form of unique ID namespace Uniproc { typedef Index_set Job_set; template class Schedule_state { private: Interval