�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �H   �� ��:�,�,��<_)H�eH�eH��uHhB���%,3;CKRZbipv~�����������������#+29AIPW^fmt{������������������%,4<DKRZaiqw���������������� (/6=ELT[bjrz������������������ $,4;AHPX_fnu|�����������������&-5=CKSZbjqx������������������ ")19AIPX`fmu}����������������� !)19@HOV^elt{�����������������$+3:AHPW_gov}������������������    $ , 3 : A H O W _ g o w  � � � � � � � � � � � � � � � �     & . 5 = D K R Z b j q x � � � � � � � � � � � � � � � � � �    " ) 1 8 @ G N U ] e l s { � � � � � � � � � � � � � � � � �    ( 0 7 > E M T [ b i p w ~ � � � � � � � � � � � � � � � � �    " * 2 9 A H P X ` h p x � � � � � � � � � � � � � � � � �  ")19@HPX`how����������������� ")18?GOV^fmt{����������������� !(/7?GOW_gnv}����������������$,3:BJQX`gov~����������������  '/7>FMT\bipw����������������� $+2:@GNV]elt{�����������������  '/7?FKRZbjry�����������������'.5=ELT[bjry����������������� "*08@GNU]emt|�����������������  (/7>FNV]elt{����������������� '/7?FNU\dlt{����������������� #*19@HOV^fmu}�����������������  (08?FMT\dlsz����������������� '.5<DKSZaipw����������������� ")18?FNV]dks{������������������ %-2:185638837649303222468363893321344040776062895395110181743551766740717286157586880918712077149350479446536646258253929118641291166982141767425596191441391832419879900744036622901214445785188719041812002915650558113804751561154415776948512771515825594130367190830684741545111361843071873316990148643268688609702949017566050140843299388570880858862074971663857629994877547986883315153859761910320121509811316667148791248368507837086125250001683262665389586585356126917471413006640052721445714163551101124007500400912474429572576918724155933977317042052828484711332693108517331399367383860327570358146264399862509127733791678038172350214915353909451449791711987079558871571055258614399026121992171903573213110323108768421219683217188823119749603313819309393223006809711622114583571550061915601161109422301976563455203819531798721918618149461731761912730835182311171854261835716418333074196178371489245937140465756789977023437651721156014447322006131179068714555002757529124590175102515128444696646100105206931503299618963867137372791473564011728089143326831463350510966519114224734495276522758278738713331663199883849603788573722515433615274708780622221803688816569368182323138144371256413010024890197899171562104120673461522996913883534140927157279135492370320102861487935818579618114630361357177014959316196065931250752566398501613908917346084620917149813021228412136812921944543414520648971420524319411100011192549239656570723150978998514203142448824318706490141571616546066179279819003381159669191985991114885716200202252479058958147098674691624172117108764925251500590671663171086958519521008174278691188151285806171938509811506825564614756555316924048131391885361752187193514655444326546716388031955990364764531176322032094372075150146028814765122801368717682350201766712472172556794714968057109024603005746178237421847318214281367113612491791161670776911071837671555406949801161187175477688481514115170149775541775909731938200511691440341633841850157420195467988812540201681682163082121275345212912130136225481292713059324567478641125278351666109472397639441111412286840091128517312623956151192423894668952564677882821726011738439071006160314405032163566562766167558466835637961513123210300642248304704853744374071300843937285701635186416360621182107196152648581084148102781170022260339261895233623944969692115365961476138845737648391932107235415050399224110098467613177871310597419985155177709881321062816630150168548161976596119745925192933438475052973166314621048614924712525040937408918813328197298301832899616855049193630339187214573033157551491032018419516742171176081766364392421423795804156897145842139189820925310780828038260705081927834517771285182934798078063535899713150837743837511620032737118599677853448612255869747930612663006132227252155418518625080225855724291798001012108625155633321351659515405220135327831664154182659819510357547235812109603537886912073679182864391673815644931154150031117857972381526118731140871611143537114531961456724545330171467156517950267186624128868031721089331511861757538946458441218815994577951054722313265791760105847536113481896953999714372274195215411518931815417006619135787771253833738144716206671075452401940314197984488463241793720782204859587524515426990308701960059351601588957770951181691211882322129759991395956413810416515830063195511367440355370347888920841590061740646816132531046311839889150954541484103616776806738322511826525941384111089036129906171424018715062572169830061644631719345568114582991586790110554031638809218365560270278619700090268268214868174126216233007389123400461791961818382356105982941512843853759071191544518509066309903210447724233376212776820148164967895017141086521445484212792909161194791652418366443301369861814085431130964322609521426201717698453569628344231245505809483081741609410256208113705081534019018064736104651193076698623520017092071074094789541721131915810534953408436655118621320271382306861558344109654961659268236112231029036216171017573830030056714103555718067862908421358253362316402465809449348811413549193447791491311910942760136401906924394308245678252008701343137882671776120216562882131397031549399218676003400626989367675603405149180701765989110303129188536811688301717214083101432189702526169359278439436476450109528816757913113062421982064416210535138481145689271755082212397326107326001313176410785925116471951600259017428348165130333853851649241612651554819361120430941835411686335533017026118980961139841086136349363031121151566710083146321605224507185841201876418196012631007505515337912139357076201015146415881373006911215817281734912828611882785195801801045443814972431101877201840505114651381866858619916465157951634960428121662281735542756027851037317469489526588947196411594239497414911347983329812671671519518277961521115014326272144547516552264494939812369337524875716459078136457801956704253193212325246724949515950021289132027043331868459299268671804964314614659462225641171224698417110653474267815300300359059614977467380260711005204579677115270274191603979275393682538176490691696670410573211358255018784458109633765661641143317479533013211214111349821262526883302451943040211454135105531957608923320270116504691129572942527581224656717264402143330099400096519435305852200640701783342215840868161834146041301162208791628443151884441462045039491201103063415451952201644512551079445796213656898166801871346928818447001952347182925165648021323226072108071460537711685944791219819960803911473582758751436132916897375647193117638635913044879600181500864113753092353706916921323197894691856593414363090136918331704670892909491951641815168677145246201271109618905925137833914787076129857498515841424144412660916894973753849207321152171046481843845077381210025672181206069239534975458183988851326165710233707119795428080908166961682345766177840701636978714802409344611044447071464908740287371209808897705251059218914042873619722198717504986100842194614761123569080113346963291991484388531084401116257583820054713965192635216917036429194281311418196063363361616803887888161179376749779561557932621444431246579411753080197998671178841310547589165645346665565278663852376711672671247568117455046909770420028227187470046489174188080428769418848127461120016430986134543341930361318443779529258817549496179260475186821390839018137678173860864911995143231144234031983562159260618556756688489137014912002523610767501541528211860627121029838186089165912674931810181881125693441052795415427115875037934484651034910361762859829538845311292835957052941105119791009119075541103371261560581652075051065331917974963263813226803731604279211741742606023215000431111527071768691696868481011333564510421346252410481085606223518576073298017111726081738235432966785283423766647350553615371194194379711948506466207338636526878789459415151999613916217208199446036060096151115310152536123685431687702993140521636931616477233220136915995188800145112995113820751666473515747585175974217315504317172414702337182911561260958146613825468950366026210587975194456599741203273503179645184867235117188195295053345858412398002457350158118951844213553080805309646461100712419618153342847299601871517816952923377116395733141235778518849943131399381896951612845848169643597201134400778893364228394816944035156849863923848182144968716455792425746680121222985717256874910897857811508844677151324371929631713193939187636881804956335464348392344274199456460704595125153763961090758613885528733380183344899922295398127001731686314276076651092273016140416146788361959759014686766111414922427815585520@s�!�,83b��������������׮9�γ��.�y�:�����Y���"�(�2`4W?� H"�%�(�*zB�DMae�oO�َI�ߥ��M���q��\+'-_GL�fh�a���������'�[��BE�H�d�hi�:� �(��/ 1 2 i4 �U b �d i Rm �t �w Cx � �� � [� �� W� � �� �� 7� �� �� �> dD �U �Z �b �m Г �� D� O� ʭ o� 2� �� i� 7� � �� �  �( 1 �7 �N �Z ^ {d �� n� /� ��  � � - �2 O: aS /U gl �l qp ws  A� ҄ |� �� l� �� ۡ R� G� w� a� ?� "� �* L8 `; �D �F �\ ka i en d{ � Ы V� ھ �� �� 5� �W'+jA�G�Khd�jk~r�Õs���2�F�$�5O� -N9A�F-P�Sy7N�&�2ZL����Ǽi�Y���y���k��� =!!'jJ 6Q �T �v .| >~ Ô �� ?� F !� !�!�!!!v5!�6!dq!�{!у!̈!�!��!נ!��!��! �!��!��!�"]"M"�%"C-"�0"0_"�/��/Q�/��/R�/�40UF0�F0�0��0!�0��0^�0Z�0��0|�0�1�1�1B1"1�&13)14A1D1�]1�e1+�1S�1B�1��1ة1�1=�1v�1��1��1��1��1��1� 2-\4�g45o4T�4��4Y5"5�&5�*53g5�l5/�5͆5�5��5��5��5ֶ57�5[�5V�5��5f�5�a6�p6��6F�6 �6͵6�6��6��7V�7D�7��7�7��7�7,�7!�7��7��7 8v8�$8�18�A8�]8�`8�g8�k8��8z�8�8��8y�8�9�,9�09tJ9qN9Ob9~9�9'�9[�9b�9��9��9�9.�9m�9D�9��9��9 :�:� :�:[:,::3:pN:|Q:qS:�T:�a:bn:%q:�t:P�:#�:��:&�:B�:��:��:}Z<W`<%d<�l<Ts<�u<�<%�<$�<M�<��<׵<�<��<��<>�<��<��<��<}�<A�<��< D=UG=1I=HJ=4]=#s=�z=�=��=3�="�=ݝ=��=��=��=M�=6�=4>*>�u>}y>N|>E�><�>��>��>��>��>��>x�>U�>�>�>@�>~�>��>�>� ?�?�?�?�%?�(?Y5?�5?;7?�teamE_project/src/main/java/kr/ync/project/admin/domain/QnAVO.java package kr.ync.project.admin.domain; import java.util.Arrays; import java.util.Date; /** * QnAVO.java * * @Autors : 이용희 * @Date : 2018. 12. 14. * @Description * QnA VO 객체 * */ public class QnAVO { private Integer qna_num; private String qna_title; private String qna_contents; private String admin_id; private String qna_division; public String getQna_division() { return qna_division; } public void setQna_division(String qna_division) { this.qna_division = qna_division; } private String[] files; public String[] getFiles() { return files; } public void setFiles(String[] files) { this.files = files; } public Integer getqna_num() { return qna_num; } public void setqna_num(Integer qna_num) { this.qna_num = qna_num; } public String getqna_title() { return qna_title; } public void setqna_title(String qna_title) { this.qna_title = qna_title; } public String getqna_contents() { return qna_contents; } public void setqna_contents(String qna_contents) { this.qna_contents = qna_contents; } public String getAdmin_id() { return admin_id; } public void setAdmin_id(String admin_id) { this.admin_id = admin_id; } @Override public String toString() { return "QnAVO [qna_num=" + qna_num + ", qna_title=" + qna_title + ", qna_contents=" + qna_contents + ", " + "admin_id=" + admin_id + ", qna_division=" + qna_division + "]"; } }core/src/main/java/com/alibaba/alink/operator/batch/regression/GlmEvaluationBatchOp.java package com.alibaba.alink.operator.batch.regression; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.java.DataSet; import org.apache.flink.ml.api.misc.param.Params; import org.apache.flink.table.api.Table; import org.apache.flink.types.Row; import com.alibaba.alink.common.annotation.InputPorts; import com.alibaba.alink.common.annotation.NameCn; import com.alibaba.alink.common.annotation.OutputPorts; import com.alibaba.alink.common.annotation.ParamSelectColumnSpec; import com.alibaba.alink.common.annotation.PortSpec; import com.alibaba.alink.common.annotation.PortType; import com.alibaba.alink.common.annotation.TypeCollections; import com.alibaba.alink.common.utils.DataSetConversionUtil; import com.alibaba.alink.common.utils.JsonConverter; import com.alibaba.alink.operator.batch.BatchOperator; import com.alibaba.alink.operator.common.regression.glm.FamilyLink; import com.alibaba.alink.operator.common.regression.glm.GlmUtil; import com.alibaba.alink.operator.common.regression.glm.GlmUtil.GlmModelSummary; import com.alibaba.alink.params.regression.GlmTrainParams; /** * Generalized Linear Model. https://en.wikipedia.org/wiki/Generalized_linear_model. */ @InputPorts(values = { @PortSpec(PortType.MODEL), @PortSpec(PortType.DATA) }) @OutputPorts(values = { @PortSpec(value = PortType.DATA) }) @ParamSelectColumnSpec(name = "featureCols", allowedTypeCollections = TypeCollections.NUMERIC_TYPES) @ParamSelectColumnSpec(name = "labelCol", allowedTypeCollections = TypeCollections.NUMERIC_TYPES) @ParamSelectColumnSpec(name = "weightCol", allowedTypeCollections = TypeCollections.NUMERIC_TYPES) @NameCn("广义线性回归评估") public class GlmEvaluationBatchOp extends BatchOperator implements GlmTrainParams { private static final long serialVersionUID = 591674929382964676L; public GlmEvaluationBatchOp() { } public GlmEvaluationBatchOp(Params params) { super(params); } @Override public GlmEvaluationBatchOp linkFrom(BatchOperator ... inputs) { checkOpSize(2, inputs); BatchOperator model = inputs[0]; BatchOperator in = inputs[1]; String[] featureColNames = getFeatureCols(); String labelColName = getLabelCol(); String weightColName = getWeightCol(); String offsetColName = getOffsetCol(); Family familyName = getFamily(); Link linkName = getLink(); double variancePower = getVariancePower(); double linkPower = getLinkPower(); int numIter = getMaxIter(); double epsilon = getEpsilon(); boolean fitIntercept = getFitIntercept(); double regParam = getRegParam(); FamilyLink familyLink = new FamilyLink(familyName, variancePower, linkName, linkPower); int numFeature = featureColNames.length; DataSet data = GlmUtil.preProc(in, featureColNames, offsetColName, weightColName, labelColName); DataSet wlsModel = model.getDataSet().mapPartition( new GlmUtil.GlmModelToWlsModel()); DataSet residual = GlmUtil.residual(wlsModel, data, numFeature, familyLink); DataSet aggSummay = GlmUtil.aggSummary(residual, wlsModel, numFeature, familyLink, regParam, numIter, epsilon, fitIntercept); //residual String[] residualColNames = new String[numFeature + 4 + 4]; TypeInformation[] residualColTypes = new TypeInformation[numFeature + 4 + 4]; for (int i = 0; i < numFeature; i++) { residualColNames[i] = featureColNames[i]; residualColTypes[i] = Types.DOUBLE; } residualColNames[numFeature] = "label"; residualColTypes[numFeature] = Types.DOUBLE; residualColNames[numFeature + 1] = "weight"; residualColTypes[numFeature + 1] = Types.DOUBLE; residualColNames[numFeature + 2] = "offset"; residualColTypes[numFeature + 2] = Types.DOUBLE; residualColNames[numFeature + 3] = "pred"; residualColTypes[numFeature + 3] = Types.DOUBLE; residualColNames[numFeature + 4] = "residualdevianceResiduals"; residualColTypes[numFeature + 4] = Types.DOUBLE; residualColNames[numFeature + 5] = "pearsonResiduals"; residualColTypes[numFeature + 5] = Types.DOUBLE; residualColNames[numFeature + 6] = "workingResiduals"; residualColTypes[numFeature + 6] = Types.DOUBLE; residualColNames[numFeature + 7] = "responseResiduals"; residualColTypes[numFeature + 7] = Types.DOUBLE; this.setSideOutputTables(new Table[] { DataSetConversionUtil.toTable(getMLEnvironmentId(), residual, residualColNames, residualColTypes) }); //summary String[] summaryColNames = new String[1]; TypeInformation[] summaryColTypes = new TypeInformation[1]; summaryColNames[0] = "summary"; summaryColTypes[0] = Types.STRING; this.setOutput(aggSummay.map( new MapFunction () { @Override public Row map(GlmModelSummary value) throws Exception { return Row.of(JsonConverter.toJson(value)); } }), summaryColNames, summaryColTypes); return this; } } makhnnar/l2custom_acis package net.sf.l2j.gameserver.network.clientpackets; import net.sf.l2j.gameserver.data.cache.CrestCache; import net.sf.l2j.gameserver.data.cache.CrestCache.CrestType; import net.sf.l2j.gameserver.idfactory.IdFactory; import net.sf.l2j.gameserver.model.actor.Player; import net.sf.l2j.gameserver.model.pledge.Clan; import net.sf.l2j.gameserver.network.SystemMessageId; public final class RequestSetPledgeCrest extends L2GameClientPacket { private int _length; private byte[] _data; @Override protected void readImpl() { _length = readD(); if (_length > 256) return; _data = new byte[_length]; readB(_data); } @Override protected void runImpl() { if (_length < 0 || _length > 256) return; final Player player = getClient().getPlayer(); if (player == null) return; final Clan clan = player.getClan(); if (clan == null) return; if (clan.getDissolvingExpiryTime() > System.currentTimeMillis()) { player.sendPacket(SystemMessageId.CANNOT_SET_CREST_WHILE_DISSOLUTION_IN_PROGRESS); return; } if ((player.getClanPrivileges() & Clan.CP_CL_REGISTER_CREST) != Clan.CP_CL_REGISTER_CREST) { player.sendPacket(SystemMessageId.YOU_ARE_NOT_AUTHORIZED_TO_DO_THAT); return; } if (_length == 0 || _data.length == 0) { if (clan.getCrestId() != 0) { clan.changeClanCrest(0); player.sendPacket(SystemMessageId.CLAN_CREST_HAS_BEEN_DELETED); } } else { if (clan.getLevel() < 3) { player.sendPacket(SystemMessageId.CLAN_LVL_3_NEEDED_TO_SET_CREST); return; } final int crestId = IdFactory.getInstance().getNextId(); if (CrestCache.getInstance().saveCrest(CrestType.PLEDGE, crestId, _data)) { clan.changeClanCrest(crestId); player.sendPacket(SystemMessageId.CLAN_EMBLEM_WAS_SUCCESSFULLY_REGISTERED); } } } }package me.andrew28.morestorage.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * @author xXAndrew28Xx */ public class ReflectionUtil { private static final String NMS_PACKAGE_PREFIX_FORMAT = "net.minecraft.server.%s"; private static final String OBC_PACKAGE_PREFIX_FORMAT = "org.bukkit.craftbukkit.%s"; private static final String PACKAGE_SEPERATOR = "."; private String serverVersion; private String nmsPackagePrefix; private String obcPackagePrefix; public ReflectionUtil(String serverVersion) { this.serverVersion = serverVersion; this.nmsPackagePrefix = String.format(NMS_PACKAGE_PREFIX_FORMAT, serverVersion); this.obcPackagePrefix = String.format(OBC_PACKAGE_PREFIX_FORMAT, serverVersion); } public String getServerVersion() { return serverVersion; } public Class getNMSClass(String packageSuffix) throws ReflectiveOperationException { return Class.forName(nmsPackagePrefix + PACKAGE_SEPERATOR + packageSuffix); } public Class getOBCClass(String packageSuffix) throws ClassNotFoundException { return Class.forName(obcPackagePrefix + PACKAGE_SEPERATOR + packageSuffix); } public Method getMethod(Class clazz, String name, Class[] parameterTypes, MethodOption... methodOptions) throws NoSuchMethodException { Method method = clazz.getMethod(name, parameterTypes); for (MethodOption methodOption : methodOptions) { switch (methodOption) { case MAKE_ACCESSIBLE: method.setAccessible(true); break; } } return method; } public Field getField(Class clazz, String name, FieldOption... fieldOptions) throws ReflectiveOperationException { Field field = clazz.getField(name); for (FieldOption fieldOption : fieldOptions) { switch (fieldOption) { case MAKE_ACCESSIBLE: field.setAccessible(true); break; case MAKE_NON_FINAL: Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); break; } } return field; } public void setFieldValue(Object object, String name, Object value) throws ReflectiveOperationException { Field field = getField(object.getClass(), name, FieldOption.MAKE_ACCESSIBLE, FieldOption.MAKE_NON_FINAL); field.set(object, value); } public enum MethodOption { MAKE_ACCESSIBLE } public enum FieldOption { MAKE_ACCESSIBLE, MAKE_NON_FINAL } } package pokedex.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.sql.DataSource; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { private DataSource dataSource; @Autowired public SecurityConfig(DataSource dataSource) { this.dataSource = dataSource; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("SELECT email, password, 'TRUE' as enabled FROM RECIPE_USER WHERE email=?") .authoritiesByUsernameQuery("SELECT email, 'ROLE_USER' as authority FROM RECIPE_USER WHERE email=?") .passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests() // .anyRequest() // .authenticated() // .and() // .httpBasic(); http.csrf().disable(); http.headers().frameOptions().disable(); } } package com.liaobaikai.ngoxdb.core.dialect.impl; import com.liaobaikai.ngoxdb.bean.ColumnType; import com.liaobaikai.ngoxdb.bean.info.ColumnInfo; import com.liaobaikai.ngoxdb.core.constant.JdbcDataType; import com.liaobaikai.ngoxdb.core.dialect.BasicDatabaseDialect; import com.liaobaikai.ngoxdb.core.enums.func.DateTypeFunctionEnum; import com.liaobaikai.ngoxdb.core.enums.func.MathFunctionEnum; import com.liaobaikai.ngoxdb.core.enums.func.StringFunctionEnum; import com.liaobaikai.ngoxdb.core.func.impl.NoArgumentSQLFunction; import com.liaobaikai.ngoxdb.core.func.impl.StandardSQLFunction; import com.mysql.cj.MysqlType; import org.springframework.stereotype.Service; import java.util.Map; /** * MySQL数据库方言 * * @author baikai.liao * @Time 2021-03-13 01:05:18 */ @Service("MySQLDatabaseDialect") public class MySQLDatabaseDialect extends BasicDatabaseDialect { public MySQLDatabaseDialect() { // 注册类型 this.registerColumnType(JdbcDataType.LONGVARBINARY, "longblob"); this.registerColumnType(JdbcDataType.MONEY, "numeric"); this.registerColumnType(JdbcDataType.SMALLMONEY, "numeric"); this.registerColumnType(JdbcDataType.LONGVARCHAR, "text"); this.registerColumnType(JdbcDataType.LONGNVARCHAR, "text"); this.registerColumnType(JdbcDataType.NCLOB, "text"); this.registerColumnType(JdbcDataType.CLOB, "text"); this.registerColumnType(JdbcDataType.LONGTEXT, "longtext"); this.registerColumnType(JdbcDataType.MEDIUMTEXT, "mediumtext"); this.registerColumnType(JdbcDataType.LONGBLOB, "longblob"); this.registerColumnType(JdbcDataType.MEDIUMBLOB, "mediumblob"); this.registerColumnType(JdbcDataType.GUID, "char"); this.registerColumnType(JdbcDataType.TIME_WITH_TIMEZONE, "time"); this.registerColumnType(JdbcDataType.TIMESTAMP_WITH_TIMEZONE, "timestamp"); this.registerColumnType(JdbcDataType.TIMESTAMPTZ, "timestamp"); this.registerColumnType(JdbcDataType.TIMESTAMPLTZ, "timestamp"); this.registerColumnType(JdbcDataType.DATETIME, "datetime"); this.registerColumnType(JdbcDataType.DATETIMEOFFSET, "datetime"); this.registerColumnType(JdbcDataType.SMALLDATETIME, "datetime"); this.registerColumnType(JdbcDataType.ENUM, "enum"); this.registerColumnType(JdbcDataType.SET, "set"); this.registerColumnType(JdbcDataType.JSON, "json"); this.registerColumnType(JdbcDataType.YEAR, "year"); // 注册函数 // 数学函数 // https://dev.mysql.com/doc/refman/8.0/en/numeric-functions.html // 不支持: // CONV() // CRC32() // DIV // LOG2() this.registerFunction(MathFunctionEnum.abs, new StandardSQLFunction("abs")); this.registerFunction(MathFunctionEnum.ceil, new StandardSQLFunction("ceil")); this.registerFunction(MathFunctionEnum.ceiling, new StandardSQLFunction("ceiling")); this.registerFunction(MathFunctionEnum.degrees, new StandardSQLFunction("degrees")); this.registerFunction(MathFunctionEnum.exp, new StandardSQLFunction("exp")); this.registerFunction(MathFunctionEnum.floor, new StandardSQLFunction("floor")); this.registerFunction(MathFunctionEnum.ln, new StandardSQLFunction("ln")); this.registerFunction(MathFunctionEnum.log, new StandardSQLFunction("log")); this.registerFunction(MathFunctionEnum.log10, new StandardSQLFunction("log10")); this.registerFunction(MathFunctionEnum.mod, new StandardSQLFunction("mod")); this.registerFunction(MathFunctionEnum.pi, new StandardSQLFunction("pi")); this.registerFunction(MathFunctionEnum.power, new StandardSQLFunction("pow"), new StandardSQLFunction("power")); this.registerFunction(MathFunctionEnum.radians, new StandardSQLFunction("radians")); this.registerFunction(MathFunctionEnum.round, new StandardSQLFunction("round")); this.registerFunction(MathFunctionEnum.sign, new StandardSQLFunction("sign")); this.registerFunction(MathFunctionEnum.sqrt, new StandardSQLFunction("sqrt")); this.registerFunction(MathFunctionEnum.trunc, new StandardSQLFunction("truncate")); this.registerFunction(MathFunctionEnum.random, new StandardSQLFunction("rand")); this.registerFunction(MathFunctionEnum.acos, new StandardSQLFunction("acos")); this.registerFunction(MathFunctionEnum.asin, new StandardSQLFunction("asin")); this.registerFunction(MathFunctionEnum.atan, new StandardSQLFunction("atan")); this.registerFunction(MathFunctionEnum.atan2, new StandardSQLFunction("atan2")); this.registerFunction(MathFunctionEnum.cos, new StandardSQLFunction("cos")); this.registerFunction(MathFunctionEnum.cot, new StandardSQLFunction("cot")); this.registerFunction(MathFunctionEnum.sin, new StandardSQLFunction("sin")); this.registerFunction(MathFunctionEnum.tan, new StandardSQLFunction("tan")); // 日期 // https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html // 不支持 // ADDDATE() DATE_ADD('1998-01-02', INTERVAL 31 DAY); // ADDTIME() ADDTIME('1997-12-31 23:59:59.999999','1 1:1:1.000002'); // CONVERT_TZ() CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') // DATE() 字符串转时间 // DATE_ADD() // DATE_FORMAT() // DATE_SUB() = SUBDATE() // DAY() = DAYOFMONTH() // DAYNAME() // DAYOFWEEK() // DAYOFYEAR() // FROM_DAYS() // GET_FORMAT() // MICROSECOND() // MINUTE() // MONTH() // MONTHNAME() // PERIOD_ADD() // PERIOD_DIFF() // QUARTER() // SEC_TO_TIME() // SUBTIME() // TIME() // TIME_TO_SEC() // DATEDIFF() // TIMEDIFF() // TIMESTAMPADD() // TO_DAYS() // TO_SECONDS() // WEEK() // WEEKDAY() // WEEKOFYEAR() // YEAR() // YEARWEEK() this.registerFunction(DateTypeFunctionEnum.to_char, new StandardSQLFunction("time_format")); this.registerFunction(DateTypeFunctionEnum.to_date, new StandardSQLFunction("str_to_date")); this.registerFunction(DateTypeFunctionEnum.to_timestamp, new StandardSQLFunction("from_unixtime")); // 数字转timestamp this.registerFunction(DateTypeFunctionEnum.age, new StandardSQLFunction("timestampdiff")); this.registerFunction(DateTypeFunctionEnum.clock_timestamp, new NoArgumentSQLFunction("now", JdbcDataType.TIMESTAMP)); // Current date and time (changes during statement execution); this.registerFunction(DateTypeFunctionEnum.current_date, new NoArgumentSQLFunction("curdate", JdbcDataType.DATE), new NoArgumentSQLFunction("current_date", JdbcDataType.DATE), new NoArgumentSQLFunction("current_date", JdbcDataType.DATE, false)); this.registerFunction(DateTypeFunctionEnum.current_time, new NoArgumentSQLFunction("curtime", JdbcDataType.TIME), new NoArgumentSQLFunction("current_time", JdbcDataType.TIME), new NoArgumentSQLFunction("current_time", JdbcDataType.TIME, false)); this.registerFunction(DateTypeFunctionEnum.current_timestamp, new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP), new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP, false)); this.registerFunction(DateTypeFunctionEnum.extract, new StandardSQLFunction("extract")); this.registerFunction(DateTypeFunctionEnum.localtime, new NoArgumentSQLFunction("sysdate", JdbcDataType.TIMESTAMP)); // Synonym for NOW() this.registerFunction(DateTypeFunctionEnum.localtimestamp, new NoArgumentSQLFunction("sysdate", JdbcDataType.TIMESTAMP)); // Synonym for NOW() this.registerFunction(DateTypeFunctionEnum.make_date, new StandardSQLFunction("makedate")); // 存在差异。。。 this.registerFunction(DateTypeFunctionEnum.make_time, new StandardSQLFunction("maketime")); this.registerFunction(DateTypeFunctionEnum.make_timestamp, new StandardSQLFunction("timestamp")); this.registerFunction(DateTypeFunctionEnum.make_timestamptz, new StandardSQLFunction("timestamp")); // https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html this.registerFunction(DateTypeFunctionEnum.now, new NoArgumentSQLFunction("now", JdbcDataType.TIMESTAMP), new NoArgumentSQLFunction("localtime", JdbcDataType.TIME), new NoArgumentSQLFunction("localtime", JdbcDataType.TIME, false), new NoArgumentSQLFunction("localtimestamp", JdbcDataType.TIMESTAMP), new NoArgumentSQLFunction("localtimestamp", JdbcDataType.TIMESTAMP, false), new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP), new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP, false)); // Current date and time (start of current transaction); this.registerFunction(DateTypeFunctionEnum.statement_timestamp, new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP)); // Current date and time (start of current statement); this.registerFunction(DateTypeFunctionEnum.timeofday, new NoArgumentSQLFunction("utc_time", JdbcDataType.TIME)); // this.registerFunction(DateTypeFunctionEnum.transaction_timestamp, new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP)); // Current date and time (start of current transaction); this.registerFunction(DateTypeFunctionEnum.last_day, new StandardSQLFunction("last_day")); // Current date and time (start of current transaction); // 带时区 this.registerFunction(DateTypeFunctionEnum.datetime_offset, new NoArgumentSQLFunction("current_timestamp", JdbcDataType.TIMESTAMP)); // utc类型 this.registerFunction(DateTypeFunctionEnum.utc_datetime, new NoArgumentSQLFunction("utc_timestamp", JdbcDataType.TIMESTAMP)); this.registerFunction(DateTypeFunctionEnum.utc_date, new NoArgumentSQLFunction("utc_date", JdbcDataType.DATE)); this.registerFunction(DateTypeFunctionEnum.utc_time, new NoArgumentSQLFunction("utc_time", JdbcDataType.TIME)); // 字符串 // https://dev.mysql.com/doc/refman/8.0/en/string-functions.html // 不支持 // BIN() // ELT() = FIELD() -> FIND_IN_SET() // EXPORT_SET() // FIND_IN_SET() // FORMAT() // FROM_BASE64() // INSERT() // LIKE // LOAD_FILE() // LOCATE() // INSTR替换 // MAKE_SET() // MATCH // // NOT LIKE // NOT REGEXP // OCT() // ORD() // QUOTE() // REGEXP // REGEXP_INSTR() // REGEXP_LIKE() // REGEXP_REPLACE() // REGEXP_SUBSTR() // RLIKE // SOUNDEX() // SOUNDS LIKE // SPACE() // STRCMP() // SUBSTRING_INDEX() // TO_BASE64() ----> encode('123', 'base64'); // UNHEX() -- from Hex // WEIGHT_STRING() this.registerFunction(StringFunctionEnum.bit_length, new StandardSQLFunction("bit_length")); this.registerFunction(StringFunctionEnum.char_length, new StandardSQLFunction("char_length")); this.registerFunction(StringFunctionEnum.character_length, new StandardSQLFunction("character_length")); this.registerFunction(StringFunctionEnum.lower, new StandardSQLFunction("lcase"), new StandardSQLFunction("lower")); this.registerFunction(StringFunctionEnum.octet_length, new StandardSQLFunction("octet_length")); this.registerFunction(StringFunctionEnum.position, new StandardSQLFunction("position")); this.registerFunction(StringFunctionEnum.substring, new StandardSQLFunction("substring"), new StandardSQLFunction("mid")); // MID(str,pos,len) is a synonym for SUBSTRING(str,pos,len). this.registerFunction(StringFunctionEnum.trim, new StandardSQLFunction("trim")); this.registerFunction(StringFunctionEnum.upper, new StandardSQLFunction("ucase"), new StandardSQLFunction("upper")); this.registerFunction(StringFunctionEnum.ascii, new StandardSQLFunction("ascii")); this.registerFunction(StringFunctionEnum.chr, new StandardSQLFunction("char")); this.registerFunction(StringFunctionEnum.concat, new StandardSQLFunction("concat")); this.registerFunction(StringFunctionEnum.concat_ws, new StandardSQLFunction("concat_ws")); this.registerFunction(StringFunctionEnum.left, new StandardSQLFunction("left")); this.registerFunction(StringFunctionEnum.length, new StandardSQLFunction("length")); this.registerFunction(StringFunctionEnum.lpad, new StandardSQLFunction("lpad")); this.registerFunction(StringFunctionEnum.ltrim, new StandardSQLFunction("ltrim")); this.registerFunction(StringFunctionEnum.md5, new StandardSQLFunction("md5")); this.registerFunction(StringFunctionEnum.repeat, new StandardSQLFunction("repeat")); this.registerFunction(StringFunctionEnum.replace, new StandardSQLFunction("replace")); this.registerFunction(StringFunctionEnum.reverse, new StandardSQLFunction("reverse")); this.registerFunction(StringFunctionEnum.right, new StandardSQLFunction("right")); this.registerFunction(StringFunctionEnum.rpad, new StandardSQLFunction("rpad")); this.registerFunction(StringFunctionEnum.rtrim, new StandardSQLFunction("rtrim")); this.registerFunction(StringFunctionEnum.strpos, new StandardSQLFunction("instr")); this.registerFunction(StringFunctionEnum.substr, new StandardSQLFunction("substr")); this.registerFunction(StringFunctionEnum.to_hex, new StandardSQLFunction("hex")); // bytes this.registerFunction(StringFunctionEnum.uuid, new NoArgumentSQLFunction("uuid", JdbcDataType.VARCHAR)); } @Override public char openQuote() { return '`'; } @Override public char closeQuote() { return '`'; } @Override public boolean supportsCommentOnBuildTable() { return true; } @Override public boolean supportsCollationOnBuildTable() { return true; } @Override public String getCollationString(String collationName) { return "COLLATE " + collationName; } @Override public boolean supportsCharsetOnBuildTable() { return true; } @Override public String getCharsetString(String charsetName) { return "CHARACTER SET " + charsetName; } @Override public String getTableCommentString(String tableName, String tableComment) { return String.format(" comment='%s' ", tableComment); } @Override public String getColumnCommentString(String tableName, String columnName, String columnComment) { return String.format(" comment '%s' ", columnComment); } @Override public boolean supportsDropForeignKey() { return true; } @Override public boolean supportsUnsignedDecimal() { return true; } @Override public String getDropForeignKeyString() { return " drop foreign key "; } @Override public boolean supportsPartitionBy() { return true; } @Override public boolean supportsIfExistsBeforeTableName() { return true; } @Override public boolean supportsIdentityColumns() { return true; } @Override public boolean doesIdentityMustPrimaryKey() { return true; } @Override public String getIdentityColumnString() { return "auto_increment"; } @Override public boolean supportsLimit() { return true; } @Override public boolean supportsTruncateTable() { return true; } @Override public int getMaximumPrecision(int jdbcDataType) { switch (jdbcDataType) { case JdbcDataType.NUMERIC: case JdbcDataType.DECIMAL: return MysqlType.DECIMAL.getPrecision().intValue(); case JdbcDataType.CHAR: case JdbcDataType.NCHAR: return MysqlType.CHAR.getPrecision().intValue(); case JdbcDataType.VARCHAR: case JdbcDataType.NVARCHAR: return MysqlType.VARCHAR.getPrecision().intValue(); case JdbcDataType.BIT: return 1; case JdbcDataType.BINARY: return MysqlType.BINARY.getPrecision().intValue(); case JdbcDataType.VARBINARY: return MysqlType.VARBINARY.getPrecision().intValue(); default: return 0; } } @Override public int getMinimumPrecision(int jdbcDataType) { switch (jdbcDataType) { case JdbcDataType.NUMERIC: case JdbcDataType.DECIMAL: case JdbcDataType.CHAR: case JdbcDataType.NCHAR: case JdbcDataType.VARCHAR: case JdbcDataType.NVARCHAR: case JdbcDataType.BIT: case JdbcDataType.BINARY: return 1; default: return 0; } } @Override public int getMaximumScale(int jdbcDataType) { switch (jdbcDataType) { case JdbcDataType.NUMERIC: case JdbcDataType.DECIMAL: return 38; default: return 0; } } @Override public int getMinimumScale(int jdbcDataType) { switch (jdbcDataType) { case JdbcDataType.CHAR: case JdbcDataType.NCHAR: case JdbcDataType.VARCHAR: case JdbcDataType.NVARCHAR: case JdbcDataType.BIT: case JdbcDataType.BINARY: return 1; default: return 0; } } @Override public int getRightDataTypeForVarchar(int columnSize, boolean[] doesIgnoredLength) { int maximumPrecision = this.getMaximumPrecision(JdbcDataType.VARCHAR); if (columnSize > maximumPrecision) { // > 65535 doesIgnoredLength[0] = true; if (columnSize > MysqlType.MEDIUMTEXT.getPrecision()) { // > 16777215 // (16777215, 4294967295] return JdbcDataType.LONGTEXT; } else if (columnSize > MysqlType.TEXT.getPrecision()) { // > 65535 return JdbcDataType.MEDIUMTEXT; } } return JdbcDataType.VARCHAR; } @Override public int getRightDataTypeForNVarchar(int columnSize, boolean[] doesIgnoredLength) { return this.getRightDataTypeForVarchar(columnSize, doesIgnoredLength); } @Override public int getRightDataTypeForChar(int columnSize, boolean[] doesIgnoredLength) { int maximumPrecision = this.getMaximumPrecision(JdbcDataType.CHAR); if (columnSize > maximumPrecision) { // > 255 return this.getRightDataTypeForVarchar(columnSize, doesIgnoredLength); } // <= 255 return JdbcDataType.CHAR; } @Override public int getRightDataTypeForNChar(int columnSize, boolean[] doesIgnoredLength) { return this.getRightDataTypeForChar(columnSize, doesIgnoredLength); } @Override public int getRightDataTypeForBinary(int columnSize, boolean[] doesIgnoredLength) { int maximumPrecision = this.getMaximumPrecision(JdbcDataType.BINARY); if (columnSize > maximumPrecision) { // > 255 return this.getRightDataTypeForVarBinary(columnSize, doesIgnoredLength); } return JdbcDataType.BINARY; } @Override public int getRightDataTypeForVarBinary(int columnSize, boolean[] doesIgnoredLength) { int maximumPrecision = this.getMaximumPrecision(JdbcDataType.VARBINARY); if (columnSize > maximumPrecision) { // > 65535 doesIgnoredLength[0] = true; if (columnSize > MysqlType.MEDIUMBLOB.getPrecision()) { // > 16777215 // (16777215, 4294967295] return JdbcDataType.LONGBLOB; } else if (columnSize > MysqlType.BLOB.getPrecision()) { // > 65535 return JdbcDataType.MEDIUMBLOB; } } return JdbcDataType.VARBINARY; } @Override public boolean supportsDecimalToInt() { return true; } @Override public boolean supportsYearToDate() { return false; } @Override public boolean supportsJoin() { return true; } @Override public Object getSqlGenericType(Object src) { return src; } @Override public boolean supportsFullTextIndex() { return true; } @Override public String getFullTextIndexString() { return "fulltext"; } @Override public boolean supportsSpatialIndex() { return true; } @Override public void registerColumnTypeForYear(ColumnType ct, ColumnInfo ci) { ct.setTypeName(ci.getColumnType()); } @Override public void registerColumnTypeForJson(ColumnType ct, ColumnInfo ci) { ct.setTypeName(ci.getColumnType()); } @Override public void registerColumnTypeForSet(ColumnType ct, ColumnInfo ci) { ct.setTypeName(ci.getColumnType()); } @Override public void registerColumnTypeForEnum(ColumnType ct, ColumnInfo ci) { ct.setTypeName(ci.getColumnType()); } @Override public void registerColumnTypeForFixedChar(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForFixedChar(ct, ci); } @Override public void registerColumnTypeForBinaryDouble(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBinaryDouble(ct, ci); } @Override public void registerColumnTypeForBinaryFloat(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBinaryFloat(ct, ci); } @Override public void registerColumnTypeForPlsqlIndexTable(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForPlsqlIndexTable(ct, ci); } @Override public void registerColumnTypeForOpaque(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForOpaque(ct, ci); } @Override public void registerColumnTypeForBfile(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBfile(ct, ci); } @Override public void registerColumnTypeForCursor(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForCursor(ct, ci); } @Override public void registerColumnTypeForIntervalDS(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForIntervalDS(ct, ci); } @Override public void registerColumnTypeForIntervalYM(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForIntervalYM(ct, ci); } @Override public void registerColumnTypeForTimestampLTZ(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTimestampLTZ(ct, ci); } @Override public void registerColumnTypeForTimestampTZ(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTimestampTZ(ct, ci); } @Override public void registerColumnTypeForJavaStruct(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForJavaStruct(ct, ci); } @Override public void registerColumnTypeForGeography(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForGeography(ct, ci); } @Override public void registerColumnTypeForGeometry(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForGeometry(ct, ci); } @Override public void registerColumnTypeForSqlVariant(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForSqlVariant(ct, ci); } @Override public void registerColumnTypeForGuid(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForGuid(ct, ci); } @Override public void registerColumnTypeForSmallMoney(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForSmallMoney(ct, ci); } @Override public void registerColumnTypeForMoney(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForMoney(ct, ci); } @Override public void registerColumnTypeForSmallDateTime(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForSmallDateTime(ct, ci); } @Override public void registerColumnTypeForDateTime(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForDateTime(ct, ci); } @Override public void registerColumnTypeForStructured(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForStructured(ct, ci); } @Override public void registerColumnTypeForDateTimeOffset(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForDateTimeOffset(ct, ci); } @Override public void registerColumnTypeForTimestampZ(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTimestampZ(ct, ci); } @Override public void registerColumnTypeForTimeZ(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTimeZ(ct, ci); } @Override public void registerColumnTypeForRefCursor(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForRefCursor(ct, ci); } @Override public void registerColumnTypeForSqlXml(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForSqlXml(ct, ci); } @Override public void registerColumnTypeForNClob(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForNClob(ct, ci); } @Override public void registerColumnTypeForLongNVarchar(ColumnType ct, ColumnInfo ci) { this.registerColumnTypeForLongVarchar(ct, ci); } @Override public void registerColumnTypeForNVarchar(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForNVarchar(ct, ci); } @Override public void registerColumnTypeForNChar(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForNChar(ct, ci); } @Override public void registerColumnTypeForRowId(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForRowId(ct, ci); } @Override public void registerColumnTypeForBoolean(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBoolean(ct, ci); } @Override public void registerColumnTypeForDataLink(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForDataLink(ct, ci); } @Override public void registerColumnTypeForRef(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForRef(ct, ci); } @Override public void registerColumnTypeForClob(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForClob(ct, ci); } @Override public void registerColumnTypeForBlob(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBlob(ct, ci); } @Override public void registerColumnTypeForArray(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForArray(ct, ci); } @Override public void registerColumnTypeForStruct(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForStruct(ct, ci); } @Override public void registerColumnTypeForDistinct(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForDistinct(ct, ci); } @Override public void registerColumnTypeForJavaObject(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForJavaObject(ct, ci); } @Override public void registerColumnTypeForOther(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForOther(ct, ci); } @Override public void registerColumnTypeForNull(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForNull(ct, ci); } @Override public void registerColumnTypeForLongVarbinary(ColumnType ct, ColumnInfo ci) { if (ci.getColumnSize() > MysqlType.MEDIUMBLOB.getPrecision()) { // > 16777215 // (16777215, 4294967295] ct.setJdbcDataType(JdbcDataType.LONGBLOB); } else if (ci.getColumnSize() > MysqlType.BLOB.getPrecision()) { // > 65535 ct.setJdbcDataType(JdbcDataType.MEDIUMBLOB); } else { ct.setJdbcDataType(JdbcDataType.BLOB); } } @Override public void registerColumnTypeForVarbinary(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForVarbinary(ct, ci); } @Override public void registerColumnTypeForBinary(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBinary(ct, ci); } @Override public void registerColumnTypeForTimestamp(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTimestamp(ct, ci); } @Override public void registerColumnTypeForTime(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTime(ct, ci); } @Override public void registerColumnTypeForDate(ColumnType ct, ColumnInfo ci) { if (ci.getDataType() == JdbcDataType.YEAR) { // 年份 ct.setTypeName(ci.getColumnType()); return; } super.registerColumnTypeForDate(ct, ci); } @Override public void registerColumnTypeForLongVarchar(ColumnType ct, ColumnInfo ci) { if (ci.getDataType() == JdbcDataType.JSON) { ct.setColumnName(ci.getColumnType()); } else if (ci.getColumnSize() > MysqlType.MEDIUMTEXT.getPrecision()) { // > 16777215 // (16777215, 4294967295] ct.setJdbcDataType(JdbcDataType.LONGTEXT); } else if (ci.getColumnSize() > MysqlType.TEXT.getPrecision()) { // > 65535 ct.setJdbcDataType(JdbcDataType.MEDIUMTEXT); } else { ct.setTypeName(MysqlType.TEXT.getName()); } } @Override public void registerColumnTypeForVarchar(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForVarchar(ct, ci); } @Override public void registerColumnTypeForChar(ColumnType ct, ColumnInfo ci) { switch (ci.getDataType()) { case JdbcDataType.ENUM: case JdbcDataType.SET: ct.setTypeName(ci.getColumnType()); break; case JdbcDataType.CHAR: super.registerColumnTypeForChar(ct, ci); } } @Override public void registerColumnTypeForDecimal(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForDecimal(ct, ci); } @Override public void registerColumnTypeForNumeric(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForNumeric(ct, ci); } @Override public void registerColumnTypeForDouble(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForDouble(ct, ci); } @Override public void registerColumnTypeForReal(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForReal(ct, ci); } @Override public void registerColumnTypeForFloat(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForFloat(ct, ci); } @Override public void registerColumnTypeForBigInt(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBigInt(ct, ci); } @Override public void registerColumnTypeForInt(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForInt(ct, ci); } @Override public void registerColumnTypeForSmallint(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForSmallint(ct, ci); } @Override public void registerColumnTypeForTinyint(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForTinyint(ct, ci); } @Override public void registerColumnTypeForBit(ColumnType ct, ColumnInfo ci) { super.registerColumnTypeForBit(ct, ci); } @Override protected void handleBuildInsertPreparedSql(final ColumnInfo c, String finalColumnName, final StringBuilder sqlBuilder, final StringBuilder sqlPlaceHolderBuilder) { sqlBuilder.append(this.toLookupName(finalColumnName)).append(","); if (JdbcDataType.YEAR == c.getDataType()) { // 年份 sqlPlaceHolderBuilder.append("year(?),"); } else { sqlPlaceHolderBuilder.append("?,"); } } } package com.github.dactiv.showcase.service.account; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.crypto.hash.SimpleHash; import org.hibernate.criterion.Order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.github.dactiv.orm.core.Page; import com.github.dactiv.orm.core.PageRequest; import com.github.dactiv.orm.core.PropertyFilter; import com.github.dactiv.orm.core.PropertyFilters; import com.github.dactiv.orm.core.RestrictionNames; import com.github.dactiv.showcase.common.enumeration.entity.GroupType; import com.github.dactiv.showcase.common.enumeration.entity.ResourceType; import com.github.dactiv.showcase.dao.account.GroupDao; import com.github.dactiv.showcase.dao.account.ResourceDao; import com.github.dactiv.showcase.dao.account.UserDao; import com.github.dactiv.showcase.entity.account.Group; import com.github.dactiv.showcase.entity.account.Resource; import com.github.dactiv.showcase.entity.account.User; import com.github.dactiv.showcase.service.ServiceException; /** * 账户管理业务逻辑 * * @author maurice * */ @Service @Transactional public class AccountManager { //用户数据访问 @Autowired private UserDao userDao; //资源数据访问 @Autowired private ResourceDao resourceDao; //组数据访问 @Autowired private GroupDao groupDao; //------------------------------用户管理-----------------------------------// /** * 更新当前用户密码 * * @param oldPassword * @param newPassword * */ //当修改成功后将shiro的认证缓存也更新清除 @CacheEvict(value="shiroAuthenticationCache",key="#entity.getUsername()") public void updateUserPassword(User entity, String newPassword) { String temp = new SimpleHash("MD5",newPassword).toHex(); userDao.updatePassword(entity.getId(),temp); entity.setPassword(temp); } /** * 通过id获取用户实体 * @param id 用户id */ public User getUser(String id) { return userDao.load(id); } /** * 通过属性过滤器查询用户分页 * * @param request 分页参数 * @param filters 属性过滤器集合 * * @return {@link Page} */ public Page searchUserPage(PageRequest request,List filters) { return userDao.findPage(request, filters); } /** * 新增用户 * * @param entity 用户实体 */ public void insertUser(User entity) { if (!isUsernameUnique(entity.getUsername())) { throw new ServiceException("登录帐号已存在"); } String password = new SimpleHash("MD5", entity.getPassword()).toHex(); entity.setPassword(password); userDao.insert(entity); } /** * 更新用户 * * @param entity 用户实体 */ //当修改成功后将shiro的认证缓存也更新清除 @CacheEvict(value="shiroAuthenticationCache",key="#entity.getUsername()") public void updateUser(User entity) { userDao.update(entity); } /** * 是否唯一的登录帐号,如果是返回true,否则返回false. * * @param username 登录帐号 * * @return boolean */ public boolean isUsernameUnique(String username) { return getUserByUsername(username) == null; } /** * 删除用户 * * @param ids 用户id集合 */ public void deleteUsers(List ids) { for (String id : ids) { deleteUser(userDao.get(id)); } } /** * 通过用户实体删除用户 * * @param entity 用户实体 */ //当删除后将shiro的认证缓存也删除 @CacheEvict(value="shiroAuthenticationCache",key="#entity.getUsername()") public void deleteUser(User entity) { userDao.delete(entity); } /** * 通过登录帐号获取用户实体 * * @param username 登录帐号 * * @return {@link User} */ public User getUserByUsername(String username) { return userDao.findUniqueByProperty("username", username); } //------------------------------资源管理-----------------------------------// /** * 通过id获取资源实体 * * @param id 资源id * * @return {@link Resource} */ public Resource getResource(String id) { return resourceDao.load(id); } /** * 通过id集合获取资源资源 * * @param ids 资源集合 * * @return List */ public List getResources(List ids) { return resourceDao.get(ids); } /** * 获取所有资源集合,但该集合已经将数据并合成树形 * * @return List */ @Transactional(readOnly=true) public List getMergeResources() { List result = resourceDao.getAll(Order.asc("sort")); return mergeResourcesToParent(result, null); } /** * 保存资源实体 * * @param entity 资源实体 */ public void saveResource(Resource entity) { //如果sort等于null值,设置一个最新的值给entity if(entity.getSort() == null) { entity.setSort(resourceDao.entityCount() + 1); } resourceDao.save(entity); } /** * 通过资源实体集合删除资源 * * @param ids 资源id集合 */ public void deleteResources(List ids) { resourceDao.deleteAll(ids); } /** * 获取所有资源 * * @param ignoreIdValue 要忽略的id属性值 * * @return List */ public List getResources(String... ignoreIdValue) { List filters = new ArrayList(); if (ArrayUtils.isNotEmpty(ignoreIdValue)) { filters.add(PropertyFilters.get("NES_id", StringUtils.join(ignoreIdValue,","))); } return resourceDao.findByPropertyFilter(filters, Order.asc("sort")); } /** * 获取资源实体的总记录数 * * @return long */ public long getResourceCount() { return resourceDao.entityCount(); } /** * 通过用户id获取该用户下的所有资源 * * @param userId 用户id * * @return List */ public List getUserResources(String userId) { return resourceDao.getUserResources(userId); } /** * 并合子类资源到父类中,返回一个新的资源集合 * * @param list 资源集合 * @param resourceType 不需要并合的资源类型 */ @Transactional(readOnly=true) public List mergeResourcesToParent(List list,ResourceType ignoreType) { return resourceDao.mergeToParent(list,ignoreType); } //------------------------------组管理-----------------------------------// /** * 通过id获取组实体 * * @param id 组id * * @return {@link Group} */ public Group getGroup(String id) { return groupDao.load(id); } /** * 通过组id,获取组集合 * * @param ids id集合 * * @return List */ public List getGroups(List ids) { return groupDao.get(ids); } /** * 保存组实体 * * @param entity 组实体 */ @CacheEvict(value="shiroAuthorizationCache",allEntries=true) public void saveGroup(Group entity) { groupDao.save(entity); } /** * 删除组实体 * * @param ids 组id集合 */ @CacheEvict(value="shiroAuthorizationCache",allEntries=true) public void deleteGroups(List ids) { groupDao.deleteAll(ids); } /** * 根据组类型获取所有组信息 * * @param groupType 组类型 * @param ignoreIdValue 要忽略的id属性值 * * @return List */ public List getGroups(GroupType groupType,String... ignoreIdValue) { List filters = new ArrayList(); if (ArrayUtils.isNotEmpty(ignoreIdValue)) { filters.add(PropertyFilters.get("NES_id", StringUtils.join(ignoreIdValue,","))); } filters.add(PropertyFilters.get("EQS_type", groupType.getValue())); return groupDao.findByPropertyFilter(filters); } /** * 根据组类型获取所有组集合,但该集合已经将数据并合成树形 * * @param type 组类型 * * @return List */ public List getMergeGroups(GroupType type) { List result = groupDao.findByProperty("type", type.getValue(),RestrictionNames.EQ,Order.asc("id")); return groupDao.mergeToParent(result); } } 100-1000 package com.yugy.v2ex.daily.adapter; import android.support.v13.app.FragmentStatePagerAdapter; import android.app.Fragment; import android.app.FragmentManager; import android.support.v4.view.PagerAdapter; import android.view.ViewGroup; import com.yugy.v2ex.daily.fragment.PhotoViewFragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by wuyexiong on 13-7-27. */ public class PhotoViewerPagerAdapter extends FragmentStatePagerAdapter { protected final HashMap mObjectRowMap = new HashMap(); private ArrayList mList = new ArrayList(); public PhotoViewerPagerAdapter(FragmentManager fm) { super(fm); } @Override public Object instantiateItem(ViewGroup container, int position) { final Object obj = super.instantiateItem(container, position); if (obj != null) { mObjectRowMap.put(obj, position); } return obj; } @Override public void destroyItem(ViewGroup container, int position, Object object) { mObjectRowMap.remove(object); super.destroyItem(container, position, object); } @Override public Fragment getItem(int position) { return PhotoViewFragment.newInstance(mList.get(position), position); } @Override public int getItemPosition(Object object) { final Integer rowId = mObjectRowMap.get(object); if (rowId == null) { return PagerAdapter.POSITION_NONE; } else { return rowId; } } @Override public int getCount() { if (mList != null) { return mList.size(); } else { return 0; } } public ArrayList getData() { return mList; } public void setData(List datas) { mList.clear(); mList.addAll(datas); notifyDataSetChanged(); } } package styx.data.jdbc; import java.util.Arrays; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import styx.data.db.GenericDatabaseTest; @RunWith(Parameterized.class) public class JdbcDatabaseTest extends GenericDatabaseTest { public JdbcDatabaseTest(String url) { super(new JdbcDatabase(url)); } @Parameters(name="{0}") public static Iterable getParameters() { return Arrays.asList( new Object[] { "jdbc:h2:mem:" }, new Object[] { "jdbc:derby:memory:test;create=true" }, new Object[] { "jdbc:sqlite::memory:" }, new Object[] { "jdbc:mysql://localhost/styx_test?user=root&password=&useSSL=false" }, new Object[] { "jdbc:postgresql://localhost/styx_test?user=postgres&password=" }); } } package com.lframework.xingyun.api.bo.sale; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.lframework.common.constants.StringPool; import com.lframework.common.utils.CollectionUtil; import com.lframework.common.utils.StringUtil; import com.lframework.starter.mybatis.service.IUserService; import com.lframework.starter.web.bo.BaseBo; import com.lframework.starter.web.utils.ApplicationUtil; import com.lframework.xingyun.basedata.dto.product.info.SaleProductDto; import com.lframework.xingyun.basedata.service.customer.ICustomerService; import com.lframework.xingyun.basedata.service.product.IProductService; import com.lframework.xingyun.basedata.service.storecenter.IStoreCenterService; import com.lframework.xingyun.sc.dto.sale.SaleOrderFullDto; import com.lframework.xingyun.sc.entity.ProductStock; import com.lframework.xingyun.sc.service.stock.IProductStockService; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @Data @EqualsAndHashCode(callSuper = true) public class GetSaleOrderBo extends BaseBo { /** * ID */ @ApiModelProperty("ID") private String id; /** * 单号 */ @ApiModelProperty("单号") private String code; /** * 仓库ID */ @ApiModelProperty("仓库ID") private String scId; /** * 仓库名称 */ @ApiModelProperty("仓库名称") private String scName; /** * 客户ID */ @ApiModelProperty("客户ID") private String customerId; /** * 客户名称 */ @ApiModelProperty("客户名称") private String customerName; /** * 销售员ID */ @ApiModelProperty("销售员ID") private String salerId; /** * 销售员姓名 */ @ApiModelProperty("销售员姓名") private String salerName; /** * 销售数量 */ @ApiModelProperty("销售数量") private Integer totalNum; /** * 赠品数量 */ @ApiModelProperty("赠品数量") private Integer giftNum; /** * 销售金额 */ @ApiModelProperty("销售金额") private BigDecimal totalAmount; /** * 备注 */ @ApiModelProperty("备注") private String description; /** * 创建人 */ @ApiModelProperty("创建人") private String createBy; /** * 创建时间 */ @ApiModelProperty("创建时间") @JsonFormat(pattern = StringPool.DATE_TIME_PATTERN) private LocalDateTime createTime; /** * 审核人 */ @ApiModelProperty("审核人") private String approveBy; /** * 审核时间 */ @ApiModelProperty("审核时间") @JsonFormat(pattern = StringPool.DATE_TIME_PATTERN) private LocalDateTime approveTime; /** * 状态 */ @ApiModelProperty("状态") private Integer status; /** * 拒绝原因 */ @ApiModelProperty("拒绝原因") private String refuseReason; /** * 订单明细 */ @ApiModelProperty("订单明细") private List details; public GetSaleOrderBo() { } public GetSaleOrderBo(SaleOrderFullDto dto) { super(dto); } @Override public BaseBo convert(SaleOrderFullDto dto) { return super.convert(dto, GetSaleOrderBo::getStatus, GetSaleOrderBo::getDetails); } @Override protected void afterInit(SaleOrderFullDto dto) { IStoreCenterService storeCenterService = ApplicationUtil.getBean(IStoreCenterService.class); this.scName = storeCenterService.findById(dto.getScId()).getName(); ICustomerService customerService = ApplicationUtil.getBean(ICustomerService.class); this.customerName = customerService.findById(dto.getCustomerId()).getName(); IUserService userService = ApplicationUtil.getBean(IUserService.class); if (!StringUtil.isBlank(dto.getSalerId())) { this.salerName = userService.findById(dto.getSalerId()).getName(); } this.createBy = userService.findById(dto.getCreateBy()).getName(); if (!StringUtil.isBlank(dto.getApproveBy())) { this.approveBy = userService.findById(dto.getApproveBy()).getName(); } this.status = dto.getStatus().getCode(); this.totalNum = dto.getTotalNum(); this.giftNum = dto.getTotalGiftNum(); this.totalAmount = dto.getTotalAmount(); if (!CollectionUtil.isEmpty(dto.getDetails())) { this.details = dto.getDetails().stream().map(t -> new OrderDetailBo(this.getScId(), t)) .collect(Collectors.toList()); } } @Data @EqualsAndHashCode(callSuper = true) public static class OrderDetailBo extends BaseBo { /** * 明细ID */ @ApiModelProperty("明细ID") private String id; /** * 商品ID */ @ApiModelProperty("商品ID") private String productId; /** * 商品编号 */ @ApiModelProperty("商品编号") private String productCode; /** * 商品名称 */ @ApiModelProperty("商品名称") private String productName; /** * SKU编号 */ @ApiModelProperty("SKU编号") private String skuCode; /** * 外部编号 */ @ApiModelProperty("外部编号") private String externalCode; /** * 单位 */ @ApiModelProperty("单位") private String unit; /** * 规格 */ @ApiModelProperty("规格") private String spec; /** * 类目名称 */ @ApiModelProperty("类目名称") private String categoryName; /** * 品牌名称 */ @ApiModelProperty("品牌名称") private String brandName; /** * 销售属性1 */ @ApiModelProperty("销售属性1") private String salePropItemName1; /** * 销售属性2 */ @ApiModelProperty("销售属性2") private String salePropItemName2; /** * 销售数量 */ @ApiModelProperty("销售数量") private Integer orderNum; /** * 原价 */ @ApiModelProperty("原价") private BigDecimal oriPrice; /** * 现价 */ @ApiModelProperty("现价") private BigDecimal taxPrice; /** * 折扣(%) */ @ApiModelProperty("折扣(%)") private BigDecimal discountRate; /** * 是否赠品 */ @ApiModelProperty("是否赠品") private Boolean isGift; /** * 税率 */ @ApiModelProperty("税率") private BigDecimal taxRate; /** * 备注 */ @ApiModelProperty("备注") private String description; /** * 仓库ID */ @ApiModelProperty(value = "仓库ID", hidden = true) @JsonIgnore private String scId; /** * 库存数量 */ @ApiModelProperty("库存数量") private Integer stockNum; public OrderDetailBo(String scId, SaleOrderFullDto.OrderDetailDto dto) { this.scId = scId; if (dto != null) { this.convert(dto); this.afterInit(dto); } } @Override public BaseBo convert(SaleOrderFullDto.OrderDetailDto dto) { return super.convert(dto); } @Override protected void afterInit(SaleOrderFullDto.OrderDetailDto dto) { this.orderNum = dto.getOrderNum(); this.oriPrice = dto.getOriPrice(); this.taxPrice = dto.getTaxPrice(); this.discountRate = dto.getDiscountRate(); IProductService productService = ApplicationUtil.getBean(IProductService.class); SaleProductDto product = productService.getSaleById(dto.getProductId()); this.productCode = product.getCode(); this.productName = product.getName(); this.skuCode = product.getSkuCode(); this.externalCode = product.getExternalCode(); this.unit = product.getUnit(); this.spec = product.getSpec(); this.categoryName = product.getCategoryName(); this.brandName = product.getBrandName(); if (!CollectionUtil.isEmpty(product.getSaleProps())) { if (product.getSaleProps().size() > 0) { this.salePropItemName1 = product.getSaleProps().get(0).getName(); } if (product.getSaleProps().size() > 1) { this.salePropItemName2 = product.getSaleProps().get(1).getName(); } } IProductStockService productStockService = ApplicationUtil.getBean(IProductStockService.class); ProductStock productStock = productStockService.getByProductIdAndScId(this.getProductId(), this.getScId()); this.stockNum = productStock == null ? 0 : productStock.getStockNum(); } } } /** * Copyright (c) 2002-2015 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * 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. */ package org.neo4j.driver.v1; import java.net.URI; import org.neo4j.driver.v1.internal.StandardSession; import org.neo4j.driver.v1.internal.pool.StandardConnectionPool; import org.neo4j.driver.v1.internal.spi.ConnectionPool; /** * A Neo4j database driver, through which you can create {@link Session sessions} to run statements against the database. *

* An example: *

 * {@code
 * // Create a driver with default configuration
 * Driver driver = GraphDatabase.driver( "bolt://localhost:7687" );
 *
 * // Establish a session
 * Session session = driver.session();
 *
 * // Running a simple statement can be done like this
 * session.run( "CREATE (n {name:'Bob'})" );
 *
 * // Or, run multiple statements together in an atomic transaction:
 * try( Transaction tx = session.beginTransaction() )
 * {
 *     tx.run( "CREATE (n {name:'Alice'})" );
 *     tx.run( "CREATE (n {name:'Tina'})" );
 *     tx.success();
 * }
 *
 * // Retrieve results
 * Result result = session.run( "MATCH (n) RETURN n.name" );
 * List names = new LinkedList<>();
 * while( result.next() )
 * {
 *     names.add( result.get("n.name").javaString() );
 * }
 *
 * // Sessions are pooled, to avoid the overhead of creating new connections - this means
 * // it is very important to close your session when you are done with it, otherwise you will
 * // run out of sessions.
 * session.close();
 *
 * // And, to clean up resources, always close the driver when your application is done
 * driver.close();
 * }
 * 
*

* * A driver maintains a connection pool for each Neo4j instance. For resource efficiency reasons you are encouraged * to use the same driver instance across your application. You can control the connection pooling behavior when you * create the driver using the {@link Config} you pass into {@link GraphDatabase#driver(URI, Config)}. */ public class Driver implements AutoCloseable { private final ConnectionPool connections; private final URI url; public Driver( URI url, Config config ) { this.url = url; this.connections = new StandardConnectionPool( config ); } /** * Establish a session * @return a session that could be used to run {@link Session#run(String) a statement} or * {@link Session#beginTransaction() a transaction }. */ public Session session() { return new StandardSession( connections.acquire( url ) ); // TODO a ConnectionPool per URL // ConnectionPool connections = new StandardConnectionPool( logging, url ); // And to get a connection from the pool could be // connections.acquire(); } /** * Close all the resources assigned to this driver * @throws Exception any error that might happen when releasing all resources */ public void close() throws Exception { connections.close(); } } /* JEditorPane.java -- Copyright (C) 2002, 2004, 2005, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing; import java.awt.Container; import java.awt.Dimension; import java.io.BufferedInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleHyperlink; import javax.accessibility.AccessibleHypertext; import javax.accessibility.AccessibleStateSet; import javax.accessibility.AccessibleText; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.plaf.TextUI; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.View; import javax.swing.text.ViewFactory; import javax.swing.text.WrappedPlainView; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; /** * A powerful text editor component that can handle different types of * content. * * The JEditorPane text component is driven by an instance of * {@link EditorKit}. The editor kit is responsible for providing * a default {@link Document} implementation, a mechanism for loading * and saving documents of its supported content type and providing * a set of {@link Action}s for manipulating the content. * * By default the following content types are supported: *

    *
  • text/plain: Plain text, handled by * {@link javax.swing.text.DefaultEditorKit}.
  • *
  • text/html: HTML 4.0 styled text, handled by * {@link javax.swing.text.html.HTMLEditorKit}.
  • *
  • text/rtf: RTF text, handled by * {@link javax.swing.text.rtf.RTFEditorKit}.
  • *
* * @author original author unknown * @author () * @author soon abalkiss at redhat dot com */ public class JEditorPane extends JTextComponent { /** * Provides accessibility support for JEditorPane. * * @author () */ protected class AccessibleJEditorPane extends AccessibleJTextComponent { /** * Creates a new AccessibleJEditorPane object. */ protected AccessibleJEditorPane() { super(); } /** * Returns a description of this AccessibleJEditorPane. If * this property is not set, then this returns the content-type of the * editor pane. * * @return a description of this AccessibleJEditorPane */ public String getAccessibleDescription() { String descr = super.getAccessibleDescription(); if (descr == null) return getContentType(); else return descr; } /** * Returns the accessible state of this AccessibleJEditorPane. * * @return the accessible state of this AccessibleJEditorPane */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet state = super.getAccessibleStateSet(); // TODO: Figure out what state must be added here to the super's state. return state; } } /** * Provides accessibility support for JEditorPanes, when the * editor kit is an instance of {@link HTMLEditorKit}. * * @author () */ protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane { /** * Returns the accessible text of the JEditorPane. This will * be an instance of * {@link JEditorPaneAccessibleHypertextSupport}. * * @return the accessible text of the JEditorPane */ public AccessibleText getAccessibleText() { return new JEditorPaneAccessibleHypertextSupport(); } } /** * This is the accessible text that is returned by * {@link AccessibleJEditorPaneHTML#getAccessibleText()}. * * @author () */ protected class JEditorPaneAccessibleHypertextSupport extends AccessibleJEditorPane implements AccessibleHypertext { /** * Creates a new JEditorPaneAccessibleHypertextSupport object. */ public JEditorPaneAccessibleHypertextSupport() { super(); } /** * The accessible representation of a HTML link. * * @author () */ public class HTMLLink extends AccessibleHyperlink { /** * The element in the document that represents the link. */ Element element; /** * Creates a new HTMLLink. * * @param el the link element */ public HTMLLink(Element el) { this.element = el; } /** * Returns true if this HTMLLink is still * valid. A HTMLLink can become invalid when the document * changes. * * @return true if this HTMLLink is still * valid */ public boolean isValid() { // I test here if the element at our element's start offset is the // same as the element in the document at this offset. If this is true, // I consider the link valid, if not, then this link no longer // represented by this HTMLLink and therefor invalid. HTMLDocument doc = (HTMLDocument) getDocument(); return doc.getCharacterElement(element.getStartOffset()) == element; } /** * Returns the number of AccessibleActions in this link object. In * general, link have 1 AccessibleAction associated with them. There are * special cases where links can have multiple actions associated, like * in image maps. * * @return the number of AccessibleActions in this link object */ public int getAccessibleActionCount() { // TODO: Implement the special cases. return 1; } /** * Performs the specified action on the link object. This ususally means * activating the link. * * @return true if the action has been performed * successfully, false otherwise */ public boolean doAccessibleAction(int i) { String href = (String) element.getAttributes().getAttribute("href"); HTMLDocument doc = (HTMLDocument) getDocument(); try { URL url = new URL(doc.getBase(), href); setPage(url); String desc = doc.getText(element.getStartOffset(), element.getEndOffset() - element.getStartOffset()); HyperlinkEvent ev = new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, url, desc, element); fireHyperlinkUpdate(ev); return true; } catch (Exception ex) { return false; } } /** * Returns the description of the action at action index i. * This method returns the text within the element associated with this * link. * * @param i the action index * * @return the description of the action at action index i */ public String getAccessibleActionDescription(int i) { HTMLDocument doc = (HTMLDocument) getDocument(); try { return doc.getText(element.getStartOffset(), element.getEndOffset() - element.getStartOffset()); } catch (BadLocationException ex) { throw (AssertionError) new AssertionError("BadLocationException must not be thrown " + "here.") .initCause(ex); } } /** * Returns an {@link URL} object, that represents the action at action * index i. * * @param i the action index * * @return an {@link URL} object, that represents the action at action * index i */ public Object getAccessibleActionObject(int i) { String href = (String) element.getAttributes().getAttribute("href"); HTMLDocument doc = (HTMLDocument) getDocument(); try { URL url = new URL(doc.getBase(), href); return url; } catch (MalformedURLException ex) { return null; } } /** * Returns an object that represents the link anchor. For examples, if * the link encloses a string, then a String object is * returned, if the link encloses an <img> tag, then an * ImageIcon object is returned. * * @return an object that represents the link anchor */ public Object getAccessibleActionAnchor(int i) { // TODO: This is only the String case. Implement all cases. return getAccessibleActionDescription(i); } /** * Returns the start index of the hyperlink element. * * @return the start index of the hyperlink element */ public int getStartIndex() { return element.getStartOffset(); } /** * Returns the end index of the hyperlink element. * * @return the end index of the hyperlink element */ public int getEndIndex() { return element.getEndOffset(); } } /** * Returns the number of hyperlinks in the document. * * @return the number of hyperlinks in the document */ public int getLinkCount() { HTMLDocument doc = (HTMLDocument) getDocument(); HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A); int count = 0; while (linkIter.isValid()) { count++; linkIter.next(); } return count; } /** * Returns the i-th hyperlink in the document or * null if there is no hyperlink with the specified index. * * @param i the index of the hyperlink to return * * @return the i-th hyperlink in the document or * null if there is no hyperlink with the specified * index */ public AccessibleHyperlink getLink(int i) { HTMLDocument doc = (HTMLDocument) getDocument(); HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A); int count = 0; while (linkIter.isValid()) { count++; if (count == i) break; linkIter.next(); } if (linkIter.isValid()) { int offset = linkIter.getStartOffset(); // TODO: I fetch the element for the link via getCharacterElement(). // I am not sure that this is correct, maybe we must use // getParagraphElement()? Element el = doc.getCharacterElement(offset); HTMLLink link = new HTMLLink(el); return link; } else return null; } /** * Returns the index of the link element at the character position * c within the document, or -1 if there is no * link at the specified position. * * @param c the character index from which to fetch the link index * * @return the index of the link element at the character position * c within the document, or -1 if there * is no link at the specified position */ public int getLinkIndex(int c) { HTMLDocument doc = (HTMLDocument) getDocument(); HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A); int count = 0; while (linkIter.isValid()) { if (linkIter.getStartOffset() <= c && linkIter.getEndOffset() > c) break; count++; linkIter.next(); } if (linkIter.isValid()) return count; else return -1; } /** * Returns the link text of the link at index i, or * null, if there is no link at the specified position. * * @param i the index of the link * * @return the link text of the link at index i, or * null, if there is no link at the specified * position */ public String getLinkText(int i) { HTMLDocument doc = (HTMLDocument) getDocument(); HTMLDocument.Iterator linkIter = doc.getIterator(HTML.Tag.A); int count = 0; while (linkIter.isValid()) { count++; if (count == i) break; linkIter.next(); } if (linkIter.isValid()) { int offset = linkIter.getStartOffset(); // TODO: I fetch the element for the link via getCharacterElement(). // I am not sure that this is correct, maybe we must use // getParagraphElement()? Element el = doc.getCharacterElement(offset); try { String text = doc.getText(el.getStartOffset(), el.getEndOffset() - el.getStartOffset()); return text; } catch (BadLocationException ex) { throw (AssertionError) new AssertionError("BadLocationException must not be thrown " + "here.") .initCause(ex); } } else return null; } } /** * Used to store a mapping for content-type to editor kit class. */ private static class EditorKitMapping { /** * The classname of the editor kit. */ String className; /** * The classloader with which the kit is to be loaded. */ ClassLoader classLoader; /** * Creates a new EditorKitMapping object. * * @param cn the classname * @param cl the classloader */ EditorKitMapping(String cn, ClassLoader cl) { className = cn; classLoader = cl; } } /** * An EditorKit used for plain text. This is the default editor kit for * JEditorPanes. * * @author () */ private static class PlainEditorKit extends DefaultEditorKit { /** * Returns a ViewFactory that supplies WrappedPlainViews. */ public ViewFactory getViewFactory() { return new ViewFactory() { public View create(Element el) { return new WrappedPlainView(el); } }; } } /** * A special stream that can be cancelled. */ private class PageStream extends FilterInputStream { /** * True when the stream has been cancelled, false otherwise. */ private boolean cancelled; protected PageStream(InputStream in) { super(in); cancelled = false; } private void checkCancelled() throws IOException { if (cancelled) throw new IOException("Stream has been cancelled"); } void cancel() { cancelled = true; } public int read() throws IOException { checkCancelled(); return super.read(); } public int read(byte[] b, int off, int len) throws IOException { checkCancelled(); return super.read(b, off, len); } public long skip(long n) throws IOException { checkCancelled(); return super.skip(n); } public int available() throws IOException { checkCancelled(); return super.available(); } public void reset() throws IOException { checkCancelled(); super.reset(); } } /** * The thread that loads documents asynchronously. */ private class PageLoader implements Runnable { private Document doc; private PageStream in; private URL old; URL page; PageLoader(Document doc, InputStream in, URL old, URL page) { this.doc = doc; this.in = new PageStream(in); this.old = old; this.page = page; } public void run() { try { read(in, doc); } catch (IOException ex) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } finally { if (SwingUtilities.isEventDispatchThread()) firePropertyChange("page", old, page); else { SwingUtilities.invokeLater(new Runnable() { public void run() { firePropertyChange("page", old, page); } }); } } } void cancel() { in.cancel(); } } private static final long serialVersionUID = 3140472492599046285L; private EditorKit editorKit; boolean focus_root; /** * Maps content-types to editor kit instances. */ static HashMap editorKits; // A mapping between content types and registered EditorKit types static HashMap registerMap; static { registerMap = new HashMap(); editorKits = new HashMap(); registerEditorKitForContentType("application/rtf", "javax.swing.text.rtf.RTFEditorKit"); registerEditorKitForContentType("text/plain", "javax.swing.JEditorPane$PlainEditorKit"); registerEditorKitForContentType("text/html", "javax.swing.text.html.HTMLEditorKit"); registerEditorKitForContentType("text/rtf", "javax.swing.text.rtf.RTFEditorKit"); } // A mapping between content types and used EditorKits HashMap editorMap; /** * The currently loading stream, if any. */ private PageLoader loader; public JEditorPane() { init(); setEditorKit(createDefaultEditorKit()); } public JEditorPane(String url) throws IOException { this(new URL(url)); } public JEditorPane(String type, String text) { init(); setEditorKit(createEditorKitForContentType(type)); setText(text); } public JEditorPane(URL url) throws IOException { init(); setEditorKit(createEditorKitForContentType("text/html")); setPage(url); } /** * Called by the constructors to set up the default bindings for content * types and EditorKits. */ void init() { editorMap = new HashMap(); } protected EditorKit createDefaultEditorKit() { return new PlainEditorKit(); } /** * Creates and returns an EditorKit that is appropriate for the given * content type. This is created using the default recognized types * plus any EditorKit types that have been registered. * * @see #registerEditorKitForContentType(String, String) * @see #registerEditorKitForContentType(String, String, ClassLoader) * @param type the content type * @return an EditorKit for use with the given content type */ public static EditorKit createEditorKitForContentType(String type) { // Try cached instance. EditorKit e = (EditorKit) editorKits.get(type); if (e == null) { EditorKitMapping m = (EditorKitMapping) registerMap.get(type); if (m != null) { String className = m.className; ClassLoader loader = m.classLoader; try { e = (EditorKit) loader.loadClass(className).newInstance(); } catch (Exception e2) { // The reference implementation returns null when class is not // loadable or instantiatable. } } // Cache this for later retrieval. if (e != null) editorKits.put(type, e); } return e; } /** * Sends a given HyperlinkEvent to all registered listeners. * * @param event the event to send */ public void fireHyperlinkUpdate(HyperlinkEvent event) { HyperlinkListener[] listeners = getHyperlinkListeners(); for (int index = 0; index < listeners.length; ++index) listeners[index].hyperlinkUpdate(event); } /** * Returns the accessible context associated with this editor pane. * * @return the accessible context associated with this editor pane */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { if (getEditorKit() instanceof HTMLEditorKit) accessibleContext = new AccessibleJEditorPaneHTML(); else accessibleContext = new AccessibleJEditorPane(); } return accessibleContext; } public final String getContentType() { return getEditorKit().getContentType(); } /** * Returns the EditorKit. If there is no EditorKit set this method * calls createDefaultEditorKit() and setEditorKit() first. */ public EditorKit getEditorKit() { if (editorKit == null) setEditorKit(createDefaultEditorKit()); return editorKit; } /** * Returns the class name of the EditorKit associated with the given * content type. * * @since 1.3 * @param type the content type * @return the class name of the EditorKit associated with this content type */ public static String getEditorKitClassNameForContentType(String type) { EditorKitMapping m = (EditorKitMapping) registerMap.get(type); String kitName = m != null ? m.className : null; return kitName; } /** * Returns the EditorKit to use for the given content type. If an * EditorKit has been explicitly set via * setEditorKitForContentType * then it will be returned. Otherwise an attempt will be made to create * an EditorKit from the default recognzied content types or any * EditorKits that have been registered. If none can be created, a * PlainEditorKit is created. * * @see #registerEditorKitForContentType(String, String) * @see #registerEditorKitForContentType(String, String, ClassLoader) * @param type the content type * @return an appropriate EditorKit for the given content type */ public EditorKit getEditorKitForContentType(String type) { // First check if an EditorKit has been explicitly set. EditorKit e = (EditorKit) editorMap.get(type); // Then check to see if we can create one. if (e == null) { e = createEditorKitForContentType(type); if (e != null) setEditorKitForContentType(type, e); } // Otherwise default to PlainEditorKit. if (e == null) e = createDefaultEditorKit(); return e; } /** * Returns the preferred size for the JEditorPane. This is implemented to * return the super's preferred size, unless one of * {@link #getScrollableTracksViewportHeight()} or * {@link #getScrollableTracksViewportWidth()} returns true, * in which case the preferred width and/or height is replaced by the UI's * minimum size. * * @return the preferred size for the JEditorPane */ public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); Container parent = getParent(); if (parent instanceof JViewport) { JViewport vp = (JViewport) getParent(); TextUI ui = getUI(); Dimension min = null; if (! getScrollableTracksViewportWidth()) { min = ui.getMinimumSize(this); int vpWidth = vp.getWidth(); if (vpWidth != 0 && vpWidth < min.width) pref.width = min.width; } if (! getScrollableTracksViewportHeight()) { if (min == null) min = ui.getMinimumSize(this); int vpHeight = vp.getHeight(); if (vpHeight != 0 && vpHeight < min.height) pref.height = min.height; } } return pref; } /** * Returns true when a Viewport should force the height of * this component to match the viewport height. This is implemented to return * true when the parent is an instance of JViewport and * the viewport height > the UI's minimum height. * * @return true when a Viewport should force the height of * this component to match the viewport height */ public boolean getScrollableTracksViewportHeight() { // Tests show that this returns true when the parent is a JViewport // and has a height > minimum UI height. Container parent = getParent(); int height = parent.getHeight(); TextUI ui = getUI(); return parent instanceof JViewport && height >= ui.getMinimumSize(this).height && height <= ui.getMaximumSize(this).height; } /** * Returns true when a Viewport should force the width of * this component to match the viewport width. This is implemented to return * true when the parent is an instance of JViewport and * the viewport width > the UI's minimum width. * * @return true when a Viewport should force the width of * this component to match the viewport width */ public boolean getScrollableTracksViewportWidth() { // Tests show that this returns true when the parent is a JViewport // and has a width > minimum UI width. Container parent = getParent(); return parent != null && parent instanceof JViewport && parent.getWidth() > getUI().getMinimumSize(this).width; } public URL getPage() { return loader != null ? loader.page : null; } protected InputStream getStream(URL page) throws IOException { URLConnection conn = page.openConnection(); // Try to detect the content type of the stream data. String type = conn.getContentType(); if (type != null) setContentType(type); InputStream stream = conn.getInputStream(); return new BufferedInputStream(stream); } public String getText() { return super.getText(); } public String getUIClassID() { return "EditorPaneUI"; } public boolean isFocusCycleRoot() { return focus_root; } protected String paramString() { return "JEditorPane"; } /** * This method initializes from a stream. */ public void read(InputStream in, Object desc) throws IOException { EditorKit kit = getEditorKit(); if (kit instanceof HTMLEditorKit && desc instanceof HTMLDocument) { HTMLDocument doc = (HTMLDocument) desc; setDocument(doc); try { InputStreamReader reader = new InputStreamReader(in); kit.read(reader, doc, 0); } catch (BadLocationException ex) { assert false : "BadLocationException must not be thrown here."; } } else { Reader inRead = new InputStreamReader(in); super.read(inRead, desc); } } /** * Establishes a binding between type and classname. This enables * us to create an EditorKit later for the given content type. * * @param type the content type * @param classname the name of the class that is associated with this * content type */ public static void registerEditorKitForContentType(String type, String classname) { registerEditorKitForContentType(type, classname, Thread.currentThread().getContextClassLoader()); } /** * Establishes the default bindings of type to classname. */ public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) { registerMap.put(type, new EditorKitMapping(classname, loader)); } /** * Replaces the currently selected content with new content represented * by the given string. */ public void replaceSelection(String content) { // TODO: Implement this properly. super.replaceSelection(content); } /** * Scrolls the view to the given reference location (that is, the value * returned by the UL.getRef method for the URL being displayed). */ public void scrollToReference(String reference) { // TODO: Implement this properly. } public final void setContentType(String type) { // Strip off content type parameters. int paramIndex = type.indexOf(';'); if (paramIndex > -1) { // TODO: Handle character encoding. type = type.substring(0, paramIndex).trim(); } if (editorKit != null && editorKit.getContentType().equals(type)) return; EditorKit kit = getEditorKitForContentType(type); if (kit != null) setEditorKit(kit); } public void setEditorKit(EditorKit newValue) { if (editorKit == newValue) return; if (editorKit != null) editorKit.deinstall(this); EditorKit oldValue = editorKit; editorKit = newValue; if (editorKit != null) { editorKit.install(this); setDocument(editorKit.createDefaultDocument()); } firePropertyChange("editorKit", oldValue, newValue); invalidate(); repaint(); // Reset the accessibleContext since this depends on the editorKit. accessibleContext = null; } /** * Explicitly sets an EditorKit to be used for the given content type. * @param type the content type * @param k the EditorKit to use for the given content type */ public void setEditorKitForContentType(String type, EditorKit k) { editorMap.put(type, k); } /** * Sets the current URL being displayed. */ public void setPage(String url) throws IOException { setPage(new URL(url)); } /** * Sets the current URL being displayed. */ public void setPage(URL page) throws IOException { if (page == null) throw new IOException("invalid url"); URL old = getPage(); // Only reload if the URL doesn't point to the same file. // This is not the same as equals because there might be different // URLs on the same file with different anchors. if (old == null || ! old.sameFile(page)) { InputStream in = getStream(page); if (editorKit != null) { Document doc = editorKit.createDefaultDocument(); doc.putProperty(Document.StreamDescriptionProperty, page); if (loader != null) loader.cancel(); loader = new PageLoader(doc, in, old, page); int prio = -1; if (doc instanceof AbstractDocument) { AbstractDocument aDoc = (AbstractDocument) doc; prio = aDoc.getAsynchronousLoadPriority(); } if (prio >= 0) { // Load asynchronously. setDocument(doc); Thread loadThread = new Thread(loader, "JEditorPane.PageLoader"); loadThread.setDaemon(true); loadThread.setPriority(prio); loadThread.start(); } else { // Load synchronously. loader.run(); setDocument(doc); } } } } /** * Sets the text of the JEditorPane. The argument t * is expected to be in the format of the current EditorKit. This removes * the content of the current document and uses the EditorKit to read in the * new text. This allows the EditorKit to handle the String rather than just * inserting in plain text. * * @param t the text to display in this JEditorPane */ public void setText(String t) { try { // Remove the current content. Document doc = getDocument(); doc.remove(0, doc.getLength()); if (t == null || t.equals("")) return; // Let the EditorKit read the text into the Document. getEditorKit().read(new StringReader(t), doc, 0); } catch (BadLocationException ble) { // TODO: Don't know what to do here. } catch (IOException ioe) { // TODO: Don't know what to do here. } } /** * Add a HyperlinkListener object to this editor pane. * * @param listener the listener to add */ public void addHyperlinkListener(HyperlinkListener listener) { listenerList.add(HyperlinkListener.class, listener); } /** * Removes a HyperlinkListener object to this editor pane. * * @param listener the listener to remove */ public void removeHyperlinkListener(HyperlinkListener listener) { listenerList.remove(HyperlinkListener.class, listener); } /** * Returns all added HyperlinkListener objects. * * @return array of listeners * * @since 1.4 */ public HyperlinkListener[] getHyperlinkListeners() { return (HyperlinkListener[]) getListeners(HyperlinkListener.class); } } package com.ispikemon.DemonicEmpowerment.item; import com.ispikemon.DemonicEmpowerment.init.DEitems; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.fml.common.registry.GameRegistry; public class FelRock extends Item { public FelRock(String name) { setRegistryName("FelRock"); setUnlocalizedName("FelRock"); GameRegistry.register(this); this.setCreativeTab(CreativeTabs.MATERIALS); addToItems(this); } public static void setItemName(Item item, String itemName) { item.setRegistryName(itemName); item.setUnlocalizedName(item.getRegistryName().toString()); } public void addToItems(Item item) { DEitems.items.add(item); } }/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.nestedmethodcall; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; /** * * @author */ public class ObjectFactory { public JAXBElement createDate(String date) { return new JAXBElement<>( new QName( "dont-care" ), String.class, "06.07.2013" ); } } greenmail-webapp/src/main/java/com/icegreen/greenmail/webapp/GreenMailListener.java100-1000 package com.icegreen.greenmail.webapp; import com.icegreen.greenmail.Managers; import com.icegreen.greenmail.user.GreenMailUser; import com.icegreen.greenmail.user.UserException; import com.icegreen.greenmail.user.UserManager; import com.icegreen.greenmail.util.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Automatically starts and stops GreenMail server upon deployment/un-deployment. * * @author mm */ public class GreenMailListener implements ServletContextListener { private final Logger log = LoggerFactory.getLogger(GreenMailListener.class); private Managers managers; private List services; private Configuration configuration; @Override public void contextInitialized(final ServletContextEvent sce) { log.info("Initializing GreenMail"); managers = new Managers(); ServletContext ctx = sce.getServletContext(); configuration = ConfigurationFactory.create(extractParameters(ctx)); services = ServiceFactory.create(configuration, managers); final UserManager userManager = managers.getUserManager(); for (Configuration.User user : configuration.getUsers()) { GreenMailUser greenMailUser = userManager.getUser(user.email); if (null == greenMailUser) { try { greenMailUser = userManager.createUser( user.email, user.login, user.password); greenMailUser.setPassword(user.password); } catch (UserException e) { throw new IllegalStateException(e); } } } for (Service s : services) { log.info("Starting GreenMail service: {}", s); s.startService(); } ContextHelper.initAttributes(ctx, managers, configuration); } @Override public void contextDestroyed(final ServletContextEvent sce) { log.info("Destroying GreenMail WebApp"); for (Service s : services) { log.info("Stopping GreenMail service: {}", s); s.stopService(); } } private Map extractParameters(ServletContext pServletContext) { Enumeration names = pServletContext.getInitParameterNames(); Map parameterMap = new HashMap<>(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); parameterMap.put(name, pServletContext.getInitParameter(name)); } return parameterMap; } public Managers getManagers() { return managers; } public Configuration getConfiguration() { return configuration; } public List getServices() { return services; } } ChengCheng-Hello/CustomViews0 package com.cc.custom.calender; import android.content.Context; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.widget.FrameLayout; /** * TODO: 类的一句话描述 *

* TODO: 类的功能和使用详细描述 *

* Created by Cheng on 2017/9/26. */ public class TXCalendarView extends FrameLayout{ public TXCalendarView(@NonNull Context context) { super(context); } public TXCalendarView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public TXCalendarView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); } } viakiba/exceltoolsrc/main/java/org/viakiba/exceltool/bean/FiledBean.java0 package org.viakiba.exceltool.bean; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @ToString @NoArgsConstructor public class FiledBean { private String filedName; private String filedType; private String filedDesc; private String excelProperty; } package br.com.builders.service; import javax.inject.Named; import br.com.builders.domain.entity.Cliente; import br.com.builders.domain.usercase.AtualizarClienteService; import br.com.builders.domain.usercase.CadastrarClienteService; import br.com.builders.domain.usercase.ExcluirClienteService; import lombok.RequiredArgsConstructor; @Named(value = "clienteService") @RequiredArgsConstructor public class ClienteService { private final CadastrarClienteService cadastrarClienteService; private final AtualizarClienteService atualizarClienteService; private final ExcluirClienteService excluirClienteService; public Cliente criarCliente(Cliente cliente) { return cadastrarClienteService.execute(cliente); } public Cliente atualizarCliente(Cliente cliente) { return atualizarClienteService.execute(cliente); } public void excluirCliente(Cliente cliente) { excluirClienteService.execute(cliente); } } package com.sh.linklist; /** * 定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点 */ public class ReverseList { public Node reverse(Node head) { Node prev = null; Node next = null; while (head != null) { next = head.next; head.next = prev; prev = head; head = next; } return prev; } public static void main(String[] args) { Node node0 = new Node(1); Node node1 = new Node(2); Node node2 = new Node(3); Node node3 = new Node(4); Node node4 = new Node(5); node0.next = node1; node1.next = node2; node2.next = node3; node3.next = node4; Node head = new ReverseList().reverse(node0); while (head != null) { System.out.print(head.val); head = head.next; } } } package org.powlab.jeye.tests.other; public class MultiClassTest1 { int x; int y; int z; int test1(int a, int b) { return a + b; } } class ExtraClass { int foo; public int testfoo(int x, int y) { return x + y * 2; } public int testbar(int a) { return a + 2; } } package com.fingerchar.api.dto; import com.fingerchar.db.domain.FcNftItems; import com.fingerchar.db.domain.FcUser; public class ItemOwners { private Long sellQuantity; private Long quantity; private Boolean onsell; private String nickname; private String address; private String avatar; private String price; private String payTokenAddress; private Long createTime; private String sellValue; private String buyValue; private Long completed; /** * */ public ItemOwners(FcNftItems items, FcUser user) { this.sellQuantity = items.getSellQuantity(); this.onsell = items.getOnsell(); this.nickname = user.getNickname(); this.address = user.getAddress(); this.avatar = user.getAvatar(); this.price = items.getPrice(); this.quantity = items.getQuantity(); this.payTokenAddress = items.getPaytokenAddress(); this.createTime = items.getCreateTime(); } public Long getSellQuantity() { return sellQuantity; } public void setSellQuantity(Long sellQuantity) { this.sellQuantity = sellQuantity; } public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } public Boolean getOnsell() { return onsell; } public void setOnsell(Boolean onsell) { this.onsell = onsell; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPayTokenAddress() { return payTokenAddress; } public void setPayTokenAddress(String payTokenAddress) { this.payTokenAddress = payTokenAddress; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public String getSellValue() { return sellValue; } public void setSellValue(String sellValue) { this.sellValue = sellValue; } public String getBuyValue() { return buyValue; } public void setBuyValue(String buyValue) { this.buyValue = buyValue; } public Long getCompleted() { return completed; } public void setCompleted(Long completed) { this.completed = completed; } } DribbleUp/react-native-navigation-v3 package com.reactnativenavigation.presentation; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import com.reactnativenavigation.parse.BottomTabOptions; import com.reactnativenavigation.parse.Options; import com.reactnativenavigation.utils.ImageLoader; import com.reactnativenavigation.utils.ImageLoadingListenerAdapter; import com.reactnativenavigation.viewcontrollers.ViewController; import com.reactnativenavigation.viewcontrollers.bottomtabs.BottomTabFinder; import com.reactnativenavigation.views.BottomTabs; import java.util.List; public class BottomTabPresenter { private final Context context; private ImageLoader imageLoader; private Options defaultOptions; private final BottomTabFinder bottomTabFinder; private BottomTabs bottomTabs; private final List tabs; public BottomTabPresenter(Context context, List tabs, ImageLoader imageLoader, Options defaultOptions) { this.tabs = tabs; this.context = context; this.bottomTabFinder = new BottomTabFinder(tabs); this.imageLoader = imageLoader; this.defaultOptions = defaultOptions; } public void setDefaultOptions(Options defaultOptions) { this.defaultOptions = defaultOptions; } public void bindView(BottomTabs bottomTabs) { this.bottomTabs = bottomTabs; } public void applyOptions() { for (int i = 0; i < tabs.size(); i++) { BottomTabOptions tab = tabs.get(i).resolveCurrentOptions(defaultOptions).bottomTabOptions; bottomTabs.setBadge(i, tab.badge.get("")); bottomTabs.setBadgeColor(tab.badgeColor.get(null)); bottomTabs.setTitleTypeface(i, tab.fontFamily); bottomTabs.setIconActiveColor(i, tab.selectedIconColor.get(null)); bottomTabs.setIconInactiveColor(i, tab.iconColor.get(null)); bottomTabs.setTitleActiveColor(i, tab.selectedTextColor.get(null)); bottomTabs.setTitleInactiveColor(i, tab.textColor.get(null)); bottomTabs.setTitleInactiveTextSizeInSp(i, tab.fontSize.hasValue() ? Float.valueOf(tab.fontSize.get()) : null); bottomTabs.setTitleActiveTextSizeInSp(i, tab.selectedFontSize.hasValue() ? Float.valueOf(tab.selectedFontSize.get()) : null); if (tab.testId.hasValue()) bottomTabs.setTag(i, tab.testId.get()); } } public void mergeChildOptions(Options options, ViewController child) { int index = bottomTabFinder.findByControllerId(child.getId()); if (index >= 0) { BottomTabOptions bto = options.bottomTabOptions; if (bto.badge.hasValue()) bottomTabs.setBadge(index, bto.badge.get()); if (bto.badgeColor.hasValue()) bottomTabs.setBadgeColor(bto.badgeColor.get()); if (bto.fontFamily != null) bottomTabs.setTitleTypeface(index, bto.fontFamily); if (bto.selectedIconColor.hasValue()) bottomTabs.setIconActiveColor(index, bto.selectedIconColor.get()); if (bto.iconColor.hasValue()) bottomTabs.setIconInactiveColor(index, bto.iconColor.get()); if (bto.selectedTextColor.hasValue()) bottomTabs.setTitleActiveColor(index, bto.selectedTextColor.get()); if (bto.textColor.hasValue()) bottomTabs.setTitleInactiveColor(index, bto.textColor.get()); if (bto.text.hasValue()) bottomTabs.setText(index, bto.text.get()); if (bto.icon.hasValue()) imageLoader.loadIcon(context, bto.icon.get(), new ImageLoadingListenerAdapter() { @Override public void onComplete(@NonNull Drawable drawable) { bottomTabs.setIcon(index, drawable); } }); if (bto.testId.hasValue()) bottomTabs.setTag(index, bto.testId.get()); } } } stori-es/stories package org.consumersunion.stories.server.business_logic; import org.consumersunion.stories.common.shared.model.NotificationTrigger; public interface NotificationService { void subscribe(int target, NotificationTrigger event); void unsubscribe(int target, NotificationTrigger event); void cleanupSubscriptions(); } src/main/java/seedu/address/model/util/SampleDataUtil.java package seedu.address.model.util; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import seedu.address.model.AddressBook; import seedu.address.model.ReadOnlyAddressBook; import seedu.address.model.order.CollectionType; import seedu.address.model.order.DeliveryDateTime; import seedu.address.model.order.Details; import seedu.address.model.order.Order; import seedu.address.model.person.Address; import seedu.address.model.person.Email; import seedu.address.model.person.Name; import seedu.address.model.person.Person; import seedu.address.model.person.Phone; import seedu.address.model.person.Remark; import seedu.address.model.tag.Tag; /** * Contains utility methods for populating {@code AddressBook} with sample data. */ public class SampleDataUtil { public static Person[] getSamplePersons() { return new Person[] { new Person(new Name(""), new Phone("87438807"), new Email(""), new Address("Blk 30 Geylang Street 29, #06-40"), new Remark("Allergic to Peanuts"), getTagSet("Regular"), UUID.fromString("6ea390c0-242c-4643-a547-21cc85773f88")), new Person(new Name(""), new Phone("99272758"), new Email(""), new Address("Blk 30 Lorong 3 Serangoon Gardens, #07-18"), new Remark("Allergic to Chicken"), getTagSet("Member", "Regular"), UUID.fromString("0d13afaa-db95-4a2a-b64d-5270e39d243d")), new Person(new Name(""), new Phone("93210283"), new Email(""), new Address("Blk 11 Ang Mo Kio Street 74, #11-04"), new Remark("Enjoys a pun or two"), getTagSet("Member")), new Person(new Name(""), new Phone("91031282"), new Email(""), new Address("Blk 436 Serangoon Gardens Street 26, #16-43"), new Remark("My really close friend"), getTagSet("Member")), new Person(new Name(""), new Phone("92492021"), new Email(""), new Address("Blk 47 Tampines Street 20, #17-35"), new Remark("Hates Pistachios"), getTagSet("Member")), new Person(new Name(""), new Phone("92624417"), new Email(""), new Address("Blk 45 Aljunied Street 85, #11-31"), new Remark("Loves Games and Anime"), getTagSet("NonMember")) }; } public static Order[] getSampleOrders() { return new Order[]{ new Order(new Remark("No Peanuts"), getDetailsList("3:Strawberry Cupcakes"), new DeliveryDateTime("25-12-2022 15:30"), CollectionType.DELIVERY, UUID.fromString("6ea390c0-242c-4643-a547-21cc85773f88")), new Order(new Remark("Please make delivery by 4pm latest"), getDetailsList("1:Chocolate Cake"), new DeliveryDateTime("22-12-2022 16:00"), CollectionType.DELIVERY, UUID.fromString("6ea390c0-242c-4643-a547-21cc85773f88")), new Order(new Remark("No candles needed"), getDetailsList("1:Cake"), new DeliveryDateTime("12-12-2022 12:30"), CollectionType.PICKUP, UUID.fromString("0d13afaa-db95-4a2a-b64d-5270e39d243d")) }; } public static ReadOnlyAddressBook getSampleAddressBook() { AddressBook sampleAb = new AddressBook(); for (Person samplePerson : getSamplePersons()) { sampleAb.addPerson(samplePerson); } for (Order sampleOrder : getSampleOrders()) { sampleAb.addOrder(sampleOrder); } return sampleAb; } /** * Returns a tag set containing the list of strings given. */ public static Set getTagSet(String... strings) { return Arrays.stream(strings) .map(Tag::new) .collect(Collectors.toSet()); } public static List

getDetailsList(String... strings) { return Arrays.stream(strings) .map(Details::new) .collect(Collectors.toList()); } } /* * Copyright 2006 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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. */ package org.kuali.ole.fp.document.web.struts; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.ole.fp.businessobject.ProcurementCardTargetAccountingLine; import org.kuali.ole.fp.businessobject.ProcurementCardTransactionDetail; import org.kuali.ole.fp.document.ProcurementCardDocument; import org.kuali.ole.sys.OLEConstants; import org.kuali.ole.sys.OLEKeyConstants; import org.kuali.ole.sys.businessobject.AccountingLine; import org.kuali.ole.sys.businessobject.TargetAccountingLine; import org.kuali.ole.sys.context.SpringContext; import org.kuali.ole.sys.document.AccountingDocument; import org.kuali.ole.sys.document.validation.event.AddAccountingLineEvent; import org.kuali.ole.sys.document.validation.event.DeleteAccountingLineEvent; import org.kuali.ole.sys.web.struts.KualiAccountingDocumentFormBase; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; import org.kuali.rice.krad.service.KualiRuleService; import org.kuali.rice.krad.service.PersistenceService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; /** * This class handles specific Actions requests for the ProcurementCard. */ public class ProcurementCardAction extends CapitalAccountingLinesActionBase { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ProcurementCardAction.class); @Override protected void loadDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException { super.loadDocument(kualiDocumentFormBase); ProcurementCardDocument procureCardDocument = (ProcurementCardDocument)kualiDocumentFormBase.getDocument(); int transactionsCount = procureCardDocument.getTransactionEntries().size(); ProcurementCardForm procurementCardForm = (ProcurementCardForm)kualiDocumentFormBase; procurementCardForm.buildNewTargetAccountingLines(transactionsCount); } /** * Override to accomodate multiple target lines. * * @param transForm */ @Override protected void processAccountingLineOverrides(KualiAccountingDocumentFormBase transForm) { ProcurementCardForm procurementCardForm = (ProcurementCardForm) transForm; processAccountingLineOverrides(procurementCardForm.getNewSourceLine()); processAccountingLineOverrides(procurementCardForm.getNewTargetLines()); if (procurementCardForm.hasDocumentId()) { AccountingDocument financialDocument = (AccountingDocument) procurementCardForm.getDocument(); processAccountingLineOverrides(financialDocument.getSourceAccountingLines()); processAccountingLineOverrides(financialDocument.getTargetAccountingLines()); } } /** * Override to add the new accounting line to the correct transaction * * @see org.kuali.module.financial.web.struts.action.KualiFinancialDocumentActionBase#insertTargetLine(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward insertTargetLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProcurementCardForm procurementCardForm = (ProcurementCardForm) form; ProcurementCardDocument procurementCardDocument = (ProcurementCardDocument) procurementCardForm.getDocument(); int targetContainerIndex = this.getSelectedContainer(request); ProcurementCardTargetAccountingLine line = (ProcurementCardTargetAccountingLine)procurementCardForm.getNewTargetLines().get(targetContainerIndex); ProcurementCardTransactionDetail transactionDetail = (ProcurementCardTransactionDetail) procurementCardDocument.getTransactionEntries().get(targetContainerIndex); line.setFinancialDocumentTransactionLineNumber(transactionDetail.getFinancialDocumentTransactionLineNumber()); // check any business rules boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(OLEConstants.NEW_TARGET_ACCT_LINES_PROPERTY_NAME + "[" + Integer.toString(targetContainerIndex) + "]", procurementCardForm.getDocument(), (AccountingLine) line)); if (rulePassed) { // add accountingLine SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line); insertAccountingLine(false, procurementCardForm, line); ProcurementCardTargetAccountingLine newLine = new ProcurementCardTargetAccountingLine(); newLine.setTransactionContainerIndex(targetContainerIndex); procurementCardForm.getNewTargetLines().set(targetContainerIndex, newLine); } return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#performBalanceInquiryForTargetLine(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward performBalanceInquiryForTargetLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProcurementCardForm procurementCardForm = (ProcurementCardForm) form; ProcurementCardDocument procurementCardDocument = (ProcurementCardDocument) procurementCardForm.getDocument(); int targetContainerIndex = this.getSelectedContainer(request); ProcurementCardTransactionDetail ProcurementCardTransactionDetail = (ProcurementCardTransactionDetail) procurementCardDocument.getTransactionEntries().get(targetContainerIndex); int targetIndex = super.getSelectedLine(request); TargetAccountingLine targetLine = (ProcurementCardTargetAccountingLine) ProcurementCardTransactionDetail.getTargetAccountingLines().get(targetIndex); return performBalanceInquiryForAccountingLine(mapping, form, request, targetLine); } /** * Override to resync base accounting lines. New lines on the PCDO document can be inserted anywhere in the list, not necessary * at the end. * * @see org.kuali.module.financial.web.struts.action.KualiFinancialDocumentActionBase#insertAccountingLine(boolean, * org.kuali.module.financial.web.struts.form.KualiFinancialDocumentFormBase, org.kuali.rice.krad.bo.AccountingLine) */ @Override protected void insertAccountingLine(boolean isSource, KualiAccountingDocumentFormBase financialDocumentForm, AccountingLine line) { AccountingDocument tdoc = financialDocumentForm.getFinancialDocument(); // add it to the document tdoc.addTargetAccountingLine((TargetAccountingLine) line); } /** * Override to get the correct container of the transaction and then delete the correct accounting line * * @see org.kuali.module.financial.web.struts.action.KualiFinancialDocumentActionBase#deleteTargetLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response */ @Override public ActionForward deleteTargetLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { int targetContainerIndex = this.getSelectedContainer(request); int targetIndex = this.getSelectedLine(request); KualiAccountingDocumentFormBase financialDocumentForm = (KualiAccountingDocumentFormBase) form; String errorPath = OLEConstants.DOCUMENT_PROPERTY_NAME + "." + OLEConstants.EXISTING_TARGET_ACCT_LINE_PROPERTY_NAME + "[" + targetIndex + "]"; boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new DeleteAccountingLineEvent(errorPath, financialDocumentForm.getDocument(), ((AccountingDocument) financialDocumentForm.getDocument()).getTargetAccountingLine(targetIndex), false)); // if the rule evaluation passed, let's delete it if (rulePassed) { deleteAccountingLineFromTransactionContainer(financialDocumentForm, targetContainerIndex, targetIndex); } else { String[] errorParams = new String[] { "target", Integer.toString(targetIndex + 1) }; GlobalVariables.getMessageMap().putError(errorPath, OLEKeyConstants.ERROR_ACCOUNTINGLINE_DELETERULE_INVALIDACCOUNT, errorParams); } return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * Override to remove the accounting line from the correct transaction * * @see org.kuali.module.financial.web.struts.action.KualiFinancialDocumentActionBase#deleteAccountingLine(boolean, * org.kuali.module.financial.web.struts.form.KualiFinancialDocumentFormBase, int) */ @Override protected void deleteAccountingLine(boolean isSource, KualiAccountingDocumentFormBase financialDocumentForm, int deleteIndex) { ProcurementCardDocument procurementCardDocument = (ProcurementCardDocument) financialDocumentForm.getDocument(); procurementCardDocument.removeTargetAccountingLine(deleteIndex); } /** * Ensures that ProcurementCardForm.newTargetLines is cleared. Otherwise works like super.reload. * * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#reload(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward reload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ProcurementCardForm procurementCardForm = (ProcurementCardForm) form; procurementCardForm.setNewTargetLines(new ArrayList()); return super.reload(mapping, procurementCardForm, request, response); } // get the index of selected transaction entry protected int getSelectedContainer(HttpServletRequest request) { int selectedContainer = -1; String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE); if (StringUtils.isNotBlank(parameterName)) { String lineNumber = StringUtils.substringBetween(parameterName, ".transactionEntries[", "]."); selectedContainer = Integer.parseInt(lineNumber); } return selectedContainer; } /** * Removes the target accounting line at the given index from the transaction container transaction entries. * * @param financialDocumentForm, targetContainerIndex, targetIndex */ protected void deleteAccountingLineFromTransactionContainer(KualiAccountingDocumentFormBase financialDocumentForm, int targetContainerIndex, int targetIndex) { ProcurementCardDocument procurementCardDocument = (ProcurementCardDocument) financialDocumentForm.getDocument(); ProcurementCardTransactionDetail procurementCardTransactionDetail = (ProcurementCardTransactionDetail) procurementCardDocument.getTransactionEntries().get(targetContainerIndex); procurementCardTransactionDetail.getTargetAccountingLines().remove(targetIndex); } } EliHar/SimpleBlockchainsrc/Blockchain.java import java.util.ArrayList; import java.util.List; /*** * * @author * */ public class Blockchain { private List blocks; private final int GENESIS_BLOCK_PREVIOUS_BLOCK_HASHCODE = 0; public Blockchain() { this.blocks = new ArrayList(); } /*** * Method that allows adding a new block to the chain * @param block * @return the newly modified blockchain */ public List addBlock(Block block) { // Ensure that the first block has no previous block hash code. if (blocks.size() == 0) { if (block.getPreviousBlockHash() != 0) { System.out.println("Invalid genesis block. The first block in the chain " + "should have a previous block hash value of 0."); } } blocks.add(block); return blocks; } /*** * Method to create a new block * @return the newly created block */ public Block createBlock() { Block block; if (blocks.size() == 0) { block = new Block(GENESIS_BLOCK_PREVIOUS_BLOCK_HASHCODE, new ArrayList()); } else { block = new Block(blocks.get(blocks.size() - 1).getCurrentBlockHash(), new ArrayList()); } return block; } @Override public String toString() { StringBuilder output = new StringBuilder(); output.append("Blockchain...\n"); for(int i = 0; i < blocks.size(); i++) { output.append("- Block # " + i + "\n") .append(blocks.get(i) + "\n"); } return output.toString(); } } package com.livejq.action; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.livejq.domain.Resource; import com.livejq.util.HibernateUtils; import com.opensymphony.xwork2.ActionSupport; public class ResourceAction extends ActionSupport { private static final long serialVersionUID = 1L; private List resource; public List getResource() { return resource; } /** * 获取数据库中的电子书信息 * @return */ public String get() { Session session = HibernateUtils.getSession(); String hql = "from Resource"; Query query = session.createQuery(hql); @SuppressWarnings("unchecked") List res = query.list(); resource = res; session.close(); System.out.println("正在查询相关书籍资料......"); return SUCCESS; } } oim-server-run/cloud/service/work/portal/oim-server-module-work-portal-common-base/src/main/java/com/oimchat/server/general/kernel/work/common/config/ServerConfig.java package com.oimchat.server.general.kernel.work.common.config; import java.util.ArrayList; import java.util.List; import com.oimchat.server.general.kernel.work.common.config.constant.ServerConstant; import com.onlyxiahui.aware.basic.work.type.net.AddressType; import com.onlyxiahui.aware.basic.work.type.net.Protocol; /** * Date 2019-01-15 16:34:38
* Description * * @author XiaHui
* @since 1.0.0 */ public class ServerConfig { /** * 网络协议类型列表 */ List protocolList = new ArrayList<>(); /** * 地址类型列表 */ List addressTypeList = new ArrayList<>(); /** * 服务类型列表 */ List serverTypeList = new ArrayList<>(); public ServerConfig() { protocolList.add(Protocol.TCP.value()); protocolList.add(Protocol.UDP.value()); protocolList.add(Protocol.HTTP.value()); protocolList.add(Protocol.WS.value()); protocolList.add(Protocol.WSS.value()); protocolList.add(Protocol.FTP.value()); addressTypeList.add(AddressType.IPv4.value()); addressTypeList.add(AddressType.IPv6.value()); addressTypeList.add(AddressType.URL.value()); serverTypeList.add(ServerConstant.ServerType.main.value()); serverTypeList.add(ServerConstant.ServerType.file.value()); serverTypeList.add(ServerConstant.ServerType.video.value()); serverTypeList.add(ServerConstant.ServerType.voice.value()); } public List getProtocolList() { return protocolList; } public List getAddressTypeList() { return protocolList; } public List getServerTypeList() { return serverTypeList; } } /* * Artificial Intelligence for Humans * Volume 3: Deep Learning and Neural Networks * Java Version * http://www.aifh.org * http://www.jeffheaton.com * * Code repository: * https://github.com/jeffheaton/aifh * * Copyright 2014-2015 by * * 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package com.heatonresearch.aifh.error; /** * An error calculation metric calculates the difference between two vector sets. One vector set will be the ideal * expected output from a Machine Learning Algorithm. The other vector set is the actual output. Training a * Machine Learning Algorithm typically involves minimizing this error. *

* Error calculation metrics are very similar to distance metrics. However, an error calculation metric operates over * a set of vectors, whereas a distance metric operates over just two vectors. */ public interface ErrorCalculation { /** * @return A new instance of this object. */ ErrorCalculation create(); /** * Called to update for each number that should be checked. * * @param actual The actual number. * @param ideal The ideal number. */ void updateError(final double[] actual, final double[] ideal, final double significance); /** * Update the error with single values. * * @param actual The actual value. * @param ideal The ideal value. */ void updateError(final double actual, final double ideal); /** * Calculate the error with MSE. * * @return The current error for the neural network. */ double calculate(); /** * Clear the error calculation and start over. */ void clear(); /** * @return The total size of the set (vector size times number of vectors). */ int getSetSize(); } cos.trader.lookup/src/main/java/ccmm/InteractionInterface.java /** */ package ccmm; /** * * A representation of the model object 'Interaction Interface'. * * * * @see ccmm.CcmmPackage#getInteractionInterface() * @model extendedMetaData="name='InteractionInterface' kind='elementOnly'" * @generated */ public interface InteractionInterface extends ComponentStructure { } // InteractionInterface Y-D-Lu/rr_frameworks_base /* * Copyright (C) 2017 The Android Open Source Project * * 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. */ package com.android.settingslib.deviceinfo; import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.support.annotation.VisibleForTesting; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceScreen; import android.text.TextUtils; import com.android.settingslib.R; import com.android.settingslib.core.lifecycle.Lifecycle; /** * Preference controller for bluetooth address */ public abstract class AbstractBluetoothAddressPreferenceController extends AbstractConnectivityPreferenceController { @VisibleForTesting static final String KEY_BT_ADDRESS = "bt_address"; private static final String[] CONNECTIVITY_INTENTS = { BluetoothAdapter.ACTION_STATE_CHANGED }; private Preference mBtAddress; public AbstractBluetoothAddressPreferenceController(Context context, Lifecycle lifecycle) { super(context, lifecycle); } @Override public boolean isAvailable() { return BluetoothAdapter.getDefaultAdapter() != null; } @Override public String getPreferenceKey() { return KEY_BT_ADDRESS; } @Override public void displayPreference(PreferenceScreen screen) { super.displayPreference(screen); mBtAddress = screen.findPreference(KEY_BT_ADDRESS); updateConnectivity(); } @Override protected String[] getConnectivityIntents() { return CONNECTIVITY_INTENTS; } @SuppressLint("HardwareIds") @Override protected void updateConnectivity() { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if (bluetooth != null && mBtAddress != null) { String address = bluetooth.isEnabled() ? bluetooth.getAddress() : null; if (!TextUtils.isEmpty(address)) { // Convert the address to lowercase for consistency with the wifi MAC address. mBtAddress.setSummary(address.toLowerCase()); } else { mBtAddress.setSummary(R.string.status_unavailable); } } } } 1-10 /* * 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. */ package com.globo.globonetwork.client.model; import com.google.api.client.util.Key; public class IPv6Network extends Network { @Key private String block1; @Key private String block2; @Key private String block3; @Key private String block4; @Key private String block5; @Key private String block6; @Key private String block7; @Key private String block8; @Key private String mask1; @Key private String mask2; @Key private String mask3; @Key private String mask4; @Key private String mask5; @Key private String mask6; @Key private String mask7; @Key private String mask8; @Override public String getNetworkAddressAsString() { return String.format("%s:%s:%s:%s:%s:%s:%s:%s", getBlock1(), getBlock2(), getBlock3(), getBlock4(), getBlock5(), getBlock6(), getBlock7(), getBlock8()); } @Override public String getMaskAsString() { return String.format("%s:%s:%s:%s:%s:%s:%s:%s", getMask1(), getMask2(), getMask3(), getMask4(), getMask5(), getMask6(), getMask7(), getMask8()); } public IPv6Network() { super.name = "redeipv6"; } @Override public boolean isv6() { return true; } public String getBlock1() { return block1; } public void setBlock1(String block1) { this.block1 = block1; } public String getBlock2() { return block2; } public void setBlock2(String block2) { this.block2 = block2; } public String getBlock3() { return block3; } public void setBlock3(String block3) { this.block3 = block3; } public String getBlock4() { return block4; } public void setBlock4(String block4) { this.block4 = block4; } public String getBlock5() { return block5; } public void setBlock5(String block5) { this.block5 = block5; } public String getBlock6() { return block6; } public void setBlock6(String block6) { this.block6 = block6; } public String getBlock7() { return block7; } public void setBlock7(String block7) { this.block7 = block7; } public String getBlock8() { return block8; } public void setBlock8(String block8) { this.block8 = block8; } public String getMask1() { return mask1; } public void setMask1(String mask1) { this.mask1 = mask1; } public String getMask2() { return mask2; } public void setMask2(String mask2) { this.mask2 = mask2; } public String getMask3() { return mask3; } public void setMask3(String mask3) { this.mask3 = mask3; } public String getMask4() { return mask4; } public void setMask4(String mask4) { this.mask4 = mask4; } public String getMask5() { return mask5; } public void setMask5(String mask5) { this.mask5 = mask5; } public String getMask6() { return mask6; } public void setMask6(String mask6) { this.mask6 = mask6; } public String getMask7() { return mask7; } public void setMask7(String mask7) { this.mask7 = mask7; } public String getMask8() { return mask8; } public void setMask8(String mask8) { this.mask8 = mask8; } } Focus 023457/Focus/Beta/API/events/misc/EventKey.java package Focus.Beta.API.events.misc; import Focus.Beta.API.Event; public class EventKey extends Event { private int key; public EventKey(int key) { this.key = key; } public int getKey() { return this.key; } public void setKey(int key) { this.key = key; } } /* ========================================================== File: ApiKey.java Description: Prompts user for api key if it does not exist. Maintainer: WakaTime <> License: BSD, see LICENSE for more details. Website: https://wakatime.com/ ===========================================================*/ package com.wakatime.intellij.plugin; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.ValidationInfo; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.UUID; public class ApiKey extends DialogWrapper { private final JPanel panel; private final JTextField input; public ApiKey(@Nullable Project project) { super(project, true); setTitle("WakaTime API Key"); setOKButtonText("Save"); panel = new JPanel(); input = new JTextField(36); panel.add(input); init(); } @Nullable @Override protected JComponent createCenterPanel() { return panel; } @Override protected ValidationInfo doValidate() { String apiKey = input.getText(); try { UUID.fromString(apiKey); } catch (Exception e) { return new ValidationInfo("Invalid api key."); } return null; } @Override public void doOKAction() { ConfigFile.setApiKey(input.getText()); super.doOKAction(); } public String promptForApiKey() { input.setText(ConfigFile.getApiKey()); this.show(); return input.getText(); } } AlexGhiondea/azure-sdk-for-java /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.management.datafactory.v2018_06_01.implementation.LinkedServiceInner; /** * Azure File Storage linked service. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = AzureFileStorageLinkedService.class) @JsonTypeName("AzureFileStorage") @JsonFlatten public class AzureFileStorageLinkedService extends LinkedServiceInner { /** * Host name of the server. Type: string (or Expression with resultType * string). */ @JsonProperty(value = "typeProperties.host") private Object host; /** * User ID to logon the server. Type: string (or Expression with resultType * string). */ @JsonProperty(value = "typeProperties.userId") private Object userId; /** * Password to logon the server. */ @JsonProperty(value = "typeProperties.password") private SecretBase password; /** * The connection string. It is mutually exclusive with sasUri property. * Type: string, SecureString or AzureKeyVaultSecretReference. */ @JsonProperty(value = "typeProperties.connectionString") private Object connectionString; /** * The Azure key vault secret reference of accountKey in connection string. */ @JsonProperty(value = "typeProperties.accountKey") private AzureKeyVaultSecretReference accountKey; /** * SAS URI of the Azure File resource. It is mutually exclusive with * connectionString property. Type: string, SecureString or * AzureKeyVaultSecretReference. */ @JsonProperty(value = "typeProperties.sasUri") private Object sasUri; /** * The Azure key vault secret reference of sasToken in sas uri. */ @JsonProperty(value = "typeProperties.sasToken") private AzureKeyVaultSecretReference sasToken; /** * The azure file share name. It is required when auth with * accountKey/sasToken. Type: string (or Expression with resultType * string). */ @JsonProperty(value = "typeProperties.fileShare") private Object fileShare; /** * The encrypted credential used for authentication. Credentials are * encrypted using the integration runtime credential manager. Type: string * (or Expression with resultType string). */ @JsonProperty(value = "typeProperties.encryptedCredential") private Object encryptedCredential; /** * Get host name of the server. Type: string (or Expression with resultType string). * * @return the host value */ public Object host() { return this.host; } /** * Set host name of the server. Type: string (or Expression with resultType string). * * @param host the host value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withHost(Object host) { this.host = host; return this; } /** * Get user ID to logon the server. Type: string (or Expression with resultType string). * * @return the userId value */ public Object userId() { return this.userId; } /** * Set user ID to logon the server. Type: string (or Expression with resultType string). * * @param userId the userId value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withUserId(Object userId) { this.userId = userId; return this; } /** * Get password to logon the server. * * @return the password value */ public SecretBase password() { return this.password; } /** * Set password to logon the server. * * @param password the password value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withPassword(SecretBase password) { this.password = password; return this; } /** * Get the connection string. It is mutually exclusive with sasUri property. Type: string, SecureString or AzureKeyVaultSecretReference. * * @return the connectionString value */ public Object connectionString() { return this.connectionString; } /** * Set the connection string. It is mutually exclusive with sasUri property. Type: string, SecureString or AzureKeyVaultSecretReference. * * @param connectionString the connectionString value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withConnectionString(Object connectionString) { this.connectionString = connectionString; return this; } /** * Get the Azure key vault secret reference of accountKey in connection string. * * @return the accountKey value */ public AzureKeyVaultSecretReference accountKey() { return this.accountKey; } /** * Set the Azure key vault secret reference of accountKey in connection string. * * @param accountKey the accountKey value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withAccountKey(AzureKeyVaultSecretReference accountKey) { this.accountKey = accountKey; return this; } /** * Get sAS URI of the Azure File resource. It is mutually exclusive with connectionString property. Type: string, SecureString or AzureKeyVaultSecretReference. * * @return the sasUri value */ public Object sasUri() { return this.sasUri; } /** * Set sAS URI of the Azure File resource. It is mutually exclusive with connectionString property. Type: string, SecureString or AzureKeyVaultSecretReference. * * @param sasUri the sasUri value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withSasUri(Object sasUri) { this.sasUri = sasUri; return this; } /** * Get the Azure key vault secret reference of sasToken in sas uri. * * @return the sasToken value */ public AzureKeyVaultSecretReference sasToken() { return this.sasToken; } /** * Set the Azure key vault secret reference of sasToken in sas uri. * * @param sasToken the sasToken value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withSasToken(AzureKeyVaultSecretReference sasToken) { this.sasToken = sasToken; return this; } /** * Get the azure file share name. It is required when auth with accountKey/sasToken. Type: string (or Expression with resultType string). * * @return the fileShare value */ public Object fileShare() { return this.fileShare; } /** * Set the azure file share name. It is required when auth with accountKey/sasToken. Type: string (or Expression with resultType string). * * @param fileShare the fileShare value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withFileShare(Object fileShare) { this.fileShare = fileShare; return this; } /** * Get the encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). * * @return the encryptedCredential value */ public Object encryptedCredential() { return this.encryptedCredential; } /** * Set the encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). * * @param encryptedCredential the encryptedCredential value to set * @return the AzureFileStorageLinkedService object itself. */ public AzureFileStorageLinkedService withEncryptedCredential(Object encryptedCredential) { this.encryptedCredential = encryptedCredential; return this; } } src/main/java/com/langel/lavcache/inject/SectorInterceptor.java package com.langel.lavcache.inject; import com.langel.lavcache.annotation.Erase; import com.langel.lavcache.annotation.Piece; import com.langel.lavcache.invoker.EraseInvoker; import com.langel.lavcache.invoker.Invocation; import com.langel.lavcache.invoker.PieceInvoker; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Optional; /** * @author L-Angel,Rick() * @date 2018/9/25 **/ public class SectorInterceptor implements MethodInterceptor { private final PieceInvoker pieceInvoker = new PieceInvoker(); private final EraseInvoker eraseInvoker = new EraseInvoker(); @Override public Object invoke(MethodInvocation invocation) throws Throwable { Method m = invocation.getMethod(); Invocation iv = Invocation.Builder.build(invocation.getArguments(), m, invocation); Optional anno = lavOp(m.getAnnotations()); if (!anno.isPresent()) { return invocation.proceed(); } if (anno.get() instanceof Piece) { return pieceInvoker.invoke(iv); } else if (anno.get() instanceof Erase) { return eraseInvoker.invoke(iv); } return invocation.proceed(); } private Optional lavOp(Annotation[] annos) { for (Annotation anno : annos) { if ((anno instanceof Piece) || (anno instanceof Erase)) { return Optional.of(anno); } } return Optional.empty(); } } sistema-ejb/src/java/be/LetrasPagoCanje.java1-10 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author argos */ @Entity @Table(name = "letras_pago_canje") @XmlRootElement @NamedQueries({ @NamedQuery(name = "LetrasPagoCanje.findAll", query = "SELECT l FROM LetrasPagoCanje l"), @NamedQuery(name = "LetrasPagoCanje.findByIdLetrasPagoCanje", query = "SELECT l FROM LetrasPagoCanje l WHERE l.idLetrasPagoCanje = :idLetrasPagoCanje"), @NamedQuery(name = "LetrasPagoCanje.findByFechaPago", query = "SELECT l FROM LetrasPagoCanje l WHERE l.fechaPago = :fechaPago"), @NamedQuery(name = "LetrasPagoCanje.findByFechaRealizoPago", query = "SELECT l FROM LetrasPagoCanje l WHERE l.fechaRealizoPago = :fechaRealizoPago"), @NamedQuery(name = "LetrasPagoCanje.findByTotalLetra", query = "SELECT l FROM LetrasPagoCanje l WHERE l.totalLetra = :totalLetra"), @NamedQuery(name = "LetrasPagoCanje.findByObservaciones", query = "SELECT l FROM LetrasPagoCanje l WHERE l.observaciones = :observaciones")}) public class LetrasPagoCanje implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id_letras_pago_canje") private Integer idLetrasPagoCanje; @Basic(optional = false) @NotNull @Column(name = "fecha_pago") @Temporal(TemporalType.DATE) private Date fechaPago; @Basic(optional = false) @NotNull @Column(name = "fecha_realizo_pago") @Temporal(TemporalType.DATE) private Date fechaRealizoPago; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Basic(optional = false) @NotNull @Column(name = "total_letra") private BigDecimal totalLetra; @Basic(optional = false) @NotNull @Size(min = 0, max = 300) @Column(name = "observaciones") private String observaciones; @JoinColumn(name = "id_estado_letras_pago_canje", referencedColumnName = "id_estado_letras_pago_canje") @ManyToOne(fetch = FetchType.LAZY) private EstadoLetrasPagoCanje estadoLetrasPagoCanje; @JoinColumn(name = "id_canje_orden_compra", referencedColumnName = "id_canje_orden_compra") @ManyToOne(optional = false, fetch = FetchType.LAZY) private CanjeOrdenCompra canjeOrdenCompra; public LetrasPagoCanje() { } public LetrasPagoCanje(Integer idLetrasPagoCanje) { this.idLetrasPagoCanje = idLetrasPagoCanje; } public LetrasPagoCanje(Integer idLetrasPagoCanje, Date fechaPago, Date fechaRealizoPago, BigDecimal totalLetra, String observaciones) { this.idLetrasPagoCanje = idLetrasPagoCanje; this.fechaPago = fechaPago; this.fechaRealizoPago = fechaRealizoPago; this.totalLetra = totalLetra; this.observaciones = observaciones; } public Integer getIdLetrasPagoCanje() { return idLetrasPagoCanje; } public void setIdLetrasPagoCanje(Integer idLetrasPagoCanje) { this.idLetrasPagoCanje = idLetrasPagoCanje; } public Date getFechaPago() { return fechaPago; } public void setFechaPago(Date fechaPago) { this.fechaPago = fechaPago; } public Date getFechaRealizoPago() { return fechaRealizoPago; } public void setFechaRealizoPago(Date fechaRealizoPago) { this.fechaRealizoPago = fechaRealizoPago; } public BigDecimal getTotalLetra() { return totalLetra; } public void setTotalLetra(BigDecimal totalLetra) { this.totalLetra = totalLetra; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } public EstadoLetrasPagoCanje getEstadoLetrasPagoCanje() { return estadoLetrasPagoCanje; } public void setEstadoLetrasPagoCanje(EstadoLetrasPagoCanje estadoLetrasPagoCanje) { this.estadoLetrasPagoCanje = estadoLetrasPagoCanje; } public CanjeOrdenCompra getCanjeOrdenCompra() { return canjeOrdenCompra; } public void setCanjeOrdenCompra(CanjeOrdenCompra canjeOrdenCompra) { this.canjeOrdenCompra = canjeOrdenCompra; } @Override public int hashCode() { int hash = 0; hash += (idLetrasPagoCanje != null ? idLetrasPagoCanje.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof LetrasPagoCanje)) { return false; } LetrasPagoCanje other = (LetrasPagoCanje) object; if ((this.idLetrasPagoCanje == null && other.idLetrasPagoCanje != null) || (this.idLetrasPagoCanje != null && !this.idLetrasPagoCanje.equals(other.idLetrasPagoCanje))) { return false; } return true; } @Override public String toString() { return "be.LetrasPagoCanje[ idLetrasPagoCanje=" + idLetrasPagoCanje + " ]"; } } package myPack; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class MainTest { @Test void testFindSpacedFile() { // fail("Not yet implemented"); } @Test void testFindSpacedFileByRegex() { Main main = new Main(); String res = main.rename("a b"); assertEquals("ab", res); } @Test void testRename() { Main main = new Main(); String res = main.rename("a b"); assertEquals("ab", res); } } /* * Copyright 2013-2021 the original author or authors. * * 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 * * https://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. */ package org.springframework.cloud.sleuth.instrument.web.client.feign; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; import feign.Client; import feign.Feign; import feign.FeignException; import feign.Request; import feign.RequestLine; import feign.RequestTemplate; import feign.Response; import okhttp3.mockwebserver.MockWebServer; import org.assertj.core.api.Assertions; import org.assertj.core.api.BDDAssertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.BDDMockito; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.BeanFactory; import org.springframework.cloud.sleuth.CurrentTraceContext; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.http.HttpClientHandler; import org.springframework.cloud.sleuth.test.TestTracingAwareSupplier; /** * @author */ @ExtendWith(MockitoExtension.class) public abstract class FeignRetriesTests implements TestTracingAwareSupplier { public final MockWebServer server = new MockWebServer(); @BeforeEach void before() throws IOException { this.server.start(); } @AfterEach void after() throws IOException { this.server.close(); } @Mock(lenient = true) BeanFactory beanFactory; @BeforeEach @AfterEach public void setup() { BDDMockito.given(this.beanFactory.getBean(CurrentTraceContext.class)) .willReturn(tracerTest().tracing().currentTraceContext()); BDDMockito.given(this.beanFactory.getBean(HttpClientHandler.class)) .willReturn(tracerTest().tracing().httpClientHandler()); } @Test public void testRetriedWhenExceededNumberOfRetries() { Client client = (request, options) -> { throw new IOException(); }; String url = "http://localhost:" + this.server.getPort(); TestInterface api = Feign.builder().client(new TracingFeignClient(tracerTest().tracing().currentTraceContext(), tracerTest().tracing().httpClientHandler(), client)).target(TestInterface.class, url); try { api.decodedPost(); Assertions.failBecauseExceptionWasNotThrown(FeignException.class); } catch (FeignException e) { } } @Test public void testRetriedWhenRequestEventuallyIsSent() { String url = "http://localhost:" + this.server.getPort(); final AtomicInteger atomicInteger = new AtomicInteger(); // Client to simulate a retry scenario final Client client = (request, options) -> { // we simulate an exception only for the first request if (atomicInteger.get() == 1) { throw new IOException(); } else { // with the second retry (first retry) we send back good result return Response.builder().status(200).reason("OK").headers(new HashMap<>()) .body("OK", Charset.defaultCharset()).request(Request.create(Request.HttpMethod.POST, "/foo", new HashMap<>(), Request.Body.empty(), new RequestTemplate())) .build(); } }; TestInterface api = Feign.builder().client(new TracingFeignClient(tracerTest().tracing().currentTraceContext(), tracerTest().tracing().httpClientHandler(), (request, options) -> { atomicInteger.incrementAndGet(); return client.execute(request, options); })).target(TestInterface.class, url); BDDAssertions.then(api.decodedPost()).isEqualTo("OK"); // request interception should take place only twice (1st request & 2nd retry) BDDAssertions.then(atomicInteger.get()).isEqualTo(2); assertException(); BDDAssertions.then(tracerTest().handler().reportedSpans().get(1).getKind()).isEqualTo(Span.Kind.CLIENT); } public void assertException() { throw new UnsupportedOperationException("Implement this assertion"); } interface TestInterface { @RequestLine("POST /") String decodedPost(); } } 1-10 package android.lorenwang.tools.bean; import android.provider.Telephony; /** * 功能作用:手机短消息实体 * 创建时间:2019-11-28 下午 15:22:35 * 创建人:王亮() * 思路: * 方法: * 注意: * 修改人: * 修改时间: * 备注: * {@link Telephony.TextBasedSmsColumns.TYPE}, * * {@link Telephony.TextBasedSmsColumns.ADDRESS}, * * {@link Telephony.TextBasedSmsColumns.DATE}, * * {@link Telephony.TextBasedSmsColumns.DATE_SENT}, * * {@link Telephony.TextBasedSmsColumns.READ}, * * {@link Telephony.TextBasedSmsColumns.STATUS}, * * {@link Telephony.TextBasedSmsColumns.SUBJECT}, * * {@link Telephony.TextBasedSmsColumns.BODY}, * * {@link Telephony.TextBasedSmsColumns.Per≥}, */ public class AtlwMobileSmsInfoBean { /** * 短信类型 */ private Integer type; /** * 短信发送方地址 */ private String sendAddress; /** * 短信接收时间 */ private Long receiveDate; /** * 短信发送时间 */ private Long sendDate; /** * 短信阅读状态,是否已读 */ private Boolean readStatus; /** * 短信短信主题,可能为空 */ private String subject; /** * 短信内容 */ private String body; /** * 短信发送方id,如果存在的话 * reference to item in {@code content://contacts/people} */ private Long personId; public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getSendAddress() { return sendAddress; } public void setSendAddress(String sendAddress) { this.sendAddress = sendAddress; } public Long getReceiveDate() { return receiveDate; } public void setReceiveDate(Long receiveDate) { this.receiveDate = receiveDate; } public Long getSendDate() { return sendDate; } public void setSendDate(Long sendDate) { this.sendDate = sendDate; } public Boolean getReadStatus() { return readStatus; } public void setReadStatus(Boolean readStatus) { this.readStatus = readStatus; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Long getPersonId() { return personId; } public void setPersonId(Long personId) { this.personId = personId; } } package zuojinjie.src.class13; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class Code03_lowestAncestor { public static class Node { public int value; public Node left; public Node right; public Node(int data) { this.value = data; } } public static Node lowestAncestor1(Node head, Node o1, Node o2) { if (head == null) { return null; } // key的父节点是value HashMap parentMap = new HashMap<>(); parentMap.put(head, null); fillParentMap(head, parentMap); HashSet o1Set = new HashSet<>(); Node cur = o1; o1Set.add(cur); while (parentMap.get(cur) != null) { cur = parentMap.get(cur); o1Set.add(cur); } cur = o2; while (!o1Set.contains(cur)) { cur = parentMap.get(cur); } return cur; } public static void fillParentMap(Node head, HashMap parentMap) { if (head.left != null) { parentMap.put(head.left, head); fillParentMap(head.left, parentMap); } if (head.right != null) { parentMap.put(head.right, head); fillParentMap(head.right, parentMap); } } public static Node lowestAncestor2(Node head, Node a, Node b) { return process(head, a, b).ans; } public static class Info { public boolean findA; public boolean findB; public Node ans; public Info(boolean fA, boolean fB, Node an) { findA = fA; findB = fB; ans = an; } } public static Info process(Node x, Node a, Node b) { if (x == null) { return new Info(false, false, null); } Info leftInfo = process(x.left, a, b); Info rightInfo = process(x.right, a, b); boolean findA = (x == a) || leftInfo.findA || rightInfo.findA; boolean findB = (x == b) || leftInfo.findB || rightInfo.findB; Node ans = null; if (leftInfo.ans != null) { ans = leftInfo.ans; } else if (rightInfo.ans != null) { ans = rightInfo.ans; } else { if (findA && findB) { ans = x; } } return new Info(findA, findB, ans); } // for test public static Node generateRandomBST(int maxLevel, int maxValue) { return generate(1, maxLevel, maxValue); } // for test public static Node generate(int level, int maxLevel, int maxValue) { if (level > maxLevel || Math.random() < 0.5) { return null; } Node head = new Node((int) (Math.random() * maxValue)); head.left = generate(level + 1, maxLevel, maxValue); head.right = generate(level + 1, maxLevel, maxValue); return head; } // for test public static Node pickRandomOne(Node head) { if (head == null) { return null; } ArrayList arr = new ArrayList<>(); fillPrelist(head, arr); int randomIndex = (int) (Math.random() * arr.size()); return arr.get(randomIndex); } // for test public static void fillPrelist(Node head, ArrayList arr) { if (head == null) { return; } arr.add(head); fillPrelist(head.left, arr); fillPrelist(head.right, arr); } public static void main(String[] args) { int maxLevel = 4; int maxValue = 100; int testTimes = 1000000; for (int i = 0; i < testTimes; i++) { Node head = generateRandomBST(maxLevel, maxValue); Node o1 = pickRandomOne(head); Node o2 = pickRandomOne(head); if (lowestAncestor1(head, o1, o2) != lowestAncestor2(head, o1, o2)) { System.out.println("Oops!"); } } System.out.println("finish!"); } } /* * 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. */ /* 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. */ package org.camunda.bpm.engine.impl.cmd; import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull; import java.io.Serializable; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.impl.cfg.CommandChecker; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.interceptor.Command; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.persistence.deploy.DeploymentCache; import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.camunda.bpm.model.bpmn.BpmnModelInstance; /** * Gives access to a deploy BPMN model instance which can be accessed by * the BPMN model API. * * @author */ public class GetDeploymentBpmnModelInstanceCmd implements Command, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; public GetDeploymentBpmnModelInstanceCmd(String processDefinitionId) { if (processDefinitionId == null || processDefinitionId.length() < 1) { throw new ProcessEngineException("The process definition id is mandatory, but '" + processDefinitionId + "' has been provided."); } this.processDefinitionId = processDefinitionId; } public BpmnModelInstance execute(CommandContext commandContext) { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); final DeploymentCache deploymentCache = configuration.getDeploymentCache(); ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadProcessDefinition(processDefinition); } BpmnModelInstance modelInstance = deploymentCache.findBpmnModelInstanceForProcessDefinition(processDefinitionId); ensureNotNull("no BPMN model instance found for process definition id " + processDefinitionId, "modelInstance", modelInstance); return modelInstance; } } /* * Copyright 2016 SRI International * * 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. */ package com.sri.pal.stress; import com.sri.pal.util.PALTestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This test uses release/renew to drop the network interface * while running the stress test. To call this test by itself: * "ant extra-tests -Dtest.prefix="NetworkStress" * @author Josh */ public class NetworkStress_ExtraFuncTest extends PALTestCase { private static final Logger log = LoggerFactory .getLogger("TestSourceLogger"); @BeforeClass public static void start() throws Exception { log.info("Starting PAL Bridge"); Stress_FuncTest.start(); } /* * Because this test does funny things with the network interfaces, it's * disabled by default. */ @Test(enabled = false) public void stress() throws Exception { // Spawn a new thread to kill the network interface new DropNetworkThread().start(); log.info("Calling the stress test"); Stress_FuncTest stressTester = new Stress_FuncTest(); stressTester.stress(); } }UranusBlockStack/ovirt-engine package org.ovirt.engine.core.common.businessentities; import org.ovirt.engine.core.compat.Guid; import java.io.Serializable; public class QuotaUsagePerUser extends IVdcQueryable implements Serializable { private Guid quotaId; private String quotaName; private double storageLimit; private double storageTotalUsage; private double storageUsageForUserGB; private int vcpuLimit; private int vcpuTotalUsage; private int vcpuUsageForUser; private long memoryLimit; private long memoryTotalUsage; private long memoryUsageForUser; public QuotaUsagePerUser(){ } public QuotaUsagePerUser(Guid quotaId, String quotaName, double storageLimit, double storageTotalUsage, int vcpuLimit, int vcpuTotalUsage, long memoryLimit, long memoryTotalUsage) { this.quotaId = quotaId; this.quotaName = quotaName; this.storageLimit = storageLimit; this.storageTotalUsage = storageTotalUsage; this.vcpuLimit = vcpuLimit; this.vcpuTotalUsage = vcpuTotalUsage; this.memoryLimit = memoryLimit; this.memoryTotalUsage = memoryTotalUsage; } public double getStorageUsageForUser() { return storageUsageForUserGB; } public void setStorageUsageForUser(double storageUsageForUserGB) { this.storageUsageForUserGB = storageUsageForUserGB; } public int getVcpuUsageForUser() { return vcpuUsageForUser; } public void setVcpuUsageForUser(int vcpuUsageForUser) { this.vcpuUsageForUser = vcpuUsageForUser; } public long getMemoryUsageForUser() { return memoryUsageForUser; } public void setMemoryUsageForUser(long memoryUsageForUser) { this.memoryUsageForUser = memoryUsageForUser; } public Guid getQuotaId() { return quotaId; } public double getStorageLimit() { return storageLimit; } public double getStorageTotalUsage() { return storageTotalUsage; } public int getVcpuLimit() { return vcpuLimit; } public int getVcpuTotalUsage() { return vcpuTotalUsage; } public long getMemoryLimit() { return memoryLimit; } public long getMemoryTotalUsage() { return memoryTotalUsage; } public double getUserStorageUsagePercentage() { return storageUsageForUserGB*100/storageLimit; } public double getUserVcpuUsagePercentage() { return (double)vcpuUsageForUser*100/vcpuLimit; } public double getUserMemoryUsagePercentage() { return (double)memoryUsageForUser*100/memoryLimit; } public double getOthersStorageUsagePercentage() { return (storageTotalUsage-storageUsageForUserGB)*100/storageLimit; } public double getOthersVcpuUsagePercentage() { return (double)(vcpuTotalUsage-vcpuUsageForUser)*100/vcpuLimit; } public double getOthersMemoryUsagePercentage() { return (double)(memoryTotalUsage-memoryUsageForUser)*100/memoryLimit; } public int getFreeVcpu() { return vcpuLimit-vcpuTotalUsage; } public long getFreeMemory() { return memoryLimit-memoryTotalUsage; } public double getFreeStorage() { return storageLimit-storageTotalUsage; } @Override public Object getQueryableId() { return getQuotaId(); } public String getQuotaName() { return quotaName; } public void setStorageLimit(double storageLimit) { this.storageLimit = storageLimit; } public void setStorageTotalUsage(double storageTotalUsage) { this.storageTotalUsage = storageTotalUsage; } public void setVcpuLimit(int vcpuLimit) { this.vcpuLimit = vcpuLimit; } public void setVcpuTotalUsage(int vcpuTotalUsage) { this.vcpuTotalUsage = vcpuTotalUsage; } public void setMemoryLimit(long memoryLimit) { this.memoryLimit = memoryLimit; } public void setMemoryTotalUsage(long memoryTotalUsage) { this.memoryTotalUsage = memoryTotalUsage; } public boolean isUnlimitedVcpu() { return vcpuLimit == QuotaVdsGroup.UNLIMITED_VCPU; } public boolean isUnlimitedMemory() { return memoryLimit == QuotaVdsGroup.UNLIMITED_MEM; } public boolean isUnlimitedStorage() { return storageLimit == QuotaStorage.UNLIMITED; } } fd-engine/src/main/java/org/flockdata/engine/concept/service/TxService.java1-10 /* * * Copyright (c) 2012-2017 "FlockData LLC" * * This file is part of FlockData. * * FlockData 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 3 of the License, or * (at your option) any later version. * * FlockData 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 FlockData. If not, see . */ package org.flockdata.engine.concept.service; import java.util.Map; import java.util.Set; import org.flockdata.authentication.SecurityHelper; import org.flockdata.authentication.SystemUserService; import org.flockdata.data.SystemUser; import org.flockdata.data.TxRef; import org.flockdata.engine.data.dao.EntityDaoNeo; import org.flockdata.engine.data.graph.CompanyNode; import org.flockdata.engine.data.graph.EntityNode; import org.flockdata.integration.KeyGenService; import org.flockdata.track.bean.ContentInputBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author mholdsworth * @since 4/09/2014 */ @Service @Transactional public class TxService { @Autowired SystemUserService sysUserService; @Autowired EntityDaoNeo trackDao; @Autowired private KeyGenService keyGenService; @Autowired private SecurityHelper securityHelper; TxRef beginTransaction(CompanyNode company) { return beginTransaction(keyGenService.getUniqueKey(), company); } TxRef beginTransaction(String id, CompanyNode company) { return trackDao.beginTransaction(id, company); } public Map findByTXRef(String txRef) { TxRef tx = findTx(txRef); return (tx == null ? null : trackDao.findByTransaction(tx)); } public TxRef handleTxRef(ContentInputBean input, CompanyNode company) { TxRef txRef = null; if (input.isTransactional()) { if (input.getTxRef() == null) { txRef = beginTransaction(company); input.setTxRef(txRef.getName()); } else { txRef = beginTransaction(input.getTxRef(), company); } } return txRef; } public TxRef findTx(String txRef) { return findTx(txRef, false); } TxRef findTx(String txRef, boolean fetchHeaders) { String userName = securityHelper.getLoggedInUser(); SystemUser su = sysUserService.findByLogin(userName); if (su == null) { throw new SecurityException("Not authorised"); } TxRef tx = trackDao.findTxTag(txRef, su.getCompany()); if (tx == null) { return null; } return tx; } public Set findTxEntities(String txName) { TxRef txRef = findTx(txName); if (txRef == null) { return null; } return trackDao.findEntitiesByTxRef(txRef.getId()); } } package com.lin.clay.emojikeyboard; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.lin.clay.emojikeyboard.adapter.ChatAdapter; import com.lin.clay.emojikeyboard.adapter.EmotionGiftsFragmentAdapter; import com.lin.clay.emojikeyboard.fragment.EmotionFragment; import com.lin.clay.emojikeyboard.fragment.GiftsFragment; import com.lin.clay.emojikeyboard.fragment.OneKeySendFragment; import com.lin.clay.emojikeyboard.model.ChatMsgModel; import com.lin.clay.emojikeyboard.model.IMChatGiftsModel; import com.lin.clay.emojikeyboard.utils.widget.CustomPasteEditText; import com.lin.clay.emojikeyboard.utils.EmotionKeyboard; import com.lin.clay.emojikeyboard.utils.GlobalOnItemClickManagerUtils; import com.lin.clay.emojikeyboard.utils.widget.NoHorizontalScrollerViewPager; import com.lin.clay.emojikeyboard.utils.ToastUtils; import com.lin.clay.emojikeyboard.utils.Utils; import com.lin.clay.statusbarutils.StatusBarUtil; import com.opensource.svgaplayer.SVGACallback; import com.opensource.svgaplayer.SVGAImageView; import com.opensource.svgaplayer.SVGAParser; import com.opensource.svgaplayer.SVGAVideoEntity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { @BindView(R.id.ibBackChat) ImageButton ibBackChat; @BindView(R.id.tv_nikeName) TextView tvNikeName; @BindView(R.id.rv_matchMsg) RecyclerView rvMatchMsg; @BindView(R.id.edit_chatMsg) CustomPasteEditText editChatMsg; @BindView(R.id.ll_chatMsg) LinearLayout llChatMsg; @BindView(R.id.img_emoji) ImageView imgEmoji; @BindView(R.id.tv_send) TextView tvSend; @BindView(R.id.img_oneKeySend) ImageView imgOneKeySend; @BindView(R.id.rl_oneKeySend) RelativeLayout rlOneKeySend; @BindView(R.id.img_giftCommon) ImageView imgGiftCommon; @BindView(R.id.rl_giftCommon) RelativeLayout rlGiftCommon; @BindView(R.id.ll_moreOperate) LinearLayout llMoreOperate; @BindView(R.id.ll_chatControl) LinearLayout llChatControl; @BindView(R.id.vp_emotionGifts) NoHorizontalScrollerViewPager vpEmotionGifts; @BindView(R.id.ll_emotionGifts) LinearLayout llEmotionGifts; @BindView(R.id.rl_root) RelativeLayout rlRoot; @BindView(R.id.svga_gift) SVGAImageView svgaGift; private static Handler mHandler = new Handler(); private ArrayList mSvgaList = new ArrayList(); private ArrayList mChatMsgList = new ArrayList<>(); private ChatAdapter mChatAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initData(); initKEG(); } private void initData() { StatusBarUtil.setSocialityStatusBar(this); ButterKnife.bind(this); Utils.init(this); svgaGift.setCallback(new SVGACallback() { @Override public void onPause() { } @Override public void onFinished() { svgaGift.setVisibility(View.GONE); } @Override public void onRepeat() { } @Override public void onStep(int i, double v) { } }); initRecyclerViewData(); tvSend.setOnTouchListener(Utils.getTouchBackListener(0.8f)); } private void initRecyclerViewData() { for (int i = 0; i < 2; i++) { ChatMsgModel chatMsgModel = new ChatMsgModel(); if (i == 0) { chatMsgModel.msgType = ChatMsgModel.TEXT_MSG_TYPE; chatMsgModel.text = "Hello World!"; chatMsgModel.isSend = true; } else { chatMsgModel.msgType = ChatMsgModel.GIFT_MSG_TYPE; chatMsgModel.giftIconId = R.drawable.gift_car_v1; chatMsgModel.giftTitle = "car_1"; chatMsgModel.strSvga = "posche.svga"; chatMsgModel.isSend = true; } mChatMsgList.add(chatMsgModel); } mChatAdapter = new ChatAdapter(this, mChatMsgList); rvMatchMsg.setLayoutManager(new LinearLayoutManager(this)); rvMatchMsg.setAdapter(mChatAdapter); mChatAdapter.setmOnGiftClickPlayListener(new ChatAdapter.OnGiftClickPlayListener() { @Override public void giftClick(String strSvga) { loadAnimation(strSvga); } }); rvMatchMsg.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if(!isInterceptBackPress()) { Utils.hideInput(MainActivity.this); } return false; } }); } //表情面板 private EmotionKeyboard mEmotionKeyboard; List emotionFragments = new ArrayList<>(); private GlobalOnItemClickManagerUtils GlobalOnItemClickManager; //表情和编辑框的绑定 private void initKEG() { mEmotionKeyboard = EmotionKeyboard.with(this) .setEmotionView(llEmotionGifts)//绑定表情面板 .setEmotionGiftsView(vpEmotionGifts)//绑定礼物表情选择 .bindToContent(rvMatchMsg)//绑定内容view .bindToEditText(editChatMsg)//判断绑定那种EditView .bindToEmotionButton(imgEmoji)//绑定表情按钮 .bindToGiftsButton(rlGiftCommon)//绑定礼物按钮 .bindToOneKeySendButton(rlOneKeySend)//u定一键发送按钮 .bindToChatControl(llChatControl) //绑定整个底部表情礼物布局 .bindKeyboardListener() //绑定键盘弹出隐藏监听 .build(); //创建全局监听 GlobalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(this); GlobalOnItemClickManager.attachToEditText(editChatMsg); emotionFragments.add(new EmotionFragment()); emotionFragments.add(new GiftsFragment()); emotionFragments.add(new OneKeySendFragment()); vpEmotionGifts.setAdapter(new EmotionGiftsFragmentAdapter(getSupportFragmentManager(), emotionFragments)); //设置缓存View的个数 vpEmotionGifts.setOffscreenPageLimit(emotionFragments.size() - 1); } @Override protected void onDestroy() { super.onDestroy(); if (GlobalOnItemClickManager != null) { GlobalOnItemClickManager.onDestrouGlobalOnItemClickManager(); } } /** * 聊天列表滚动到底部 * * @param delay */ public void chatListScroolDelay(int delay) { mHandler.postDelayed(new Runnable() { @Override public void run() { rvMatchMsg.smoothScrollToPosition(mChatMsgList.size()); } }, delay); } @Override public void onBackPressed() { /** * 判断是否拦截返回键操作 */ if (!isInterceptBackPress()) { super.onBackPressed(); } } /** * 是否拦截返回键操作,如果此时表情布局未隐藏,先隐藏表情布局 * * @return true则隐藏表情布局,拦截返回键操作 * false 则不拦截返回键操作 */ public boolean isInterceptBackPress() { return mEmotionKeyboard.interceptBackPress(); } /** * 模拟从服务器加载礼物信息 */ public void loadChatGifts() { ArrayList data = new ArrayList<>(); for (int i = 0; i < 2; i++) { IMChatGiftsModel imChatGiftsModel = new IMChatGiftsModel(); imChatGiftsModel.id = i; if (i == 0) { imChatGiftsModel.iconId = R.drawable.gift_car_home; } else { imChatGiftsModel.iconId = R.drawable.gift_other_home; } ArrayList items = new ArrayList<>(); for (int j = 0; j < 9; j++) { IMChatGiftsModel.GiftDetail giftDetail = new IMChatGiftsModel.GiftDetail(); giftDetail.id = String.valueOf((1000 + j)); if (i == 0) { giftDetail.title = "car_" + (j + 1); giftDetail.coverImgId = getResources().getIdentifier("gift_car_v" + (j + 1), "drawable", getPackageName()); giftDetail.scene = "汽车"; giftDetail.strSvga = "posche.svga"; } else { giftDetail.title = "other_" + (j + 1); giftDetail.coverImgId = getResources().getIdentifier("gift_other_v" + (j + 1), "drawable", getPackageName()); giftDetail.scene = "其它"; giftDetail.strSvga = randomSvga(); } giftDetail.price = (int) (Math.random() * 1000); items.add(giftDetail); } imChatGiftsModel.items = items; data.add(imChatGiftsModel); } loadIMChatGiftsSuccess(data); } private String randomSvga() { if (mSvgaList.size() == 0) { mSvgaList.add("angel.svga"); mSvgaList.add("alarm.svga"); mSvgaList.add("EmptyState.svga"); mSvgaList.add("heartbeat.svga"); mSvgaList.add("rose_1.5.0.svga"); mSvgaList.add("rose_2.0.0.svga"); mSvgaList.add("test.svga"); mSvgaList.add("test2.svga"); } return mSvgaList.get((int) Math.floor(Math.random() * mSvgaList.size())); } /** * 将礼物对象提交给fragment * * @param data */ private void loadIMChatGiftsSuccess(ArrayList data) { List fragments = getSupportFragmentManager().getFragments(); if (fragments != null) { for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); if (fragment instanceof GiftsFragment) { GiftsFragment giftsFragment = (GiftsFragment) fragment; giftsFragment.loadIMChatGiftsSuccess(data); } } } } /** * 赠送礼物 * * @param checkGifts */ public void gradualGifts(IMChatGiftsModel.GiftDetail checkGifts) { loadAnimation(checkGifts.strSvga); ChatMsgModel chatMsgModel = new ChatMsgModel(); chatMsgModel.msgType = ChatMsgModel.GIFT_MSG_TYPE; chatMsgModel.giftIconId = checkGifts.coverImgId; chatMsgModel.giftTitle = checkGifts.title; chatMsgModel.strSvga = checkGifts.strSvga; chatMsgModel.isSend = true; mChatMsgList.add(chatMsgModel); mChatAdapter.notifyItemInserted(mChatMsgList.size() - 1); chatListScroolDelay(100); } /** * 发送一键发送消息 * * @param oneKeyMsg */ public void sendOneKeyMsg(String oneKeyMsg) { ChatMsgModel chatMsgModel = new ChatMsgModel(); chatMsgModel.isSend = true; chatMsgModel.text = KeyMsg; mChatMsgList.add(chatMsgModel); mChatAdapter.notifyItemInserted(mChatMsgList.size() - 1); chatListScroolDelay(100); } /** * 长按播放礼物 * * @param giftId * @param title * @param strSvga */ public void playFrameGift(String giftId, String title, String strSvga) { loadAnimation(strSvga); } private void loadAnimation(String strSvga) { SVGAParser parser = new SVGAParser(this); parser.parse(strSvga, new SVGAParser.ParseCompletion() { @Override public void onComplete(@NotNull SVGAVideoEntity videoItem) { svgaGift.setVisibility(View.VISIBLE); svgaGift.setVideoItem(videoItem); svgaGift.setLoops(1); svgaGift.startAnimation(); } @Override public void onError() { } }); } @OnClick({R.id.ibBackChat, R.id.svga_gift, R.id.tv_send}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.ibBackChat: onBackPressed(); break; case R.id.svga_gift: svgaGift.stopAnimation(); break; case R.id.tv_send: sendTextMsg(); break; } } private void sendTextMsg() { String textMsg = editChatMsg.getText().toString(); if (TextUtils.isEmpty(textMsg)) { ToastUtils.showToast(this, "请先输入消息内容", Toast.LENGTH_SHORT, ToastUtils.DEFEAT); return; } editChatMsg.setText(""); ChatMsgModel chatMsgModel = new ChatMsgModel(); chatMsgModel.isSend = true; chatMsgModel.text = textMsg; mChatMsgList.add(chatMsgModel); mChatAdapter.notifyItemInserted(mChatMsgList.size() - 1); chatListScroolDelay(100); } } 0 begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|type operator|. name|DataTypePhysicalVariation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|AcidUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|HiveStorageHandler import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|Table import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|VirtualColumn import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|optimizer operator|. name|signature operator|. name|Signature import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|TableSample import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|BaseWork operator|. name|BaseExplainVectorization import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|Explain operator|. name|Level import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|Explain operator|. name|Vectorization import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|serde operator|. name|serdeConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|serde2 operator|. name|typeinfo operator|. name|TypeInfo import|; end_import begin_import import|import name|java operator|. name|io operator|. name|Serializable import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|BitSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Objects import|; end_import begin_comment comment|/** * Table Scan Descriptor Currently, data is only read from a base source as part * of map-reduce framework. So, nothing is stored in the descriptor. But, more * things will be added here as table scan is invoked as part of local work. **/ end_comment begin_class annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"TableScan" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|USER block|, name|Level operator|. name|DEFAULT block|, name|Level operator|. name|EXTENDED block|} argument_list|) specifier|public class|class name|TableScanDesc extends|extends name|AbstractOperatorDesc implements|implements name|IStatsGatherDesc block|{ specifier|private specifier|static specifier|final name|long name|serialVersionUID init|= literal|1L decl_stmt|; specifier|private name|String name|alias decl_stmt|; specifier|private name|List argument_list|< name|VirtualColumn argument_list|> name|virtualCols decl_stmt|; specifier|private name|String name|statsAggKeyPrefix decl_stmt|; comment|// stats publishing/aggregating key prefix comment|/** * A list of the partition columns of the table. * Set by the semantic analyzer only in case of the analyze command. */ specifier|private name|List argument_list|< name|String argument_list|> name|partColumns decl_stmt|; comment|/** * Used for split sampling (row count per split) * For example, * select count(1) from ss_src2 tablesample (10 ROWS) s; * provides first 10 rows from all input splits */ specifier|private name|int name|rowLimit init|= operator|- literal|1 decl_stmt|; comment|/** * A boolean variable set to true by the semantic analyzer only in case of the analyze command. * */ specifier|private name|boolean name|gatherStats decl_stmt|; specifier|private name|boolean name|statsReliable decl_stmt|; specifier|private name|String name|tmpStatsDir decl_stmt|; specifier|private name|ExprNodeGenericFuncDesc name|filterExpr decl_stmt|; specifier|private name|Serializable name|filterObject decl_stmt|; specifier|private name|String name|serializedFilterExpr decl_stmt|; specifier|private name|String name|serializedFilterObject decl_stmt|; comment|// Both neededColumnIDs and neededColumns should never be null. comment|// When neededColumnIDs is an empty list, comment|// it means no needed column (e.g. we do not need any column to evaluate comment|// SELECT count(*) FROM t). specifier|private name|List argument_list|< name|Integer argument_list|> name|neededColumnIDs decl_stmt|; specifier|private name|List argument_list|< name|String argument_list|> name|neededColumns decl_stmt|; specifier|private name|List argument_list|< name|String argument_list|> name|neededNestedColumnPaths decl_stmt|; comment|// all column names referenced including virtual columns. used in ColumnAccessAnalyzer specifier|private specifier|transient name|List argument_list|< name|String argument_list|> name|referencedColumns decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILTER_EXPR_CONF_STR init|= literal|"hive.io.filter.expr.serialized" decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILTER_TEXT_CONF_STR init|= literal|"hive.io.filter.text" decl_stmt|; specifier|public specifier|static specifier|final name|String name|FILTER_OBJECT_CONF_STR init|= literal|"hive.io.filter.object" decl_stmt|; comment|// input file name (big) to bucket number specifier|private name|Map argument_list|< name|String argument_list|, name|Integer argument_list|> name|bucketFileNameMapping decl_stmt|; specifier|private name|String name|dbName init|= literal|null decl_stmt|; specifier|private name|String name|tableName init|= literal|null decl_stmt|; specifier|private name|boolean name|isMetadataOnly init|= literal|false decl_stmt|; specifier|private name|boolean name|isTranscationalTable decl_stmt|; specifier|private name|boolean name|vectorized decl_stmt|; specifier|private name|AcidUtils operator|. name|AcidOperationalProperties name|acidOperationalProperties init|= literal|null decl_stmt|; specifier|private specifier|transient name|TableSample name|tableSample decl_stmt|; specifier|private specifier|transient name|Table name|tableMetadata decl_stmt|; specifier|private name|BitSet name|includedBuckets decl_stmt|; specifier|private name|int name|numBuckets init|= operator|- literal|1 decl_stmt|; specifier|public name|TableScanDesc parameter_list|() block|{ name|this argument_list|( literal|null argument_list|, literal|null argument_list|) expr_stmt|; block|} annotation|@ name|SuppressWarnings argument_list|( literal|"nls" argument_list|) specifier|public name|TableScanDesc parameter_list|( name|Table name|tblMetadata parameter_list|) block|{ name|this argument_list|( literal|null argument_list|, name|tblMetadata argument_list|) expr_stmt|; block|} specifier|public name|TableScanDesc parameter_list|( specifier|final name|String name|alias parameter_list|, name|Table name|tblMetadata parameter_list|) block|{ name|this argument_list|( name|alias argument_list|, literal|null argument_list|, name|tblMetadata argument_list|) expr_stmt|; block|} specifier|public name|TableScanDesc parameter_list|( specifier|final name|String name|alias parameter_list|, name|List argument_list|< name|VirtualColumn argument_list|> name|vcs parameter_list|, name|Table name|tblMetadata parameter_list|) block|{ name|this operator|. name|alias operator|= name|alias expr_stmt|; name|this operator|. name|virtualCols operator|= name|vcs expr_stmt|; name|this operator|. name|tableMetadata operator|= name|tblMetadata expr_stmt|; if|if condition|( name|tblMetadata operator|!= literal|null condition|) block|{ name|dbName operator|= name|tblMetadata operator|. name|getDbName argument_list|() expr_stmt|; name|tableName operator|= name|tblMetadata operator|. name|getTableName argument_list|() expr_stmt|; block|} name|isTranscationalTable operator|= name|AcidUtils operator|. name|isTransactionalTable argument_list|( name|this operator|. name|tableMetadata argument_list|) expr_stmt|; if|if condition|( name|isTranscationalTable condition|) block|{ name|acidOperationalProperties operator|= name|AcidUtils operator|. name|getAcidOperationalProperties argument_list|( name|this operator|. name|tableMetadata argument_list|) expr_stmt|; block|} block|} annotation|@ name|Override specifier|public name|Object name|clone parameter_list|() block|{ name|List argument_list|< name|VirtualColumn argument_list|> name|vcs init|= operator|new name|ArrayList argument_list|< name|VirtualColumn argument_list|> argument_list|( name|getVirtualCols argument_list|() argument_list|) decl_stmt|; return|return operator|new name|TableScanDesc argument_list|( name|getAlias argument_list|() argument_list|, name|vcs argument_list|, name|this operator|. name|tableMetadata argument_list|) return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"alias" argument_list|) specifier|public name|String name|getAlias parameter_list|() block|{ return|return name|alias return|; block|} annotation|@ name|Signature specifier|public name|String name|getPredicateString parameter_list|() block|{ if|if condition|( name|filterExpr operator|== literal|null condition|) block|{ return|return literal|null return|; block|} return|return name|PlanUtils operator|. name|getExprListString argument_list|( name|Arrays operator|. name|asList argument_list|( name|filterExpr argument_list|) argument_list|) return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"table" argument_list|, name|jsonOnly operator|= literal|true argument_list|) specifier|public name|String name|getTableName parameter_list|() block|{ return|return name|this operator|. name|tableName return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"database" argument_list|, name|jsonOnly operator|= literal|true argument_list|) specifier|public name|String name|getDatabaseName parameter_list|() block|{ return|return name|this operator|. name|dbName return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"columns" argument_list|, name|jsonOnly operator|= literal|true argument_list|) specifier|public name|List argument_list|< name|String argument_list|> name|getColumnNamesForExplain parameter_list|() block|{ return|return name|this operator|. name|neededColumns return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"isTempTable" argument_list|, name|jsonOnly operator|= literal|true argument_list|) specifier|public name|boolean name|isTemporary parameter_list|() block|{ return|return name|tableMetadata operator|. name|isTemporary argument_list|() return|; block|} annotation|@ name|Explain argument_list|( name|explainLevels operator|= block|{ name|Level operator|. name|USER block|} argument_list|) specifier|public name|String name|getTbl parameter_list|() block|{ name|StringBuilder name|sb init|= operator|new name|StringBuilder argument_list|() decl_stmt|; name|sb operator|. name|append argument_list|( name|this operator|. name|tableMetadata operator|. name|getCompleteName argument_list|() argument_list|) expr_stmt|; name|sb operator|. name|append argument_list|( literal|"," operator|+ name|alias argument_list|) expr_stmt|; if|if condition|( name|AcidUtils operator|. name|isFullAcidTable argument_list|( name|tableMetadata argument_list|) condition|) block|{ name|sb operator|. name|append argument_list|( literal|", ACID table" argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|isTranscationalTable argument_list|() condition|) block|{ name|sb operator|. name|append argument_list|( literal|", transactional table" argument_list|) expr_stmt|; block|} name|sb operator|. name|append argument_list|( literal|",Tbl:" argument_list|) expr_stmt|; name|sb operator|. name|append argument_list|( name|this operator|. name|statistics operator|. name|getBasicStatsState argument_list|() argument_list|) expr_stmt|; name|sb operator|. name|append argument_list|( literal|",Col:" argument_list|) expr_stmt|; name|sb operator|. name|append argument_list|( name|this operator|. name|statistics operator|. name|getColumnStatsState argument_list|() argument_list|) expr_stmt|; return|return name|sb operator|. name|toString argument_list|() return|; block|} specifier|public name|boolean name|isTranscationalTable parameter_list|() block|{ return|return name|isTranscationalTable return|; block|} specifier|public name|AcidUtils operator|. name|AcidOperationalProperties name|getAcidOperationalProperties parameter_list|() block|{ return|return name|acidOperationalProperties return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"Output" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|USER block|} argument_list|) specifier|public name|List argument_list|< name|String argument_list|> name|getOutputColumnNames parameter_list|() block|{ return|return name|this operator|. name|neededColumns return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"filterExpr" argument_list|) specifier|public name|String name|getFilterExprString parameter_list|() block|{ if|if condition|( name|filterExpr operator|== literal|null condition|) block|{ return|return literal|null return|; block|} return|return name|PlanUtils operator|. name|getExprListString argument_list|( name|Arrays operator|. name|asList argument_list|( name|filterExpr argument_list|) argument_list|) return|; block|} comment|// @Signature // XXX specifier|public name|ExprNodeGenericFuncDesc name|getFilterExpr parameter_list|() block|{ return|return name|filterExpr return|; block|} specifier|public name|void name|setFilterExpr parameter_list|( name|ExprNodeGenericFuncDesc name|filterExpr parameter_list|) block|{ name|this operator|. name|filterExpr operator|= name|filterExpr expr_stmt|; block|} specifier|public name|Serializable name|getFilterObject parameter_list|() block|{ return|return name|filterObject return|; block|} specifier|public name|void name|setFilterObject parameter_list|( name|Serializable name|filterObject parameter_list|) block|{ name|this operator|. name|filterObject operator|= name|filterObject expr_stmt|; block|} specifier|public name|void name|setNeededColumnIDs parameter_list|( name|List argument_list|< name|Integer argument_list|> name|neededColumnIDs parameter_list|) block|{ name|this operator|. name|neededColumnIDs operator|= name|neededColumnIDs expr_stmt|; block|} specifier|public name|List argument_list|< name|Integer argument_list|> name|getNeededColumnIDs parameter_list|() block|{ return|return name|neededColumnIDs return|; block|} specifier|public name|List argument_list|< name|String argument_list|> name|getNeededNestedColumnPaths parameter_list|() block|{ return|return name|neededNestedColumnPaths return|; block|} specifier|public name|void name|setNeededNestedColumnPaths parameter_list|( name|List argument_list|< name|String argument_list|> name|neededNestedColumnPaths parameter_list|) block|{ name|this operator|. name|neededNestedColumnPaths operator|= name|neededNestedColumnPaths expr_stmt|; block|} specifier|public name|void name|setNeededColumns parameter_list|( name|List argument_list|< name|String argument_list|> name|neededColumns parameter_list|) block|{ name|this operator|. name|neededColumns operator|= name|neededColumns expr_stmt|; block|} specifier|public name|List argument_list|< name|String argument_list|> name|getNeededColumns parameter_list|() block|{ return|return name|neededColumns return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"Pruned Column Paths" argument_list|) specifier|public name|List argument_list|< name|String argument_list|> name|getPrunedColumnPaths parameter_list|() block|{ name|List argument_list|< name|String argument_list|> name|result init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; for|for control|( name|String name|p range|: name|neededNestedColumnPaths control|) block|{ if|if condition|( name|p operator|. name|indexOf argument_list|( literal|'.' argument_list|) operator|>= literal|0 condition|) block|{ name|result operator|. name|add argument_list|( name|p argument_list|) expr_stmt|; block|} block|} return|return name|result return|; block|} specifier|public name|void name|setReferencedColumns parameter_list|( name|List argument_list|< name|String argument_list|> name|referencedColumns parameter_list|) block|{ name|this operator|. name|referencedColumns operator|= name|referencedColumns expr_stmt|; block|} specifier|public name|List argument_list|< name|String argument_list|> name|getReferencedColumns parameter_list|() block|{ return|return name|referencedColumns return|; block|} specifier|public name|void name|setAlias parameter_list|( name|String name|alias parameter_list|) block|{ name|this operator|. name|alias operator|= name|alias expr_stmt|; block|} specifier|public name|void name|setPartColumns parameter_list|( name|List argument_list|< name|String argument_list|> name|partColumns parameter_list|) block|{ name|this operator|. name|partColumns operator|= name|partColumns expr_stmt|; block|} specifier|public name|List argument_list|< name|String argument_list|> name|getPartColumns parameter_list|() block|{ return|return name|partColumns return|; block|} specifier|public name|void name|setGatherStats parameter_list|( name|boolean name|gatherStats parameter_list|) block|{ name|this operator|. name|gatherStats operator|= name|gatherStats expr_stmt|; block|} annotation|@ name|Override annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"GatherStats" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|EXTENDED block|} argument_list|) annotation|@ name|Signature specifier|public name|boolean name|isGatherStats parameter_list|() block|{ return|return name|gatherStats return|; block|} annotation|@ name|Override specifier|public name|String name|getTmpStatsDir parameter_list|() block|{ return|return name|tmpStatsDir return|; block|} specifier|public name|void name|setTmpStatsDir parameter_list|( name|String name|tmpStatsDir parameter_list|) block|{ name|this operator|. name|tmpStatsDir operator|= name|tmpStatsDir expr_stmt|; block|} specifier|public name|List argument_list|< name|VirtualColumn argument_list|> name|getVirtualCols parameter_list|() block|{ return|return name|virtualCols return|; block|} specifier|public name|void name|setVirtualCols parameter_list|( name|List argument_list|< name|VirtualColumn argument_list|> name|virtualCols parameter_list|) block|{ name|this operator|. name|virtualCols operator|= name|virtualCols expr_stmt|; block|} specifier|public name|void name|addVirtualCols parameter_list|( name|List argument_list|< name|VirtualColumn argument_list|> name|virtualCols parameter_list|) block|{ name|this operator|. name|virtualCols operator|. name|addAll argument_list|( name|virtualCols argument_list|) expr_stmt|; block|} specifier|public name|boolean name|hasVirtualCols parameter_list|() block|{ return|return name|virtualCols operator|!= literal|null operator|&& operator|! name|virtualCols operator|. name|isEmpty argument_list|() return|; block|} specifier|public name|void name|setStatsAggPrefix parameter_list|( name|String name|k parameter_list|) block|{ name|statsAggKeyPrefix operator|= name|k expr_stmt|; block|} annotation|@ name|Override annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"Statistics Aggregation Key Prefix" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|EXTENDED block|} argument_list|) specifier|public name|String name|getStatsAggPrefix parameter_list|() block|{ return|return name|statsAggKeyPrefix return|; block|} specifier|public name|boolean name|isStatsReliable parameter_list|() block|{ return|return name|statsReliable return|; block|} specifier|public name|void name|setStatsReliable parameter_list|( name|boolean name|statsReliable parameter_list|) block|{ name|this operator|. name|statsReliable operator|= name|statsReliable expr_stmt|; block|} specifier|public name|void name|setRowLimit parameter_list|( name|int name|rowLimit parameter_list|) block|{ name|this operator|. name|rowLimit operator|= name|rowLimit expr_stmt|; block|} annotation|@ name|Signature specifier|public name|int name|getRowLimit parameter_list|() block|{ return|return name|rowLimit return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"Row Limit Per Split" argument_list|) specifier|public name|Integer name|getRowLimitExplain parameter_list|() block|{ return|return name|rowLimit operator|>= literal|0 condition|? name|rowLimit else|: literal|null return|; block|} specifier|public name|Map argument_list|< name|String argument_list|, name|Integer argument_list|> name|getBucketFileNameMapping parameter_list|() block|{ return|return name|bucketFileNameMapping return|; block|} specifier|public name|void name|setBucketFileNameMapping parameter_list|( name|Map argument_list|< name|String argument_list|, name|Integer argument_list|> name|bucketFileNameMapping parameter_list|) block|{ name|this operator|. name|bucketFileNameMapping operator|= name|bucketFileNameMapping expr_stmt|; block|} specifier|public name|void name|setIsMetadataOnly parameter_list|( name|boolean name|metadata_only parameter_list|) block|{ name|isMetadataOnly operator|= name|metadata_only expr_stmt|; block|} specifier|public name|boolean name|getIsMetadataOnly parameter_list|() block|{ return|return name|isMetadataOnly return|; block|} annotation|@ name|Signature specifier|public name|String name|getQualifiedTable parameter_list|() block|{ return|return name|dbName operator|+ literal|"." operator|+ name|tableName return|; block|} specifier|public name|Table name|getTableMetadata parameter_list|() block|{ return|return name|tableMetadata return|; block|} specifier|public name|void name|setTableMetadata parameter_list|( name|Table name|tableMetadata parameter_list|) block|{ name|this operator|. name|tableMetadata operator|= name|tableMetadata expr_stmt|; block|} specifier|public name|TableSample name|getTableSample parameter_list|() block|{ return|return name|tableSample return|; block|} specifier|public name|void name|setTableSample parameter_list|( name|TableSample name|tableSample parameter_list|) block|{ name|this operator|. name|tableSample operator|= name|tableSample expr_stmt|; block|} specifier|public name|String name|getSerializedFilterExpr parameter_list|() block|{ return|return name|serializedFilterExpr return|; block|} specifier|public name|void name|setSerializedFilterExpr parameter_list|( name|String name|serializedFilterExpr parameter_list|) block|{ name|this operator|. name|serializedFilterExpr operator|= name|serializedFilterExpr expr_stmt|; block|} specifier|public name|String name|getSerializedFilterObject parameter_list|() block|{ return|return name|serializedFilterObject return|; block|} specifier|public name|void name|setSerializedFilterObject parameter_list|( name|String name|serializedFilterObject parameter_list|) block|{ name|this operator|. name|serializedFilterObject operator|= name|serializedFilterObject expr_stmt|; block|} specifier|public name|void name|setIncludedBuckets parameter_list|( name|BitSet name|bitset parameter_list|) block|{ name|this operator|. name|includedBuckets operator|= name|bitset expr_stmt|; block|} specifier|public name|BitSet name|getIncludedBuckets parameter_list|() block|{ return|return name|this operator|. name|includedBuckets return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"buckets included" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|EXTENDED block|} argument_list|) specifier|public name|String name|getIncludedBucketExplain parameter_list|() block|{ if|if condition|( name|this operator|. name|includedBuckets operator|== literal|null condition|) block|{ return|return literal|null return|; block|} name|StringBuilder name|sb init|= operator|new name|StringBuilder argument_list|() decl_stmt|; name|sb operator|. name|append argument_list|( literal|"[" argument_list|) expr_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|this operator|. name|includedBuckets operator|. name|size argument_list|() condition|; name|i operator|++ control|) block|{ if|if condition|( name|this operator|. name|includedBuckets operator|. name|get argument_list|( name|i argument_list|) condition|) block|{ name|sb operator|. name|append argument_list|( name|i argument_list|) expr_stmt|; name|sb operator|. name|append argument_list|( literal|',' argument_list|) expr_stmt|; block|} block|} name|sb operator|. name|append argument_list|( name|String operator|. name|format argument_list|( literal|"] of %d" argument_list|, name|numBuckets argument_list|) argument_list|) expr_stmt|; return|return name|sb operator|. name|toString argument_list|() return|; block|} specifier|public name|int name|getNumBuckets parameter_list|() block|{ return|return name|numBuckets return|; block|} specifier|public name|void name|setNumBuckets parameter_list|( name|int name|numBuckets parameter_list|) block|{ name|this operator|. name|numBuckets operator|= name|numBuckets expr_stmt|; block|} specifier|public name|boolean name|isNeedSkipHeaderFooters parameter_list|() block|{ name|boolean name|rtn init|= literal|false decl_stmt|; if|if condition|( name|tableMetadata operator|!= literal|null operator|&& name|tableMetadata operator|. name|getTTable argument_list|() operator|!= literal|null condition|) block|{ name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|params init|= name|tableMetadata operator|. name|getTTable argument_list|() operator|. name|getParameters argument_list|() decl_stmt|; if|if condition|( name|params operator|!= literal|null condition|) block|{ name|String name|skipHVal init|= name|params operator|. name|get argument_list|( name|serdeConstants operator|. name|HEADER_COUNT argument_list|) decl_stmt|; name|int name|hcount init|= name|skipHVal operator|== literal|null condition|? literal|0 else|: name|Integer operator|. name|parseInt argument_list|( name|skipHVal argument_list|) decl_stmt|; name|String name|skipFVal init|= name|params operator|. name|get argument_list|( name|serdeConstants operator|. name|FOOTER_COUNT argument_list|) decl_stmt|; name|int name|fcount init|= name|skipFVal operator|== literal|null condition|? literal|0 else|: name|Integer operator|. name|parseInt argument_list|( name|skipFVal argument_list|) decl_stmt|; name|rtn operator|= operator|( name|hcount operator|!= literal|0 operator||| name|fcount operator|!= literal|0 operator|) expr_stmt|; block|} block|} return|return name|rtn return|; block|} annotation|@ name|Override specifier|public name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|getOpProps parameter_list|() block|{ return|return name|opProps return|; block|} annotation|@ name|Explain argument_list|( name|displayName operator|= literal|"properties" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|DEFAULT block|, name|Level operator|. name|USER block|, name|Level operator|. name|EXTENDED block|} argument_list|) specifier|public name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|getOpPropsWithStorageHandlerProps parameter_list|() block|{ name|HiveStorageHandler name|storageHandler init|= name|tableMetadata operator|. name|getStorageHandler argument_list|() decl_stmt|; return|return name|storageHandler operator|== literal|null condition|? name|opProps else|: name|storageHandler operator|. name|getOperatorDescProperties argument_list|( name|this argument_list|, name|opProps argument_list|) return|; block|} specifier|public class|class name|TableScanOperatorExplainVectorization extends|extends name|OperatorExplainVectorization block|{ specifier|private specifier|final name|TableScanDesc name|tableScanDesc decl_stmt|; specifier|private specifier|final name|VectorTableScanDesc name|vectorTableScanDesc decl_stmt|; specifier|public name|TableScanOperatorExplainVectorization parameter_list|( name|TableScanDesc name|tableScanDesc parameter_list|, name|VectorTableScanDesc name|vectorTableScanDesc parameter_list|) block|{ comment|// Native vectorization supported. name|super argument_list|( name|vectorTableScanDesc argument_list|, literal|true argument_list|) expr_stmt|; name|this operator|. name|tableScanDesc operator|= name|tableScanDesc expr_stmt|; name|this operator|. name|vectorTableScanDesc operator|= name|vectorTableScanDesc expr_stmt|; block|} annotation|@ name|Explain argument_list|( name|vectorization operator|= name|Vectorization operator|. name|DETAIL argument_list|, name|displayName operator|= literal|"vectorizationSchemaColumns" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|DEFAULT block|, name|Level operator|. name|EXTENDED block|} argument_list|) specifier|public name|String name|getSchemaColumns parameter_list|() block|{ name|String index|[] name|projectedColumnNames init|= name|vectorTableScanDesc operator|. name|getProjectedColumnNames argument_list|() decl_stmt|; name|TypeInfo index|[] name|projectedColumnTypeInfos init|= name|vectorTableScanDesc operator|. name|getProjectedColumnTypeInfos argument_list|() decl_stmt|; comment|// We currently include all data, partition, and any vectorization available comment|// virtual columns in the VRB. specifier|final name|int name|size init|= name|projectedColumnNames operator|. name|length decl_stmt|; name|int index|[] name|projectionColumns init|= operator|new name|int index|[ name|size index|] decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|size condition|; name|i operator|++ control|) block|{ name|projectionColumns index|[ name|i index|] operator|= name|i expr_stmt|; block|} name|DataTypePhysicalVariation index|[] name|projectedColumnDataTypePhysicalVariations init|= name|vectorTableScanDesc operator|. name|getProjectedColumnDataTypePhysicalVariations argument_list|() decl_stmt|; return|return name|BaseExplainVectorization operator|. name|getColumnAndTypes argument_list|( name|projectionColumns argument_list|, name|projectedColumnNames argument_list|, name|projectedColumnTypeInfos argument_list|, name|projectedColumnDataTypePhysicalVariations argument_list|) operator|. name|toString argument_list|() return|; block|} block|} annotation|@ name|Explain argument_list|( name|vectorization operator|= name|Vectorization operator|. name|OPERATOR argument_list|, name|displayName operator|= literal|"TableScan Vectorization" argument_list|, name|explainLevels operator|= block|{ name|Level operator|. name|DEFAULT block|, name|Level operator|. name|EXTENDED block|} argument_list|) specifier|public name|TableScanOperatorExplainVectorization name|getTableScanVectorization parameter_list|() block|{ name|VectorTableScanDesc name|vectorTableScanDesc init|= operator|( name|VectorTableScanDesc operator|) name|getVectorDesc argument_list|() decl_stmt|; if|if condition|( name|vectorTableScanDesc operator|== literal|null condition|) block|{ return|return literal|null return|; block|} return|return operator|new name|TableScanOperatorExplainVectorization argument_list|( name|this argument_list|, name|vectorTableScanDesc argument_list|) return|; block|} comment|/* * This TableScanDesc flag is strictly set by the Vectorizer class for vectorized MapWork * vertices. */ specifier|public name|void name|setVectorized parameter_list|( name|boolean name|vectorized parameter_list|) block|{ name|this operator|. name|vectorized operator|= name|vectorized expr_stmt|; block|} specifier|public name|boolean name|isVectorized parameter_list|() block|{ return|return name|vectorized return|; block|} annotation|@ name|Override specifier|public name|boolean name|isSame parameter_list|( name|OperatorDesc name|other parameter_list|) block|{ if|if condition|( name|getClass argument_list|() operator|. name|getName argument_list|() operator|. name|equals argument_list|( name|other operator|. name|getClass argument_list|() operator|. name|getName argument_list|() argument_list|) condition|) block|{ name|TableScanDesc name|otherDesc init|= operator|( name|TableScanDesc operator|) name|other decl_stmt|; return|return name|Objects operator|. name|equals argument_list|( name|getQualifiedTable argument_list|() argument_list|, name|otherDesc operator|. name|getQualifiedTable argument_list|() argument_list|) operator|&& name|ExprNodeDescUtils operator|. name|isSame argument_list|( name|getFilterExpr argument_list|() argument_list|, name|otherDesc operator|. name|getFilterExpr argument_list|() argument_list|) operator|&& name|getRowLimit argument_list|() operator|== name|otherDesc operator|. name|getRowLimit argument_list|() operator|&& name|isGatherStats argument_list|() operator|== name|otherDesc operator|. name|isGatherStats argument_list|() return|; block|} return|return literal|false return|; block|} specifier|public name|boolean name|isFullAcidTable parameter_list|() block|{ return|return name|isTranscationalTable argument_list|() operator|&& operator|! name|getAcidOperationalProperties argument_list|() operator|. name|isInsertOnly argument_list|() return|; block|} block|} end_class end_unit /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * 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. */ package com.android.ide.eclipse.adt.internal.editors.layout.configuration; import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX; import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; /** * Action which brings up the "Create new XML File" wizard, pre-selected with the * animation category */ class SelectThemeAction extends Action { private final ConfigurationChooser mConfiguration; private final String mTheme; public SelectThemeAction(ConfigurationChooser configuration, String title, String theme, boolean selected) { super(title, IAction.AS_RADIO_BUTTON); assert theme.startsWith(STYLE_RESOURCE_PREFIX) || theme.startsWith(ANDROID_STYLE_RESOURCE_PREFIX) : theme; mConfiguration = configuration; mTheme = theme; if (selected) { setChecked(selected); } } @Override public void run() { mConfiguration.selectTheme(mTheme); mConfiguration.onThemeChange(); } } package ukitinu.es7db.search; import java.util.ArrayList; import java.util.List; class MustElements { private final List matches = new ArrayList<>(); List getElements() { return new ArrayList<>(matches); } void addMatch(String field, String text, boolean isFuzzy) { matches.add(new MatchElement(field, text, isFuzzy)); } } package ru.project.bots.logic.queues; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Update; import ru.project.bots.dto.MessageContainer; import ru.project.bots.logic.daemons.MessageProcessor; import ru.project.bots.dto.ConfigDTO; import java.util.concurrent.ConcurrentLinkedQueue; public class SimpleMessageQueue implements MessageQueue { /* * Concurrent queue to keep updates until it process * */ private final ConcurrentLinkedQueue updates = new ConcurrentLinkedQueue<>(); /* * Concurrent queue to complete messages before it send * */ private final ConcurrentLinkedQueue messages = new ConcurrentLinkedQueue<>(); public SimpleMessageQueue(ConfigDTO configDTO) { init(configDTO); } private void init(ConfigDTO config){ MessageProcessor.setUpdates(updates); MessageProcessor.setMessageQueue(this); for (int i = 0; i < config.getMessageProcessorThreads(); i++) { new Thread(new MessageProcessor()).start(); } } @Override public void putUpdate(Update update) { /* * Put new update to queue and notufi one thread * */ synchronized (updates){ updates.add(update); updates.notify(); } } @Override public void putMessage(MessageContainer message) { /* * Put ready message to executor and notify 1 thread * */ synchronized (messages){ messages.add(message); messages.notify(); } } @Override public ConcurrentLinkedQueue getMessageQueue(){ return this.messages; } } package io.everydata.sinks; import io.everydata.config.Config; public class SinkConfig implements Config { } package org.craft.blocks.states; import java.util.*; public final class BlockStates { /** * Block state handling logs orientation */ public static BlockState logOrientation; /** * Block states handling connexions between cables */ public static BlockState cableConnexions; /** * Block state handling electric power (0-15) */ public static BlockState electricPower; public static BlockState powered; public static BlockState powerSourceMode; /** * Maps String representations of block states to their respective BlockState object */ public static final HashMap BLOCK_STATES_REGISTRY = new HashMap(); /** * Maps String representations of block states values to their respective IBlockStateValue instance. */ public static final HashMap> BLOCK_STATES_VALUES_REGISTRY = new HashMap>(); /** * Registers all blocks states of the game */ public static void init() { registerState(logOrientation = new BaseBlockState("orientation")); for(EnumLogBlockStates state : EnumLogBlockStates.values()) { registerValue(logOrientation, state); } registerState(cableConnexions = new BaseBlockState("connexions")); for(EnumConnexionStates state : EnumConnexionStates.values()) { registerValue(cableConnexions, state); } registerState(electricPower = new BaseBlockState("electricPower")); for(EnumPowerStates state : EnumPowerStates.values()) { registerValue(electricPower, state); } registerState(powerSourceMode = new BaseBlockState("powerSourceMode")); for(EnumPowerSourceMode state : EnumPowerSourceMode.values()) { registerValue(powerSourceMode, state); } registerState(powered = new BaseBlockState("powered")); registerValue(powered, new BaseBlockStateValue("true")); registerValue(powered, new BaseBlockStateValue("false")); } /** * Registers a block state into the BLOCK_STATE_REGISTRY field */ public static void registerState(BlockState state) { if(BLOCK_STATES_REGISTRY.containsKey(state.toString())) { throw new IllegalArgumentException("Id " + state.toString() + " is already used by " + BLOCK_STATES_REGISTRY.get(state.toString()) + " when trying to add " + state); } BLOCK_STATES_REGISTRY.put(state.toString(), state); BLOCK_STATES_VALUES_REGISTRY.put(state, new HashMap()); } /** * Returns the block state in BLOCK_STATE_REGISTRY with given id */ public static BlockState getState(String string) { return BLOCK_STATES_REGISTRY.get(string); } /** * Registers a block state into the BLOCK_STATE_REGISTRY field */ public static void registerValue(BlockState state, IBlockStateValue value) { HashMap map = BLOCK_STATES_VALUES_REGISTRY.get(state); map.put(value.toString(), value); } /** * Returns the block state in BLOCK_STATE_REGISTRY with given id */ public static IBlockStateValue getValue(BlockState state, String string) { return BLOCK_STATES_VALUES_REGISTRY.get(state).get(string); } public static Collection getValues(BlockState state) { return BLOCK_STATES_VALUES_REGISTRY.get(state).values(); } } core/src/main/java/ship/build/web/model/QueryResult.java package ship.build.web.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor public class QueryResult { @Getter @Setter protected Object result; public QueryResult(final Object result) { this.result = result; } } hernad/zimbra9 /* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Synacor, Inc. * * This program 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, * version 2 of the License. * * 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, see . * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.service.mail; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.Element; import com.zimbra.common.soap.MailConstants; import com.zimbra.common.util.StringUtil; import com.zimbra.common.util.ZimbraLog; import com.zimbra.common.calendar.ZCalendar.ZCalendarBuilder; import com.zimbra.common.calendar.ZCalendar.ZVCalendar; import com.zimbra.common.mime.MimeConstants; import com.zimbra.cs.ldap.LdapUtil; import com.zimbra.cs.mailbox.MailServiceException; import com.zimbra.cs.mailbox.Mailbox; import com.zimbra.cs.mailbox.OperationContext; import com.zimbra.cs.mailbox.Mailbox.AddInviteData; import com.zimbra.cs.mailbox.calendar.Invite; import com.zimbra.cs.service.FileUploadServlet; import com.zimbra.cs.service.FileUploadServlet.Upload; import com.zimbra.cs.service.util.ItemId; import com.zimbra.soap.ZimbraSoapContext; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * @author schemers */ public class ImportAppointments extends MailDocumentHandler { private static final String[] TARGET_FOLDER_PATH = new String[] { MailConstants.A_FOLDER }; @Override protected String[] getProxiedIdPath(Element request) { return TARGET_FOLDER_PATH; } /** * Return false - need to mine "content" for pointers to data in the owner mailbox and resolve these * before proxying. */ @Override protected boolean checkMountpointProxy(Element request) { return false; } String DEFAULT_FOLDER_ID = Mailbox.ID_FOLDER_CALENDAR + ""; private enum SourceSpecMethod { ATTACH_ID, MSG_PART, INLINE_TEXT } @Override public Element handle(Element request, Map context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Mailbox mbox = getRequestedMailbox(zsc); OperationContext octxt = getOperationContext(zsc, context); String folder = request.getAttribute(MailConstants.A_FOLDER, DEFAULT_FOLDER_ID); ItemId iidFolder = new ItemId(folder, zsc); String ct = request.getAttribute(MailConstants.A_CONTENT_TYPE); if (!ct.equalsIgnoreCase("ics") && !ct.equalsIgnoreCase(MimeConstants.CT_TEXT_CALENDAR)) throw ServiceException.INVALID_REQUEST("unsupported content type: " + ct, null); Element content = request.getElement(MailConstants.E_CONTENT); List uploads = null; InputStream is = null; String partStr = null; String attachment = content.getAttribute(MailConstants.A_ATTACHMENT_ID, null); String messageId = content.getAttribute(MailConstants.A_MESSAGE_ID, null); if (attachment != null && messageId != null) { throw ServiceException.INVALID_REQUEST("use either aid or mid but not both", null); } SourceSpecMethod sourceSpecMethod; if (messageId != null) { sourceSpecMethod = SourceSpecMethod.MSG_PART; } else if (attachment != null) { sourceSpecMethod = SourceSpecMethod.ATTACH_ID; } else { sourceSpecMethod = SourceSpecMethod.INLINE_TEXT; } try { if (SourceSpecMethod.MSG_PART.equals(sourceSpecMethod)) { // Get content from part of existing message. ItemId iid = new ItemId(messageId, zsc); String part = content.getAttribute(MailConstants.A_PART); partStr = CreateContact.fetchItemPart(zsc, octxt, mbox, iid, part, null, MimeConstants.P_CHARSET_UTF8); is = new ByteArrayInputStream(partStr.getBytes(MimeConstants.P_CHARSET_UTF8)); } // if the "target item" is remote, we will need to proxy the request ItemId iidTarget = getProxyTarget(zsc, octxt, iidFolder, true); if (iidTarget != null) { ZimbraLog.misc.info("Proxying ImportAppointments - folder=" + folder + ", acct=" + iidTarget.getAccountId()); if (SourceSpecMethod.MSG_PART.equals(sourceSpecMethod)) { /* Bug 77131 change specification method to something that will work in the proxied context */ content.addAttribute(MailConstants.A_MESSAGE_ID, (String) null); content.addAttribute(MailConstants.A_PART, (String) null); Upload up = FileUploadServlet.saveUpload(is, "upload.ics", MimeConstants.CT_TEXT_CALENDAR, zsc.getAuthtokenAccountId()); content.addAttribute(MailConstants.A_ATTACHMENT_ID, up.getId()); } return proxyRequest(request, context, iidFolder, iidTarget); } if (SourceSpecMethod.ATTACH_ID.equals(sourceSpecMethod)) { is = parseUploadedContent(zsc, attachment, uploads = new ArrayList()); } else if (SourceSpecMethod.INLINE_TEXT.equals(sourceSpecMethod)) { // Convert LF to CRLF because the XML parser normalizes element text to LF. String text = StringUtil.lfToCrlf(content.getText()); is = new ByteArrayInputStream(text.getBytes(MimeConstants.P_CHARSET_UTF8)); } List icals = ZCalendarBuilder.buildMulti(is, MimeConstants.P_CHARSET_UTF8); is.close(); is = null; List invites = Invite.createFromCalendar(mbox.getAccount(), null, icals, true, true, null); Set uidsSeen = new HashSet(); StringBuilder ids = new StringBuilder(); for (Invite inv : invites) { // handle missing UIDs on remote calendars by generating them as needed String uid = inv.getUid(); if (uid == null) { uid = LdapUtil.generateUUID(); inv.setUid(uid); } boolean addRevision; if (!uidsSeen.contains(uid)) { addRevision = true; uidsSeen.add(uid); } else { addRevision = false; } // and add the invite to the calendar! try { AddInviteData aid = mbox.addInvite(octxt, inv, iidFolder.getId(), false, addRevision); if (aid != null) { if (ids.length() > 0) ids.append(","); ids.append(aid.calItemId).append("-").append(aid.invId); } } catch (ServiceException e) { ZimbraLog.calendar.warn("Skipping bad iCalendar object during import: uid=" + inv.getUid(), e); } } Element response = zsc.createElement(MailConstants.IMPORT_APPOINTMENTS_RESPONSE); Element cn = response.addElement(MailConstants.E_APPOINTMENT); cn.addAttribute(MailConstants.A_IDS, ids.toString()); cn.addAttribute(MailConstants.A_NUM, invites.size()); return response; } catch (IOException e) { throw MailServiceException.UNABLE_TO_IMPORT_APPOINTMENTS(e.getMessage(), e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (attachment != null) FileUploadServlet.deleteUploads(uploads); } } private static InputStream parseUploadedContent(ZimbraSoapContext lc, String attachId, List uploads) throws ServiceException { Upload up = FileUploadServlet.fetchUpload(lc.getAuthtokenAccountId(), attachId, lc.getAuthToken()); if (up == null) throw MailServiceException.NO_SUCH_UPLOAD(attachId); uploads.add(up); try { return up.getInputStream(); } catch (IOException e) { throw ServiceException.FAILURE(e.getMessage(), e); } } } 10-100 package com.cloud.storage.snapshot; import com.cloud.engine.subsystem.api.storage.SnapshotInfo; import com.cloud.engine.subsystem.api.storage.VolumeInfo; import com.cloud.legacymodel.communication.answer.Answer; import com.cloud.legacymodel.communication.command.Command; import com.cloud.legacymodel.exceptions.ResourceAllocationException; import com.cloud.legacymodel.storage.Volume; import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; /** * * */ public interface SnapshotManager { public static final int HOURLYMAX = 8; public static final int DAILYMAX = 8; public static final int WEEKLYMAX = 8; public static final int MONTHLYMAX = 12; public static final int DELTAMAX = 16; /** * For each of the volumes in the account, (which can span across multiple zones and multiple secondary storages), delete * the dir on the secondary storage which contains the backed up snapshots for that volume. This is called during * deleteAccount. * * @param accountId The account which is to be deleted. */ boolean deleteSnapshotDirsForAccount(long accountId); String getSecondaryStorageURL(SnapshotVO snapshot); //void deleteSnapshotsDirForVolume(String secondaryStoragePoolUrl, Long dcId, Long accountId, Long volumeId); boolean canOperateOnVolume(Volume volume); Answer sendToPool(Volume vol, Command cmd); SnapshotVO getParentSnapshot(VolumeInfo volume); Snapshot backupSnapshot(Long snapshotId); SnapshotInfo takeSnapshot(VolumeInfo volume) throws ResourceAllocationException; } package ai.subut.kurjun.model.repository; import java.util.ArrayList; import java.util.List; /** * Package types supported by Kurjun repositories. * */ public final class PackageType { public static final String DEB = "deb"; public static final String SNAP = "snap"; public static final String SUBUTAI = "subutai"; private PackageType() { // not to be constructed } public static List getPackageTypes() { List ls = new ArrayList<>(); ls.add( DEB ); ls.add( SNAP ); ls.add( SUBUTAI ); return ls; } } src/main/java/net/minecraft/client/particle/EntityPickupFX.java package net.minecraft.client.particle; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.world.World; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public class EntityPickupFX extends EntityFX { private Entity entityToPickUp; private Entity entityPickingUp; private int age; private int maxAge; private float yOffs; private static final String __OBFID = "CL_00000930"; public EntityPickupFX(World p_i1233_1_, Entity p_i1233_2_, Entity p_i1233_3_, float p_i1233_4_) { super(p_i1233_1_, p_i1233_2_.posX, p_i1233_2_.posY, p_i1233_2_.posZ, p_i1233_2_.motionX, p_i1233_2_.motionY, p_i1233_2_.motionZ); this.entityToPickUp = p_i1233_2_; this.entityPickingUp = p_i1233_3_; this.maxAge = 3; this.yOffs = p_i1233_4_; } public void renderParticle(Tessellator p_70539_1_, float p_70539_2_, float p_70539_3_, float p_70539_4_, float p_70539_5_, float p_70539_6_, float p_70539_7_) { float f6 = ((float)this.age + p_70539_2_) / (float)this.maxAge; f6 *= f6; double d0 = this.entityToPickUp.posX; double d1 = this.entityToPickUp.posY; double d2 = this.entityToPickUp.posZ; double d3 = this.entityPickingUp.lastTickPosX + (this.entityPickingUp.posX - this.entityPickingUp.lastTickPosX) * (double)p_70539_2_; double d4 = this.entityPickingUp.lastTickPosY + (this.entityPickingUp.posY - this.entityPickingUp.lastTickPosY) * (double)p_70539_2_ + (double)this.yOffs; double d5 = this.entityPickingUp.lastTickPosZ + (this.entityPickingUp.posZ - this.entityPickingUp.lastTickPosZ) * (double)p_70539_2_; double d6 = d0 + (d3 - d0) * (double)f6; double d7 = d1 + (d4 - d1) * (double)f6; double d8 = d2 + (d5 - d2) * (double)f6; int i = this.getBrightnessForRender(p_70539_2_); int j = i % 65536; int k = i / 65536; OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)j / 1.0F, (float)k / 1.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); d6 -= interpPosX; d7 -= interpPosY; d8 -= interpPosZ; RenderManager.instance.renderEntityWithPosYaw(this.entityToPickUp, (double)((float)d6), (double)((float)d7), (double)((float)d8), this.entityToPickUp.rotationYaw, p_70539_2_); } public void onUpdate() { ++this.age; if (this.age == this.maxAge) { this.setDead(); } } public int getFXLayer() { return 3; } }package io.basc.framework.convert.lang; import java.io.IOException; import java.util.Collections; import java.util.Set; import io.basc.framework.convert.ConversionException; import io.basc.framework.convert.ConversionFailedException; import io.basc.framework.convert.TypeDescriptor; import io.basc.framework.core.annotation.CharsetName; import io.basc.framework.io.IOUtils; import io.basc.framework.io.Resource; public class ResourceToStringConversionService extends ConditionalConversionService { @Override public String convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) throws ConversionException { CharsetName charsetName = targetType.getAnnotation(CharsetName.class); String charset = charsetName == null ? null : charsetName.value(); try { return (String) ((Resource) source).read((is) -> { return IOUtils.toString(is, charset); }); } catch (IOException e) { throw new ConversionFailedException(sourceType, targetType, source, e); } } @Override public Set getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(Resource.class, String.class)); } } aliyun/alibabacloud-webplus-demo-java /* * MIT License * * Copyright (c) 2019-present Alibaba Group * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.alibaba.webplus.demo.controller; import java.io.IOException; import java.util.List; import java.util.Map; import com.alibaba.webplus.demo.helper.DbHelper; import com.alibaba.webplus.demo.model.Todo; import com.alibaba.webplus.demo.model.InternationalizationLambda; import com.alibaba.webplus.demo.service.TodoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * @author Baiji * @author Aomo */ @RestController @RequestMapping("/todolist") public class TodoListController extends BaseController { @Autowired private TodoService todoService; @CrossOrigin @RequestMapping(value = "", method = RequestMethod.GET) public ModelAndView index(Map model) throws IOException { model.put(InternationalizationLambda.DEFAULT_MODEL_KEY, this.getI18nLambda()); model.putAll(this.getCommonModel()); if (DbHelper.isMysqlDatabasePresent()) { return new ModelAndView("todolist", model); } return new ModelAndView("redirect:/"); } @GetMapping(value = "/api/{id}") public Todo findById(@PathVariable("id") Long id) { return this.todoService.getById(id); } @GetMapping(value = "/api") public List list(@RequestParam(value = "completed", required = false) Boolean completed) { if (completed == null) { return this.todoService.getAll(); } return this.todoService.getByStatus(completed); } @PostMapping(value = "/api", consumes = MediaType.APPLICATION_JSON_VALUE) public void create(@RequestBody Todo item) { this.todoService.create(item); } @PutMapping(value = "/api/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) public void update(@PathVariable("id") Long id, @RequestBody Todo item) { this.todoService.update(id, item); } @DeleteMapping("/api/{id}") public void removeById(@PathVariable("id") Long id) { this.todoService.removeById(id); } @DeleteMapping("/api") public void removeByStatus(@RequestParam("completed") Boolean completed) { this.todoService.removeByStatus(completed); } @GetMapping("/api/count") public Map count() { return this.todoService.count(); } } FurkanYazbahar/WebServiceAndroid0 package Database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MySqlConnection { static String ip = "localhost"; static String port = "3306"; static String userName = "root"; static String pass = ""; static String database = "news_DB"; static String timeZone = "?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey"; static private String connectString = "jdbc:mysql://" + ip + ":" + port + "/" + database + timeZone; public Connection getConnect(){ Connection c = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); c = DriverManager.getConnection(connectString,userName,pass); System.out.println("Connection Success"); } catch (SQLException e) { e.printStackTrace(); System.out.println("Connection Fails"); } catch (ClassNotFoundException e) { e.printStackTrace(); } return c; } public static void main(String[] args) { MySqlConnection con = new MySqlConnection(); con.getConnect(); } }package com.loserico.junit.spring; import javax.annotation.Resource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; /** * The @PropertySource annotation takes the properties' filenames and sets the * properties to the Environment resource. * * @author Loser * @since Aug 8, 2016 * @version * */ @Configuration @PropertySource({ "classpath:myProp.properties" }) public class MyConfig { @Resource private Environment environment; @Bean(name = "message") public String getMessage() { return environment.getProperty("message"); } }/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.view; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.engine.view.ViewCalculationConfiguration; import com.opengamma.engine.view.ViewCalculationConfiguration.MergedOutput; import com.opengamma.financial.analytics.DoubleCurrencyLabelledMatrix2D; import com.opengamma.financial.analytics.DoubleLabelledMatrix1D; import com.opengamma.financial.analytics.SumUtils; import com.opengamma.util.async.AsynchronousExecution; import com.opengamma.util.money.Currency; import com.opengamma.util.money.CurrencyAmount; /** * Calculates simple, linear aggregates at the portfolio node level over merged outputs. */ public class MergedOutputLinearAggregationPortfolioNodeFunction extends AbstractFunction.NonCompiledInvoker { @Override public ComputationTargetType getTargetType() { return ComputationTargetType.PORTFOLIO_NODE; } @Override public Set getResults(final FunctionCompilationContext context, final ComputationTarget target) { return ImmutableSet.of(ValueSpecification.of(ValueRequirementNames.MERGED_OUTPUT, target.toSpecification(), ValueProperties.all())); } @Override public Set getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final String mergedOutputName = desiredValue.getConstraint(ValuePropertyNames.NAME); final ViewCalculationConfiguration calcConfig = context.getViewCalculationConfiguration(); final MergedOutput mergedOutput = calcConfig.getMergedOutput(mergedOutputName); if (mergedOutput == null) { return null; } final Set requirements = new HashSet<>(); final PortfolioNode node = target.getPortfolioNode(); for (final Position position : node.getPositions()) { requirements.add( new ValueRequirement(ValueRequirementNames.MERGED_OUTPUT, ComputationTargetType.POSITION, position.getUniqueId(), desiredValue.getConstraints())); } for (final PortfolioNode childNode : node.getChildNodes()) { requirements.add(new ValueRequirement(ValueRequirementNames.MERGED_OUTPUT, ComputationTargetType.PORTFOLIO_NODE, childNode.getUniqueId(), desiredValue.getConstraints())); } return requirements; } @Override public Set getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map inputs) { final ValueRequirement exampleInput = Iterables.getFirst(inputs.values(), null); if (exampleInput == null) { return null; } final String mergedOutputName = exampleInput.getConstraint(ValuePropertyNames.NAME); final ValueProperties properties = createValueProperties().with(ValuePropertyNames.NAME, mergedOutputName).get(); return ImmutableSet.of(ValueSpecification.of(ValueRequirementNames.MERGED_OUTPUT, target.toSpecification(), properties)); } @Override public Set execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set desiredValues) throws AsynchronousExecution { // TODO jonathan 2014-01-13 -- as a proof-of-concept this supports aggregating very specific types. It should be // extended as required. final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final String mergedOutputName = desiredValue.getConstraint(ValuePropertyNames.NAME); Object value = null; for (final ComputedValue input : inputs.getAllValues()) { Object inputValue = input.getValue(); if (inputValue instanceof String) { if (((String) inputValue).length() == 0) { continue; } } final String ccyCode = input.getSpecification().getProperty(ValuePropertyNames.CURRENCY); final Currency ccy = ccyCode != null ? Currency.parse(ccyCode) : null; if (ccy != null) { // When merging outputs we want to allow aggregation across currencies, so we add another dimension to known // data structures to include the currency if (inputValue instanceof Double) { inputValue = CurrencyAmount.of(ccy, (double) inputValue); } else if (inputValue instanceof DoubleLabelledMatrix1D) { final DoubleLabelledMatrix1D inputMatrix = (DoubleLabelledMatrix1D) inputValue; // TODO jonathan 2014-01-08 -- an optional constraint should control whether we aggregate by key or label // We default to this since we usually want to see the matrix aggregated across currencies by label (e.g. 7D) // rather than repeating labels where the keys are slightly different (e.g. due to holiday differences) if (value != null && !(value instanceof DoubleCurrencyLabelledMatrix2D)) { throw new OpenGammaRuntimeException("Unable to aggregate " + value.getClass() + " with " + DoubleCurrencyLabelledMatrix2D.class); } inputValue = new DoubleCurrencyLabelledMatrix2D( inputMatrix.getKeys(), inputMatrix.getLabels(), inputMatrix.getLabelsTitle(), new Currency[] { ccy }, new Currency[] { ccy }, ValuePropertyNames.CURRENCY, new double[][] { inputMatrix.getValues() }, inputMatrix.getValuesTitle()); } } final String requirementDisplayName = ValueRequirementNames.MERGED_OUTPUT + " (" + mergedOutputName + ")"; value = addValue(value, inputValue, requirementDisplayName); } if (value == null) { value = ""; } return Collections.singleton( new ComputedValue(new ValueSpecification(ValueRequirementNames.MERGED_OUTPUT, target.toSpecification(), desiredValue.getConstraints()), value)); } protected Object addValue(final Object previousSum, final Object currentValue, final String requirementDisplayName) { if (previousSum == null) { return currentValue; } if (previousSum instanceof DoubleCurrencyLabelledMatrix2D && currentValue instanceof DoubleCurrencyLabelledMatrix2D) { final DoubleCurrencyLabelledMatrix2D previousSumMatrix = (DoubleCurrencyLabelledMatrix2D) previousSum; final DoubleCurrencyLabelledMatrix2D currentValueMatrix = (DoubleCurrencyLabelledMatrix2D) currentValue; return previousSumMatrix.addUsingDoubleLabels(currentValueMatrix); } return SumUtils.addValue(previousSum, currentValue, requirementDisplayName); } @Override public boolean canHandleMissingInputs() { return true; } } // Template Source: Enum.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models; /** * The Enum Print Orientation. */ public enum PrintOrientation { /** * portrait */ PORTRAIT, /** * landscape */ LANDSCAPE, /** * reverse Landscape */ REVERSE_LANDSCAPE, /** * reverse Portrait */ REVERSE_PORTRAIT, /** * For PrintOrientation values that were not expected from the service */ UNEXPECTED_VALUE } package utpb.science.fair.models.category; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import utpb.science.fair.models.group.Group; import utpb.science.fair.models.judge.Judge; import utpb.science.fair.models.project.Project; public class Category implements Comparable { public static final String[] CATEGORIES = { "Behavioral/Social Science", "Chemistry", "Earth/Space Science", "Environmental Science", "Life Science", "Mathematics/Physics" }; public static final String BEHAVIORAL_SOCIAL_SCIENCE = "Behavioral/Social Science"; public static final String CHEMISTRY = "Chemistry"; public static final String EARTH_SPACE_SCIENCE = "Earth/Space Science"; public static final String ENVIRONMENTAL_SCIENCE = "Environmental Science"; public static final String LIFE_SCIENCE = "Life Science"; public static final String MATHEMATICS_PHYSICS = "Mathematics/Physics"; private final String _name; private List _projects = new LinkedList<>(); private List _judges = new LinkedList<>(); private List _groups = new LinkedList<>(); public Category(String name) { _name = Objects.requireNonNull(name); } public Category(String name, List projects) { _name = Objects.requireNonNull(name); _projects = Objects.requireNonNull(projects); } public String getName() { return _name; } public List getProjects() { return _projects; } public void setProjects(List projects) { _projects = Objects.requireNonNull(projects); } public boolean addProject(Project project) { return _projects.add(Objects.requireNonNull(project)); } public boolean removeProject(Project project) { return _projects.remove(Objects.requireNonNull(project)); } public List getJudges() { return _judges; } public void setJudges(List judges) { _judges = Objects.requireNonNull(judges); } public boolean addJudge(Judge judge) { return _judges.add(Objects.requireNonNull(judge)); } public boolean removeJudge(Judge judge) { return _judges.remove(Objects.requireNonNull(judge)); } public List getGroups() { return _groups; } public void setGroups(List groups) { _groups = Objects.requireNonNull(groups); } @Override public int hashCode() { return Objects.hash(_judges, _name, _projects, _groups); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Category other = (Category) obj; return Objects.equals(_judges, other._judges) && Objects.equals(_name, other._name) && Objects.equals(_projects, other._projects) && Objects.equals(_groups, other._groups); } @Override public int compareTo(Category o) { return _name.compareToIgnoreCase(o.getName()); } @Override public String toString() { return String.format("Category[name=%s, judgeCount=%d, groupCount=%d, projectCount=%d]", _name, _judges.size(), _groups.size(), _projects.size()); } /** * Sorts or prioritizes the Croup with the most Projects. */ public static final Comparator GREATEST_PROJECT_COUNT = new ProjectsCountComparator(); private static class ProjectsCountComparator implements Comparator { @Override public int compare(Category o1, Category o2) { return o2.getProjects().size() - o1.getProjects().size(); } } } DaveWei520/java-algorithm-learningsrc/main/java/willem/weiyu/algorithm/sort/MergeSort.java package willem.weiyu.algorithm.sort; import java.util.Arrays; /** * 归并排序:归并排序是建立在归并操作上的一种有效的排序算法, * 该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。 * 将已有序的子序列合并,得到完全有序的序列; * 即先使每个子序列有序,再使子序列段间有序。 * */ public class MergeSort { /** * 时间复杂度:O(nlogn) * 空间复杂度:O(n) * @param array */ public static void mergeSort(int[] array) { //在排序前,先建立一个长度等于原数组的临时数组,避免递归中频繁开辟空间 int[] temp = new int[array.length]; divide(array, 0, array.length - 1, temp); } private static void divide(int[] array, int left, int right, int[] temp) { if (left < right) { int mid = (left + right) / 2; //左边归并排序,使得左子序列有序 divide(array, left, mid, temp); //右边归并排序,使得右子序列有序 divide(array, mid + 1, right, temp); //将两个有序子数组合并 merge(array, left, mid, right, temp); } } private static void merge(int[] array, int left, int mid, int right, int[] temp) { //左序列指针 int i = left; //右序列指针 int j = mid + 1; //临时数组指针 int t = 0; while (i <= mid && j <= right) { if (array[i] <= array[j]) { temp[t++] = array[i++]; } else { temp[t++] = array[j++]; } } //将左边剩余元素填充进temp中 while (i <= mid) { temp[t++] = array[i++]; } //将右边剩余元素填充进temp中 while (j <= right) { temp[t++] = array[j++]; } for (int k = 0; k < t; k++) { array[left + k] = temp[k]; } } public static void main(String[] args) { int[] array = new int[]{20, 7, 28, 32, 1, 9, 5, 2}; System.out.println("归并排序前=>" + Arrays.toString(array)); mergeSort(array); System.out.println("归并排序后=>" + Arrays.toString(array)); } } // -------------------------------------------------------------------------------- // Copyright 2002-2022 Echo Three, LLC // // 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. // -------------------------------------------------------------------------------- package com.echothree.model.control.associate.server.transfer; import com.echothree.model.control.associate.common.transfer.AssociateProgramTransfer; import com.echothree.model.control.associate.server.control.AssociateControl; import com.echothree.model.control.sequence.common.transfer.SequenceTransfer; import com.echothree.model.control.sequence.server.control.SequenceControl; import com.echothree.model.data.associate.server.entity.AssociateProgram; import com.echothree.model.data.associate.server.entity.AssociateProgramDetail; import com.echothree.model.data.sequence.server.entity.Sequence; import com.echothree.model.data.user.server.entity.UserVisit; import com.echothree.util.server.persistence.Session; import com.echothree.util.server.string.PercentUtils; public class AssociateProgramTransferCache extends BaseAssociateTransferCache { SequenceControl sequenceControl = Session.getModelController(SequenceControl.class); /** Creates a new instance of AssociateProgramTransferCache */ public AssociateProgramTransferCache(UserVisit userVisit, AssociateControl associateControl) { super(userVisit, associateControl); setIncludeEntityInstance(true); } @Override public AssociateProgramTransfer getTransfer(AssociateProgram associateProgram) { AssociateProgramTransfer associateProgramTransfer = get(associateProgram); if(associateProgramTransfer == null) { AssociateProgramDetail associateProgramDetail = associateProgram.getLastDetail(); String associateProgramName = associateProgramDetail.getAssociateProgramName(); Sequence associateSequence = associateProgramDetail.getAssociateSequence(); SequenceTransfer associateSequenceTransfer = associateSequence == null? null: sequenceControl.getSequenceTransfer(userVisit, associateSequence); Sequence associatePartyContactMechanismSequence = associateProgramDetail.getAssociatePartyContactMechanismSequence(); SequenceTransfer associatePartyContactMechanismSequenceTransfer = associatePartyContactMechanismSequence == null? null: sequenceControl.getSequenceTransfer(userVisit, associatePartyContactMechanismSequence); Sequence associateReferralSequence = associateProgramDetail.getAssociateReferralSequence(); SequenceTransfer associateReferralSequenceTransfer = associateReferralSequence == null? null: sequenceControl.getSequenceTransfer(userVisit, associateReferralSequence); String itemIndirectSalePercent = PercentUtils.getInstance().formatFractionalPercent(associateProgramDetail.getItemIndirectSalePercent()); String itemDirectSalePercent = PercentUtils.getInstance().formatFractionalPercent(associateProgramDetail.getItemDirectSalePercent()); Boolean isDefault = associateProgramDetail.getIsDefault(); Integer sortOrder = associateProgramDetail.getSortOrder(); String description = associateControl.getBestAssociateProgramDescription(associateProgram, getLanguage()); associateProgramTransfer = new AssociateProgramTransfer(associateProgramName, associateSequenceTransfer, associatePartyContactMechanismSequenceTransfer, associateReferralSequenceTransfer, itemIndirectSalePercent, itemDirectSalePercent, isDefault, sortOrder, description); put(associateProgram, associateProgramTransfer); } return associateProgramTransfer; } } /* Copyright (c) 2021 Fraunhofer IOSB-INA Lemgo, eine rechtlich nicht selbstaendige Einrichtung der Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. Copyright (c) 2021 Fraunhofer IOSB-ILT Karlsruhe, eine rechtlich nicht selbstaendige Einrichtung der Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. Copyright (c) 2021 Fraunhofer IAIS, eine rechtlich nicht selbstaendige Einrichtung der Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. Copyright (c) 2021 Fraunhofer IESE, eine rechtlich nicht selbstaendige Einrichtung der Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. Copyright (c) 2021 Fraunhofer IWU Karlsruhe, eine rechtlich nicht selbstaendige Einrichtung der Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. This source code is licensed under the Apache License 2.0 (see LICENSE.txt). This source code may use other Open Source software components (see LICENSE.txt). */ package io.adminshell.aas.v3.model.impl; import java.util.Objects; import io.adminshell.aas.v3.util.*; import io.adminshell.aas.v3.dataformat.*; import io.adminshell.aas.v3.model.*; import io.adminshell.aas.v3.model.builder.*; /** * Default implementation of package io.adminshell.aas.v3.model.Key * * A key is a reference to an element by its id. */ public class DefaultKey implements Key { @IRI("https://admin-shell.io/aas/3/0/RC01/Key/idType") protected KeyType idType; @IRI("https://admin-shell.io/aas/3/0/RC01/Key/type") protected KeyElements type; @IRI("https://admin-shell.io/aas/3/0/RC01/Key/value") protected String value; public DefaultKey() {} @Override public int hashCode() { return Objects.hash(this.idType, this.type, this.value); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj == null) { return false; } else if (this.getClass() != obj.getClass()) { return false; } else { DefaultKey other = (DefaultKey) obj; return Objects.equals(this.idType, other.idType) && Objects.equals(this.type, other.type) && Objects.equals(this.value, other.value); } } @Override public KeyType getIdType() { return idType; } @Override public void setIdType(KeyType idType) { this.idType = idType; } @Override public KeyElements getType() { return type; } @Override public void setType(KeyElements type) { this.type = type; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } /** * This builder class can be used to construct a DefaultKey bean. */ public static class Builder extends KeyBuilder { @Override protected Builder getSelf() { return this; } @Override protected DefaultKey newBuildingInstance() { return new DefaultKey(); } } } P3trur0/heartbit package io.hackitaly.jmusixmatch.entity; import com.google.gson.annotations.SerializedName; /** * A class to denote the Header part of the JSON body. * * The Header contains the following elements : * 1. status_code * 2. execute_time * 3. available * * @author * @version 1.0 */ public class Header { @SerializedName("status_code") private int status_code; @SerializedName("execute_time") private float execute_time; @SerializedName("available") private int available; /** * @return the status_code */ public int getStatus_code() { return status_code; } /** * @param status_code * the status_code to set */ public void setStatus_code(int status_code) { this.status_code = status_code; } /** * @return the execute_time */ public float getExecute_time() { return execute_time; } /** * @param execute_time * the execute_time to set */ public void setExecute_time(float execute_time) { this.execute_time = execute_time; } /** * @return the available */ public int getAvailable() { return available; } /** * @param available * the available to set */ public void setAvailable(int available) { this.available = available; } public String toString() { return status_code + " : " + execute_time; } } mathletfactory_lib/src/net/mumie/mathletfactory/math/algebra/op/node/MultipleOfZNode.java /* * The MIT License (MIT) * * Copyright (c) 2010 Technische Universitaet Berlin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.mumie.mathletfactory.math.algebra.op.node; import java.text.DecimalFormat; import net.mumie.mathletfactory.math.algebra.rel.node.RelNode; import net.mumie.mathletfactory.math.number.NumberFactory; /** * This node represents an Operation that is a multiple of Z, i.e. this node * represents any integer Number that is needed solving an equation or * relation where this node occurs in a left- or right hand side. * WARNING: This node is only for internal use and should not be used by * Application Programmers! * @author Paehler * @mm.docstatus finished */ public class MultipleOfZNode extends OpNode { private Integer m_zValue = null; private boolean m_naturalsOnly = false; public MultipleOfZNode(Class entryClass) { super(entryClass); m_base.setDouble(0); m_zValue = new Integer(0); } public boolean isLeaf(){ return true; } protected String nodeToContentMathML() { return ""; } public String nodeToString() { return m_naturalsOnly ? "\u2115" : "\u2124"; } public String toString(int printFlags, DecimalFormat format){ return printFactorAndExponent(nodeToString(), printFlags, format); } /** * Returns true if only the natural numbers are allowed. */ public boolean isNaturalsOnly(){ return m_naturalsOnly; } /** * Sets, whether only the natural numbers are allowed. */ public void setNaturalsOnly(boolean naturalsOnly){ m_naturalsOnly = naturalsOnly; } public int getMinChildrenNr(){ return 0; } public int getMaxChildrenNr(){ return 0; } public void calculate(){ if(m_zValue == null) throw new IllegalStateException("calculation not allowed for this node without setting Z!"); m_base = NumberFactory.newInstance(m_numberClass, m_zValue.doubleValue()); } public void calculateDouble(){ if(m_zValue == null) throw new IllegalStateException("calculation not allowed for this node without setting Z!"); m_base.setDouble(m_zValue.doubleValue()); } public void setZ(int z){ m_zValue = new Integer(z); } public void setZ(Integer z){ m_zValue = z; } public Integer getZ(){ return m_zValue; } /** * Should not be called for this node. * @throws IllegalArgumentException * @see net.mumie.mathletfactory.math.algebra.op.node.OpNode#getDerivative(String) */ public OpNode getDerivative(String string){ throw new IllegalArgumentException(); } /** * Should not be called for this node. * @throws IllegalArgumentException */ public OpNode[] solveStepFor(String identifier){ throw new IllegalArgumentException(); } /** * Should not be called for this node. * @throws IllegalArgumentException */ public RelNode getMonotonicDecreasingRel(OpNode operand){ throw new IllegalArgumentException(); } /** * Should not be called for this node. * @throws IllegalArgumentException */ public RelNode getMonotonicIncreasingRel(OpNode operand){ throw new IllegalArgumentException(); } /** * Should not be called for this node. * @throws IllegalArgumentException */ public RelNode getNodeDefinedRel(OpNode operand){ throw new IllegalArgumentException(); } /** * Should not be called for this node. * @throws IllegalArgumentException */ public RelNode getZeroRel(OpNode operand){ throw new IllegalArgumentException(); } /** * Should not be called for this node. * @throws IllegalArgumentException */ public RelNode getZeroRel(){ throw new IllegalArgumentException(); } } app/src/main/java/com/hadesky/app/cacw/DeletableEditText.java package com.hadesky.app.cacw; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; /** * 自定义View,带有一个删除键 * Created by Derek on 2015/8/17. */ public class DeletableEditText extends EditText implements View.OnFocusChangeListener, TextWatcher { private int mUnderlineColor; private Paint mPaint; private int mClearIconId; private BitmapDrawable mClearIcon; private int mClearIconSize; private int mIconLeftX; private int mIconRightX; private boolean isClearIconVisible = true; private Resources mResources; public DeletableEditText(Context context) { this(context, null); } public DeletableEditText(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.editTextStyle); } public DeletableEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mResources = getResources(); TypedArray typedArray = mResources.obtainAttributes(attrs, R.styleable.DeletableEditText); final int count = typedArray.getIndexCount(); for (int i = 0; i < count; i++) { int attr = typedArray.getIndex(i); switch (attr) { case R.styleable.DeletableEditText_clear_icon: mClearIconId = typedArray.getResourceId(attr, -1); break; case R.styleable.DeletableEditText_underline_color: mUnderlineColor = typedArray.getColor(attr, mResources.getColor(android.R.color.darker_gray)); default: break; } } typedArray.recycle(); init(); } private void init() { //这里的18是调试出来的,估计换设备调试要跪 final Bitmap ClearIconBitmap = DecodeBitmap.decodeSampledBitmapFromResource(mResources, mClearIconId, 18, 18); mClearIcon = new BitmapDrawable(mResources, ClearIconBitmap); mPaint = new Paint(); mPaint.setStrokeWidth(3.0f); mPaint.setColor(mUnderlineColor); if (mClearIcon == null) { throw new RuntimeException("没有为删除图标设置资源"); } mClearIconSize = Math.max(mClearIcon.getIntrinsicWidth(), mClearIcon.getIntrinsicHeight()); //默认隐藏clear按钮 setIsClearIconVisible(false); //设置焦点变化的监听器 setOnFocusChangeListener(this); //设置内容变化监听器 addTextChangedListener(this); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //计算icon绘制的位置 mIconRightX = getMeasuredWidth() - getCompoundDrawablePadding() - getPaddingRight(); mIconLeftX = getMeasuredWidth() - mClearIconSize - getCompoundDrawablePadding() - getPaddingRight(); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (isClearIconVisible) { boolean isTouch = event.getX() > mIconLeftX && event.getX() < mIconRightX; if (isTouch) { this.setText(""); } } } return super.onTouchEvent(event); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int x=this.getScrollX(); int w=this.getMeasuredWidth(); canvas.drawLine(0, this.getHeight() - 1, w+x, this.getHeight() - 1, mPaint); } public void setIsClearIconVisible(boolean isClearIconVisible) { this.isClearIconVisible = isClearIconVisible; if (isClearIconVisible) { setCompoundDrawablesWithIntrinsicBounds(null, null, mClearIcon, null); } else { setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } } @Override public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); setIsClearIconVisible(getText().length() > 0); } @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { setIsClearIconVisible(getText().length() > 0); } else { setIsClearIconVisible(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } @Override public boolean isInEditMode() { return super.isInEditMode(); } } swmwlm/demos package net.ijiangtao.tech.demo.webasynctask.controller; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoWebasynctaskApplicationTests { @Test public void contextLoads() { } public static void main(String[] args) { System.out.println("A/B".split("|")); } } package birthday_celebrations; import birthday_celebrations.interfaces.Birthable; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List objects = new LinkedList<>(); String input = scanner.nextLine(); while (!"End".equals(input)) { String[] elements = input.split("\\s+"); switch (elements[0]) { case "Citizen": objects.add(new Citizen(elements[1], Integer.parseInt(elements[2]), elements[3], elements[4])); break; case "Pet": objects.add(new Pet(elements[1], elements[2])); break; } input = scanner.nextLine(); } String year = scanner.nextLine(); for (Birthable object : objects) { String currentDate = object.getBirthDate(); currentDate = currentDate.substring(currentDate.length() - 4); if (currentDate.equals(year)) { System.out.println(object.getBirthDate()); } } } } tanwen19932/HanLP /* *

* Hankcs * * 2016-09-05 PM8:39 * * * Copyright (c) 2008-2016, 码农场. All Right Reserved, http://www.hankcs.com/ * This source is subject to Hankcs. Please contact Hankcs to get more information. * */ package com.hankcs.hanlp.model.perceptron.feature; import com.hankcs.hanlp.model.perceptron.tagset.TagSet; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author hankcs */ public class ImmutableFeatureMap extends FeatureMap { public Map featureIdMap; public ImmutableFeatureMap(Map featureIdMap, TagSet tagSet) { super(tagSet); this.featureIdMap = featureIdMap; } public ImmutableFeatureMap(Set> entrySet, TagSet tagSet) { super(tagSet); this.featureIdMap = new HashMap(); for (Map.Entry entry : entrySet) { featureIdMap.put(entry.getKey(), entry.getValue()); } } @Override public int idOf(String string) { Integer id = featureIdMap.get(string); if (id == null) return -1; return id; } @Override public int size() { return featureIdMap.size(); } @Override public Set> entrySet() { return featureIdMap.entrySet(); } }package com.bina.varsim.fastqLiftover; import com.bina.varsim.fastqLiftover.types.GenomeLocation; import com.bina.varsim.fastqLiftover.types.MapBlock; import com.bina.varsim.types.ChrString; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for GenomeLocation */ public class GenomeLocationTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public GenomeLocationTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(GenomeLocationTest.class); } public void testGenomeLocationSimple() { final String locationString = "1-100-INV-"; final GenomeLocation genomeLocation = new GenomeLocation(locationString); assertEquals(new ChrString("1"), genomeLocation.chromosome); assertEquals(100, genomeLocation.location); assertEquals(MapBlock.BlockType.INV, genomeLocation.feature); assertEquals(1, genomeLocation.direction); } } /** * Copyright 2013 Wicked Forms (https://github.com/thombergs/wicked-forms) * * 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. */ package org.wickedsource.wickedforms.model.binding; import org.apache.commons.beanutils.PropertyUtils; /** * This implementation of the {@link Binding} interface binds a form element to * a specified property of a specified object. Using a {@link PropertyBinding}, * you can for example bind the "name" attribute of a Person object to a text * field within a form. * * @author () * * @param * the type of the bound object. */ public class PropertyBinding implements Binding { private final Object boundObject; private final String property; /** * Constructor linking the value of form element to a specified property of * a specified object. * * @param boundObject * the object that contains the property that is the target of * this binding. Note that the class of the object must be * public, otherwise the binding may lead to runtime exceptions * due to reflection errors. * @param property * the name of the property. Note that this property must be of * type T, otherwise a runtime exception will occur. The methods * {@link #getValue()} and {@link #setValue(Object)} will access * this property via reflection. Also, this property must be * accessible through public setter and getter complying to the * Java Beans standard. */ public PropertyBinding(Object boundObject, String property) { this.boundObject = boundObject; this.property = property; } @Override public void setValue(T value) { try { PropertyUtils.setSimpleProperty(boundObject, property, value); } catch (Exception e) { throw new IllegalStateException(String.format( "Binding error! Setting property '%s' on bound object of class %s failed!", property, boundObject.getClass()), e); } } @Override @SuppressWarnings("unchecked") public T getValue() { try { return (T) PropertyUtils.getSimpleProperty(boundObject, property); } catch (Exception e) { throw new IllegalStateException(String.format( "Binding error! Getting property '%s' from bound object of class %s failed!", property, boundObject.getClass()), e); } } } 1000+ /** * Copyright Microsoft Corporation * * 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. */ package com.microsoft.windowsazure.services.media.entityoperations; /** * * */ public interface EntityUpdateOperation extends EntityOperation { /** * Get the contents of the merge request that will be sent to the server. * * @return The payload object */ Object getRequestContents(); } // THIS SOURCE CODE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND, AND ITS AUTHOR AND THE JOURNAL OF MACHINE LEARNING RESEARCH (JMLR) AND JMLR'S PUBLISHERS AND DISTRIBUTORS, DISCLAIM ANY AND ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR NON INFRINGEMENT. THE USER ASSUMES ALL LIABILITY AND RESPONSIBILITY FOR USE OF THIS SOURCE CODE, AND NEITHER THE AUTHOR NOR JMLR, NOR JMLR'S PUBLISHERS AND DISTRIBUTORS, WILL BE LIABLE FOR DAMAGES OF ANY KIND RESULTING FROM ITS USE. Without lim- iting the generality of the foregoing, neither the author, nor JMLR, nor JMLR's publishers and distributors, warrant that the Source Code will be error-free, will operate without interruption, or will meet the needs of the user. // // -------------------------------------------------------------------------- // // Copyright 2016 // // This file is part of ML-Flex. // // ML-Flex 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 3 of the License, or // any later version. // // ML-Flex 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 ML-Flex. If not, see . package mlflex.evaluation; import mlflex.core.*; import mlflex.ensemblelearners.AbstractEnsembleLearner; import mlflex.helper.FileUtilities; import mlflex.helper.ListUtilities; import mlflex.helper.ResultsFileUtilities; import java.util.ArrayList; /** This class has functionality to save results from classification analyses. These results are saved in a variety of text files within the Output directory. * @author */ public class ClassificationResultsSaver { // These descriptions are used in headers of the results files as an aid to users private static final String PERFORMANCE_METRICS_COMMENT = " Measures of classification performance across all classes (dependent variables). The weighted average metrics were weighted by the class distribution. Cross-validation assignments were stratified by class, where possible."; private static final String PER_CLASS_METRICS_COMMENT = " Measures of classification performance for each class (dependent variable)."; private static final String CONFUSION_MATRIX_COMMENT = " Confusion matrix that helps visual classification performance for each class (dependent variable)."; private static final String NUM_FEATURES_COMMENT = " For the top N features identified via feature selection, the AUC that resulted when N features were used for classification. Note that it is possible none of these AUC values will be equal to the AUC values in the performance metrics files because the 'best' number of features is selected in each cross-validation fold, whereas these values are calculated using the same number of features in each fold."; private static final String ALGORITHM_OUTPUT_COMMENT = " Standard output produced by the external machine-learning library that was used for classification.\n"; private static final String PREDICTIONS_COMMENT = " Instance-level predictions produced via classification."; private static final String ENSEMBLE_COMMENT = " Various ensemble-learning approaches were used for classification. See the README files for details."; private static final String MULTI_ITERATION_COMMENT = " Each column contains the results for a given iteration."; private static final String MULTI_ITERATION_AVERAGE_COMMENT = " For each combination, results were averaged across all iterations."; private static final String OVERALL_COMMENT = " Each column contains results for a particular combination of data set and classification algorithm (and feature selection algorithm where applicable)."; private ModelSelector _modelSelector; private boolean _evaluateInner; /** Constructor that allows specification of objects that contain information about the classification tasks that have been performed. * * @param modelSelector Model selector representing the combination of data processor and algorithms for which results will be saved. * @param evaluateInner Whether to save results for inner cross-validation folds */ public ClassificationResultsSaver(ModelSelector modelSelector, boolean evaluateInner) throws Exception { _modelSelector = modelSelector; _evaluateInner = evaluateInner; } /** Saves results from a classification experiment to output files for outer (and possibly inner) cross-validation folds. * * @throws Exception */ public void SaveClassificationResults() throws Exception { Singletons.Log.Debug("Save classification results for outer fold(s)"); SaveClassificationResultValues(_modelSelector.GetResultsFilePaths(true, false), true); // Is this a training/Action experiment rather than cross-validation? If so, save prediction results for training data. if (_evaluateInner && Settings.IsTrainTestExperiment()) { Singletons.Log.Debug("Save classification results for inner fold(s)"); SaveClassificationResultValues(_modelSelector.GetResultsFilePaths(true, true), false); } Singletons.Log.Debug("Save algorithm output summary"); SaveAlgorithmOutputSummary(_modelSelector.GetResultsFilePaths(true, false).ALGORITHM_OUTPUT); } /** Saves classification result values for either inner or outer cross-validation folds. This should only get called for inner folds if we are performing a training/Action experiment. * * @param filePaths File paths indicating where the results will be stored * @param outer Whether results should be saved for outer cross-validation folds * @throws Exception */ private void SaveClassificationResultValues(ClassificationResultsFilePaths filePaths, boolean outer) throws Exception { Singletons.Log.Debug("Assign variables that depend on whether results are being saved for inner or outer cross-validation folds"); Predictions predictions = outer ? _modelSelector.GetBestOuterPredictionsAllFolds() : _modelSelector.GetBestInnerPredictions(1); Singletons.Log.Debug("Calculate and save performance metrics to " + filePaths.PERFORMANCE_METRICS); SavePerformanceMetrics(new PredictionResults(predictions), filePaths.PERFORMANCE_METRICS, PERFORMANCE_METRICS_COMMENT); Singletons.Log.Debug("Calculate and save per-class metrics"); SavePerClassMetrics(new PredictionResults(predictions), filePaths.PER_CLASS_METRICS, PER_CLASS_METRICS_COMMENT); SaveConfusionMatrix(new PredictionResults(predictions), filePaths.CONFUSION_MATRIX, CONFUSION_MATRIX_COMMENT); Singletons.Log.Debug("Save results that indicate how performance varied per number of features included in models"); SaveNumFeaturesResults(filePaths.NUM_FEATURES, _modelSelector, outer, NUM_FEATURES_COMMENT); Singletons.Log.Debug("Save file that describes predictions that have been made, including class probabilities when applicable"); SavePredictionsFile(predictions, filePaths.PREDICTIONS, PREDICTIONS_COMMENT); } /** Saves results to output files for a wide variety of performance metrics. * * @param results Prediction results object used for calculating the metrics * @param outFilePath Absolute path where the file will be saved * @param headerComment Descriptive comment that will be placed at the top of the output file * @throws Exception */ private static void SavePerformanceMetrics(PredictionResults results, String outFilePath, String headerComment) throws Exception { ArrayList nameValueResults = new ArrayList(); if (results.Predictions.Size() == 0) return; // Basic definitions for many of the evaluation metrics can be found here: http://weka.sourceforge.net/doc/weka/classifiers/Evaluation.html Singletons.Log.Debug("Save performance metrics - step 1"); nameValueResults.add(NameValuePair.Create("Weighted average AUC", results.GetWekaEvaluation().weightedAreaUnderROC())); Singletons.Log.Debug("Save performance metrics - step 1.2"); nameValueResults.add(NameValuePair.Create("Weighted average F-Measure", results.GetWekaEvaluation().weightedFMeasure())); Singletons.Log.Debug("Save performance metrics - step 1.3"); nameValueResults.add(NameValuePair.Create("Weighted average true positive rate", results.GetWekaEvaluation().weightedTruePositiveRate())); Singletons.Log.Debug("Save performance metrics - step 1.4"); nameValueResults.add(NameValuePair.Create("Weighted average false positive rate", results.GetWekaEvaluation().weightedFalsePositiveRate())); Singletons.Log.Debug("Save performance metrics - step 1.5"); nameValueResults.add(NameValuePair.Create("Weighted average sensitivity (recall)", results.GetWekaEvaluation().weightedRecall())); // Not sure what the following should mean because you don't know which class is 'positive' and which is negative' and because you may have more than two classes. These aren't displayed in Weka output, possible for same reason. //nameValueResults.add(NameValuePair.Create("Weighted True Negative Rate", results.GetWekaEvaluation().weightedTrueNegativeRate())); //nameValueResults.add(NameValuePair.Create("Weighted False Negative Rate", results.GetWekaEvaluation().weightedFalseNegativeRate())); // This one is displayed in Weka, but I'm not sure what they mean by it //nameValueResults.add(NameValuePair.Create("Weighted Specificity / Precision", results.GetWekaEvaluation().weightedPrecision())); Singletons.Log.Debug("Save performance metrics - step 2"); nameValueResults.add(NameValuePair.Create("Total number correct", results.GetTotalNumberCorrect())); nameValueResults.add(NameValuePair.Create("Total number incorrect", results.GetTotalNumberIncorrect())); nameValueResults.add(NameValuePair.Create("Accuracy", results.GetAccuracy())); nameValueResults.add(NameValuePair.Create("Error rate", results.GetErrorRate())); nameValueResults.add(NameValuePair.Create("Error rate expected by chance", results.GetBaselineErrorRate())); nameValueResults.add(NameValuePair.Create("Improvement over error rate expected by chance", results.GetBaselineImprovement())); nameValueResults.add(NameValuePair.Create("Kappa statistic", results.GetWekaEvaluation().kappa())); nameValueResults.add(NameValuePair.Create("Mean absolute error", results.GetWekaEvaluation().meanAbsoluteError())); nameValueResults.add(NameValuePair.Create("Mean prior absolute error", results.GetWekaEvaluation().meanPriorAbsoluteError())); nameValueResults.add(NameValuePair.Create("Root mean squared error", results.GetWekaEvaluation().rootMeanSquaredError())); nameValueResults.add(NameValuePair.Create("Root mean prior squared error", results.GetWekaEvaluation().rootMeanPriorSquaredError())); nameValueResults.add(NameValuePair.Create("Relative absolute error (%)", results.GetWekaEvaluation().relativeAbsoluteError())); nameValueResults.add(NameValuePair.Create("Root relative squared error (%)", results.GetWekaEvaluation().rootRelativeSquaredError())); // These copy what is output in Weka. I need to find a reference to what they actually mean Singletons.Log.Debug("Save performance metrics - step 3"); nameValueResults.add(NameValuePair.Create("Kononenko & Bratko information score (bits)", results.GetWekaEvaluation().KBInformation())); nameValueResults.add(NameValuePair.Create("Kononenko & Bratko information score (bits / instance)", results.GetWekaEvaluation().KBMeanInformation())); nameValueResults.add(NameValuePair.Create("Kononenko & Bratko relative information score (%)", results.GetWekaEvaluation().KBRelativeInformation())); // These copy what is output in Weka. I need to find a reference to what they actually mean Singletons.Log.Debug("Save performance metrics - step 4"); nameValueResults.add(NameValuePair.Create("Class complexity - order (bits)", results.GetWekaEvaluation().SFPriorEntropy())); nameValueResults.add(NameValuePair.Create("Class complexity - order (bits / instance)", results.GetWekaEvaluation().SFMeanPriorEntropy())); nameValueResults.add(NameValuePair.Create("Class complexity - scheme (bits)", results.GetWekaEvaluation().SFSchemeEntropy())); nameValueResults.add(NameValuePair.Create("Class complexity - scheme (bits / instance)", results.GetWekaEvaluation().SFMeanSchemeEntropy())); nameValueResults.add(NameValuePair.Create("Complexity improvement (bits)", results.GetWekaEvaluation().SFEntropyGain())); nameValueResults.add(NameValuePair.Create("Complexity improvement (bits / instance)", results.GetWekaEvaluation().SFMeanEntropyGain())); nameValueResults.add(0, new NameValuePair("Metric", "Result")); // Save the metrics to a file Singletons.Log.Debug("Save performance metrics - step 5"); ResultsFileUtilities.AppendMatrixColumn(nameValueResults, outFilePath, headerComment); } /** Saves results to output files for a wide variety of per-class metrics. * * @param results Prediction results object used for calculating the metrics * @param outFilePath File path where the results will be saved * @param headerComment Descriptive comment that will be placed at the top of the output file * @throws Exception */ private static void SavePerClassMetrics(PredictionResults results, String outFilePath, String headerComment) throws Exception { if (results.Predictions.Size() == 0) return; ArrayList nameValueResults = new ArrayList(); for (String dependentVariableClass : Singletons.InstanceVault.DependentVariableOptions) { nameValueResults.add(NameValuePair.Create("Number instances predicted as [" + dependentVariableClass + "]", results.GetNumPredictedAsDependentVariableClass(dependentVariableClass))); nameValueResults.add(NameValuePair.Create("Number instances predicted as [" + dependentVariableClass + "] correctly", results.GetNumPredictedAsDependentVariableClassCorrectly(dependentVariableClass))); nameValueResults.add(NameValuePair.Create("Number instances predicted as [" + dependentVariableClass + "] incorrectly", results.GetNumPredictedAsDependentVariableClassIncorrectly(dependentVariableClass))); } for (String dependentVariableClass : Singletons.InstanceVault.DependentVariableOptions) { nameValueResults.add(NameValuePair.Create("Proportion instances predicted as [" + dependentVariableClass + "]", results.GetProportionPredictedAsDependentVariableClass(dependentVariableClass))); // Could be considered true-positive rate nameValueResults.add(NameValuePair.Create("Proportion instances predicted as [" + dependentVariableClass + "] correctly", results.GetProportionPredictedAsDependentVariableClassCorrectly(dependentVariableClass))); // Could be considered false-positive rate nameValueResults.add(NameValuePair.Create("Proportion instances predicted as [" + dependentVariableClass + "] incorrectly", results.GetProportionPredictedAsDependentVariableClassIncorrectly(dependentVariableClass))); } for (String dependentVariableClass : Singletons.InstanceVault.DependentVariableOptions) { nameValueResults.add(NameValuePair.Create("Number [" + dependentVariableClass + "] instances predicted correctly", results.GetNumActualsWithDependentVariableClassThatWerePredictedCorrectly(dependentVariableClass))); nameValueResults.add(NameValuePair.Create("Number [" + dependentVariableClass + "] instances predicted incorrectly", results.GetNumActualsWithDependentVariableClassThatWerePredictedIncorrectly(dependentVariableClass))); } for (String dependentVariableClass : Singletons.InstanceVault.DependentVariableOptions) { // Could be considered sensitivity / recall nameValueResults.add(NameValuePair.Create("Proportion [" + dependentVariableClass + "] instances predicted correctly", results.GetProportionActualsWithDependentVariableClassThatWerePredictedCorrectly(dependentVariableClass))); nameValueResults.add(NameValuePair.Create("Proportion [" + dependentVariableClass + "] instances predicted incorrectly", results.GetProportionActualsWithDependentVariableClassThatWerePredictedIncorrectly(dependentVariableClass))); } nameValueResults.add(0, new NameValuePair("Metric", "Result")); ResultsFileUtilities.AppendMatrixColumn(nameValueResults, outFilePath, headerComment); } private static void SaveConfusionMatrix(PredictionResults predictionResults, String outFilePath, String headerComment) throws Exception { ArrayList> outLines = new ArrayList>(); // Add actual classes as header row outLines.add(ListUtilities.CreateStringList("")); outLines.get(0).addAll(ListUtilities.Prefix(Singletons.InstanceVault.DependentVariableOptions, "Predicted as ")); // Add rows for (String actualClass : Singletons.InstanceVault.DependentVariableOptions) { ArrayList row = ListUtilities.CreateStringList(actualClass); for (String predictedClass : Singletons.InstanceVault.DependentVariableOptions) row.add(String.valueOf(predictionResults.GetNumActualsPredictedAs(actualClass, predictedClass))); outLines.add(row); } FileUtilities.WriteLinesToFile(outFilePath, outLines, headerComment); } /** Saves results that indicate how performance varied per number of features included in models. * * @param filePath Absolute path where the results file will be saved * @param modelSelector Model selector representing the combination of data processor and algorithms for which results will be saved * @param outer Whether results should be saved for outer cross-validation folds or not * @param headerComment Descriptive comment that will be placed at the top of the output file * @throws Exception */ private void SaveNumFeaturesResults(String filePath, ModelSelector modelSelector, boolean outer, String headerComment) throws Exception { ArrayList numFeaturesOptions = Singletons.Config.GetNumFeaturesOptions(modelSelector.Processor, modelSelector.FeatureSelectionAlgorithm); if (numFeaturesOptions.size() <= 1) return; ArrayList nameValueResults = new ArrayList(); for (int numFeatures : numFeaturesOptions) { Predictions predictions = outer ? modelSelector.GetOuterPredictionsAllFolds(numFeatures) : modelSelector.GetInnerPredictions(numFeatures, 1); nameValueResults.add(NameValuePair.Create(String.valueOf(numFeatures), new PredictionResults(predictions).GetWekaEvaluation().weightedAreaUnderROC())); } nameValueResults.add(0, new NameValuePair("Number of Features", "AUC")); ResultsFileUtilities.AppendMatrixColumn(nameValueResults, filePath, headerComment); } /** Saves an output file that summarizes predictions that were made. This output file can be used by external applications to analyze the predictions. * * @param predictions Predictions object @throws Exception * @param outFilePath Absolute path where the file will be stored * @param headerComment Descriptive comment that will be placed at the top of the output file */ private static void SavePredictionsFile(Predictions predictions, String outFilePath, String headerComment) throws Exception { Singletons.Log.Debug("Beginning to save predictions"); ArrayList dependentVariableClasses = Singletons.InstanceVault.DependentVariableOptions; ArrayList> outRows = new ArrayList>(); Singletons.Log.Debug("Format the predictions file header"); ArrayList headerVals = ListUtilities.CreateStringList("Instance_ID", "Dependent_Variable_Value", "Prediction"); for (String x : dependentVariableClasses) headerVals.add(x + "_Probability"); // Singletons.Log.Debug("Include the raw dependent variable when relevant"); // if (Singletons.InstanceVault.RawDependentVariableValuesAreContinuous()) // headerVals.add(1, "Raw_Dependent_Variable_Value"); outRows.add(headerVals); // boolean rawDependentVariablesAreContinous = Singletons.InstanceVault.RawDependentVariableValuesAreContinuous(); Singletons.Log.Debug("Build output for each prediction that has been made"); for (String instanceID : predictions.GetInstanceIDs()) { Prediction prediction = predictions.Get(instanceID); ArrayList predictionVals = ListUtilities.CreateStringList(prediction.InstanceID, prediction.DependentVariableValue, prediction.Prediction); for (int i=0; i inFilePaths = new ArrayList(); ArrayList inFileDescriptions = new ArrayList(); for (PredictionEvaluator evaluator : _modelSelector.PredictionEvaluators) if (FileUtilities.FileExists(evaluator.GetAlgorithmOutputFilePath())) { inFilePaths.add(evaluator.GetAlgorithmOutputFilePath()); if (_modelSelector.PredictionEvaluators.size() > 1) { String description = ""; if (inFileDescriptions.size() > 0) description = "\n"; description += ListUtilities.Join(ListUtilities.CreateStringList("#", 50), "") + "\n"; description += "## Fold " + evaluator.OuterFold; if (Singletons.Config.GetNumFeaturesOptions(_modelSelector.Processor, _modelSelector.FeatureSelectionAlgorithm).size() > 1) description += ", Number Features = " + evaluator.NumFeatures; description += "\n"; description += ListUtilities.Join(ListUtilities.CreateStringList("#", 50), "") + "\n\n"; inFileDescriptions.add(description); } else inFileDescriptions.add(""); } if (inFilePaths.size() > 0) FileUtilities.ConcatenateFiles(inFilePaths, inFileDescriptions, outFilePath, ALGORITHM_OUTPUT_COMMENT); } /** When an experiment has multiple iterations, this method saves a summary that spans all iterations. * * @param isForTrainingData Whether the results are for training data (inner folds) * @throws Exception */ public void SaveMultiIterationClassificationResults(boolean isForTrainingData) throws Exception { // Get the column names that will be used (one for each iteration) ArrayList columnNames = ListUtilities.CreateStringList(ListUtilities.CreateIntegerSequenceList(1, Singletons.Config.GetNumIterations())); columnNames = ListUtilities.Prefix(columnNames, "Iteration "); // Combine results for performance metrics ResultsFileUtilities.CombineMatrixFiles(PERFORMANCE_METRICS_COMMENT + MULTI_ITERATION_COMMENT, ResultsFileUtilities.GetAllIterationFilePaths(_modelSelector.GetResultsFilePaths(true, isForTrainingData).PERFORMANCE_METRICS), _modelSelector.GetResultsFilePaths(false, isForTrainingData).PERFORMANCE_METRICS, false, ListUtilities.InsertIntoStringList(columnNames, "Metric", 0)); // Combine results for per-class metrics ResultsFileUtilities.CombineMatrixFiles(PER_CLASS_METRICS_COMMENT + MULTI_ITERATION_COMMENT, ResultsFileUtilities.GetAllIterationFilePaths(_modelSelector.GetResultsFilePaths(true, isForTrainingData).PER_CLASS_METRICS), _modelSelector.GetResultsFilePaths(false, isForTrainingData).PER_CLASS_METRICS, false, ListUtilities.InsertIntoStringList(columnNames, "Metric", 0)); // Combine results for number of features vs. AUC if (FeatureSelectionEvaluator.NeedToSelectFeatures(_modelSelector.Processor, _modelSelector.FeatureSelectionAlgorithm) && Singletons.Config.GetNumFeaturesOptions(_modelSelector.Processor, _modelSelector.FeatureSelectionAlgorithm).size() > 1) ResultsFileUtilities.CombineMatrixFiles(NUM_FEATURES_COMMENT + MULTI_ITERATION_COMMENT, ResultsFileUtilities.GetAllIterationFilePaths(_modelSelector.GetResultsFilePaths(true, isForTrainingData).NUM_FEATURES), _modelSelector.GetResultsFilePaths(false, isForTrainingData).NUM_FEATURES, false, ListUtilities.InsertIntoStringList(columnNames, "Number of Features", 0)); } /** This method saves results for ensemble learning. * * @param predictions Ensemble learning predictions that were made * @param filePaths Paths where the files should be stored * @throws Exception */ public static void SaveEnsembleResults(Predictions predictions, ClassificationResultsFilePaths filePaths) throws Exception { SavePerformanceMetrics(new PredictionResults(predictions), filePaths.PERFORMANCE_METRICS, PERFORMANCE_METRICS_COMMENT + ENSEMBLE_COMMENT); SavePerClassMetrics(new PredictionResults(predictions), filePaths.PER_CLASS_METRICS, PER_CLASS_METRICS_COMMENT + ENSEMBLE_COMMENT); SaveConfusionMatrix(new PredictionResults(predictions), filePaths.CONFUSION_MATRIX, CONFUSION_MATRIX_COMMENT + ENSEMBLE_COMMENT); SavePredictionsFile(predictions, filePaths.PREDICTIONS, PREDICTIONS_COMMENT + ENSEMBLE_COMMENT); } /** This method stores ensemble results when multiple iterations were performed. * * @param ensembleLearner The ensemble learner that generated the predictions * @throws Exception */ public static void SaveMultiIterationEnsembleResults(AbstractEnsembleLearner ensembleLearner) throws Exception { ArrayList columnNames = ListUtilities.CreateStringList(ListUtilities.CreateIntegerSequenceList(1, Singletons.Config.GetNumIterations())); columnNames = ListUtilities.Prefix(columnNames, "Iteration "); ResultsFileUtilities.CombineMatrixFiles(PERFORMANCE_METRICS_COMMENT + MULTI_ITERATION_COMMENT, ResultsFileUtilities.GetAllIterationFilePaths(ensembleLearner.GetResultsFilePaths(true).PERFORMANCE_METRICS), ensembleLearner.GetResultsFilePaths(false).PERFORMANCE_METRICS, false, ListUtilities.InsertIntoStringList(columnNames, "Metric", 0)); ResultsFileUtilities.CombineMatrixFiles(PER_CLASS_METRICS_COMMENT + MULTI_ITERATION_COMMENT, ResultsFileUtilities.GetAllIterationFilePaths(ensembleLearner.GetResultsFilePaths(true).PER_CLASS_METRICS), ensembleLearner.GetResultsFilePaths(false).PER_CLASS_METRICS, false, ListUtilities.InsertIntoStringList(columnNames, "Metric", 0)); } /** This method saves output files that summarize the performance of the entire experiment at a high level. When multiple iterations are used, the values are averaged. * * @throws Exception */ public static void SaveOverallResultsSummaries() throws Exception { String outDirPath = Settings.GetOutputResultsDir("", false); ArrayList inDirPaths = new ArrayList(); ArrayList headerItems = ListUtilities.CreateStringList(""); // Add a column name for each model selector for (ModelSelector modelSelector : ModelSelector.GetAllModelSelectors()) { inDirPaths.add(modelSelector.GetResultsFilePaths(false, false).DIRECTORY_PATH); headerItems.add(modelSelector.GetDescription(" - ")); } // Add a column name for each ensemble learner for (AbstractEnsembleLearner ensembleLearner : AbstractEnsembleLearner.GetAllEnsembleLearners()) { inDirPaths.add(ensembleLearner.GetResultsFilePaths(false).DIRECTORY_PATH); headerItems.add(ensembleLearner.GetFormattedDescription()); } ClassificationResultsFilePaths fileNames = new ClassificationResultsFilePaths(""); // Save the summary for performance metrics ResultsFileUtilities.CombineMatrixFiles("", ListUtilities.AppendStringToListItems(inDirPaths, fileNames.PERFORMANCE_METRICS), outDirPath + fileNames.PERFORMANCE_METRICS, true, null); String headerComment = "#" + PERFORMANCE_METRICS_COMMENT + OVERALL_COMMENT + (Singletons.Config.GetNumIterations() > 1 ? MULTI_ITERATION_AVERAGE_COMMENT : ""); FileUtilities.InsertFileHeaderLine(outDirPath + fileNames.PERFORMANCE_METRICS, headerComment + "\n" + ListUtilities.Join(headerItems, "\t")); // Save the summary for per-class metrics ResultsFileUtilities.CombineMatrixFiles("", ListUtilities.AppendStringToListItems(inDirPaths, fileNames.PER_CLASS_METRICS), outDirPath + fileNames.PER_CLASS_METRICS, true, null); headerComment = "#" + PER_CLASS_METRICS_COMMENT + OVERALL_COMMENT + (Singletons.Config.GetNumIterations() > 1 ? MULTI_ITERATION_AVERAGE_COMMENT : ""); FileUtilities.InsertFileHeaderLine(outDirPath + fileNames.PER_CLASS_METRICS, headerComment + "\n" + ListUtilities.Join(headerItems, "\t")); } }src/test/java/com/android/tools/r8/optimize/argumentpropagation/ReturnTypeStrengtheningTest.java // Copyright (c) 2022, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.optimize.argumentpropagation; import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.android.tools.r8.NeverInline; import com.android.tools.r8.NoVerticalClassMerging; import com.android.tools.r8.TestBase; import com.android.tools.r8.TestParameters; import com.android.tools.r8.TestParametersCollection; import com.android.tools.r8.utils.codeinspector.ClassSubject; import com.android.tools.r8.utils.codeinspector.FoundClassSubject; import com.android.tools.r8.utils.codeinspector.FoundMethodSubject; import com.android.tools.r8.utils.codeinspector.InstructionSubject; import com.android.tools.r8.utils.codeinspector.MethodSubject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ReturnTypeStrengtheningTest extends TestBase { @Parameter(0) public TestParameters parameters; @Parameters(name = "{0}") public static TestParametersCollection data() { return getTestParameters().withAllRuntimesAndApiLevels().build(); } @Test public void test() throws Exception { testForR8(parameters.getBackend()) .addInnerClasses(getClass()) .addKeepMainRule(Main.class) .enableInliningAnnotations() .enableNoVerticalClassMergingAnnotations() // TODO(b/173398086): uniqueMethodWithName() does not work with argument changes. .noMinification() .setMinApi(parameters.getApiLevel()) .compile() .inspect( inspector -> { ClassSubject mainClassSubject = inspector.clazz(Main.class); assertThat(mainClassSubject, isPresent()); ClassSubject aClassSubject = inspector.clazz(A.class); assertThat(aClassSubject, isPresent()); // Return type of get() should be strengthened to A. MethodSubject getMethodSubject = mainClassSubject.uniqueMethodWithName("get"); assertThat(getMethodSubject, isPresent()); assertEquals( aClassSubject.getFinalName(), getMethodSubject.getProgramMethod().getReturnType().getTypeName()); // Method consume(I) should be rewritten to consume(A). MethodSubject testBMethodSubject = mainClassSubject.uniqueMethodWithName("consume"); assertThat(testBMethodSubject, isPresent()); assertEquals( aClassSubject.getFinalName(), testBMethodSubject.getProgramMethod().getParameter(0).getTypeName()); // There should be no casts in the application. for (FoundClassSubject classSubject : inspector.allClasses()) { for (FoundMethodSubject methodSubject : classSubject.allMethods()) { assertTrue( methodSubject .streamInstructions() .noneMatch(InstructionSubject::isCheckCast)); } } }) .run(parameters.getRuntime(), Main.class) .assertSuccessWithOutputLines("A"); } static class Main { public static void main(String[] args) { consume(get()); } @NeverInline static I get() { return new A(); } @NeverInline static void consume(I i) { i.m(); } } @NoVerticalClassMerging interface I { void m(); } static class A implements I { @Override public void m() { System.out.println("A"); } } } 0 /* * Copyright 2013 Cloudera Inc. * * 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. */ package org.kitesdk.compat; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; public class DynConstructors { public static class Ctor extends DynMethods.UnboundMethod { private final Constructor ctor; private final Class constructed; private Ctor(Constructor constructor, Class constructed) { super(null, "newInstance"); this.ctor = constructor; this.constructed = constructed; } public Class getConstructedClass() { return constructed; } public C newInstanceChecked(Object... args) throws Exception { try { return ctor.newInstance(args); } catch (InstantiationException e) { throw e; } catch (IllegalAccessException e) { throw e; } catch (InvocationTargetException e) { // rethrow the cause is an exception Throwables.propagateIfPossible(e.getCause(), Exception.class); // otherwise, propagate the throwable throw Throwables.propagate(e.getCause()); } } public C newInstance(Object... args) { try { return newInstanceChecked(args); } catch (Exception e) { throw Throwables.propagate(e); } } @Override @SuppressWarnings("unchecked") public R invoke(Object target, Object... args) { Preconditions.checkArgument(target == null, "Invalid call to constructor: target must be null"); return (R) newInstance(target, args); } @Override @SuppressWarnings("unchecked") public R invokeChecked(Object target, Object... args) throws Exception { Preconditions.checkArgument(target == null, "Invalid call to constructor: target must be null"); return (R) newInstanceChecked(args); } @Override public boolean isStatic() { return true; } @Override public String toString() { return Objects.toStringHelper(this) .add("constructor", ctor) .add("class", constructed) .toString(); } } public static class Builder { private final Class baseClass; private Ctor ctor = null; public Builder(Class baseClass) { this.baseClass = baseClass; } public Builder() { this.baseClass = null; } public Builder impl(Class... types) { impl(baseClass, types); return this; } public Builder impl(String className, Class... types) { // don't do any work if an implementation has been found if (ctor != null) { return this; } try { Class targetClass = Class.forName(className); impl(targetClass, types); } catch (NoClassDefFoundError e) { // cannot load this implementation } catch (ClassNotFoundException e) { // not the right implementation } return this; } public Builder impl(Class targetClass, Class... types) { // don't do any work if an implementation has been found if (ctor != null) { return this; } try { ctor = new Ctor(targetClass.getConstructor(types), targetClass); } catch (NoSuchMethodException e) { // not the right implementation } return this; } public Builder hiddenImpl(Class... types) { hiddenImpl(baseClass, types); return this; } @SuppressWarnings("unchecked") public Builder hiddenImpl(String className, Class... types) { // don't do any work if an implementation has been found if (ctor != null) { return this; } try { Class targetClass = Class.forName(className); hiddenImpl(targetClass, types); } catch (NoClassDefFoundError e) { // cannot load this implementation } catch (ClassNotFoundException e) { // not the right implementation } return this; } public Builder hiddenImpl(Class targetClass, Class... types) { // don't do any work if an implementation has been found if (ctor != null) { return this; } try { Constructor hidden = targetClass.getDeclaredConstructor(types); AccessController.doPrivileged(new MakeAccessible(hidden)); ctor = new Ctor(hidden, targetClass); } catch (SecurityException e) { // unusable } catch (NoSuchMethodException e) { // not the right implementation } return this; } @SuppressWarnings("unchecked") public Ctor buildChecked() throws NoSuchMethodException { if (ctor != null) { return ctor; } throw new NoSuchMethodException( "Cannot find constructor for " + baseClass); } @SuppressWarnings("unchecked") public Ctor build() { if (ctor != null) { return ctor; } throw new RuntimeException("Cannot find constructor for " + baseClass); } } private static class MakeAccessible implements PrivilegedAction { private Constructor hidden; public MakeAccessible(Constructor hidden) { this.hidden = hidden; } @Override public Void run() { hidden.setAccessible(true); return null; } } } JingZiLa/aliyun-openapi-java-sdk /* * 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. */ package com.aliyuncs.outboundbot.transform.v20191226; import com.aliyuncs.outboundbot.model.v20191226.PublishScriptResponse; import com.aliyuncs.transform.UnmarshallerContext; public class PublishScriptResponseUnmarshaller { public static PublishScriptResponse unmarshall(PublishScriptResponse publishScriptResponse, UnmarshallerContext _ctx) { publishScriptResponse.setRequestId(_ctx.stringValue("PublishScriptResponse.RequestId")); publishScriptResponse.setSuccess(_ctx.booleanValue("PublishScriptResponse.Success")); publishScriptResponse.setCode(_ctx.stringValue("PublishScriptResponse.Code")); publishScriptResponse.setMessage(_ctx.stringValue("PublishScriptResponse.Message")); publishScriptResponse.setHttpStatusCode(_ctx.integerValue("PublishScriptResponse.HttpStatusCode")); return publishScriptResponse; } }biblioteca-back/src/main/java/co/edu/uniandes/quantum/biblioteca/entities/BlogEntity.java0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.quantum.biblioteca.entities; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.ManyToOne; /** * * @author da.leon */ @Entity public class BlogEntity extends BaseEntity implements Serializable{ @ManyToOne private UsuarioEntity miUsuario; /** * titulo del libro sobre el cual se crea el blog */ private String tituloLibro; /** * cambia el titulo del libro * @param nuevoTitulo nuevo titulo del libro */ public void setTituloLibro(String nuevoTitulo) { tituloLibro = nuevoTitulo; } /** * obtiene el titulo del libro * @return devuelve el titulo del libro */ public String getTituloLibro() { return tituloLibro; } } /** * Copyright 2021 Shulie Technology, Co.Ltd * Email: * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pamirs.attach.plugin.shadowjob.common.api; import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * 作业操作的模板. * * @author zhangliang */ public final class JobOperateTemplate { private final CoordinatorRegistryCenter registryCenter; public JobOperateTemplate(CoordinatorRegistryCenter registryCenter) { this.registryCenter = registryCenter; } /** * 作业操作. * * @param jobName 作业名称 * @param serverIp 作业服务器IP地址 * @return 操作失败的作业服务器IP地址列表(作业维度操作)或作业名称列表(IP维度操作) */ public Collection operate(final String jobName, final String serverIp, final JobOperateCallback callback) { Collection result; if (jobName != null && serverIp != null) { boolean isSuccess = callback.doOperate(jobName, serverIp); if (!isSuccess) { result = new ArrayList(1); result.add(serverIp); } else { result = Collections.emptyList(); } } else if (jobName != null) { JobNodePath jobNodePath = new JobNodePath(jobName); List ipList = registryCenter.getChildrenKeys(jobNodePath.getServerNodePath()); result = new ArrayList(ipList.size()); for (String each : ipList) { boolean isSuccess = callback.doOperate(jobName, each); if (!isSuccess) { result.add(each); } } } else { List jobNames = registryCenter.getChildrenKeys("/"); result = new ArrayList(jobNames.size()); for (String each : jobNames) { boolean isSuccess = callback.doOperate(each, serverIp); if (!isSuccess) { result.add(each); } } } return result; } } dreajay/jcodejCodes-jms/src/main/java/com/jcodes/jms/JMSSubscriber.java package com.jcodes.jms; import java.util.Hashtable; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.directory.InitialDirContext; /** * 1. 在JNDI 名称空间查找TopicConnectionFactory 和Topic; * 2. 创建Topic Connection; * 3. 创建TopicSession; * 4. 创建TopicSubscriber; * 5. 从Topic 接收预订; * 6. 关闭并断开与连接对象的连接。 * @author dreajay * Dec 14, 2012 */ public class JMSSubscriber { public static void main(String[] args) { String topicName = "cn=psTopic"; String tcfName = "cn=psTcf"; Context jndiContext = null; TopicConnectionFactory topicConnectionFactory = null; TopicConnection topicConnection = null; TopicSession topicSession = null; Topic topic = null; TopicSubscriber subscriber = null; TextMessage message = null; String initialContextFactory = "com.sun.jndi.fscontext.RefFSContextFactory"; String providerUrl = "file:/D:/JNDI"; // String initialContextFactory = "com.ibm.ejs.ns.jndi.CNInitialContextFactory"; // String providerUrl = "iiop://itsog:900/ptpCtx"; // String providerUrl = "ldap://itsog/cn=psCtx,o=itsog,c=uk"; // String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory"; try { // Step 2 Set up Initial Context for JNDI lookup(步骤二,建立初始上下文以便JNDI 查找。) Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.REFERRAL, "throw"); jndiContext = new InitialDirContext(env); // Step 3 Get the TopicConnection factory from the JNDI Namespace(步骤三,从JNDI 名称空间获取主题连接库。) topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup(tcfName); // Step 4 Create a TopicConnection(步骤四,创建主题连接。) topicConnection = topicConnectionFactory.createTopicConnection(); // Step 5 Start The topic connection(步骤五,启动主题连接。) topicConnection.start(); // Step 6 Create a topic session from the topic connection(步骤六,从主题连接创建主题会话。) topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // Step 7 Obtain a Topic from the JNDI namespace(步骤七,从JNDI名称空间获取主题。) topic = (Topic) jndiContext.lookup(topicName); // Step 8 Create a topic subscriber for the topic.(步骤八,为主题创建主题订户。) subscriber = topicSession.createSubscriber(topic);// Non durable subscriber(非持久预定者) // Step 9 Receive Subscription(步骤九,接收预订。) message = (TextMessage) subscriber.receive(); System.out.println("\n *** The Message is " + message.getText()); // Step 10 Close the connection and other open resources(步骤十,关闭连接和其它打开资源。) subscriber.close(); topicSession.close(); topicConnection.close(); } catch (Exception e) { e.printStackTrace(); } } } package com.floreerin.doit_android_sample_ui; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.google.android.material.navigation.NavigationView; public class ch06_MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentCallback { private long backkeyClickTime = 0; Toolbar ch06_toolbar; ch06_Fragment1 ch06_fragment1; ch06_Fragment2 ch06_fragment2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ch06_activity_main); // 상단 바 설정 ch06_toolbar = findViewById(R.id.ch06_toolbar); setSupportActionBar(ch06_toolbar); // 전체 화면 설정 DrawerLayout drawer = findViewById(R.id.ch06_drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, ch06_toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); // 바로가기 메뉴 화면 설정 NavigationView navigationView = findViewById(R.id.ch06_nav_view); navigationView.setNavigationItemSelectedListener(this); // 프레그먼트 설정 ch06_fragment1 = new ch06_Fragment1(); ch06_fragment2 = new ch06_Fragment2(); getSupportFragmentManager().beginTransaction().add(R.id.ch06_showview, ch06_fragment1).commit(); // 처음에 나오는 화면은 fragment1으로 설정 } // 바로가기 메뉴가 나타난 상태에서 back 버튼 클릭 시 @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.ch06_drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { if( System.currentTimeMillis() > backkeyClickTime + 2000){ backkeyClickTime = System.currentTimeMillis(); Toast.makeText(getApplicationContext(), "뒤로 가기 버튼을 누르면 메인화면으로 이동합니다.",Toast.LENGTH_LONG).show(); } else if(System.currentTimeMillis() <= backkeyClickTime + 2000){ finish(); } } } // 네비게이션 메뉴 클릭 이벤트 @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { int id = menuItem.getItemId(); if (id == R.id.ch06_nav_1){ onFragmentSelected(1, null); } else if (id == R.id.ch06_nav_2){ onFragmentSelected(2, null); } DrawerLayout drawer = findViewById(R.id.ch06_drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onFragmentSelected(int position, Bundle bundle) { Fragment curFragment = null; if(position == 1){ curFragment = ch06_fragment1; ch06_toolbar.setTitle("서비스(Service)"); } else if (position == 2){ curFragment = ch06_fragment2; ch06_toolbar.setTitle("브로드케스트, 위험권한"); } getSupportFragmentManager().beginTransaction().replace(R.id.ch06_showview, curFragment).commit(); } } package ch.fcappenzell.tools.tournamentOrganiser.service; import ch.fcappenzell.tools.tournamentOrganiser.model.team.Team; import ch.fcappenzell.tools.tournamentOrganiser.repo.TeamRepo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static java.lang.Boolean.TRUE; @RequiredArgsConstructor @Service @Transactional @Slf4j public class TeamsService { private final TeamRepo teamRepo; public List list() throws Exception { log.info("Fetching all teams"); return teamRepo.findAll(); } public Team get(Long id) throws Exception { log.info("Fetching team by id: {}", id); return teamRepo.findById(id).get(); } public Team create(Team team) throws Exception { log.info("Saving new Team: {}", team.getName()); return teamRepo.save(team); } public List createTeams(List teams) throws Exception { teams.forEach(team -> log.info("Saving new Team: {}", team)); return teamRepo.saveAll(teams); } public Team update(Team team) throws Exception { log.info("Updating team: {}", team.getName()); return teamRepo.save(team); } public Boolean delete(Long id) throws Exception{ log.info("Deleting team by ID: {}", id); teamRepo.deleteById(id); return TRUE; } } src/main/java/net/lshift/spki/convert/DiscriminatingConverter.java package net.lshift.spki.convert; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.lshift.spki.InvalidInputException; import net.lshift.spki.sexpform.Sexp; /** * Convert to/from a clazz given a list of known subclasses * each with a different SExpName */ public class DiscriminatingConverter extends ConverterImpl { private final Map> nameMap = new HashMap<>(); private final Set> classes = new HashSet<>(); public DiscriminatingConverter( final Class clazz, final Class[] classes) { super(clazz); for (final Class subclass: classes) { addClass(subclass); } } private void addClass(final Class subclass) { if (!clazz.isAssignableFrom(subclass)) { throw new ConvertReflectionException(this, subclass, "Class is not a subclass of " + clazz.getCanonicalName()); } final Converter converter = ConverterCache.getConverter(subclass); if (!(converter instanceof ListConverter)) { throw new ConvertReflectionException(this, subclass, "Converter isn't a list converter"); } final String name = ((ListConverter)converter).getName(); if (nameMap.containsKey(name)) { throw new ConvertReflectionException(this, subclass, "Two subclasses share the sexp name " + name); } nameMap.put(name, subclass); this.classes.add(subclass); } @Override public Sexp write(final T o) { @SuppressWarnings("unchecked") final Class subclass = (Class) o.getClass(); if (!classes.contains(subclass) && getDiscriminatedSuperclass(subclass) != clazz) { throw new ConvertReflectionException(this, subclass, "Class is not a member of discriminated union: " + clazz.getCanonicalName()); } return writeUnchecked(subclass, o); } @Override public T read(final ConverterCatalog r, final Sexp in) throws InvalidInputException { final byte[] discrim = in.list().getHead().getBytes(); final String stringDiscrim = ConvertUtils.stringOrNull(discrim); final Class subclass = lookupSubclass(r, stringDiscrim); assertMatches(discrim, stringDiscrim); return readElement(subclass, r, in); } protected Class lookupSubclass( final ConverterCatalog r, final String stringDiscrim) throws ConvertException { Class subclass = nameMap.get(stringDiscrim); if (subclass == null) { subclass = r.getExtraDiscrim(clazz, stringDiscrim); } if (subclass == null) { throw new ConvertException( "Unable to find converter: " + stringDiscrim); } return subclass; } public static Class getDiscriminatedSuperclass(Class clazz) { List> answers = new ArrayList<>(); getDiscriminatedSuperclasses(clazz, answers, clazz); if (answers.isEmpty()) { throw new ConvertReflectionException(clazz, "has no discriminated superclass"); } if (answers.size() > 1) { throw new ConvertReflectionException(clazz, "is ambiguous: discriminated superclasses " + answers); } return answers.get(0); } private static void getDiscriminatedSuperclasses( Class clazz, List> answers, Class sup) { if (sup == null) return; if (sup.getAnnotation(Convert.Discriminated.class) != null) { answers.add(sup); return; } getDiscriminatedSuperclasses(clazz, answers, sup.getSuperclass()); for (Class supsup: sup.getInterfaces()) { getDiscriminatedSuperclasses(clazz, answers, supsup); } } public String toString() { return String.format("DiscriminatingConverter<%s>", clazz.getSimpleName()) ; } } eventstorm-projects/eventstormeventstorm-sql-apt/src/main/java/eu/eventstorm/sql/apt/ViewMapperFactoryGenerator.java package eu.eventstorm.sql.apt; import static eu.eventstorm.sql.apt.Helper.writeNewLine; import java.io.IOException; import java.io.Writer; import java.util.List; import javax.annotation.processing.ProcessingEnvironment; import javax.tools.JavaFileObject; import eu.eventstorm.sql.apt.log.Logger; import eu.eventstorm.sql.apt.log.LoggerFactory; import eu.eventstorm.sql.apt.model.ViewDescriptor; import eu.eventstorm.sql.jdbc.ResultSetMapper; /** * @author */ public final class ViewMapperFactoryGenerator implements Generator { private final Logger logger; public ViewMapperFactoryGenerator() { logger = LoggerFactory.getInstance().getLogger(ViewMapperFactoryGenerator.class); } public void generate(ProcessingEnvironment env, SourceCode sourceCode) { sourceCode.forEachViewByPackage((pack, descriptors) -> { try { create(env, pack, descriptors); } catch (Exception cause) { logger.error("ViewMapperFactoryGenerator -> Exception for [" + pack + "] -> [" + cause.getMessage() + "]", cause); } }); } public void create(ProcessingEnvironment env, String pack, List descriptors) throws IOException { JavaFileObject object = env.getFiler().createSourceFile(pack + ".Mappers"); Writer writer = object.openWriter(); Helper.writePackage(writer, pack); Helper.writeGenerated(writer, ViewMapperFactoryGenerator.class.getName()); writer.write("public final class Mappers {"); Helper.writeNewLine(writer); for (ViewDescriptor desc : descriptors) { Helper.writeNewLine(writer); writer.write(" public static final "); writer.write(ResultSetMapper.class.getName()); writer.write("<"); writer.write(desc.element().toString()); writer.write("> "); writer.write(Helper.toUpperCase(desc.element().getSimpleName().toString())); writer.write(" = new "); writer.write(desc.element().getSimpleName().toString()); writer.write("Mapper();"); Helper.writeNewLine(writer); } Helper.writeNewLine(writer); writer.write('}'); writer.close(); } } package com.github.saturn220.dispatcher; import java.io.Serializable; /** * Container of event data transmitted to listeners. * * @author * @since 06.05.2020 */ public class EventData implements Serializable { protected Object value; protected Object value2; protected Object value3; protected EventData() {} public EventData(Object value) { this.value = value; } public EventData(Object value1, Object value2) { this.value = value1; this.value2 = value2; } public EventData(Object value1, Object value2, Object value3) { this.value = value1; this.value2 = value2; this.value3 = value3; } @SuppressWarnings("unchecked") public T get() { return (T) value; } @SuppressWarnings("unchecked") public T get2() { return (T) value2; } @SuppressWarnings("unchecked") public T get3() { return (T) value3; } public T get(Class clazz) { return cast(clazz, value); } public T get2(Class clazz) { return cast(clazz, value2); } public T get3(Class clazz) { return cast(clazz, value3); } private T cast(Class clazz, Object value) { if (!clazz.isInstance(value)) { System.err.println("Dispatcher. Cannot cast to: " + clazz); return null; } return clazz.cast(value); } private String toStringIsNotNull(Object obj) { return toStringIsNotNull(obj, ""); } private String toStringIsNotNull(Object obj, String separator) { if (obj == null) return ""; return separator + obj; } @Override public String toString() { return toStringIsNotNull(value) + toStringIsNotNull(value2, ":") + toStringIsNotNull(value3, ":"); } } package com.quantcast.mode; import com.quantcast.commands.CommandsExecutorFactory; import com.quantcast.exceptions.InvalidCommandException; import com.quantcast.input.InputArgs; import com.quantcast.input.InputHandler; import com.quantcast.model.Command; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Mode running in which input commands are given from an interactive shell. */ public class InteractiveMode extends Mode { Command command ; public InteractiveMode( final CommandsExecutorFactory commandExecutorFactory) { super(commandExecutorFactory); command = new Command(); } /** * {@inheritDoc} */ @Override public void process() throws IOException, InvalidCommandException { final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String input = reader.readLine(); InputHandler inputHandler = new InputHandler(); InputArgs inputArgs = inputHandler.getInputArgs(processUserInput(input)); command.setInputArgs(inputArgs); processCommand(command); } @Override public void process(InputArgs inputArgs) throws IOException, InvalidCommandException { command.setInputArgs(inputArgs); processCommand(command); } public String[] processUserInput(String inputLine) throws InvalidCommandException { final List tokensList = Arrays.stream(inputLine.trim().split(" ")) .map(String::trim) .filter(token -> (token.length() > 0)).collect(Collectors.toList()); String a[]=new String[tokensList.size()-1]; if (tokensList.size() == 0) { throw new InvalidCommandException(); } command.setCommandName( tokensList.get(0).toLowerCase()); tokensList.remove(0); return tokensList.toArray(a); } } dgtransport/src/main/java/com/paxonpilot/dgtransport/controller/MainViewController.java0 package com.paxonpilot.dgtransport.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainViewController extends BaseController{ @RequestMapping("/sys/mainview") public String mainList(HttpServletRequest request){ return "/main"; } @RequestMapping("/history") public String historyList(){ return "/history"; } } src/test/java/org/elasticsearch/test/unit/common/xcontent/builder/BuilderRawFieldTests.java /* * Licensed to ElasticSearch and under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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. */ package org.elasticsearch.test.unit.common.xcontent.builder; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.testng.annotations.Test; import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; /** * */ public class BuilderRawFieldTests { @Test public void testJsonRawField() throws IOException { testRawField(XContentType.JSON); } @Test public void testSmileRawField() throws IOException { testRawField(XContentType.SMILE); } private void testRawField(XContentType type) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(type); builder.startObject(); builder.field("field1", "value1"); builder.rawField("_source", XContentFactory.contentBuilder(type).startObject().field("s_field", "s_value").endObject().copiedBytes()); builder.field("field2", "value2"); builder.endObject(); XContentParser parser = XContentFactory.xContent(type).createParser(builder.copiedBytes()); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("field1")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING)); assertThat(parser.text(), equalTo("value1")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("_source")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.START_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("s_field")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING)); assertThat(parser.text(), equalTo("s_value")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT)); assertThat(parser.nextToken(), equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("field2")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.VALUE_STRING)); assertThat(parser.text(), equalTo("value2")); assertThat(parser.nextToken(), equalTo(XContentParser.Token.END_OBJECT)); } } /* * ********************************************************************************************************************* * * TheseFoolishThings: Miscellaneous utilities * http://tidalwave.it/projects/thesefoolishthings * * Copyright (C) 2009 - 2021 by Tidalwave s.a.s. (http://tidalwave.it) * * ********************************************************************************************************************* * * 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. * * ********************************************************************************************************************* * * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src * git clone https://github.com/tidalwave-it/thesefoolishthings-src * * ********************************************************************************************************************* */ package it.tidalwave.role.ui.spi; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import it.tidalwave.util.As; import it.tidalwave.util.AsException; import it.tidalwave.util.Id; import it.tidalwave.util.RoleFactory; import it.tidalwave.util.spi.AsDelegateProvider; import it.tidalwave.role.ContextManager; import it.tidalwave.role.Identifiable; import it.tidalwave.role.SimpleComposite; import it.tidalwave.role.spi.DefaultContextManagerProvider; import it.tidalwave.role.ui.PresentationModel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static java.util.Collections.emptyList; import static it.tidalwave.util.Parameters.r; import static it.tidalwave.role.SimpleComposite._SimpleComposite_; import static org.testng.Assert.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.*; /*********************************************************************************************************************** * * @author * **********************************************************************************************************************/ @Slf4j public class SimpleCompositePresentableTest { /******************************************************************************************************************* * ******************************************************************************************************************/ public static class MockDatum implements As, Identifiable { @Getter @Nonnull private final Id id; @CheckForNull private SimpleComposite composite; @Getter private List children = new ArrayList<>(); public MockDatum (@Nonnull final String id) { this.id = new Id(id); } @Nonnull public MockDatum withChildren (@Nonnull final MockDatum ... children) { return withChildren(Arrays.asList(children)); } @Nonnull public MockDatum withChildren (@Nonnull final List children) { composite = SimpleComposite.ofCloned(this.children = children); return this; } @Override @Nonnull public T as (@Nonnull final Class roleType) { return as(roleType, As.Defaults.throwAsException(roleType)); } @Override @Nonnull public T as (@Nonnull final Class roleType, @Nonnull final NotFoundBehaviour notFoundBehaviour) { if (roleType.equals(SimpleComposite.class) && (composite != null)) { return roleType.cast(composite); } return notFoundBehaviour.run(new AsException(roleType)); } @Override @Nonnull public Collection asMany (@Nonnull final Class roleType) { if (roleType.equals(SimpleComposite.class) && (composite != null)) { return new ArrayList<>(Arrays.asList(roleType.cast(composite))); } return new ArrayList<>(); } @Override @Nonnull public String toString() { return String.format("MockDatum(%s)", id); } } /******************************************************************************************************************* * ******************************************************************************************************************/ static class MockRole1 { } /******************************************************************************************************************* * ******************************************************************************************************************/ @RequiredArgsConstructor static class MockRole2 { @Getter @Nonnull private final MockDatum datum; } /******************************************************************************************************************* * ******************************************************************************************************************/ static class MockRoleFactory implements RoleFactory { @Override @Nonnull public Object createRoleFor (@Nonnull final MockDatum datum) { return new MockRole2(datum); } } /******************************************************************************************************************* * ******************************************************************************************************************/ @BeforeMethod public void setup() { AsDelegateProvider.Locator.set(AsDelegateProvider.empty()); ContextManager.Locator.set(new DefaultContextManagerProvider()); } /******************************************************************************************************************* * ******************************************************************************************************************/ @Test public void must_create_a_PresentationModel_containing_the_proper_children() { // given final MockDatum c1 = new MockDatum("c1"); final MockDatum c2 = new MockDatum("c2"); final MockDatum c3 = new MockDatum("c3"); final MockDatum b1 = new MockDatum("b1").withChildren(c1, c2, c3); final MockDatum b2 = new MockDatum("b2"); final MockDatum b3 = new MockDatum("b3"); final MockDatum a = new MockDatum("a").withChildren(b1, b2, b3); final SimpleCompositePresentable underTest = new SimpleCompositePresentable(a, new DefaultPresentationModelFactory()); final MockRole1 role1 = new MockRole1(); final MockRoleFactory roleFactory = new MockRoleFactory(); // when final PresentationModel pm = underTest.createPresentationModel(r(role1, roleFactory)); // then assertProperPresentationModel("", pm, a); } /******************************************************************************************************************* * ******************************************************************************************************************/ private void assertProperPresentationModel (@Nonnull final String indent, @Nonnull final PresentationModel pm, @Nonnull final MockDatum datum) { log.debug("assertProperPresentationModel() - {} {}, {}", indent, pm, datum); pm.as(MockRole1.class); // must not throw AsException final MockRole2 role = pm.as(MockRole2.class); // must not throw AsException assertThat(role.getDatum(), is(sameInstance(datum))); final List childrenPm = pm.maybeAs(_SimpleComposite_).map(c -> c.findChildren().results()).orElse(emptyList()); final List notPMs = new ArrayList<>(childrenPm); notPMs.removeIf(object -> object instanceof PresentationModel); if (!notPMs.isEmpty()) { fail("Unexpected objects that are not PresentationModel: " + notPMs); } final List childrenData = datum.getChildren(); assertThat(childrenPm.size(), is(childrenData.size())); for (int i = 0; i < childrenPm.size(); i++) { assertProperPresentationModel(indent + " ", childrenPm.get(i), childrenData.get(i)); } } }0 package com.tyust.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.tyust.entity.Category; import com.tyust.service.CategoryService; @Controller @RequestMapping("category") public class CategoryController { @Autowired private CategoryService categoryService; @RequestMapping("/findAll.do") public String findAll(ModelMap map){ List parents = categoryService.findAll(); map.addAttribute("parents", parents); return "/jsps/left"; } } package com.mahogano.core.magento.mapper; import com.mahogano.core.magento.entity.ReportViewedProductAggregatedDaily; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class ReportViewedProductAggregatedDailyMapper implements RowMapper { @Override public ReportViewedProductAggregatedDaily mapRow(ResultSet rs, int i) throws SQLException { ReportViewedProductAggregatedDaily reportViewedProductAggregatedDaily = new ReportViewedProductAggregatedDaily(); reportViewedProductAggregatedDaily.setId(rs.getInt("id")); reportViewedProductAggregatedDaily.setPeriod(rs.getTimestamp("period") != null ? rs.getTimestamp("period").toLocalDateTime() : null); reportViewedProductAggregatedDaily.setStoreId(rs.getInt("store_id")); reportViewedProductAggregatedDaily.setProductId(rs.getInt("product_id")); reportViewedProductAggregatedDaily.setProductName(rs.getString("product_name")); reportViewedProductAggregatedDaily.setProductPrice(rs.getBigDecimal("product_price")); reportViewedProductAggregatedDaily.setViewsNum(rs.getInt("views_num")); reportViewedProductAggregatedDaily.setRatingPos(rs.getInt("rating_pos")); return reportViewedProductAggregatedDaily; } } 100-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. */ package org.apache.openejb.resource.heroku; import org.apache.openejb.loader.SystemInstance; import org.apache.openejb.testng.PropertiesBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HerokuDatabasePropertiesProviderTest { @Before @After public void reset() { SystemInstance.reset(); } @Test public void herokuToJava() { SystemInstance.get().setProperty("DATABASE_URL", "postgres://user:pwd@host.com:5432/db"); assertEquals( new PropertiesBuilder() .p("Password", "") .p("JdbcUrl", "jdbc:postgresql://host.com:5432/db") .p("UserName", "user") .p("JdbcDriver", "org.postgresql.Driver") .build(), new HerokuDatabasePropertiesProvider().provides()); } } hjc851/SourceCodePlagiarismDetectionDataset package seng2200; public class Sate { public synchronized void raisingStays(double keh) { int marquezHeight; marquezHeight = 1649735069; this.lifespan += keh; } public synchronized double becomeHours() { String quality; quality = "cZrWd0yTSI0PR"; return this.lifespan; } static final String evaluate = "z6B"; public synchronized void arrangedMention(String constitute) { String minutes; minutes = "qrxAFsDxngrWvhkY8"; this.nickname = constitute; } private double lifespan = 0.0; private String nickname = null; Sate() { this.lifespan = 0; this.nickname = ""; } Sate(String mention) { this.lifespan = 0; this.nickname = mention; } public synchronized String toString() { int indictment; indictment = -1500965386; return this.nickname; } Sate(String nominate, double beh) { this.lifespan = beh; this.nickname = nominate; } } package cn.howardliu.aliyun.ddns.provider; import org.junit.Test; import static org.junit.Assert.assertNotNull; /** *
created at 17-4-25 * * @author liuxh * @version 1.0.0 * @since 1.0.0 */ public class ProviderFactoryTest { @Test public void getWanIpProvider() throws Exception { assertNotNull(ProviderFactory.getWanIpProvider("ipEcho")); } } package developer.billx.android.gram.favorites; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.bottomnavigation.BottomNavigationView; import developer.billx.android.gram.R; import developer.billx.android.gram.util.BottomNavViewHelper; public class FavoritesActivity extends AppCompatActivity { private static final String TAG = "FavoritesActivity"; private Context mContext = FavoritesActivity.this; private static final int ACTIVITY_ID = 3; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); Log.d(TAG, "onCreate: begun"); setupBottomNavView(); } private void setupBottomNavView() { Log.d(TAG, "setupBottomNavView: setting up bottom nav"); BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavBar); BottomNavViewHelper.setupBottomNavView(bottomNavigationView); BottomNavViewHelper.allowNavigation(mContext, bottomNavigationView); Menu menu = bottomNavigationView.getMenu(); MenuItem item = menu.getItem(ACTIVITY_ID); item.setChecked(true); } } package com.lidong.spring.pratice3; /** * 以接口的方式为LoginAction提供登录检查服务 只需要知道LoginAction要实现登录操作需要一个login()方法 * 不需要知道login()方法如何实现 用到的时候只需要远程调用其他服务器上的实现方法 * * @author LiDong * */ public interface UserDaoIf { public boolean login(); } package com.bartnorsk.basic; /** * @author * */ public class SubstractionOfTwoNucleotide extends Nucleotide { private Nucleotide leftMember = null; private Nucleotide rightMember = null; private SubstractionOfTwoNucleotide() { super(2, "-"); } public SubstractionOfTwoNucleotide(Nucleotide leftMember, Nucleotide rightMember) { super(2, "-"); this.leftMember = leftMember; this.rightMember = rightMember; } /** * @see com.bartnorsk.basic.INucleotide#execute() */ @Override public Object execute() { return (double)this.leftMember.execute() - (double)this.rightMember.execute(); } /* * Value can not be changed * * @see com.bartnorsk.basic.Nucleotide#setValue(java.lang.Object) */ public void setValue(Object o) { super.setValue("-"); } } orderPackage/Ordine.java package com.poli.ordine1; public class Ordine{ private int numProdotti=0; private String name; private Linea head; private Linea last; public Ordine(String name){ this.name=name;} public Ordine aggiungi(Prodotto prod, int id){ /* if(numProdotti==0){ head=new Linea(id, prod ); last=head; } else{ last=last.newLine(id,prod); } return linea;*/ if(head==null){ head=new Linea(id,prod); last=head; } else{ last=last.newLine(id,prod); } return this; } public int importo(){ return head.sum(); } public String toString(){ return head.getString(); } } // copyright 2018 nqzero - offered under the terms of the MIT License package com.nqzero.permit; import java.lang.reflect.Field; public class Unsafer { private static Object getField(Class klass,String name) { try { Field f = klass.getDeclaredField(name); f.setAccessible(true); return f.get(null); } catch (Exception e) { return null; } } public static final sun.misc.Unsafe uu = (sun.misc.Unsafe) getField(sun.misc.Unsafe.class,"theUnsafe"); } src/main/java/firemerald/custombgm/client/ClientState.java package firemerald.custombgm.client; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.annotation.Nullable; import firemerald.custombgm.api.ICustomMusic; import firemerald.custombgm.api.IPlayer; import firemerald.custombgm.api.ISoundLoop; import firemerald.custombgm.client.audio.LoopingSounds; import firemerald.custombgm.init.LSSounds; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.MusicTicker; import net.minecraft.client.audio.MusicTicker.MusicType; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.MathHelper; import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import paulscode.sound.SoundSystem; @SideOnly(Side.CLIENT) public class ClientState { public static final MusicType MUSIC_TYPE_EMPTY = EnumHelper.addEnum(MusicTicker.MusicType.class, "empty", new Class[] { SoundEvent.class, Integer.TYPE, Integer.TYPE }, new Object[] { LSSounds.EMPTY.sound, 0, 0 }); public static final Queue QUEUED_ACTIONS = new ConcurrentLinkedQueue<>(); public static IPlayer clientPlayer = null; public static MusicHandler currentBGM = null; public static ResourceLocation currentBGMName = null; public static int menuMus = -1; public static class MusicHandler implements ISoundLoop { private ISoundLoop oldMusic; public final ISoundLoop newMusic; private float transition; private static final float TRANSITION_PER_TICK = 1 / 40f; private float volume = 1; public MusicHandler(@Nullable MusicHandler oldMusic, @Nullable ISoundLoop newMusic) { this.oldMusic = oldMusic; this.newMusic = newMusic; if (newMusic != null) newMusic.setVolume(0); transition = 0; } @Override public void stopSound() { if (newMusic != null) newMusic.stopSound(); if (oldMusic != null) oldMusic.stopSound(); } public void instantStart() { if (oldMusic != null) { oldMusic.stopSound(); oldMusic = null; } if (newMusic != null) { if (transition == 0) { newMusic.playSound(); } newMusic.setVolume(volume); } transition = 1; } public void tick(boolean isRoot) { if (oldMusic instanceof MusicHandler) ((MusicHandler) oldMusic).tick(false); if (transition < 1) { if (transition == 0 && newMusic != null) { newMusic.playSound(); } transition += TRANSITION_PER_TICK; if (transition >= 1) { if (oldMusic != null) { oldMusic.stopSound(); oldMusic = null; } if (newMusic != null) newMusic.setVolume(volume); } else if (isRoot) this.setVolume(volume); } } @Override public void setVolume(float volume) { this.volume = volume; float oldVol = flattenedHann(transition); float newVol = 1 - oldVol; newVol = MathHelper.sqrt(newVol); oldVol = MathHelper.sqrt(oldVol); if (oldMusic != null) oldMusic.setVolume(oldVol * volume); if (newMusic != null) newMusic.setVolume(newVol * volume); } public static float cubic(float f) { return ((4 * f - 6) * f + 3) * f; } public static float flattenedHann(float f) { return (float) ((9 * Math.sin((f + 0.5) * Math.PI) / 16d) + (Math.sin((f + 0.5) * 3 * Math.PI) / 16d) + 0.5); } @Override public boolean isStopped() { return (newMusic == null || newMusic.isStopped()) && (oldMusic == null || oldMusic.isStopped()); } @Override public void playSound() { if (newMusic != null) newMusic.playSound(); if (oldMusic != null) oldMusic.playSound(); } @Override public void pauseSound() { if (newMusic != null) newMusic.pauseSound(); if (oldMusic != null) oldMusic.pauseSound(); } @Override public void resumeSound() { if (newMusic != null) newMusic.resumeSound(); if (oldMusic != null) oldMusic.resumeSound(); } @Override public float getVolume() { return volume; } @Override public void updateCategoryVolume() { if (newMusic != null) newMusic.updateCategoryVolume(); if (oldMusic != null) oldMusic.updateCategoryVolume(); } @Override public SoundCategory getCategory() { return newMusic != null ? newMusic.getCategory() : oldMusic != null ? oldMusic.getCategory() : SoundCategory.MASTER; } @Override public void setPitch(float pitch) { if (newMusic != null) newMusic.setPitch(pitch); if (oldMusic != null) oldMusic.setPitch(pitch); } } public static MusicType getCustomMusic(MusicType type, Minecraft mc) { if (!SoundSystem.initialized()) return type; if (currentBGM != null && currentBGM.isStopped()) { currentBGM = null; currentBGMName = null; menuMus = -1; } ResourceLocation loopSound; if (mc.currentScreen instanceof ICustomMusic) { loopSound = ((ICustomMusic) mc.currentScreen).getMusic(mc.player, currentBGMName); } else { loopSound = ClientState.clientPlayer != null ? ClientState.clientPlayer.getMusicOverride() : null; if (loopSound == null) { boolean isMenu; if (type == MusicType.MENU) isMenu = true; else { isMenu = false; menuMus = -1; } ConfigClientOptions config = ConfigClientOptions.INSTANCE; if (isMenu && config.titleMusic.val.length > 0) { if (menuMus == -1) menuMus = (int) (Math.random() * config.titleMusic.val.length); loopSound = config.titleMusic.val[menuMus]; } } } if (loopSound == null) //is nothing { if (currentBGM != null && !currentBGM.isStopped()) currentBGM = new ClientState.MusicHandler(currentBGM, null); //go to nothing } else if (!loopSound.equals(currentBGMName)) //changed { currentBGM = new ClientState.MusicHandler(currentBGM, LoopingSounds.grabSound(loopSound, SoundCategory.MUSIC, true)); //change } currentBGMName = loopSound; return loopSound == null ? type : MUSIC_TYPE_EMPTY; } }package chat.client; import chat.client.gui.ChatClientCtrl; import chat.client.gui.LoginWindow; import chat.network.objectprotocol.ChatServerObjectProxy; import chat.services.IChatServer; /** * Created by IntelliJ IDEA. * User: grigo * Date: Mar 18, 2009 * Time: 3:24:40 PM */ public class StartObjectClient { public static void main(String[] args) { IChatServer server = new ChatServerObjectProxy("localhost", 55555); ChatClientCtrl ctrl = new ChatClientCtrl(server); LoginWindow logWin = new LoginWindow("Chat XYZ", ctrl); logWin.setSize(200, 200); logWin.setVisible(true); } } 0 package seedu.address.storage.notes; import static seedu.address.commons.core.Messages.MESSAGE_DUPLICATE_NOTES; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.notes.Notes; import seedu.address.model.notes.NotesManager; import seedu.address.model.notes.ReadOnlyNotes; /** * Immutable NotesManager that is serializable to JSON format. */ @JsonRootName(value = "notesManager") public class JsonSerializableNotesManager { private final List notes = new ArrayList<>(); /** * Constructs a {@code JsonSerializableNotesManager} with the given notes. * @param notes */ @JsonCreator public JsonSerializableNotesManager(@JsonProperty("notes") List notes) { this.notes.addAll(notes); } /** * Converts a given {@code ReadOnlyNoes} into this class for Jackson use. * * @param source future changes to this will not affect the created {@code JsonSerializableNotesManager}. */ public JsonSerializableNotesManager(ReadOnlyNotes source) { notes.addAll(source.getNotesList().stream().map(JsonAdaptedNotes::new).collect(Collectors.toList())); } /** * Converts notes records into the model's {@code NotesManager} object. * @return * @throws IllegalValueException */ public NotesManager toModelType() throws IllegalValueException { NotesManager notesManager = new NotesManager(); for (JsonAdaptedNotes jsonAdaptedNotes : notes) { Notes note = jsonAdaptedNotes.toModelType(); if (notesManager.hasNote(note)) { throw new IllegalValueException(MESSAGE_DUPLICATE_NOTES); } notesManager.addNote(note); } return notesManager; } } java/tag/customTag/src/com/cdsf/tag/base/Item.java0 package com.cdsf.tag.base; import java.io.IOException; import javax.servlet.jsp.JspException; /** * 标签结构:
{@literal
label:
}
* @author hedingliang */ @SuppressWarnings("serial") public class Item extends TagI18n { protected String wrapId; protected boolean required; protected int cols = 1; protected int rows = 1; protected int itemWidth; protected int itemHeight; protected int textWidth = 100; protected int iptWidth = 124; protected int baseWidth = 230; protected int baseHeight = 24; /** * @author hedingliang * @description 作为父类时,宽高的初始化, 可能之前也可能之后, 所以需要子类执行super.preInit()调用 */ public void preInit() { //初始化宽高 itemWidth = baseWidth * cols + (cols-1)*4; iptWidth = itemWidth - textWidth - 6; itemHeight = baseHeight * rows + (rows-1)*4; } /** * @author hedingliang * @description 作为父类时,子类覆盖此方法返回body前面的内容 */ public String beforeBody() { return ""; } /** * @author hedingliang * @description 作为父类时,子类覆盖此方法返回body后面的内容 */ public String afterBody() { return ""; } /** * @author hedingliang * @description 作为父类时,子类覆盖此方法返回修改后的bodyContent的内容 */ public String modifyBody(){ if (bodyContent != null) { return bodyContent.getString(); } else { return ""; } } /** * @author hedingliang * @description 标签会缓存,在一个标签输出完毕后执行一点清理工作 */ public void clean(){} @Override public int doStartTag(){ try { preInit(); StringBuffer sb = new StringBuffer(); sb.append("
"); sb.append("
"); sb.append(getLabel()); sb.append("
"); sb.append("
"); sb.append(beforeBody()); pageContext.getOut().write(sb.toString()); } catch (IOException e) { e.printStackTrace(); } return EVAL_BODY_BUFFERED; } @Override public int doEndTag() throws JspException { try { StringBuffer sb = new StringBuffer(); sb.append(modifyBody()); sb.append(afterBody()); sb.append("
"); sb.append("
"); pageContext.getOut().write(sb.toString()); clean(); } catch (IOException e) { e.printStackTrace(); } return EVAL_PAGE; } /** * @author hedingliang * @param cols 值只能为2或者3 */ public void setCols(int cols) { if (cols > 1 && cols < 4) { this.cols = cols; } } /** * @author hedingliang * @param rows 值只能为3,4或者5 */ public void setRows(int rows) { if (rows > 2 && rows < 6) { this.rows = rows; } } /** * @author hedingliang * @param textWidth ipt区域宽度,只能为数字 */ public void setTextWidth(String textWidth) { if (("" + textWidth).matches("\\d+")) { this.textWidth = Integer.valueOf(textWidth); } } /** * @author hedingliang * @param required 是否必须,只能为true */ public void setRequired(boolean required) { if (required) { this.required = required; } } /** * @author hedingliang * @return width:xxpx * @description label区域宽度 */ public String getWrapStyle() { if (cols != 1 || rows != 1 || getWrapFloat() != null) { return "style=\"" + getWrapWidth() + getWrapHeight() + getWrapFloat() + "\""; }else { return ""; } } /** * @author hedingliang * @return width:xxpx; * @description item的宽度 */ public String getWrapWidth() { if (cols != 1) { return "width:" + itemWidth + "px;"; }else { return ""; } } /** * @author hedingliang * @return height:xxpx; * @description item的高度 */ public String getWrapHeight() { if (rows != 1) { return "height:" + itemHeight + "px;"; }else { return ""; } } /** * @author hedingliang * @return float:xx; * @description item的浮动 */ public String getWrapFloat() { return null; } /** * @author hedingliang * @return width:xxpx * @description label区域宽度 */ public String getTextStyle() { if (textWidth != 100 || rows != 1) { return "style=\"" + getTextWidth() + getTextHeight() + "\""; }else { return ""; } } /** * @author hedingliang * @return width:xxpx * @description label区域宽度 */ public String getTextWidth() { if (textWidth != 100) { return "width:" + textWidth + "px;"; }else { return ""; } } /** * @author hedingliang * @return height:xxpx; * @description item的高度 */ public String getTextHeight() { if (rows != 1) { return "height:" + itemHeight + "px;line-height:" + itemHeight + "px;"; }else { return ""; } } /** * @author hedingliang * @return width:xxpx * @description label区域宽度 */ public String getIptStyle() { if (cols != 1 || rows != 1 || textWidth != 100) { return "style=\"" + getIptWidth() + getIptHeight() + "\""; }else { return ""; } } /** * @author hedingliang * @return width:xxpx * @description ipt区域宽度 */ public String getIptWidth() { if (textWidth != 0 || cols != 1) { return "width:" + iptWidth + "px;"; }else { return ""; } } /** * @author hedingliang * @return height:xxpx; * @description item的高度 */ public String getIptHeight() { if (rows != 1) { return "height:" + (itemHeight - 6) + "px;"; } else { return ""; } } /** * @author hedingliang * @return 根据是否必须,会在前面加红色*号 */ public String getLabel() { return (required ? "*" : "") + super.getLabel(); } /** * @author hedingliang * @return 如果有id,返回id="id" */ public String getWrapId() { return wrapId != null ? " id=\"" + wrapId + "\"" : ""; } public void setWrapId(String wrapId) { this.wrapId = wrapId; } } /* * Copyright 2009 Inspire-Software.com * * 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. */ package org.yes.cart.bulkimport.csv.impl; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.yes.cart.bulkcommon.csv.CsvImpExColumn; import org.yes.cart.bulkcommon.csv.CsvImpExTuple; import org.yes.cart.utils.DateUtils; import static org.junit.Assert.*; /** */ public class CsvDateValueAdapterImplTest { private final Mockery mockery = new JUnit4Mockery(); @Test public void fromRaw() throws Exception { final CsvImpExColumn ldColumn = this.mockery.mock(CsvImpExColumn.class, "ldColumn"); final CsvImpExColumn ldtColumn = this.mockery.mock(CsvImpExColumn.class, "ldtColumn"); final CsvImpExTuple tuple = this.mockery.mock(CsvImpExTuple.class, "tuple"); final CsvDateValueAdapterImpl adapter = new CsvDateValueAdapterImpl(); this.mockery.checking(new Expectations() {{ oneOf(ldColumn).getContext(); will(returnValue("yyyy-MM-dd")); oneOf(ldtColumn).getContext(); will(returnValue("yyyy-MM-dd HH:mm:ss")); oneOf(ldColumn).getContext(); will(returnValue("yyyy-MM-dd")); oneOf(ldtColumn).getContext(); will(returnValue("yyyy-MM-dd HH:mm:ss")); }}); assertEquals( DateUtils.ldParseSDT("2017-06-06"), adapter.fromRaw("2017-06-06", "DATE", ldColumn, tuple) ); assertEquals( DateUtils.ldParseSDT("2017-06-06"), adapter.fromRaw("2017-06-06 15:30:17", "DATE", ldtColumn, tuple) ); assertEquals( DateUtils.ldtParseSDT("2017-06-06"), adapter.fromRaw("2017-06-06", "DATETIME", ldColumn, tuple) ); assertEquals( DateUtils.ldtParseSDT("2017-06-06 15:30:17"), adapter.fromRaw("2017-06-06 15:30:17", "DATETIME", ldtColumn, tuple) ); this.mockery.assertIsSatisfied(); } }1-10 package com.engineerbetter.converger; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v2.organizations.DeleteOrganizationRequest; import org.cloudfoundry.client.v2.organizations.ListOrganizationsRequest; import org.cloudfoundry.client.v2.organizations.ListOrganizationsResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import com.engineerbetter.converger.facade.CloudFoundryFacade; import com.engineerbetter.converger.facade.CloudFoundryFacade.OrgRole; import com.engineerbetter.converger.facade.CloudFoundryFacade.SpaceRole; import com.engineerbetter.converger.facade.UaaFacade; import com.engineerbetter.converger.properties.UpsProperties; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(ConvergerApplication.class) @WebIntegrationTest(randomPort=true) public class UploadIntegrationTest { @Value("${local.server.port}") private int port; private RestTemplate rest = new TestRestTemplate(); @Autowired private CloudFoundryClient cfClient; @Autowired private CloudFoundryFacade cfFacade; @Autowired private UaaFacade uaaFacade; @Before public void setup() { String orgId = cfFacade.createOrg("my-lovely-org"); String prodId = cfFacade.createSpace("DEV", orgId); Map credentials = new HashMap<>(); credentials.put("username", "sa"); credentials.put("password", ""); credentials.put("secret", "needed"); UpsProperties upsProperties = new UpsProperties("OracleDB", credentials); cfFacade.createUps(upsProperties, prodId); } @After public void teardown() { ListOrganizationsResponse response = cfClient.organizations().list(ListOrganizationsRequest.builder().name("my-lovely-org").build()).block(); if(response.getResources().size() > 0) { String orgId = response.getResources().get(0).getMetadata().getId(); cfClient.organizations().delete(DeleteOrganizationRequest.builder().organizationId(orgId).recursive(true).build()).block(); } deleteUser(""); deleteUser(""); } @Test public void converge() throws Exception { ClassPathResource fixture = new ClassPathResource("fixtures/declaration.yml"); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Content-Type", "application/x-yaml"); requestHeaders.add("Accept", "application/json"); URI uri = new URI("http://127.0.0.1:"+port); byte[] bytes = new byte[(int)fixture.contentLength()]; fixture.getInputStream().read(bytes); RequestEntity postRequest = new RequestEntity(bytes, requestHeaders, HttpMethod.POST, uri); ResponseEntity response = rest.exchange(postRequest, String.class); assertThat(response.getStatusCode(), is(HttpStatus.OK)); assertThat(response.getBody(), is("Converged org my-lovely-org")); Optional dyId = uaaFacade.findUser(""); assertThat(" should exist in UAA", dyId.isPresent(), is(true)); Optional orgId = cfFacade.findOrg("my-lovely-org"); assertThat("my-lovely-org should exist", orgId.isPresent(), is(true)); assertThat(" should be in my-lovely-org", cfFacade.isUserInOrg(dyId.get(), orgId.get()), is(true)); assertThat(" should be manager of my-lovely-org", cfFacade.hasOrgRole(dyId.get(), orgId.get(), OrgRole.MANAGER), is(true)); assertThat(" should be auditor of my-lovely-org", cfFacade.hasOrgRole(dyId.get(), orgId.get(), OrgRole.AUDITOR), is(true)); Optional devId = cfFacade.findSpace("DEV", orgId.get()); assertThat("DEV should exist", devId.isPresent(), is(true)); Optional djId = uaaFacade.findUser(""); assertThat(" should exist in UAA", djId.isPresent(), is(true)); assertThat(" should be DEV space manager", cfFacade.hasSpaceRole(djId.get(), devId.get(), SpaceRole.AUDITOR), is(true)); assertThat(" should be DEV space developer", cfFacade.hasSpaceRole(djId.get(), devId.get(), SpaceRole.DEVELOPER), is(true)); assertThat(" should be DEV space manager", cfFacade.hasSpaceRole(djId.get(), devId.get(), SpaceRole.MANAGER), is(true)); Optional oracleDbId = cfFacade.findUps("OracleDB", devId.get()); assertThat("OracleDB should exist", oracleDbId.isPresent(), is(true)); Map credentials = new HashMap<>(); credentials.put("username", "sa"); credentials.put("password", ""); UpsProperties oracleDb = new UpsProperties("OracleDB", credentials); assertThat("OracleDB should have been updated", cfFacade.getUps(oracleDbId.get()), equalTo(oracleDb)); assertThat("PROD should exist", cfFacade.findSpace("PROD", orgId.get()).isPresent(), is(true)); } @Test public void plan() throws Exception { ClassPathResource fixture = new ClassPathResource("fixtures/declaration.yml"); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Content-Type", "application/x-yaml"); requestHeaders.add("Accept", "application/json"); URI uri = new URI("http://1172.16.17.32:"+port+"/plan"); byte[] bytes = new byte[(int)fixture.contentLength()]; fixture.getInputStream().read(bytes); RequestEntity postRequest = new RequestEntity(bytes, requestHeaders, HttpMethod.POST, uri); ResponseEntity> response = rest.exchange(postRequest, new ParameterizedTypeReference>(){}); assertThat(response.getBody(), hasItem("Would create UaaUserIntent [properties=UaaUserProperties [email=, givenName=Dan, familyName=Young]]")); assertThat(response.getBody(), hasItem("Would not create OrgIntent [name=my-lovely-org]")); assertThat(response.getBody(), hasItem("Would set as manager of my-lovely-org")); assertThat(response.getBody(), hasItem("Would set as auditor of my-lovely-org")); assertThat(response.getBody(), hasItem(containsString("Would not create SpaceIntent [name=DEV"))); assertThat(response.getBody(), hasItem("Would set as auditor of DEV")); assertThat(response.getBody(), hasItem("Would set as developer of DEV")); assertThat(response.getBody(), hasItem("Would set as manager of DEV")); assertThat(response.getBody(), hasItem(containsString("Would create SpaceIntent [name=PROD"))); assertThat(response.getBody(), hasItem(containsString("Would update UpsIntent, changing entry password from oldpassword to secret in credentials, and removing entry secret->notneeded from credentials"))); } private void deleteUser(String email) { Optional id = uaaFacade.findUser(email); if(id.isPresent()) { uaaFacade.deleteUser(id.get()); } } } public static int color(int[] color, int[] a, int[] b) { int count = 0; boolean[][] check = new boolean[7][7]; for (int i = 0; i < b.length; i++) { int l = a[i]; int r = b[i]; if (!check[color[l]][color[r]]) { count++; check[color[l]][color[r]] = true; check[color[r]][color[l]] = true; } } return count; }package com.structurizr.api; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.structurizr.Workspace; import com.structurizr.io.json.JsonReader; import com.structurizr.io.json.JsonWriter; public class StructurizrClient { private static final Log log = LogFactory.getLog(StructurizrClient.class); private static final String GMT_TIME_ZONE = "GMT"; public static final String STRUCTURIZR_API_URL = "structurizr.api.url"; public static final String STRUCTURIZR_API_KEY = "structurizr.api.key"; public static final String STRUCTURIZR_API_SECRET = "structurizr.api.secret"; private String url; private String apiKey; private String apiSecret; /** * Creates a new Structurizr client based upon configuration in a structurizr.properties file * on the classpath with the following name-value pairs: * - structurizr.api.url * - structurizr.api.key * - structurizr.api.secret */ public StructurizrClient() { try { Properties properties = new Properties(); InputStream in = StructurizrClient.class.getClassLoader().getResourceAsStream("structurizr.properties"); if (in != null) { properties.load(in); this.url = properties.getProperty(STRUCTURIZR_API_URL); this.apiKey = properties.getProperty(STRUCTURIZR_API_KEY); this.apiSecret = properties.getProperty(STRUCTURIZR_API_SECRET); in.close(); } } catch (Exception e) { log.error(e); } } /** * Creates a new Structurizr client with the specified API URL, key and secret. */ public StructurizrClient(String url, String apiKey, String apiSecret) { this.url = url; this.apiKey = apiKey; this.apiSecret = apiSecret; } public Workspace getWorkspace(long workspaceId) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url + "/workspace/" + workspaceId); addHeaders(httpGet, "", ""); debugRequest(httpGet); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { debugResponse(response); String json = EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return new JsonReader().read(new StringReader(json)); } else { ApiError apiError = ApiError.parse(json); throw new StructurizrClientException(apiError.getMessage()); } } } public void putWorkspace(Workspace workspace) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url + "/workspace/" + workspace.getId()); JsonWriter jsonWriter = new JsonWriter(true); StringWriter stringWriter = new StringWriter(); jsonWriter.write(workspace, stringWriter); StringEntity stringEntity = new StringEntity(stringWriter.toString(), ContentType.APPLICATION_JSON); httpPut.setEntity(stringEntity); addHeaders(httpPut, EntityUtils.toString(stringEntity), ContentType.APPLICATION_JSON.toString()); debugRequest(httpPut); try (CloseableHttpResponse response = httpClient.execute(httpPut)) { debugResponse(response); log.info(EntityUtils.toString(response.getEntity())); } } private void debugRequest(HttpRequestBase httpRequest) { log.debug(httpRequest.getMethod() + " " + httpRequest.getURI().getPath()); Header[] headers = httpRequest.getAllHeaders(); for (Header header : headers) { log.debug(header.getName() + ": " + header.getValue()); } } private void debugResponse(CloseableHttpResponse response) { log.info(response.getStatusLine()); } private void addHeaders(HttpRequestBase httpRequest, String content, String contentType) throws Exception { String httpMethod = httpRequest.getMethod(); String date = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneId.of(GMT_TIME_ZONE))); String path = httpRequest.getURI().getPath(); String contentMd5 = new Md5Digest().generate(content); HashBasedMessageAuthenticationCode hmac = new HashBasedMessageAuthenticationCode(apiSecret); HmacContent hmacContent = new HmacContent(httpMethod, path, contentMd5, contentType, date); httpRequest.addHeader(HttpHeaders.AUTHORIZATION, new HmacAuthorizationHeader(apiKey, hmac.generate(hmacContent.toString())).format()); httpRequest.addHeader(HttpHeaders.DATE, date); httpRequest.addHeader(HttpHeaders.CONTENT_MD5, Base64.getEncoder().encodeToString(contentMd5.getBytes())); httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType); } }package org.phash.mvp; import org.neo4j.graphdb.RelationshipType; enum MVPRelationshipTypes implements RelationshipType { TO_VP, TO_CHILD, TO_DP } LukasGaedicke/Programming-Challenges-v1.40 package com.example.namegenerator.resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.namegenerator.service.NameService; @RestController @RequestMapping("/namegenerator") public class NamegeneratorResource { @Autowired private NameService nameservice; @GetMapping public ResponseEntity generateOneName() { return ResponseEntity.ok(nameservice.generateName(1)); } @GetMapping("/{quantity}") public ResponseEntity generateNames(@PathVariable int quantity) { return ResponseEntity.ok(nameservice.generateName(quantity)); } } 1-10 package com.sync.sz.sample.web.UI; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by Administrator on 2017/2/26 0026. */ public class LoginUIServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 527088995/mblogweb/src/main/java/mblog/web/controller/site/posts/PostController.java /** * */ package mblog.web.controller.site.posts; import com.alibaba.fastjson.JSON; import mblog.base.data.Data; import mblog.base.lang.Consts; import mblog.ds.rabbitConfig.RabbitConfig; import mblog.modules.blog.data.PostVO; import mblog.modules.blog.service.ArticleTypeService; import mblog.modules.blog.service.BlogClassService; import mblog.modules.blog.service.ChannelService; import mblog.modules.blog.service.PostService; import mblog.modules.user.data.AccountProfile; import mblog.util.JacksonUtil; import mblog.web.controller.BaseController; import mblog.web.controller.site.Views; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.AmqpException; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.IOException; /** * 文章操作 * @author langhsu * */ @Controller @RequestMapping("/post") public class PostController extends BaseController { private final Logger logger = LoggerFactory.getLogger(PostController.class); @Autowired private PostService postService; @Autowired private ChannelService channelService; @Autowired private BlogClassService blogClassService; @Autowired private ArticleTypeService articleTypeService; @Resource private RabbitTemplate rabbitTemplate; /** * 发布文章页 * @return */ @GetMapping("/editing") public String view(Long id, ModelMap model) { model.put("channels", channelService.findAll(Consts.STATUS_NORMAL)); model.put("blogClasss", blogClassService.findAll(Consts.STATUS_NORMAL)); model.put("articleTypes", articleTypeService.findAll(Consts.STATUS_NORMAL)); if (null != id && id > 0) { AccountProfile profile = getSubject().getProfile(); PostVO view = postService.get(id); Assert.notNull(view, "该文章已被删除"); Assert.isTrue(view.getAuthorId() == profile.getId(), "该文章不属于你"); model.put("view", view); } model.put("channels", channelService.findAll(Consts.STATUS_NORMAL)); return view(Views.ROUTE_POST_EDITING); } /** * 提交发布 * @param post * @return */ @PostMapping("/submit") public String post(PostVO post, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException { Assert.notNull(post, "参数不完整"); Assert.state(StringUtils.isNotBlank(post.getTitle()), "标题不能为空"); Assert.state(StringUtils.isNotBlank(post.getContent()), "内容不能为空"); AccountProfile profile = getSubject().getProfile(); post.setAuthorId(profile.getId()); post.setAuthorName(profile.getName()); /** * 保存预览图片 */ if (file != null && !file.isEmpty()) { String thumbnail = fileRepo.store(file, appContext.getThumbsDir()); if (StringUtils.isNotBlank(post.getThumbnail())) { fileRepo.deleteFile(post.getThumbnail()); } post.setThumbnail(thumbnail); } // 修改时, 验证归属 if (post.getId() > 0) { PostVO exist = postService.get(post.getId()); Assert.notNull(exist, "文章不存在"); Assert.isTrue(exist.getAuthorId() == profile.getId(), "该文章不属于你"); postService.update(post); } else { this.convertAndSend(RabbitConfig.EXCHANGE_B, RabbitConfig.ROUTINGKEY_B, JacksonUtil.toJson(post)); //postService.post(post); } return Views.REDIRECT_USER_POSTS; } /** * 发送消息 * * @param exchange 交换机名称 * @param routingKey 路由key * @param message 消息内容 * @throws AmqpException */ private void convertAndSend(String exchange, String routingKey, final Object message) throws AmqpException { try { rabbitTemplate.convertAndSend(exchange, routingKey, message); } catch (Exception e) { logger.error("MQ消息发送异常,消息ID:{},消息体:{}, exchangeName:{}, routingKey:{}", JSON.toJSONString(message), exchange, routingKey, e); // TODO 保存消息到数据库 } } /** * 删除文章 * @param id * @return */ @RequestMapping("/delete/{id}") public @ResponseBody Data delete(@PathVariable Long id) { Data data = Data.failure("操作失败"); if (id != null) { AccountProfile up = getSubject().getProfile(); try { postService.delete(id, up.getId()); data = Data.success("操作成功", Data.NOOP); } catch (Exception e) { data = Data.failure(e.getMessage()); } } return data; } } package fm.jiecao.jiecaovideoplayer.View; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import java.util.Timer; import java.util.TimerTask; import fm.jiecao.jcvideoplayer_lib.JCBuriedPointStandard; import fm.jiecao.jcvideoplayer_lib.JCMediaManager; import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer; import fm.jiecao.jiecaovideoplayer.R; /** * Created by Nathen * On 2016/05/01 22:59 */ public class JCVideoPlayerStandardFresco extends JCVideoPlayer { protected ImageView ivBack; protected ProgressBar pbBottom, pbLoading; protected TextView tvTitle; public SimpleDraweeView ivThumb; protected ImageView ivCover; private static Timer mDismissControlViewTimer; private static JCBuriedPointStandard jc_BuriedPointStandard; public JCVideoPlayerStandardFresco(Context context) { super(context); } public JCVideoPlayerStandardFresco(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void init(Context context) { super.init(context); pbBottom = (ProgressBar) findViewById(R.id.bottom_progressbar); tvTitle = (TextView) findViewById(R.id.title); ivBack = (ImageView) findViewById(R.id.back); ivThumb = (SimpleDraweeView) findViewById(R.id.thumb); ivCover = (ImageView) findViewById(R.id.cover); pbLoading = (ProgressBar) findViewById(R.id.loading); ivThumb.setOnClickListener(this); ivBack.setOnClickListener(this); } @Override public boolean setUp(String url, Object... objects) { if (super.setUp(url, objects)) { tvTitle.setText(objects[0].toString()); if (mIfCurrentIsFullscreen) { fullscreenButton.setImageResource(R.drawable.jc_shrink); } else { fullscreenButton.setImageResource(R.drawable.jc_enlarge); ivBack.setVisibility(View.GONE); } return true; } return false; } @Override public int getLayoutId() { return R.layout.jc_layout_standard_fresco; } @Override protected void setStateAndUi(int state) { super.setStateAndUi(state); switch (mCurrentState) { case CURRENT_STATE_NORMAL: changeUiToNormal(); cancelDismissControlViewTimer(); break; case CURRENT_STATE_PREPAREING: changeUiToShowUiPrepareing(); startDismissControlViewTimer(); break; case CURRENT_STATE_PLAYING: changeUiToShowUiPlaying(); startDismissControlViewTimer(); break; case CURRENT_STATE_PAUSE: changeUiToShowUiPause(); cancelDismissControlViewTimer(); break; case CURRENT_STATE_ERROR: changeUiToError(); break; } } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: cancelDismissControlViewTimer(); break; case MotionEvent.ACTION_UP: startDismissControlViewTimer(); break; } return super.onTouch(v, event); } @Override public void onClick(View v) { super.onClick(v); int i = v.getId(); if (i == R.id.thumb) { if (mCurrentState == CURRENT_STATE_NORMAL) { if (jc_BuriedPointStandard != null) { jc_BuriedPointStandard.onClickStartThumb(mUrl, mObjects); } prepareVideo(); startDismissControlViewTimer(); } } else if (i == R.id.surface_container) { if (jc_BuriedPointStandard != null && JCMediaManager.instance().listener == this) { if (mIfCurrentIsFullscreen) { jc_BuriedPointStandard.onClickBlankFullscreen(mUrl, mObjects); } else { jc_BuriedPointStandard.onClickBlank(mUrl, mObjects); } } onClickUiToggle(); startDismissControlViewTimer(); } else if (i == R.id.back) { backFullscreen(); } } private void onClickUiToggle() { if (mCurrentState == CURRENT_STATE_PREPAREING) { if (bottomContainer.getVisibility() == View.VISIBLE) { changeUiToClearUiPrepareing(); } else { changeUiToShowUiPrepareing(); } } else if (mCurrentState == CURRENT_STATE_PLAYING) { if (bottomContainer.getVisibility() == View.VISIBLE) { changeUiToClearUiPlaying(); } else { changeUiToShowUiPlaying(); } } else if (mCurrentState == CURRENT_STATE_PAUSE) { if (bottomContainer.getVisibility() == View.VISIBLE) { changeUiToClearUiPause(); } else { changeUiToShowUiPause(); } } } @Override protected void setProgressAndTime(int progress, int secProgress, int currentTime, int totalTime) { super.setProgressAndTime(progress, secProgress, currentTime, totalTime); if (progress != 0) pbBottom.setProgress(progress); if (secProgress != 0) pbBottom.setSecondaryProgress(secProgress); } @Override protected void resetProgressAndTime() { super.resetProgressAndTime(); pbBottom.setProgress(0); pbBottom.setSecondaryProgress(0); } //Unified management Ui private void changeUiToNormal() { topContainer.setVisibility(View.VISIBLE); bottomContainer.setVisibility(View.INVISIBLE); startButton.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.VISIBLE); ivCover.setVisibility(View.VISIBLE); pbBottom.setVisibility(View.INVISIBLE); updateStartImage(); } private void changeUiToShowUiPrepareing() { topContainer.setVisibility(View.VISIBLE); bottomContainer.setVisibility(View.VISIBLE); startButton.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.VISIBLE); ivThumb.setVisibility(View.INVISIBLE); ivCover.setVisibility(View.VISIBLE); pbBottom.setVisibility(View.INVISIBLE); } private void changeUiToClearUiPrepareing() { // changeUiToClearUi(); topContainer.setVisibility(View.INVISIBLE); bottomContainer.setVisibility(View.INVISIBLE); startButton.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); pbBottom.setVisibility(View.INVISIBLE); // loadingProgressBar.setVisibility(View.VISIBLE); ivCover.setVisibility(View.VISIBLE); } private void changeUiToShowUiPlaying() { topContainer.setVisibility(View.VISIBLE); bottomContainer.setVisibility(View.VISIBLE); startButton.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); ivCover.setVisibility(View.INVISIBLE); pbBottom.setVisibility(View.INVISIBLE); updateStartImage(); } private void changeUiToClearUiPlaying() { changeUiToClearUi(); pbBottom.setVisibility(View.VISIBLE); } private void changeUiToShowUiPause() { topContainer.setVisibility(View.VISIBLE); bottomContainer.setVisibility(View.VISIBLE); startButton.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); ivCover.setVisibility(View.INVISIBLE); pbBottom.setVisibility(View.INVISIBLE); updateStartImage(); } private void changeUiToClearUiPause() { changeUiToClearUi(); pbBottom.setVisibility(View.VISIBLE); } private void changeUiToClearUi() { topContainer.setVisibility(View.INVISIBLE); bottomContainer.setVisibility(View.INVISIBLE); startButton.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); ivCover.setVisibility(View.INVISIBLE); pbBottom.setVisibility(View.INVISIBLE); } private void changeUiToError() { topContainer.setVisibility(View.INVISIBLE); bottomContainer.setVisibility(View.INVISIBLE); startButton.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); ivCover.setVisibility(View.VISIBLE); pbBottom.setVisibility(View.INVISIBLE); updateStartImage(); } private void updateStartImage() { if (mCurrentState == CURRENT_STATE_PLAYING) { startButton.setImageResource(R.drawable.jc_click_pause_selector); } else if (mCurrentState == CURRENT_STATE_ERROR) { startButton.setImageResource(R.drawable.jc_click_error_selector); } else { startButton.setImageResource(R.drawable.jc_click_play_selector); } } private void startDismissControlViewTimer() { cancelDismissControlViewTimer(); mDismissControlViewTimer = new Timer(); mDismissControlViewTimer.schedule(new TimerTask() { @Override public void run() { if (getContext() != null && getContext() instanceof Activity) { ((Activity) getContext()).runOnUiThread(new Runnable() { @Override public void run() { if (mCurrentState != CURRENT_STATE_NORMAL && mCurrentState != CURRENT_STATE_ERROR) { bottomContainer.setVisibility(View.INVISIBLE); topContainer.setVisibility(View.INVISIBLE); pbBottom.setVisibility(View.VISIBLE); startButton.setVisibility(View.INVISIBLE); } } }); } } }, 2500); } private void cancelDismissControlViewTimer() { if (mDismissControlViewTimer != null) { mDismissControlViewTimer.cancel(); } } public static void setJcBuriedPointStandard(JCBuriedPointStandard jcBuriedPointStandard) { jc_BuriedPointStandard = jcBuriedPointStandard; JCVideoPlayer.setJcBuriedPoint(jcBuriedPointStandard); } } mahmoudimus/ac1-10 package com.atlassian.plugin.connect.plugin.auth.scope.whitelist; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import com.atlassian.fugue.Pair; import com.atlassian.plugin.connect.api.util.ServletUtils; import com.atlassian.plugin.connect.plugin.auth.scope.ApiResourceInfo; import com.google.common.base.Function; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.dom4j.Document; import org.dom4j.Element; import static com.atlassian.plugin.connect.api.util.Dom4jUtils.readDocument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Collections2.transform; /** * An api scope for SOAP requests */ public final class RpcEncodedSoapApiScopeHelper { private final String path; private final Collection soapActions; private final String httpMethod; private transient final Iterable apiResourceInfo; public RpcEncodedSoapApiScopeHelper(final String path, Collection soapActions, String httpMethod) { this.path = path; this.soapActions = soapActions; this.httpMethod = checkNotNull(httpMethod).toUpperCase(); this.apiResourceInfo = transform(soapActions, from -> new ApiResourceInfo(path, RpcEncodedSoapApiScopeHelper.this.httpMethod, from.name)); } public RpcEncodedSoapApiScopeHelper(String path, final String namespace, Collection methods, String httpMethod) { // convert to ArrayList because the Collection subclass returned from Collections2.transform() has a broken equals() this(path, new ArrayList<>(transform(methods, from -> new SoapScope(namespace, from))), httpMethod); } public static Optional> getMethod(HttpServletRequest rq) { Document doc = readDocument(rq); if (null == doc) { return Optional.empty(); } Element root = doc.getRootElement(); if (null == root) { return Optional.empty(); } Element body = root.element("Body"); if (null == body) { return Optional.empty(); } Element methodElement = (Element) body.elements().get(0); if (null == methodElement) { return Optional.empty(); } String name = methodElement.getName(); String namespace = methodElement.getNamespaceURI(); return Optional.of(Pair.pair(namespace, name)); } public boolean allow(HttpServletRequest request) { if (!httpMethod.equals(request.getMethod())) { return false; } final String pathInfo = ServletUtils.extractPathInfo(request); if (path.equals(pathInfo)) { Optional> maybeNamespaceAndName = getMethod(request); if (!maybeNamespaceAndName.isPresent()) { return false; } Pair namespaceAndName = maybeNamespaceAndName.get(); for (SoapScope scope : soapActions) { if (scope.match(namespaceAndName.left(), namespaceAndName.right())) { return true; } } } return false; } public Iterable getApiResourceInfos() { return apiResourceInfo; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RpcEncodedSoapApiScopeHelper that = (RpcEncodedSoapApiScopeHelper) o; // don't consider apiResourceInfo because they are a static transform of soapActions and path return new EqualsBuilder() .append(path, that.path) .append(soapActions, that.soapActions) .build(); } @Override public int hashCode() { // don't consider apiResourceInfo because they are a static transform of soapActions and path return new HashCodeBuilder(41, 5) .append(path) .append(soapActions) .build(); } @Override public String toString() { // don't consider apiResourceInfo because they are a static transform of soapActions and path return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE) .append("path", path) .append("soapActions", soapActions) .build(); } public static class SoapScope { private final String namespace; private final String name; public SoapScope(String namespace, String name) { this.namespace = namespace; this.name = name; } public boolean match(String namespace, String name) { return this.namespace.equals(namespace) && this.name.equals(name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SoapScope that = (SoapScope) o; return new EqualsBuilder() .append(name, that.name) .append(namespace, that.namespace) .build(); } @Override public int hashCode() { return new HashCodeBuilder(37, 11) .append(name) .append(namespace) .build(); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE) .append("name", name) .append("namespace", namespace) .build(); } } } package com.clicky.profepa.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.clicky.profepa.R; import com.clicky.profepa.data.Documentos; import com.clicky.profepa.data.PROFEPAPreferences; import com.parse.GetCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; /** * * Created by Clicky on 3/22/15. * */ public class ReportFragment extends Fragment { private static String EXTRA_FOLIO = "folio"; private TextView txtFolio, txtTitular; private EditText editReport; private String folio; public static ReportFragment newInstance(String folio){ ReportFragment frag = new ReportFragment(); Bundle args = new Bundle(); args.putString(EXTRA_FOLIO, folio); frag.setArguments(args); return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_report, container, false); Toolbar toolbar = (Toolbar)v.findViewById(R.id.toolbar); ((ActionBarActivity)getActivity()).setSupportActionBar(toolbar); setUpBar(); txtFolio = (TextView)v.findViewById(R.id.txt_folio); txtTitular = (TextView)v.findViewById(R.id.txt_titular); editReport = (EditText)v.findViewById(R.id.edit_reporte); getFolio(); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); decodeArguments(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_reporte, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().onBackPressed(); return true; case R.id.action_send: if(validate()){ sendReport(); }else{ Toast.makeText(getActivity(),R.string.error_fields,Toast.LENGTH_SHORT).show(); } return true; default: return super.onOptionsItemSelected(item); } } private void decodeArguments(){ Bundle args = getArguments(); if(args != null) { folio = args.getString(EXTRA_FOLIO); } } private boolean validate(){ return !editReport.getText().toString().isEmpty(); } private void setUpBar(){ ActionBarActivity activity = (ActionBarActivity)getActivity(); activity.getSupportActionBar().setHomeButtonEnabled(true); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); getActivity().setTitle(R.string.title_reportar); } private void getFolio(){ ParseQuery query = Documentos.getQuery(); query.include("Titular"); query.whereEqualTo("objectId", folio); query.fromLocalDatastore(); query.getFirstInBackground(new GetCallback() { public void done(Documentos doc, ParseException e) { if (e == null) { // Results were successfully found from the local datastore. txtFolio.setText(doc.getFolioProg().toString()); txtTitular.setText(doc.getTitular().getString("Nombre")); } else { // There was an error. Log.i("ResultFragment", "findFolio: Error finding document: " + e.getMessage()); } } }); } private void sendReport(){ PROFEPAPreferences prefs = new PROFEPAPreferences(getActivity()); ParseObject inspeccion = new ParseObject("Inspecciones"); inspeccion.put("Reporte", "Error"); inspeccion.put("Detalles", editReport.getText().toString()); inspeccion.put("Inspector", ParseObject.createWithoutData("Inspectores", prefs.getInspector())); inspeccion.put("Documentos", ParseObject.createWithoutData("Documentos", folio)); inspeccion.saveEventually(); Toast.makeText(getActivity(),R.string.toast_sent,Toast.LENGTH_LONG).show(); getActivity().onBackPressed(); } } package com.lchli.lottery.user.model; import com.lchli.lottery.BaseResponse; import com.lchli.lottery.user.repo.entity.User; public class UserResponse extends BaseResponse { public UserModel data; } slilichenko/dataflow-sample-applicationstimeseries-streaming/timeseries-java-applications/TimeSeriesPipeline/src/test/java/com/google/dataflow/sample/timeseriesflow/test/SnapShotUtils.java /* * 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. */ package com.google.dataflow.sample.timeseriesflow.test; import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.Data; import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSAccum; import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSAccumSequence; import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSKey; import com.google.dataflow.sample.timeseriesflow.transforms.ConvertAccumToSequence; import com.google.dataflow.sample.timeseriesflow.transforms.MajorKeyWindowSnapshot; import com.google.protobuf.util.Timestamps; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Reshuffle; import org.apache.beam.sdk.transforms.windowing.SlidingWindows; import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.joda.time.Duration; import org.joda.time.Instant; public class SnapShotUtils { public static PCollection> testSnapShotScalability(Pipeline p) { ScaleTestingOptions options = p.getOptions().as(ScaleTestingOptions.class); TSKey key = TSDataTestUtils.KEY_A_A; // Create Metrics TSAccum.Builder tsAccumBuilder = TSAccum.newBuilder().setKey(key); for (double i = 0D; i < (double) options.getNumFeatures(); i++) { tsAccumBuilder.putDataStore(String.valueOf(i), Data.newBuilder().setDoubleVal(i).build()); } return p.apply(Create.of(tsAccumBuilder.build())) .apply(ParDo.of(new SnapShotUtils.GenerateKeys(options.getNumKeys()))) .apply(Reshuffle.viaRandomKey()) .apply(ParDo.of(new SnapShotUtils.GenerateData(options.getNumSecs()))) .apply( ConvertAccumToSequence.builder() .setWindow( Window.into( SlidingWindows.of( Duration.standardSeconds( options.getTypeTwoComputationsLengthInSecs())) .every( Duration.standardSeconds( options.getTypeOneComputationsLengthInSecs())))) .build()) .apply(MajorKeyWindowSnapshot.generateWindowSnapshot()); } private static class GenerateKeys extends DoFn { final int keyCount; public GenerateKeys(int keyCount) { this.keyCount = keyCount; } @ProcessElement public void process(@Element TSAccum input, OutputReceiver o) { for (int i = 0; i < keyCount; i++) { TSKey key = input.getKey().toBuilder().setMajorKey(input.getKey().getMajorKey() + i).build(); o.output(input.toBuilder().setKey(key).build()); ; } } } private static class GenerateData extends DoFn> { final int accumCount; Instant start = Instant.ofEpochMilli(TSDataTestUtils.START); public GenerateData(int accumCount) { this.accumCount = accumCount; } @ProcessElement public void process(@Element TSAccum input, OutputReceiver> o) { for (int i = 0; i < accumCount; i++) { o.outputWithTimestamp( KV.of( input.getKey(), input .toBuilder() .setLowerWindowBoundary( Timestamps.fromMillis(start.plus(Duration.standardSeconds(i)).getMillis())) .setUpperWindowBoundary( Timestamps.fromMillis( start.plus(Duration.standardSeconds(i + 1)).getMillis())) .build()), start.plus(Duration.standardSeconds(i))); } } } public static class IterableTSAccumTSKeyDoFn extends DoFn, TSKey> { @ProcessElement public void process(ProcessContext pc) { pc.element().forEach(x -> pc.output(x.getKey())); } } public static class IterableTSAccumSequenceTSKeyDoFn extends DoFn, TSKey> { @ProcessElement public void process(ProcessContext pc) { pc.element().forEach(x -> pc.output(x.getKey())); } } } /* * Fabric3 * Copyright (c) 2009-2015 Metaform Systems * * 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. * Portions originally based on Apache Tuscany 2007 * licensed under the Apache 2.0 license. */ package org.fabric3.spi.model.instance; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fabric3.api.model.type.component.Component; import org.fabric3.spi.model.type.component.CompositeImplementation; /** * An instantiated composite component in the domain. */ public class LogicalCompositeComponent extends LogicalComponent { private static final long serialVersionUID = 6661201121307925462L; private Map> wires = new HashMap<>(); private Map> components = new HashMap<>(); private Map channels = new HashMap<>(); private List> resources = new ArrayList<>(); private boolean autowire; /** * Instantiates a composite component. * * @param uri the component URI * @param definition the component definition * @param parent the component parent */ public LogicalCompositeComponent(URI uri, Component definition, LogicalCompositeComponent parent) { super(uri, definition, parent); } /** * Instantiates a composite component. * * @param uri the component URI * @param definition the component definition * @param autowire true if autowire is enabled */ public LogicalCompositeComponent(URI uri, Component definition, boolean autowire) { super(uri, definition, null); this.autowire = autowire; } /** * Adds a wire to this composite component. * * @param logicalReference the wire source * @param logicalWire the wire to be added to this composite component */ public void addWire(LogicalReference logicalReference, LogicalWire logicalWire) { List logicalWires = wires.get(logicalReference); if (logicalWires == null) { logicalWires = new ArrayList<>(); wires.put(logicalReference, logicalWires); } logicalWires.add(logicalWire); } /** * Adds a set of wires to this composite component. * * @param logicalReference the source for the wires * @param newWires the wires to add */ public void addWires(LogicalReference logicalReference, List newWires) { List logicalWires = wires.get(logicalReference); if (logicalWires == null) { logicalWires = new ArrayList<>(); wires.put(logicalReference, logicalWires); } logicalWires.addAll(newWires); } /** * Gets the resolved targets sourced by the specified logical reference. * * @param logicalReference Logical reference that sources the wire. * @return Resolved targets for the reference. */ public List getWires(LogicalReference logicalReference) { List logicalWires = wires.get(logicalReference); if (logicalWires == null) { return Collections.emptyList(); } return logicalWires; } /** * Returns a map of wires keyed by logical reference contained in this composite. * * @return a map of wires keyed by logical reference contained in this composite */ public Map> getWires() { return wires; } /** * Returns the child components of the current component. * * @return the child components of the current component */ public Collection> getComponents() { return components.values(); } /** * Returns a child component with the given URI. * * @param uri the child component URI * @return a child component with the given URI. */ public LogicalComponent getComponent(URI uri) { return components.get(uri); } /** * Removes a child component with the given URI. * * @param uri the child component URI */ public void removeComponent(URI uri) { components.remove(uri); } /** * Adds a child component * * @param component the child component to add */ public void addComponent(LogicalComponent component) { components.put(component.getUri(), component); } /** * Returns the channels contained in the current component. * * @return the channels contained in the current component */ public Collection getChannels() { return channels.values(); } /** * Returns a channel with the given URI. * * @param uri the channel URI * @return the channel */ public LogicalChannel getChannel(URI uri) { return channels.get(uri); } /** * Removes a channel with the given URI. * * @param uri the channel URI */ public void removeChannel(URI uri) { channels.remove(uri); } /** * Adds a channel. * * @param channel the channel to add */ public void addChannel(LogicalChannel channel) { channels.put(channel.getUri(), channel); } public Collection> getResources() { return resources; } public void addResource(LogicalResource resource) { resources.add(resource); } /** * Sets the component state. * * @param state the instance state */ @Override public void setState(LogicalState state) { super.setState(state); for (LogicalComponent component : getComponents()) { component.setState(state); } } /** * Returns true if autowire is enabled. * * @return true if autowire is enabled */ public boolean isAutowire() { return autowire; } } jusbrasil/mirror package net.vidageek.mirror.provider.java; import static java.lang.String.format; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import net.vidageek.mirror.exception.MirrorException; import net.vidageek.mirror.provider.GenericTypeAccessor; import net.vidageek.mirror.provider.ParameterizedElementReflectionProvider; /** * @author dnfeitosa */ public class PureJavaParameterizedElementReflectionProvider implements ParameterizedElementReflectionProvider { private final GenericTypeAccessor accessor; public PureJavaParameterizedElementReflectionProvider(GenericTypeAccessor accessor) { this.accessor = accessor; } public Class getTypeAtPosition(int index) { ParameterizedType genericType; try { genericType = (ParameterizedType) accessor.getGenericTypes(); } catch (ClassCastException e) { throw new MirrorException("Element is not parameterized with a generic type.", e); } Type[] typeArguments = genericType.getActualTypeArguments(); try { return (Class) typeArguments[index]; } catch (ArrayIndexOutOfBoundsException e) { throw new MirrorException(format("No type declared at position %d.", index)); } } } app/src/main/java/com/ericksoncv/androidtvapptutorial/ui/VideoDetailsFragment.java package com.ericksoncv.androidtvapptutorial.ui; import android.content.Intent; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import androidx.leanback.app.DetailsFragment; import androidx.leanback.widget.Action; import androidx.leanback.widget.ArrayObjectAdapter; import androidx.leanback.widget.ClassPresenterSelector; import androidx.leanback.widget.DetailsOverviewRow; import androidx.leanback.widget.FullWidthDetailsOverviewRowPresenter; import androidx.leanback.widget.HeaderItem; import androidx.leanback.widget.ListRow; import androidx.leanback.widget.ListRowPresenter; import androidx.leanback.widget.OnActionClickedListener; import androidx.leanback.widget.SparseArrayObjectAdapter; import com.ericksoncv.androidtvapptutorial.ui.presenter.CardPresenter; import com.ericksoncv.androidtvapptutorial.ui.presenter.DetailsDescriptionPresenter; import com.ericksoncv.androidtvapptutorial.ui.background.PicassoBackgroundManager; import com.ericksoncv.androidtvapptutorial.common.Utils; import com.ericksoncv.androidtvapptutorial.data.MovieProvider; import com.ericksoncv.androidtvapptutorial.model.Movie; import com.squareup.picasso.Picasso; import java.io.IOException; import java.util.ArrayList; public class VideoDetailsFragment extends DetailsFragment { private static final String TAG = VideoDetailsFragment.class.getSimpleName(); private static final int DETAIL_THUMB_WIDTH = 274; private static final int DETAIL_THUMB_HEIGHT = 274; private static final String MOVIE = "Movie"; private static final int ACTION_PLAY_VIDEO = 0; private CustomFullWidthDetailsOverviewRowPresenter mFwdorPresenter; private PicassoBackgroundManager mPicassoBackgroundManager; private Movie mSelectedMovie; private DetailsRowBuilderTask mDetailsRowBuilderTask; @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); mFwdorPresenter = new CustomFullWidthDetailsOverviewRowPresenter(new DetailsDescriptionPresenter()); mPicassoBackgroundManager = new PicassoBackgroundManager(getActivity()); mSelectedMovie = (Movie)getActivity().getIntent().getSerializableExtra(MOVIE); mDetailsRowBuilderTask = (DetailsRowBuilderTask) new DetailsRowBuilderTask().execute(mSelectedMovie); mPicassoBackgroundManager.updateBackgroundWithDelay(mSelectedMovie.getCardImageUrl());; } @Override public void onStop() { mDetailsRowBuilderTask.cancel(true); super.onStop(); } private class DetailsRowBuilderTask extends AsyncTask { @Override protected DetailsOverviewRow doInBackground(Movie... params) { DetailsOverviewRow row = new DetailsOverviewRow(mSelectedMovie); try { Bitmap poster = Picasso.with(getActivity()) .load(mSelectedMovie.getCardImageUrl()) .resize(Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_WIDTH), Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_HEIGHT)) .centerCrop() .get(); row.setImageBitmap(getActivity(), poster); } catch (IOException e) { Log.w(TAG, e.toString()); } return row; } @Override protected void onPostExecute(DetailsOverviewRow row) { /* 1st row: DetailsOverviewRow */ SparseArrayObjectAdapter sparseArrayObjectAdapter = new SparseArrayObjectAdapter(); /*for (int i = 0; i<10; i++){ sparseArrayObjectAdapter.set(i, new Action(i, "label1", "label2")); }*/ sparseArrayObjectAdapter.set(0, new Action(ACTION_PLAY_VIDEO, "Play Video")); sparseArrayObjectAdapter.set(1, new Action(1, "Action 2", "label")); sparseArrayObjectAdapter.set(2, new Action(2, "Action 3", "label")); row.setActionsAdapter(sparseArrayObjectAdapter); mFwdorPresenter.setOnActionClickedListener(new OnActionClickedListener() { @Override public void onActionClicked(Action action) { if (action.getId() == ACTION_PLAY_VIDEO) { Intent intent = new Intent(getActivity(), PlaybackOverlayActivity.class); intent.putExtra("Movie", mSelectedMovie); intent.putExtra("shouldStart", true); startActivity(intent); } } }); /* 2nd row: ListRow */ ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter()); /*for(int i = 0; i < 10; i++){ Movie movie = new Movie(); if(i%3 == 0) { movie.setCardImageUrl("http://heimkehrend.raindrop.jp/kl-hacker/wp-content/uploads/2014/08/DSC02580.jpg"); } else if (i%3 == 1) { movie.setCardImageUrl("http://heimkehrend.raindrop.jp/kl-hacker/wp-content/uploads/2014/08/DSC02630.jpg"); } else { movie.setCardImageUrl("http://heimkehrend.raindrop.jp/kl-hacker/wp-content/uploads/2014/08/DSC02529.jpg"); } movie.setTitle("title" + i); movie.setStudio("studio" + i); listRowAdapter.add(movie); }*/ ArrayList mItems = MovieProvider.getMovieItems(); for (Movie movie : mItems) { listRowAdapter.add(movie); } HeaderItem headerItem = new HeaderItem(0, "Related Videos"); ClassPresenterSelector classPresenterSelector = new ClassPresenterSelector(); mFwdorPresenter.setInitialState(FullWidthDetailsOverviewRowPresenter.STATE_SMALL); Log.e(TAG, "mFwdorPresenter.getInitialState: " +mFwdorPresenter.getInitialState()); classPresenterSelector.addClassPresenter(DetailsOverviewRow.class, mFwdorPresenter); classPresenterSelector.addClassPresenter(ListRow.class, new ListRowPresenter()); ArrayObjectAdapter adapter = new ArrayObjectAdapter(classPresenterSelector); /* 1st row */ adapter.add(row); /* 2nd row */ adapter.add(new ListRow(headerItem, listRowAdapter)); /* 3rd row */ //adapter.add(new ListRow(headerItem, listRowAdapter)); setAdapter(adapter); } } } dheavy/simple-java-calc-engine package com.davybraun.learningjava.calcengine; public class Multiplier extends CalculateBase { public Multiplier() {} public Multiplier(double leftVal, double rightVal) { super(leftVal, rightVal); } @Override public void calculate() { setResult(getLeftVal() * getRightVal()); } } cedleg/sysinfo /* * Copyright [2018] [] * * 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. */ package com.cedleg.sysinfo; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 52; public static final String FILEPATCH = getFilePatch().toString(); private DataFragment bfrag; private ExportFragment efrag; private android.support.v7.app.ActionBar actionBar; private Toolbar myToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); //myToolbar.setTitleTextColor(Color.WHITE); actionBar=getSupportActionBar(); actionBar.setDisplayUseLogoEnabled(false); actionBar.setDisplayHomeAsUpEnabled(true); // Initialize the actionMode callback //initializeActionModeCallBack(); //Check and request authorisation if (Build.VERSION.SDK_INT >= 23) checkAndRequestPermissions(); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); //Get the ViewPager and set it's PagerAdapter so that it can display items PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), this); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); //Give the TabLayout the ViewPager //tabLayout.setTabTextColors(R.color.white, ContextCompat.getColor(this, R.color.tab_selector)); tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator)); tabLayout.setupWithViewPager(viewPager); // Iterate over all tabs and set the custom view for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayout.Tab tab = tabLayout.getTabAt(i); tab.setCustomView(pagerAdapter.getTabView(i)); } //Initiate fragment and list bfrag = new DataFragment(); efrag = new ExportFragment(); bfrag.setListChangeListener(new DataFragment.ListChangeListener() { @Override public void onListChange(List strings) { efrag.updateStringList(strings); } }); efrag.setStringChangeListener(new ExportFragment.StringChangeListener() { @Override public void onFinalStringChange(String str) { WriteFile(str); } }); //Give state color tab textview tabLayout.getTabAt(1).select(); tabLayout.getTabAt(0).select(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent aboutView = new Intent(this, AboutActivity.class); startActivity(aboutView); return true; } if(id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } /***** CLASS PAGE ADAPTER POUR TABLAYOUT *******/ class PagerAdapter extends FragmentPagerAdapter { String tabTitles[] = new String[] { "Infos", "Export", "Email" }; Context context; public PagerAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; } @Override public int getCount() { return tabTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return bfrag; case 1: return efrag; case 2: return new EmailFragment(); } return null; } @Override public CharSequence getPageTitle(int position) { // Generate title based on item position return tabTitles[position]; } public View getTabView(int position) { View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null); AppCompatTextView tv = (AppCompatTextView) tab.findViewById(R.id.custom_text); tv.setText(tabTitles[position]); return tab; } } /************* FIN DE CLASSE ************/ public static File getFilePatch(){ Calendar calendrier = Calendar.getInstance(); int jour = calendrier.get(Calendar.DAY_OF_MONTH); int mois = calendrier.get(Calendar.MONTH); int annee = calendrier.get(Calendar.YEAR); int heure = calendrier.get(Calendar.HOUR_OF_DAY ); int minute = calendrier.get(Calendar.MINUTE); int seconde = calendrier.get(Calendar.SECOND); String datestr = Integer.toString(jour)+Integer.toString(mois)+Integer.toString(annee); String heurestr = Integer.toString(heure)+Integer.toString(minute)+Integer.toString(seconde); File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Sysinfo"+"/"+ DataFragment.DEVICEMODEL+"-"+heurestr+datestr+".txt"); return storageDir; } public void WriteFile(String data) { File filedirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Sysinfo"); File file = new File(FILEPATCH); FileWriter filewriter = null; try{ if (!filedirectory.exists()) { filedirectory.mkdirs(); } file.createNewFile(); filewriter = new FileWriter(file,false); filewriter.write(data); Snackbar.make(findViewById(R.id.viewpager), "Write in file succesfull ", Snackbar.LENGTH_LONG).show(); }catch(Exception e) { Snackbar.make(findViewById(R.id.viewpager), "Write in file failed ", Snackbar.LENGTH_LONG).show(); } finally { if (filewriter != null) { try { filewriter.close(); } catch (IOException e) { Log.e("GREC", e.getMessage(), e); }}} } /*PERMISSIONS REQUEST AT RUN TIME*/ private boolean checkAndRequestPermissions() { int storage = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE); int phoneState = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE); List listPermissionsNeeded = new ArrayList<>(); if (storage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE); } if (phoneState != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(android.Manifest.permission.READ_PHONE_STATE); } if (!listPermissionsNeeded.isEmpty()) { if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) { Toast.makeText(MainActivity.this, "Accept permission Storage for use Export fonctionality." +"\n"+ "Go to Setting/Application/SysInfo/Authorisation", Toast.LENGTH_LONG).show(); } else if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_PHONE_STATE)) { Toast.makeText(MainActivity.this, "Accept permission Phone State for read telephony informations." +"\n"+ "Go to Setting/Application/SysInfo/Authorisation", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray (new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS); } return false; } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_ID_MULTIPLE_PERMISSIONS: { Map perms = new HashMap<>(); perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED); for(int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); StringBuilder builder = new StringBuilder(); if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { if (BuildConfig.DEBUG) { Log.e("value", "Permission storage Granted, success."); } builder.append("Permission storage granted\n"); } else { if (BuildConfig.DEBUG) { Log.e("value", "Permission Storage Denied, please accept to use Export functionality"); } builder.append("Permission Storage denied, please accept to use Export functionality\n"); } if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { if (BuildConfig.DEBUG) { Log.e("value", "Permission phone state Granted, success"); } builder.append("Permission phone state granted\n"); } else { if (BuildConfig.DEBUG) { Log.e("value", "Permission phone state Denied, You cannot read telephony informations."); } builder.append("Permission phone state denied, please accept to use telephony functionality\n"); } Snackbar.make(findViewById(R.id.viewpager), builder, Snackbar.LENGTH_LONG).show(); break; } } } } shelaratyahoo/UltimateGoal package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.ElapsedTime; @TeleOp(name="TestArm", group = "Linear Opmode") public class TestArm extends LinearOpMode { // Declare OpMode members. private ElapsedTime runtime; static final double powerFactor = 0.3; private Arm arm = null; public TestArm(){ runtime = new ElapsedTime(); } @Override public void runOpMode() { //Create Arm object. arm = new Arm(hardwareMap, telemetry, runtime, powerFactor); log("Arm object created."); arm.Initialize(); log("arm Initialize."); //Hold the arm // arm.holdArmUp(); // log("hold Arm Up"); boolean gamepad1_left_bumper = false; boolean gamepad1_right_bumper = false; // Wait for the game to start (driver presses PLAY) waitForStart(); // run until the end of the loop or the driver presses STOP while(opModeIsActive()) { gamepad1_left_bumper = gamepad1.left_bumper; gamepad1_right_bumper = gamepad1.right_bumper; if(gamepad1_left_bumper == true) { arm.holdArmUp(); log("Arm Up"); } else if(gamepad1_right_bumper == true) { arm.holdArmDown(); log("Arm Down"); } else { arm.stopArm(); log("Arm stopped.."); } //arm.wait(1000); } } public void log(String logInfo) { telemetry.addLine( logInfo); telemetry.update(); } } SkRPG/src/me/limeglass/skrpg/Conditions/CondSkillbarIsSetup.java package me.limeglass.skrpg.Conditions; import org.bukkit.entity.Player; import com.sucy.skill.SkillAPI; import ch.njol.skript.conditions.base.PropertyCondition; public class CondSkillbarIsSetup extends PropertyCondition { @Override public boolean check(Player player) { return SkillAPI.getPlayerData(player).getSkillBar().isSetup(); } @Override protected String getPropertyName() { return "SkillAPI skillbar is setup"; } } jer-lim/NUS-TA-Teaching-MaterialCS2030/AY1819 Sem 1/Labs/lab5/lab5/PrimeFactor.java import java.util.Scanner; import java.util.stream.IntStream; class Main { static boolean isPrime(int x) { return IntStream .range(2, x) .noneMatch(d -> x % d == 0); } static IntStream factors(int x) { return IntStream .rangeClosed(2, x) .filter(d -> x % d == 0); } static IntStream primeFactors(int x) { return factors(x) .filter(d -> isPrime(d)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.print("Prime factors of " + n + " are:"); primeFactors(n) .forEach(x -> System.out.print(" " + x)); System.out.println(); //System.out.println(Reverse(sc.nextInt())); } } 0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.thorqin.webapi.smc; import java.awt.Dialog; import java.util.Set; import javax.swing.JOptionPane; import com.github.thorqin.webapi.mail.MailConfig.MailSetting.MailSettingItem; import com.github.thorqin.webapi.utility.StringUtil; /** * * @author nuo.qin */ public class MailDialog extends javax.swing.JDialog { public String key; public Set keys; private MailSettingItem mailItem; public boolean ok = false; private int panelHeight = 0; private int windowHeight = 0; public MailDialog(Dialog parent, boolean modal) { super(parent, modal); initComponents(); } public MailSettingItem getSetting() { return mailItem; } public void setSetting(MailSettingItem rule) { this.mailItem = rule; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); textHost = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); textFrom = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); textPort = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); comboSecurity = new javax.swing.JComboBox(); jLabel8 = new javax.swing.JLabel(); textConfigName = new javax.swing.JTextField(); checkNeedAuth = new javax.swing.JCheckBox(); panelAuth = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); textUser = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); textPassword = new javax.swing.JTextField(); buttonOK = new javax.swing.JButton(); buttonCancel = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Mail Setting"); setModal(true); setModalityType(java.awt.Dialog.ModalityType.DOCUMENT_MODAL); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setOpaque(false); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel1.setText("SMTP Server Host (must)"); jLabel7.setText("From Address"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel3.setText("SMTP Port: e.g. 25, 465(SSL), 587(TLS) (must)"); jLabel6.setText("Security"); comboSecurity.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "no", "ssl", "starttls" })); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel8.setText("Config Name"); checkNeedAuth.setText("Need Authentication"); checkNeedAuth.setOpaque(false); checkNeedAuth.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkNeedAuthActionPerformed(evt); } }); panelAuth.setOpaque(false); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel2.setText("Login User (must)"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel5.setText("Password (must)"); javax.swing.GroupLayout panelAuthLayout = new javax.swing.GroupLayout(panelAuth); panelAuth.setLayout(panelAuthLayout); panelAuthLayout.setHorizontalGroup( panelAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelAuthLayout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(panelAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textUser) .addComponent(textPassword)) .addGap(0, 0, 0)) ); panelAuthLayout.setVerticalGroup( panelAuthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelAuthLayout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textHost, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textFrom, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE) .addComponent(textPort, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(comboSecurity, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textConfigName) .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(checkNeedAuth, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelAuth, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textConfigName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(checkNeedAuth) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelAuth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(comboSecurity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); buttonOK.setText("OK"); buttonOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonOKActionPerformed(evt); } }); buttonCancel.setText("Cancel"); buttonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonCancelActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator2) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(buttonCancel) .addComponent(buttonOK)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// //GEN-END:initComponents private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed if (textConfigName.getText().trim().isEmpty()) { JOptionPane.showMessageDialog(null, "Must specify config name!", "Error", JOptionPane.WARNING_MESSAGE); textConfigName.requestFocus(true); return; } if (keys != null && keys.contains(textConfigName.getText().trim())) { JOptionPane.showMessageDialog(null, "Config name already exists!", "Error", JOptionPane.WARNING_MESSAGE); textConfigName.requestFocus(true); return; } if (textHost.getText().trim().isEmpty()) { JOptionPane.showMessageDialog(null, "Must specify server host!", "Error", JOptionPane.WARNING_MESSAGE); textHost.requestFocus(true); return; } if (!StringUtil.isInteger(textPort.getText().trim())) { JOptionPane.showMessageDialog(null, "Must specify server port(an integer value)!", "Error", JOptionPane.WARNING_MESSAGE); textPort.requestFocus(true); return; } if (checkNeedAuth.isSelected()) { if (textUser.getText().trim().isEmpty()) { JOptionPane.showMessageDialog(null, "Must specify login user!", "Error", JOptionPane.WARNING_MESSAGE); textUser.requestFocus(true); return; } if (textPassword.getText().trim().isEmpty()) { JOptionPane.showMessageDialog(null, "Must specify login password!", "Error", JOptionPane.WARNING_MESSAGE); textPassword.requestFocus(true); return; } } key = textConfigName.getText(); mailItem.auth = checkNeedAuth.isSelected(); mailItem.host = textHost.getText().trim(); mailItem.port = Integer.parseInt(textPort.getText()); mailItem.user = textUser.getText().trim(); mailItem.password = textPassword.getText().trim(); mailItem.from = textFrom.getText().trim(); mailItem.secure = (String)comboSecurity.getSelectedItem(); ok = true; this.dispose(); }//GEN-LAST:event_buttonOKActionPerformed private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed this.dispose(); }//GEN-LAST:event_buttonCancelActionPerformed private String generateKey() { String name = "default"; String newKey = name; int i = 1; while (keys.contains(newKey)) { newKey = name + i; i++; } return newKey; } private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened if (mailItem == null) { mailItem = new MailSettingItem(); } if (key == null) { textConfigName.setText(generateKey()); } else { textConfigName.setText(key); textConfigName.setEnabled(false); } this.panelHeight = panelAuth.getHeight(); this.windowHeight = this.getHeight(); checkNeedAuth.setSelected(mailItem.auth); changeAuthSetting(); textHost.setText(mailItem.host); textPort.setText(String.valueOf(mailItem.port)); textUser.setText(mailItem.user); textPassword.setText(mailItem.password); textFrom.setText(mailItem.from); comboSecurity.setSelectedItem(mailItem.secure); }//GEN-LAST:event_formWindowOpened private void changeAuthSetting() { if (checkNeedAuth.isSelected()) { panelAuth.setVisible(true); this.setSize(this.getWidth(), windowHeight); } else { panelAuth.setVisible(false); this.setSize(this.getWidth(), windowHeight - panelHeight); } } private void checkNeedAuthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkNeedAuthActionPerformed changeAuthSetting(); }//GEN-LAST:event_checkNeedAuthActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonCancel; private javax.swing.JButton buttonOK; private javax.swing.JCheckBox checkNeedAuth; private javax.swing.JComboBox comboSecurity; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JSeparator jSeparator2; private javax.swing.JPanel panelAuth; private javax.swing.JTextField textConfigName; private javax.swing.JTextField textFrom; private javax.swing.JTextField textHost; private javax.swing.JTextField textPassword; private javax.swing.JTextField textPort; private javax.swing.JTextField textUser; // End of variables declaration//GEN-END:variables } package org.tdar.dataone.server; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang.StringUtils; import org.dataone.service.types.v1.SystemMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.tdar.dataone.service.DataOneService; @Path(AbstractDataOneResponse.BASE_PATH + "meta") @Component @Scope("prototype") public class SystemMetadataResponse extends AbstractDataOneResponse { private final transient Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private DataOneService service; /* * Raises: * Exceptions.NotImplemented – * (errorCode=501, detailCode=2041) * Ping is a required operation and so an operational member node should never return this exception unless under development. * * Exceptions.ServiceFailure – * (errorCode=500, detailCode=2042) * * A ServiceFailure exception indicates that the node is not currently operational as a member node. A coordinating node or monitoring service may use this * as an indication that the member node should be taken out of the pool of active nodes, though ping should be called on a regular basis to determine when * the node might b ready to resume normal operations. * * Exceptions.InsufficientResources – * (errorCode=413, detailCode=2045) * * A ping response may return InsufficientResources if for example the system is in a state where normal DataONE operations may be impeded by an unusually * high load on the node. */ @Context private HttpServletResponse response; @Context private HttpServletRequest request; @GET @Path("{id:.*}") @Produces(APPLICATION_XML) public Response meta(@PathParam("id") String id) { setupResponseContext(response, request); if (StringUtils.isBlank(id)) { return Response.serverError().entity(getNotFoundError()).status(Status.NOT_FOUND).build(); } try { service.checkForChecksumConflict(id); SystemMetadata metadataRequest = service.metadataRequest(id); if (metadataRequest == null) { return Response.serverError().entity(getNotFoundError()).status(Status.NOT_FOUND).build(); } return Response.ok(metadataRequest).build(); } catch (Exception e) { logger.error("error in metadataResponse: {}", e, e); return Response.serverError().entity(getNotFoundError()).status(Status.NOT_FOUND).build(); } } } chapter12/Deck.java public class Deck{ private Card[] theDeck; public Deck(){ theDeck = new Card[52]; int[] suits = Card.CARD_SUITS; int curCard =0; for (int suit : Card.CARD_SUITS){ for (int rank : Card.CARD_RANKS){ theDeck[curCard] = new Card(rank, suit); curCard++; } } } public void shuffle(){ for (int i=0; i< theDeck.length; i++){ Card current = theDeck[i]; int swapPosition = (int)(52* Math.random()); // I need to remember what was in swapPosition Card swapCard= theDeck[swapPosition]; theDeck[swapPosition] = current; theDeck[i] = swapCard; } } public Card[] dealHand(int size) { if(size<0 || size> theDeck.length) return null; Card[] result = new Card[size]; for (int i=0; i< size; i++) { int deckIndex =0; while(deckIndex < theDeck.length && theDeck[deckIndex]==null) { deckIndex++; } result[i] = theDeck[deckIndex]; theDeck[deckIndex] = null; } return result; } public Card topCard(){ return theDeck[0]; } }ses-app/ses-web-ros/src/main/java/com/redescooter/ses/web/ros/service/base/OpeAllocatePartsBService.java package com.redescooter.ses.web.ros.service.base; import com.baomidou.mybatisplus.extension.service.IService; import com.redescooter.ses.web.ros.dm.OpeAllocatePartsB; import java.util.List; public interface OpeAllocatePartsBService extends IService { int updateBatch(List list); int batchInsert(List list); int insertOrUpdate(OpeAllocatePartsB record); int insertOrUpdateSelective(OpeAllocatePartsB record); } package org.enricogiurin.codingchallenges.codeforces.old.c1114; import java.util.Scanner; public class ProblemA { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int d = scanner.nextInt(); int m = scanner.nextInt(); int g = scanner.nextInt(); int p = scanner.nextInt(); int b = scanner.nextInt(); if ((g - a) < 0) { System.out.println("NO"); return; } g -= a; if ((g + p) < d) { System.out.println("NO"); return; } int gPrev = g; g = Math.max(0, g - d); d -= gPrev - g; if (d > 0) { p -= d; } if ((g + p + b) >= m) { System.out.println("YES"); } else { System.out.println("NO"); } } } package com.tangenta.evaluator; import com.tangenta.parser.result.Panic; import com.tangenta.common.Expr; import com.tangenta.common.Val; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; // Env is an key-value environment when evaluating Expr. public class Env { private final Map env; private Env(Map env) { this.env = env; } // set() is used to set a key-value pair. public void set(Expr.Sym sym, Val v) { env.put(sym, v); } // get() is used to get a key-value from environment. public Val get(Expr.Sym sym) { return env.get(sym); } // standard() defined basic operators and functions for valuating, such as `random`, `car`, 'cdr', etc. public static Env standard() { Random random = new Random(); return new Env(new HashMap(){{ put(new Expr.Sym("+"), new Val.Func(args -> args.stream().map(v -> { if (!(v instanceof Val.Int)) throw Panic.msg("+ should be use on integer"); return ((Val.Int) v).value; }).reduce(Integer::sum).map(Val.Int::new).orElseThrow(() -> { return Panic.msg("+ should apply to at lease 1 arguments"); }))); put(new Expr.Sym("*"), new Val.Func(args -> args.stream().map(v -> { if (!(v instanceof Val.Int)) throw Panic.msg("* should be use on integer"); return ((Val.Int) v).value; }).reduce((i1, i2) -> i1 * i2).map(Val.Int::new).orElseThrow(() -> { return Panic.msg("* should apply to at lease 1 arguments"); }))); put(new Expr.Sym("-"), new Val.Func(args -> args.stream().map(v -> { if (!(v instanceof Val.Int)) throw Panic.msg("- should be use on integer"); Integer ret = ((Val.Int) v).value; return args.size() == 1 ? -ret : ret; }).reduce((i1, i2) -> i1 - i2).map(Val.Int::new).orElseThrow(() -> { return Panic.msg("- should apply to at lease 1 arguments"); }))); put(new Expr.Sym("<"), new Val.Func(args -> { if (args.size() != 2 || !args.stream().allMatch(e -> e instanceof Val.Int)) throw Panic.msg("< can only compare two int"); Integer first = ((Val.Int) args.get(0)).value; Integer second = ((Val.Int) args.get(1)).value; return new Val.Bool(first < second); })); put(new Expr.Sym("random"), new Val.Func(args -> { if (args.size() != 1 || !(args.get(0) instanceof Val.Int)) { throw Panic.msg("random can only be applied to 1 int"); } Integer max = ((Val.Int) args.get(0)).value; return new Val.Int(random.nextInt(max)); })); put(new Expr.Sym("eq?"), new Val.Func(args -> { if (args.size() != 2) { throw Panic.msg("eq? can only be applied to 2 symbols"); } Val left = args.get(0); Val right = args.get(1); if (left instanceof Val.Int && right instanceof Val.Int) { return new Val.Bool(((Val.Int) left).value.equals(((Val.Int) right).value)); } else if (left instanceof Val.Bool && right instanceof Val.Bool) { return new Val.Bool(((Val.Bool) left).value.equals(((Val.Bool) right).value)); } else if (left instanceof Val.Lst && right instanceof Val.Lst) { return new Val.Bool(((Val.Lst) left).value.equals(((Val.Lst) right).value)); } else return new Val.Bool(false); })); put(new Expr.Sym("car"), new Val.Func(args -> { if (args.size() != 1 || !(args.get(0) instanceof Val.Lst)) { throw Panic.msg("Car must apply to one list"); } List lstVals = ((Val.Lst) args.get(0)).value; if (lstVals.isEmpty()) { throw Panic.msg("car on empty list"); } return lstVals.get(0); })); put(new Expr.Sym("cdr"), new Val.Func(args -> { if (args.size() != 1 || !(args.get(0) instanceof Val.Lst)) { throw Panic.msg("Cdr must apply to one list"); } List lstVals = ((Val.Lst) args.get(0)).value; if (lstVals.isEmpty()) { throw Panic.msg("cdr on empty list"); } return new Val.Lst(lstVals.stream().skip(1).collect(Collectors.toList())); })); put(new Expr.Sym("and"), new Val.Func(args -> new Val.Bool(args.stream().map(arg -> { if (!(arg instanceof Val.Bool)) { throw Panic.msg("And must be applied to booleans"); } return ((Val.Bool) arg).value; }).reduce(true, (a, b) -> a && b)))); put(new Expr.Sym("or"), new Val.Func(args -> new Val.Bool(args.stream().map(arg -> { if (!(arg instanceof Val.Bool)) { throw Panic.msg("Or must be applied to booleans"); } return ((Val.Bool) arg).value; }).reduce(false, (a, b) -> a || b)))); }}); } // create() create an environment from a given map. public static Env create(Map env) { return new Env(env); } // expand() create an environment with the old one adding more kv pairs. public static Env expand(Env old, Map newEnv) { return new Env(new HashMap(){{ putAll(old.env); putAll(newEnv); }}); } } package com.ibm.dataservices; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //@RestController @SpringBootApplication @ComponentScan("com") public class DataserviceApp { //@RequestMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE) //public String home() { // return "Nothing here. Go to /sample"; //} static public void main(String[] args) throws Exception { SpringApplication.run(DataserviceApp.class, args); } } package cn.wwl.radio.executor.functions; import cn.wwl.radio.adnmb.bean.AdnmbPost; import cn.wwl.radio.adnmb.bean.AdnmbThread; import cn.wwl.radio.console.ConsoleManager; import cn.wwl.radio.executor.ConsoleFunction; import cn.wwl.radio.adnmb.AdnmbClient; import cn.wwl.radio.adnmb.bean.AdnmbForumID; import cn.wwl.radio.executor.FunctionExecutor; import cn.wwl.radio.network.SocketTransfer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class AdnmbClientFunction implements ConsoleFunction { public static final String SELECT_FORUM = "#forum"; public static final String GET_THREAD = "#thread"; public static final String GET_MORE = "#more"; public static final String PREFIX = "ADNMB > "; private final List allForum = new ArrayList<>(); private final Map posts = new HashMap<>(); private AdnmbThread targetThread; private AdnmbForumID targetForum; private boolean enable = true; // private int threadCount = 1; private int pageCount = 1; @Override public void onInit() { Map> forumLists = AdnmbClient.getInstance().getForumLists(); int forums = 0; for (Map.Entry> entry : forumLists.entrySet()) { forums += entry.getValue().size(); allForum.addAll(entry.getValue()); } if (forums != 0) { ConsoleManager.getConsole().printToConsole("Loaded " + forums + " Forum from Adnmb!"); SocketTransfer.getInstance().echoToConsole("Adnmb Ready. Loaded " + forums + " Forums. Use cmd " + SELECT_FORUM + " List all Forums."); } } @Override public List isHookSpecialMessage() { return List.of(SELECT_FORUM, GET_THREAD, GET_MORE); } @Override public void onExecuteFunction(List parameter) { if (enable) { SocketTransfer.getInstance().echoToConsole("Adnmb client now is Off"); enable = false; } else { SocketTransfer.getInstance().echoToConsole("Adnmb client now is On"); enable = true; } } @Override public void onHookSpecialMessage(String message) { if (!enable) { return; } if (allForum.isEmpty()) { echoWithPrefix("Adnmb is Not ready! Please wait Sec."); return; } if (message.startsWith(PREFIX)) { return; } message = FunctionExecutor.removeUnknownCommandTag(message); if (message.contains(SELECT_FORUM)) { if (message.equals(SELECT_FORUM)) { if (targetThread != null) { targetThread = null; echoWithPrefix("Return to Forum."); pageCount = 1; renderForums(); return; } echoWithPrefix("Adnmb Forums: "); allForum.forEach(forum -> { echoWithPrefix(" " + forum.toString()); }); printBottom(); return; } try { String str = message.substring(SELECT_FORUM.length() + 1); targetForum = AdnmbClient.getInstance().getForumByID(Integer.parseInt(str)); echoWithPrefix("Select Forum: " + targetForum.toString()); posts.clear(); pageCount = 1; } catch (Exception e) { SocketTransfer.getInstance().echoToConsole("Cannot Parse the Forum cmd! Please Try again!"); ConsoleManager.getConsole().printError("Parse Forum ERROR!"); ConsoleManager.getConsole().printException(e); } return; } if (message.contains(GET_MORE)) { if (targetForum == null) { echoWithPrefix("Please Choose Forum First!"); return; } SocketTransfer.getInstance().echoToConsole("\r\n\r\n\r\n", false); if (targetThread == null) { renderForums(); } else { targetThread.setCurrentPage(targetThread.getCurrentPage() + 1); List post = AdnmbClient.getInstance().getReplys(targetThread); renderThread(post); } printBottom(); return; } if (message.contains(GET_THREAD)) { if (message.equals(GET_THREAD)) { echoWithPrefix("Usage: " + GET_THREAD + "_[ID] Get Thread data."); printBottom(); return; } try { Integer threadID = Integer.parseInt(message.substring(GET_THREAD.length() + 1)); if (posts.containsKey(threadID)) { targetThread = posts.get(threadID); List post = AdnmbClient.getInstance().getReplys(targetThread); renderThread(post); } // else { // List post = AdnmbClient.getInstance().getReplys(threadID, threadCount++, false); // renderThread(post); // } printBottom(); return; } catch (Exception e) { SocketTransfer.getInstance().echoToConsole("Try process Thread Failed!"); ConsoleManager.getConsole().printError("Try process Thread Failed!"); ConsoleManager.getConsole().printException(e); return; } } } // CSGO中文缓冲区 大约160左右 private void processEchoContent(String s) { if (s.contains("\n")) { String[] split = s.split("\n"); for (String str : split) { SocketTransfer.getInstance().echoToConsole(str, false); } } else { if (s.length() > 150) { if (s.contains(",")) { String[] split = s.split(","); for (String str : split) { processEchoContent(str); } return; } if (s.contains("。")) { String[] split = s.split("。"); for (String str : split) { processEchoContent(str); } return; } StringBuilder buffer = new StringBuilder(); for (int i = 0; i < s.length(); i++) { buffer.append(s.charAt(i)); if (i % 150 == 0) { SocketTransfer.getInstance().echoToConsole(buffer.toString(), false); buffer.setLength(0); } } SocketTransfer.getInstance().echoToConsole(buffer.toString(), false); } else { SocketTransfer.getInstance().echoToConsole(s, false); } } } private void renderThread(List data) { if (data == null || data.size() == 0) { echoWithPrefix("No more Threads!"); return; } data.forEach(post -> { String str = post.getCookie() + " --- " + post.getTime() + " --- ID: " + post.getId(); SocketTransfer.getInstance().echoToConsole(str, false); processEchoContent(post.getContent()); if (!post.getImage().equals("")) { SocketTransfer.getInstance().echoToConsole("图片: " + post.getImage(), false); } SocketTransfer.getInstance().echoToConsole("\r\n", false); }); } private void renderForums() { List threads = AdnmbClient.getInstance().getThreads(targetForum, pageCount++); if (threads.isEmpty()) { SocketTransfer.getInstance().echoToConsole("Get new Page Failed! Please Try again!"); return; } threads.forEach(thread -> { posts.put(thread.getId(), thread); String str = thread.getCookie() + " --- " + thread.getTime() + " --- 串号: " + thread.getId() + " --- 回复: " + thread.getTotalReply(); SocketTransfer.getInstance().echoToConsole(str, false); processEchoContent(thread.getContent()); if (!thread.getImage().equals("")) { SocketTransfer.getInstance().echoToConsole("图片: " + thread.getImage(), false); } SocketTransfer.getInstance().echoToConsole("\r\n\r\n", false); }); } private void printBottom() { echoWithPrefix("cmd: " + SELECT_FORUM + " -> List Forums, " + SELECT_FORUM + "_[ID] Choose Forums."); echoWithPrefix("cmd: " + GET_THREAD + "_[ThreadID] Fetch Thread."); echoWithPrefix("cmd: " + GET_MORE + " -> MORE Threads, MORE Reply!"); } private void echoWithPrefix(String str) { SocketTransfer.getInstance().echoToConsole(PREFIX + str, false); } } xingmeichen/spring-cloud-shop package quick.pager.shop.goods.request.classification; import lombok.Data; import lombok.EqualsAndHashCode; import quick.pager.shop.user.request.Request; /** * 商品分类 * * @author siguiyang * @version 3.0 */ @EqualsAndHashCode(callSuper = true) @Data public class GoodsClassificationSaveRequest extends Request { private static final long serialVersionUID = 6958547173183868641L; /** * 分类名称 */ private String className; /** * spu主键 */ private Long spuId; /** * 序号 */ private Integer sequence; } Trainerredstone7/IntegratedCrafting package org.cyclops.integratedcrafting.core; import org.cyclops.integratedcrafting.IntegratedCrafting; import org.cyclops.integratedcrafting.api.crafting.ICraftingProcessOverrideRegistry; import org.cyclops.integratedcrafting.core.crafting.processoverride.CraftingProcessOverrideBrewingStand; import org.cyclops.integratedcrafting.core.crafting.processoverride.CraftingProcessOverrideCraftingTable; /** * @author rubensworks */ public class CraftingProcessOverrides { public static ICraftingProcessOverrideRegistry REGISTRY = IntegratedCrafting._instance.getRegistryManager() .getRegistry(ICraftingProcessOverrideRegistry.class); public static final CraftingProcessOverrideCraftingTable CRAFTING_TABLE = REGISTRY.register(new CraftingProcessOverrideCraftingTable()); public static final CraftingProcessOverrideBrewingStand BREWING_STAND = REGISTRY.register(new CraftingProcessOverrideBrewingStand()); public static void load() {} } package de.patgrosse.asyncfoldercompare.gui.start; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; public class CredentialsDialog extends JDialog implements AFCSettingsHolder { private static final long serialVersionUID = 6593740400698562171L; private AFCGUIStarter parent; private JLabel oldDesc, newDesc; private CredentialPanel oldCred, newCred; private JButton closeButton; public CredentialsDialog(AFCGUIStarter parent) { super(parent, true); this.parent = parent; setLayout(new GridBagLayout()); setTitle("Change credentials"); setDefaultCloseOperation(DISPOSE_ON_CLOSE); oldDesc = new JLabel("Credentials for old folder:"); GridBagConstraints gbcOldDesc = new GridBagConstraints(); gbcOldDesc.gridx = 0; gbcOldDesc.gridy = 0; gbcOldDesc.weightx = 1.0; gbcOldDesc.anchor = GridBagConstraints.WEST; gbcOldDesc.insets = new Insets(10, 10, 10, 10); add(oldDesc, gbcOldDesc); oldCred = new CredentialPanel(parent.getLastSettings().getCredentialsOld().getDomain(), parent.getLastSettings().getCredentialsOld().getUser(), parent.getLastSettings().getCredentialsOld().getPassword()); GridBagConstraints gbcOldCred = new GridBagConstraints(); gbcOldCred.gridx = 0; gbcOldCred.gridy = 1; gbcOldCred.weightx = 1.0; gbcOldCred.fill = GridBagConstraints.HORIZONTAL; gbcOldCred.anchor = GridBagConstraints.WEST; gbcOldCred.insets = new Insets(0, 10, 10, 10); add(oldCred, gbcOldCred); newDesc = new JLabel("Credentials for new folder:"); GridBagConstraints gbcNewDesc = new GridBagConstraints(); gbcNewDesc.gridx = 0; gbcNewDesc.gridy = 2; gbcNewDesc.weightx = 1.0; gbcNewDesc.anchor = GridBagConstraints.WEST; gbcNewDesc.insets = new Insets(10, 10, 10, 10); add(newDesc, gbcNewDesc); newCred = new CredentialPanel(parent.getLastSettings().getCredentialsNew().getDomain(), parent.getLastSettings().getCredentialsNew().getUser(), parent.getLastSettings().getCredentialsNew().getPassword()); GridBagConstraints gbcNewCred = new GridBagConstraints(); gbcNewCred.gridx = 0; gbcNewCred.gridy = 3; gbcNewCred.weightx = 1.0; gbcNewCred.fill = GridBagConstraints.HORIZONTAL; gbcNewCred.anchor = GridBagConstraints.WEST; gbcNewCred.insets = new Insets(0, 10, 10, 10); add(newCred, gbcNewCred); closeButton = new JButton("Close"); closeButton.setIcon(UIManager.getIcon("InternalFrame.closeIcon")); closeButton.addActionListener(e -> dispatchEvent(new WindowEvent(CredentialsDialog.this, WindowEvent.WINDOW_CLOSING))); GridBagConstraints gbcCloseButton = new GridBagConstraints(); gbcCloseButton.gridx = 0; gbcCloseButton.gridy = 4; gbcNewCred.fill = GridBagConstraints.HORIZONTAL; gbcNewCred.insets = new Insets(10, 10, 10, 10); add(closeButton, gbcCloseButton); pack(); setLocationRelativeTo(parent); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { saveSettings(); } }); } @Override public void saveSettings() { parent.getLastSettings().getCredentialsOld().setDomain(oldCred.getDomain()); parent.getLastSettings().getCredentialsOld().setUser(oldCred.getUser()); parent.getLastSettings().getCredentialsOld().setPassword(oldCred.getPassword()); parent.getLastSettings().getCredentialsNew().setDomain(newCred.getDomain()); parent.getLastSettings().getCredentialsNew().setUser(newCred.getUser()); parent.getLastSettings().getCredentialsNew().setPassword(newCred.getPassword()); } private static class CredentialPanel extends JPanel { private static final long serialVersionUID = 7826038409001435494L; private JLabel domainLabel, userLabel, passwordLabel; private JTextField domainField, userField, passwordField; public CredentialPanel(String domain, String user, String password) { setLayout(new GridBagLayout()); domainLabel = new JLabel("Domain:"); GridBagConstraints gbcDomainLabel = new GridBagConstraints(); gbcDomainLabel.gridx = 0; gbcDomainLabel.gridy = 0; gbcDomainLabel.anchor = GridBagConstraints.WEST; add(domainLabel, gbcDomainLabel); domainField = new JTextField(domain); GridBagConstraints gbcDomainField = new GridBagConstraints(); gbcDomainField.gridx = 1; gbcDomainField.gridy = 0; gbcDomainField.weightx = 1.0; gbcDomainField.fill = GridBagConstraints.HORIZONTAL; gbcDomainField.anchor = GridBagConstraints.WEST; add(domainField, gbcDomainField); userLabel = new JLabel("User:"); GridBagConstraints gbcUserLabel = new GridBagConstraints(); gbcUserLabel.gridx = 0; gbcUserLabel.gridy = 1; gbcUserLabel.anchor = GridBagConstraints.WEST; add(userLabel, gbcUserLabel); userField = new JTextField(user); GridBagConstraints gbcUserField = new GridBagConstraints(); gbcUserField.gridx = 1; gbcUserField.gridy = 1; gbcUserField.weightx = 1.0; gbcUserField.fill = GridBagConstraints.HORIZONTAL; gbcUserField.anchor = GridBagConstraints.WEST; add(userField, gbcUserField); passwordLabel = new JLabel("Password:"); GridBagConstraints gbcPasswordLabel = new GridBagConstraints(); gbcPasswordLabel.gridx = 0; gbcPasswordLabel.gridy = 2; gbcPasswordLabel.anchor = GridBagConstraints.WEST; add(passwordLabel, gbcPasswordLabel); passwordField = new JTextField(password); GridBagConstraints gbcPasswordField = new GridBagConstraints(); gbcPasswordField.gridx = 1; gbcPasswordField.gridy = 2; gbcPasswordField.weightx = 1.0; gbcPasswordField.fill = GridBagConstraints.HORIZONTAL; gbcPasswordField.anchor = GridBagConstraints.WEST; add(passwordField, gbcPasswordField); } public String getDomain() { return domainField.getText(); } public String getUser() { return userField.getText(); } public String getPassword() { return passwordField.getText(); } } } unshare/mapstructcore/src/main/java/org/mapstruct/SubclassExhaustiveStrategy.java /* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct; /** * Strategy for dealing with subclassMapping annotated methods. * * @since 1.5 * @author */ public enum SubclassExhaustiveStrategy { /** * If there is no valid constructor or known method to create the return value of a with `@SubclassMapping` * annotated mapping then a compilation error will be thrown. */ COMPILE_ERROR, /** * If there is no valid constructor or known method to create the return value of a with `@SubclassMapping` * annotated mapping then an {@link IllegalArgumentException} will be thrown if a call is made with a type for which * there is no {@link SubclassMapping} available. */ RUNTIME_EXCEPTION; } app/src/main/java/cn/mstar/store/activity/MyFavoriteManagmentActivity.java package cn.mstar.store.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import cn.mstar.store.R; import cn.mstar.store.app.MyApplication; import cn.mstar.store.customviews.LoadingDialog; import cn.mstar.store.entity.FavoriteManagerItem; import cn.mstar.store.fragments.FavoriteItemListFragment; import cn.mstar.store.utils.Constants; import cn.mstar.store.utils.L; import cn.mstar.store.utils.MaFragmentManagerSpace; import cn.mstar.store.utils.NewLink; import cn.mstar.store.utils.Utils; import cn.mstar.store.utils.VolleyRequest; public class MyFavoriteManagmentActivity extends FragmentActivity { private static int SCREENWIDTH ; ListView lv_favorite_list; FrameLayout frameLayout; RelativeLayout rel_all_items; ImageView iv_indicator; ViewHolder vh; ImageView iv_back; TextView tv_toptitle; private int ALL_FAVORITE_COUNT = 0; private FragmentManager fragmentManager; private boolean firstTransaction = true; private FavoriteItemListFragment previousFragment; private String tokenKey; @Bind(R.id.lny_loading_layout) protected LinearLayout lny_loading_layout; @Bind(R.id.lny_network_error_view) protected LinearLayout lny_network_error_layout; @Bind(R.id.lny_no_result) protected LinearLayout lny_noresult; @Bind(R.id.lny_content) LinearLayout lny_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_favorite_managment); tokenKey = Utils.getTokenKey((MyApplication) getApplication()); // init the progress stuffs. ButterKnife.bind(this); all_invisible(); lny_loading_layout.setVisibility(View.VISIBLE); initViews(); Utils.setNavigationBarColor(this, getResources().getColor(R.color.status_bar_color)); Utils.setStatusBarColor(this, getResources().getColor(R.color.status_bar_color)); // load favorite data from server initTopBar(getString(R.string.myfavorite_title)); SCREENWIDTH = getScreenWidth (this); // Toast.makeText(this, "screenwidth is "+SCREENWIDTH, Toast.LENGTH_SHORT).show(); loadData(); } public void all_invisible() { lny_loading_layout.setVisibility(View.GONE); lny_network_error_layout.setVisibility(View.GONE); lny_noresult.setVisibility(View.GONE); lny_content.setVisibility(View.GONE); } public void networkExceptionError() { all_invisible(); lny_network_error_layout.setVisibility(View.VISIBLE); } public void noResultFound() { // if the listadapter is = 0... then this... otherwise, the only the bottom progress stuff. all_invisible(); lny_noresult.setVisibility(View.VISIBLE); } public int getScreenWidth (Context context) { DisplayMetrics metrics = new DisplayMetrics(); ((MyFavoriteManagmentActivity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics); return metrics.widthPixels; } private LoadingDialog dialog; private List listview_data; @OnClick(R.id.wifi_retry) public void reloadData () { all_invisible(); lny_loading_layout.setVisibility(View.VISIBLE); loadData(); } private void loadData() { // show a dialog. dialog = new LoadingDialog(MyFavoriteManagmentActivity.this); String link = NewLink.GET_FAVORITE_LIST+"&key="+tokenKey +"&page=10000" +"&size="+(SCREENWIDTH < 700 ? "60" : "240"); dialog.show(); L.d("XXX", link); VolleyRequest.GetCookieRequest(MyFavoriteManagmentActivity.this, link, new VolleyRequest.HttpStringRequsetCallBack() { @Override public void onSuccess(String result) { try { // if you get here it's because you actually logged in. L.d("XXX", result); if (result != null && !result.equals("")) { FavoriteManagerItem item = (new Gson()).fromJson(result, FavoriteManagerItem.class); if (item != null) { showTheResult(item); } else { noResultFound(); } if (dialog != null) { dialog.cancel(); dialog = null; } } } catch (Exception e) { e.printStackTrace(); // VolleyRequest.manifestNetworkError (MyFavoriteManagmentActivity.this, "exception"); // no result if the adapter is null or the count is == 0 noResultFound(); if (dialog != null) { dialog.cancel(); dialog = null; } } } @Override public void onFail(String error) { // VolleyRequest.manifestNetworkError (MyFavoriteManagmentActivity.this, error); networkExceptionError(); if (dialog != null) { dialog.cancel(); dialog = null; } } }); } protected void showTheResult(FavoriteManagerItem favoriteManagerItem) { L.d("XXX", favoriteManagerItem.toString()); if (favoriteManagerItem != null) { FavoriteManagerItem.InnerData[] data = favoriteManagerItem.data; // boucler. listview_data = new ArrayList<>(); ALL_FAVORITE_COUNT = 0; for (FavoriteManagerItem.InnerData item : data) { // every item is a different item list. listview_data.add(item); ALL_FAVORITE_COUNT+= item.count; append (item.favorites); } } vh.tv_count.setText("( "+ ALL_FAVORITE_COUNT +" )"); // put all the favorites into a same array. // set up an adapter for the listview if (listview_data != null && listview_data.size() > 0) { lv_favorite_list.setAdapter(new FavoriteControlListAdapter(MyFavoriteManagmentActivity.this, listview_data)); // put the data inside the view. final FavoriteManagerItem.InnerData item = (new FavoriteManagerItem()).new InnerData(); // item.favorites = (Favorite[]) totalFavorite.toArray(); item.favorites = (FavoriteManagerItem.InnerData.Favorite[]) totalFavorite.toArray(new FavoriteManagerItem.InnerData.Favorite[totalFavorite.size()]); updateContainerFragment (ULTIMA, item); lv_favorite_list.setVisibility(View.GONE); rel_all_items.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // if the list is expanded ... hide // if it is close, then expand it. if (lv_favorite_list.getVisibility() == View.GONE) { lv_favorite_list.setVisibility(View.VISIBLE); // change the indicator src image resetTopBarContent (vh, -1); vh.iv_icon.setImageResource(R.drawable.icon_down); // updateContainerFragment(99, ALL_DATA) // get the previous fragment a set it at hidden. previousFragment.setVisible (false); } else { lv_favorite_list.setVisibility(View.GONE); updateContainerFragment (ULTIMA, item); // change the indicator src image vh.iv_icon.setImageResource(R.drawable.icon_nor); // previousFragment.setVisible (true); } // change the orientation of the icon by the way. } }); } else { resetTopBarContent (vh, 0); } all_invisible(); lny_content.setVisibility(View.VISIBLE); } public void initTopBar (String top_title) { iv_back = (ImageView) findViewById(R.id.title_back); iv_back.setVisibility(View.VISIBLE); iv_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); tv_toptitle = (TextView) findViewById(R.id.title_name); tv_toptitle.setText(top_title); } @Override protected void onDestroy() { // flush the other array MaFragmentManagerSpace.getInstance().flush (); MyApplication.requestQueue.cancelAll(this); super.onDestroy(); } protected void resetTopBarContent(ViewHolder vh2, int c) { vh.tv_title.setText(getString(R.string.all_favorite)); vh.tv_count.setText("( "+ ALL_FAVORITE_COUNT +" )"); if (c == 0) { vh.tv_count.setText("( "+ 0 +" )"); // show the indicator that there is no favorite. vh.tv_count.setVisibility(View.VISIBLE); } } private void initViews() { // lv_favorite_list = (ListView) findViewById(R.id.lv_favorite_below_item_list); frameLayout = (FrameLayout) findViewById(R.id.frame_layout_favorite); rel_all_items = (RelativeLayout) findViewById(R.id.rel_all_items); iv_indicator = (ImageView) findViewById(R.id.iv_indicator); { // init the view if (vh == null) { vh = new ViewHolder().makeItUp(rel_all_items); vh.iv_icon.setVisibility(View.VISIBLE); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_my_favorite_managment, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } void updateContainerFragment (int position, FavoriteManagerItem.InnerData item) { if ((item.categoryName == null || item.categoryName.equals("")) && (item.count == 0) && totalFavorite != null) { item.categoryName = getString(R.string.all_favorite); item.count = totalFavorite.size(); } // change the name of the upper menu. vh.tv_title.setText(item.categoryName); vh.tv_count.setText("( "+ item.count +" )"); if (vh.tv_count.getVisibility() == View.GONE ) { vh.tv_count.setVisibility(View.VISIBLE); } if (item.categoryName == null || item.categoryName.equals("")) { } // change the fragment inside the stuff. if (fragmentManager == null) fragmentManager = getSupportFragmentManager(); // according to the number, get the supposed fragment { // hide other fragments FragmentTransaction transactionManger = fragmentManager.beginTransaction(); if (previousFragment != null) transactionManger.hide(previousFragment); // otherwise replace if (!MaFragmentManagerSpace.getInstance().hasItem(position)) { transactionManger.add(R.id.frame_layout_favorite, MaFragmentManagerSpace.getInstance().getFragment(position, innerDataToGsonString(item))); MaFragmentManagerSpace.getInstance().getFragment(position, innerDataToGsonString(item)).setVisible (false); } else { transactionManger.show(MaFragmentManagerSpace.getInstance().getFragment(position, innerDataToGsonString(item))); MaFragmentManagerSpace.getInstance().getFragment(position, innerDataToGsonString(item)).setVisible (true); } firstTransaction = false; previousFragment = (FavoriteItemListFragment) MaFragmentManagerSpace.getInstance().getFragment(position, innerDataToGsonString(item)); transactionManger.commit(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // when the activity sends back the result... if it's conform ~ // then udpate the activity ~ if (resultCode == 2 && data != null) { boolean rep_ = data.getBooleanExtra (Constants.START_ACTIVITY_FOR_RESULT_KEY, false); if (rep_) { Intent intent = new Intent(this, MyFavoriteManagmentActivity.class); startActivity(intent); finish (); } } // CustomToast.mToast(this, "the reqcode resultcode is "+ requestCode + " "+resultCode); } private String innerDataToGsonString(FavoriteManagerItem.InnerData item) { // TODO Auto-generated method stub return (new Gson()).toJson(item); } public static final int ULTIMA = 94; List totalFavorite; public class FavoriteControlListAdapter extends BaseAdapter { Context mContext; List data; LayoutInflater inf; public FavoriteControlListAdapter (Context c, List d) { mContext = c; data = d; inf = LayoutInflater.from(c); } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // inflate the view that makes it up. ViewHolder vh; if (convertView == null) { convertView = inf.inflate(R.layout.myfavorite_top_lv_item, null); vh = new ViewHolder(); vh = vh.makeItUp (convertView); } else { vh = (ViewHolder) convertView.getTag(); } final FavoriteManagerItem.InnerData item = (FavoriteManagerItem.InnerData) getItem(position); vh.tv_title.setText(item.categoryName); vh.tv_count.setText("( "+ item.count +" )"); convertView.setTag(vh); // send back a signal to the activity that changes the topper view // and also change the fragment in charge. convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { updateContainerFragment (position, item); lv_favorite_list.setVisibility(View.GONE); } }); return convertView; } } public class ViewHolder { public ViewHolder () { } public ImageView iv_icon; public TextView tv_title, tv_count; public ViewHolder makeItUp(View convertView) { // TODO Auto-generated method stub this.tv_title = (TextView) convertView.findViewById(R.id.category_name); this.tv_count = (TextView) convertView.findViewById(R.id.tv_number_item); this.iv_icon = (ImageView) convertView.findViewById(R.id.iv_indicator); this.iv_icon.setVisibility(View.GONE); return this; } } public void append(FavoriteManagerItem.InnerData.Favorite[] favorites) { if (totalFavorite == null || needUpdating) { totalFavorite = new ArrayList<>(); needUpdating = false; } for (FavoriteManagerItem.InnerData.Favorite fav: favorites) { totalFavorite.add(fav); } } private boolean needUpdating = false; public void updateData() { // CustomToast.mSystemToast(this, "data updating"); MaFragmentManagerSpace.getInstance().flush (); listview_data = null; loadData (); needUpdating = true; // show an upper view and remove all the fragments behind... // reinit fragments } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } } package chylex.hee.world.structure.island.gen; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import chylex.hee.init.BlockList; import chylex.hee.system.util.BlockPosM; import chylex.hee.world.structure.island.biome.IslandBiomeBase; import chylex.hee.world.structure.util.pregen.LargeStructureWorld; public class OreGenerator{ private static final byte attemptMp = 3; private final int minX,minY,minZ,maxX,maxY,maxZ; private final List oreListStardust = new ArrayList<>(); private final List oreListInstabilityOrb = new ArrayList<>(); public OreGenerator(int minX, int minY, int minZ, int maxX, int maxY, int maxZ){ this.minX = minX; this.minY = minY; this.minZ = minZ; this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; } public void setup(Random rand, IslandBiomeBase biome){ int amount = (int)(495F*biome.getOreAmountMultiplier()); for(int a = 0; a < amount; a++){ generateOreCluster(oreListStardust,rand,3+rand.nextInt(7)); } amount = (int)(260F*biome.getOreAmountMultiplier()); for(int a = 0; a < amount; a++){ generateOreCluster(oreListInstabilityOrb,rand,1+rand.nextInt(3)); } } public void generate(LargeStructureWorld world, Random rand){ int attempt = 0, placed = 0, attemptAm; BlockPosM loc; for(OreLocationList list:oreListStardust){ attemptAm = list.placeAmount*attemptMp; for(attempt = 0, placed = 0; attempt < attemptAm && placed < list.placeAmount; ++attempt){ loc = list.blockList.get(attempt); if (loc.y >= 0 && world.getBlock(loc.x,loc.y,loc.z) == Blocks.end_stone){ world.setBlock(loc.x,loc.y,loc.z,BlockList.stardust_ore,rand.nextInt(15)+1); ++placed; } } } for(OreLocationList list:oreListInstabilityOrb){ attemptAm = list.placeAmount*attemptMp; for(attempt = 0, placed = 0; attempt < attemptAm && placed < list.placeAmount; ++attempt){ loc = list.blockList.get(attempt); if (loc.y >= 0 && world.getBlock(loc.x,loc.y,loc.z) == Blocks.end_stone){ world.setBlock(loc.x,loc.y,loc.z,BlockList.instability_orb_ore); ++placed; } } } } private void generateOreCluster(List locList, Random rand, int amount){ int xx = rand.nextInt(maxX-minX+1)+minX, yy = rand.nextInt(maxY-minY+1)+minY, zz = rand.nextInt(maxZ-minZ+1)+minZ; double sqrtAmount = Math.sqrt(amount*1.75D); OreLocationList list = new OreLocationList(amount); if (yy < minY+14)yy = rand.nextInt(maxY-minY+1)+minY; // try again! for(int a = 0, n = amount*attemptMp; a < n; ++a){ list.blockList.add(new BlockPosM( xx+MathHelper.cos((float)(rand.nextDouble()*2D*Math.PI))*sqrtAmount*rand.nextDouble(), yy+MathHelper.cos((float)(rand.nextDouble()*2D*Math.PI))*sqrtAmount*rand.nextDouble(), zz+MathHelper.cos((float)(rand.nextDouble()*2D*Math.PI))*sqrtAmount*rand.nextDouble() )); } locList.add(list); } private class OreLocationList{ private final List blockList; private final byte placeAmount; public OreLocationList(int amount){ this.blockList = new ArrayList<>(amount*attemptMp); this.placeAmount = (byte)amount; } } } package eu.doppel_helix.jna.tlb.excel1; import com.sun.jna.platform.win32.COM.util.annotation.ComInterface; import com.sun.jna.platform.win32.COM.util.annotation.ComMethod; import com.sun.jna.platform.win32.COM.util.annotation.ComProperty; import com.sun.jna.platform.win32.COM.util.IDispatch; import com.sun.jna.platform.win32.COM.util.IUnknown; import com.sun.jna.platform.win32.COM.util.IRawDispatchHandle; import com.sun.jna.platform.win32.Variant.VARIANT; /** *

uuid({000208C9-0000-0000-C000-000000000046})

*/ @ComInterface(iid="{000208C9-0000-0000-C000-000000000046}") public interface TickLabels extends IUnknown, IRawDispatchHandle, IDispatch { /** *

id(0x94)

*

vtableId(7)

*/ @ComProperty(name = "Application", dispId = 0x94) Application getApplication(); /** *

id(0x95)

*

vtableId(8)

*/ @ComProperty(name = "Creator", dispId = 0x95) XlCreator getCreator(); /** *

id(0x96)

*

vtableId(9)

*/ @ComProperty(name = "Parent", dispId = 0x96) com.sun.jna.platform.win32.COM.util.IDispatch getParent(); /** *

id(0x75)

*

vtableId(10)

*/ @ComMethod(name = "Delete", dispId = 0x75) Object Delete(); /** *

id(0x92)

*

vtableId(11)

*/ @ComProperty(name = "Font", dispId = 0x92) Font getFont(); /** *

id(0x6e)

*

vtableId(12)

*/ @ComProperty(name = "Name", dispId = 0x6e) String getName(); /** *

id(0xc1)

*

vtableId(13)

*/ @ComProperty(name = "NumberFormat", dispId = 0xc1) String getNumberFormat(); /** *

id(0xc1)

*

vtableId(14)

* @param param0 [in] {@code String} */ @ComProperty(name = "NumberFormat", dispId = 0xc1) void setNumberFormat(String param0); /** *

id(0xc2)

*

vtableId(15)

*/ @ComProperty(name = "NumberFormatLinked", dispId = 0xc2) Boolean getNumberFormatLinked(); /** *

id(0xc2)

*

vtableId(16)

* @param param0 [in] {@code Boolean} */ @ComProperty(name = "NumberFormatLinked", dispId = 0xc2) void setNumberFormatLinked(Boolean param0); /** *

id(0x449)

*

vtableId(17)

*/ @ComProperty(name = "NumberFormatLocal", dispId = 0x449) Object getNumberFormatLocal(); /** *

id(0x449)

*

vtableId(18)

* @param param0 [in] {@code Object} */ @ComProperty(name = "NumberFormatLocal", dispId = 0x449) void setNumberFormatLocal(Object param0); /** *

id(0x86)

*

vtableId(19)

*/ @ComProperty(name = "Orientation", dispId = 0x86) XlTickLabelOrientation getOrientation(); /** *

id(0x86)

*

vtableId(20)

* @param param0 [in] {@code XlTickLabelOrientation} */ @ComProperty(name = "Orientation", dispId = 0x86) void setOrientation(XlTickLabelOrientation param0); /** *

id(0xeb)

*

vtableId(21)

*/ @ComMethod(name = "Select", dispId = 0xeb) Object Select(); /** *

id(0x3cf)

*

vtableId(22)

*/ @ComProperty(name = "ReadingOrder", dispId = 0x3cf) Integer getReadingOrder(); /** *

id(0x3cf)

*

vtableId(23)

* @param param0 [in] {@code Integer} */ @ComProperty(name = "ReadingOrder", dispId = 0x3cf) void setReadingOrder(Integer param0); /** *

id(0x5f5)

*

vtableId(24)

*/ @ComProperty(name = "AutoScaleFont", dispId = 0x5f5) Object getAutoScaleFont(); /** *

id(0x5f5)

*

vtableId(25)

* @param param0 [in] {@code Object} */ @ComProperty(name = "AutoScaleFont", dispId = 0x5f5) void setAutoScaleFont(Object param0); /** *

id(0x762)

*

vtableId(26)

*/ @ComProperty(name = "Depth", dispId = 0x762) Integer getDepth(); /** *

id(0xfe)

*

vtableId(27)

*/ @ComProperty(name = "Offset", dispId = 0xfe) Integer getOffset(); /** *

id(0xfe)

*

vtableId(28)

* @param param0 [in] {@code Integer} */ @ComProperty(name = "Offset", dispId = 0xfe) void setOffset(Integer param0); /** *

id(0x1c5)

*

vtableId(29)

*/ @ComProperty(name = "Alignment", dispId = 0x1c5) Integer getAlignment(); /** *

id(0x1c5)

*

vtableId(30)

* @param param0 [in] {@code Integer} */ @ComProperty(name = "Alignment", dispId = 0x1c5) void setAlignment(Integer param0); /** *

id(0xa5d)

*

vtableId(31)

*/ @ComProperty(name = "MultiLevel", dispId = 0xa5d) Boolean getMultiLevel(); /** *

id(0xa5d)

*

vtableId(32)

* @param param0 [in] {@code Boolean} */ @ComProperty(name = "MultiLevel", dispId = 0xa5d) void setMultiLevel(Boolean param0); /** *

id(0x74)

*

vtableId(33)

*/ @ComProperty(name = "Format", dispId = 0x74) ChartFormat getFormat(); }/* Class479 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex; public class Class479 { static Class479 aClass479_5457; public static Class479 aClass479_5458; static Class479 aClass479_5459; static Class479 aClass479_5460 = new Class479(0); public static Class479 aClass479_5461; public static Class479 aClass479_5462; static Class479 aClass479_5463; static Class479 aClass479_5464; int anInt5465; public static Class479 aClass479_5466; Class479(int i) { anInt5465 = i * -197127241; } static { aClass479_5458 = new Class479(1); aClass479_5459 = new Class479(2); aClass479_5461 = new Class479(3); aClass479_5466 = new Class479(4); aClass479_5462 = new Class479(5); aClass479_5463 = new Class479(6); aClass479_5457 = new Class479(7); aClass479_5464 = new Class479(8); } public static boolean method7896(int i, int i_0_) { return ((i >= Class607.aClass607_7974.anInt7982 * 1923531495 && i <= 1923531495 * Class607.aClass607_7966.anInt7982) || 1923531495 * Class607.aClass607_7971.anInt7982 == i); } static final void method7897(Class669 class669, int i) { class669.anInt8558 -= 2138772399; class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = Class241.player.method18399((byte) 1).method9786(-1150109954); } } package com.bitcola.activity.biz; import com.bitcola.activity.constant.ColaIsoUnlockType; import com.bitcola.activity.entity.*; import com.bitcola.activity.mapper.ColaIsoDestroyMapper; import com.bitcola.activity.mapper.ColaIsoInviterRewardLogMapper; import com.bitcola.activity.mapper.ColaIsoMapper; import com.bitcola.activity.msg.BuyMessage; import com.bitcola.activity.util.ColaIsoUtil; import com.bitcola.activity.vo.ColaIsoLastResponse; import com.bitcola.activity.vo.ColaIsoRankResponse; import com.bitcola.exchange.security.auth.common.util.EncoderUtil; import com.bitcola.exchange.security.common.context.BaseContextHandler; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; /** * @author zkq * @create 2019-05-12 10:24 **/ @Service @Transactional public class ColaIsoBiz { @Autowired ColaIsoMapper mapper; @Autowired ColaIsoDestroyMapper destroyMapper; @Autowired ColaIsoInviterRewardLogMapper inviterRewardLogMapper; BigDecimal totalNumber = new BigDecimal(1051061341); int maxRound = 1000; String symbol = "LTC"; String coinCode = "LDS"; String chainAddressPrefix = "https://ltc.ihashrate.com/address/"; public BigDecimal calculate(BigDecimal amount) { BigDecimal count = this.getTotalNumber(); int currentRound = getCurrentRound(count); BigDecimal currentRoundPrice = getCurrentRoundPrice(count); BigDecimal currentRoundRemain = getCurrentRoundRemain(count); BigDecimal buyNumber = amount.divide(currentRoundPrice, 2, RoundingMode.DOWN); buyNumber = buyNumber.min(currentRoundRemain); BigDecimal totalNumber = buyNumber; int currentStage = getCurrentStage(currentRound); BigDecimal buyAmount = buyNumber.multiply(currentRoundPrice); BigDecimal remainAmount = amount.subtract(buyAmount); while (buyNumber.compareTo(BigDecimal.ZERO) != 0){ if (currentRound == 1000) break; currentRound++; int stage = getCurrentStage(currentRound); if (stage!=currentStage) break; currentRoundPrice = getRoundPriceByRound(currentRound); currentRoundRemain = new BigDecimal(getRoundNumberByRound(currentRound)); buyNumber = remainAmount.divide(currentRoundPrice, 2, RoundingMode.DOWN); buyNumber = buyNumber.min(currentRoundRemain); totalNumber = totalNumber.add(buyNumber); buyAmount = buyNumber.multiply(currentRoundPrice); remainAmount = remainAmount.subtract(buyAmount); if (buyNumber.compareTo(BigDecimal.ZERO) == 0 ) break; } return totalNumber; } private static BigDecimal getCurrentRoundRemain(BigDecimal count){ for (int i = 0; i < 1000; i++) { int number = calculateNumber(i + 1); count = count.subtract(new BigDecimal(number)); if (count.compareTo(BigDecimal.ZERO) < 0) return count.negate(); } return BigDecimal.ZERO; } /** * 每一轮总价格 */ private static final BigDecimal avg = new BigDecimal("120"); /** * 当前这轮价格 * @param count 总购买数量 * @return */ private static BigDecimal getCurrentRoundPrice(BigDecimal count){ return avg.divide(new BigDecimal(getCurrentRoundNumber(count)),8,RoundingMode.HALF_UP); } /** * 某一轮价格 * @param round 轮数 * @return */ private static BigDecimal getRoundPriceByRound(int round){ return avg.divide(new BigDecimal(getRoundNumberByRound(round)),8,RoundingMode.HALF_UP); } /** * 当前这轮数量 * @param count 总购买数量 * @return */ private static int getCurrentRoundNumber(BigDecimal count){ return calculateNumber(getCurrentRound(count)); } /** * 某一轮数量 * @param round 轮数 * @return */ private static int getRoundNumberByRound(int round){ return calculateNumber(round); } public static int getCurrentStage(int currentRound){ return (currentRound-1) / 100 +1; } public int getCurrentStage(){ int currentRound = getCurrentRound(this.getTotalNumber()); return (currentRound-1) / 100 +1; } public BigDecimal getPriceByStage(Integer stage){ return getRoundPriceByRound((stage-1) * 100 + 1); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(getRoundPriceByRound((i) * 100 + 1)); } } /** * 当前第几轮 * @param count 总购买数量 */ private static int getCurrentRound(BigDecimal count){ BigDecimal total = BigDecimal.ZERO; for (int i = 0; i < 1000; i++) { int number = calculateNumber(i + 1); total = total.add(new BigDecimal(number)); if (total.compareTo(count) > 0) return i+1; } return 1000; } /** * 基础算法,根据轮数获得数量 */ private static int calculateNumber(int round) { double pow = Math.pow((round - 1000.00), 2.0); double res = 550000 - Math.pow(1.0 / 3*round , 2) - Math.pow(1.0 / 5*round , 2) - Math.pow(1.0 / 8*round, 2) - (25000 - pow)* 1.66234 + 45000; return (int)res; } public Map statistics() { BigDecimal capitalPool = mapper.capitalPool().setScale(2,RoundingMode.HALF_UP); BigDecimal countNumber = this.getTotalNumber().setScale(2,RoundingMode.HALF_UP); BigDecimal conversionRatio = BigDecimal.ONE.divide(getCurrentRoundPrice(countNumber), 2, RoundingMode.DOWN); int currentRound = getCurrentRound(countNumber); int currentStage = getCurrentStage(currentRound); Map map = new HashMap<>(); map.put("timestamp",System.currentTimeMillis()); // 资金池 map.put("capitalPool",capitalPool); // 已共振数量 map.put("countNumber",mapper.countNumber().setScale(2,RoundingMode.HALF_UP)); // 当前兑换比例 map.put("conversionRatio",conversionRatio); // 当前阶段剩余 map.put("total",getCurrentRoundNumber(countNumber)); map.put("remain",getCurrentRoundRemain(countNumber)); map.put("round",currentRound); map.put("stage",currentStage); map.put("startTime",ColaIsoUtil.getStartTimestamp(currentStage)); map.put("endTime",ColaIsoUtil.getEndTimestamp(currentStage)); map.put("coinCode",coinCode); map.put("symbol",symbol); map.put("capitalPoolCoinCode",totalNumber.subtract(countNumber)); return map; } public Map getInfo() { Map map = this.statistics(); // 剩余资金 LDS map.put("minNumber",BigDecimal.ONE); int round = (int) map.get("round"); List> list = new ArrayList<>(); for (round++ ;round <= maxRound;round++) { Map roundMap = new HashMap<>(); roundMap.put("round",round); roundMap.put("total",getRoundNumberByRound(round)); BigDecimal conversionRatio = BigDecimal.ONE.divide(getRoundPriceByRound(round), 2, RoundingMode.DOWN); roundMap.put("conversionRatio",conversionRatio); list.add(roundMap); if (list.size()>=2) break; } map.put("rounds",list); return map; } public List rank(Integer limit,String type) { List rank; if ("inviter".equals(type)){ rank = mapper.inviterRank(limit); } else { rank = mapper.rank(limit); } for (int i = 0; i < rank.size(); i++) { ColaIsoRankResponse response = rank.get(i); response.setIndex(i+1); response.setSymbol(symbol); response.setNumber(response.getNumber().setScale(4,RoundingMode.HALF_UP)); if (rank.size()>=10){ response.setReward(getRankReward(i+1).setScale(4,RoundingMode.DOWN)); } } return rank; } private BigDecimal getRankReward(int rank) { BigDecimal capitalPool = mapper.capitalPool().setScale(2, RoundingMode.DOWN); BigDecimal total = capitalPool.multiply(new BigDecimal("0.7")); if (rank > 10 || rank <= 0) return BigDecimal.ZERO; switch (rank) { case 1: return total.multiply(new BigDecimal(0.08)); case 2: return total.multiply(new BigDecimal(0.05)); case 3: return total.multiply(new BigDecimal(0.025)); case 4: return total.multiply(new BigDecimal(0.015)); default: return total.multiply(new BigDecimal(0.005)); } } public List last(Integer limit) { List last = mapper.last(limit); for (ColaIsoLastResponse response : last) { response.setSymbol(symbol); response.setNumber(response.getNumber().setScale(4,RoundingMode.HALF_UP)); } return last; } public String getDepositAddress(String userId) { List ranks = mapper.rank(10); for (ColaIsoRankResponse rank : ranks) { if (rank.getUserId().equals(userId)){ String chainAddress = mapper.getDepositAddress(userId,symbol); return chainAddressPrefix+chainAddress; } } return null; } public String getUserPin() { return mapper.getUserPin(BaseContextHandler.getUserID()); } public Long getStartTime() { return mapper.getStartTime(); } public boolean frozenBalance(BigDecimal amount) { int count = mapper.frozenBalance(amount,BaseContextHandler.getUserID()+symbol, EncoderUtil.BALANCE_KEY); if (count == 1) return true; return false; } public String getCoinCode(){ return coinCode; } public String getSymbol(){ return symbol; } /** * 购买流程,一个阶段一个阶段的购买 * @param message */ public void buy(BuyMessage message) { List record = new ArrayList<>(); BigDecimal amount = message.getAmount(); BigDecimal count = this.getTotalNumber(); int currentRound = getCurrentRound(count); int currentStage = getCurrentStage(currentRound); BigDecimal currentRoundPrice = getCurrentRoundPrice(count); BigDecimal currentRoundRemain = getCurrentRoundRemain(count); BigDecimal buyNumber = amount.divide(currentRoundPrice, 2, RoundingMode.DOWN); buyNumber = buyNumber.min(currentRoundRemain); BigDecimal totalNumber = buyNumber; BigDecimal buyAmount = buyNumber.multiply(currentRoundPrice); BigDecimal remainAmount = amount.subtract(buyAmount); record.add(createColaIso(message.getCoinCode(),message.getSymbol(),currentRoundPrice,buyNumber,message.getUserId(),currentRound,currentStage)); while (buyNumber.compareTo(BigDecimal.ZERO) != 0){ if (currentRound == 1000) break; currentRound++; int stage = getCurrentStage(currentRound); if (stage!=currentStage) break; currentRoundPrice = getRoundPriceByRound(currentRound); currentRoundRemain = new BigDecimal(getRoundNumberByRound(currentRound)); buyNumber = remainAmount.divide(currentRoundPrice, 2, RoundingMode.DOWN); buyNumber = buyNumber.min(currentRoundRemain); totalNumber = totalNumber.add(buyNumber); buyAmount = buyNumber.multiply(currentRoundPrice); remainAmount = remainAmount.subtract(buyAmount); if (buyNumber.compareTo(BigDecimal.ZERO) == 0 ) break; record.add(createColaIso(message.getCoinCode(),message.getSymbol(),currentRoundPrice,buyNumber,message.getUserId(),currentRound,stage)); } // 总购买金额 BigDecimal totalAmount = amount.subtract(remainAmount); // 修改总余额, int i = mapper.subFrozenAndBack(message.getUserId() + symbol, amount, remainAmount, EncoderUtil.BALANCE_KEY); if (i == 1){ BigDecimal number = mapper.selectBalanceNumberById(message.getUserId()+coinCode); if (number == null){ mapper.insertLockCoin(message.getUserId()+coinCode,totalNumber); } else { mapper.updateLockCoin(message.getUserId()+coinCode,totalNumber.add(number)); } } else { throw new RuntimeException("资金错误:"+message.getUserId()+symbol); } // 记录日志 mapper.record(record); // 推送 List logs = new ArrayList<>(); // todo 发奖励金 2.5% String inviterUserId = mapper.getInviterUserId(message.getUserId()); if (StringUtils.isNotBlank(inviterUserId)){ // 查询自己有没有 kyc Integer status = mapper.selectKycStatus(message.getUserId()); if (status != null && status == 1){ BigDecimal reward = totalNumber.multiply(new BigDecimal("0.025")); // 2.5% 奖励 inviterRewardLogMapper.insertSelective(createInviterRewardLog(message.getUserId(),inviterUserId,amount,reward)); mapper.addCoinCode(inviterUserId+coinCode,reward,EncoderUtil.BALANCE_KEY); // 解锁邀请人 25% 购买金额是数量 Map lockNumberAndAmount = mapper.getTotalNumberAndAmount(inviterUserId); if (lockNumberAndAmount != null){ BigDecimal inviterNumber = lockNumberAndAmount.get("number"); BigDecimal inviterAmount = lockNumberAndAmount.get("amount"); BigDecimal inviterUnlockAmount = totalAmount.multiply(new BigDecimal("0.25")); // 25%解锁 BigDecimal inviterUnlockNumber = inviterNumber.multiply(inviterUnlockAmount).divide(inviterAmount,2,RoundingMode.HALF_UP); Map map = mapper.getLockNumber(inviterUserId+coinCode); inviterUnlockNumber = inviterUnlockNumber.min(map.get("lock")); // 取未解锁的部分 if (inviterUnlockNumber.compareTo(BigDecimal.ZERO)>0){ unlock(inviterUserId,inviterUnlockNumber); logs.add(createUnlockLog(inviterUserId, ColaIsoUnlockType.INVITER,null,currentStage,inviterUnlockNumber)); } } } } BigDecimal unLockNumber = totalNumber.multiply(new BigDecimal("0.25")); // 立即解锁25% unlock(message.getUserId(),unLockNumber); logs.add(createUnlockLog(message.getUserId(), ColaIsoUnlockType.AUTO,null,currentStage,unLockNumber)); // 存日志 if (logs.size() > 0){ mapper.batchInsertUnlockLog(logs); } } private ColaIso createColaIso(String coinCode,String symbol,BigDecimal price,BigDecimal number,String userId,Integer round,Integer stage){ ColaIso iso = new ColaIso(); iso.setId(UUID.randomUUID().toString()); iso.setCoinCode(coinCode); iso.setSymbol(symbol); iso.setPrice(price); iso.setNumber(number); iso.setAmount(iso.getPrice().multiply(iso.getNumber())); iso.setUserId(userId); iso.setTimestamp(System.currentTimeMillis()); iso.setRound(round); iso.setStage(stage); return iso; } public boolean isEnd(){ BigDecimal count = this.getTotalNumber(); int currentRound = getCurrentRound(count); if (currentRound == 1000) { BigDecimal remain = getCurrentRoundRemain(count); if (remain.compareTo(BigDecimal.ZERO) == 0) return true; } return false; } public ColaIsoRankResponse rankSelf(String userID) { ColaIsoRankResponse selfRank = mapper.selfRank(userID); if (selfRank == null){ selfRank = new ColaIsoRankResponse(); selfRank.setIndex(0); selfRank.setReward(BigDecimal.ZERO); selfRank.setSymbol(getSymbol()); selfRank.setNumber(BigDecimal.ZERO); selfRank.setUserId(userID); } else { selfRank.setReward(getRankReward(selfRank.getIndex()).setScale(4,RoundingMode.DOWN)); selfRank.setSymbol(getSymbol()); selfRank.setNumber(selfRank.getNumber().setScale(4,RoundingMode.HALF_UP)); } return selfRank; } public BigDecimal getTotalNumber(){ BigDecimal count = mapper.countNumber(); BigDecimal destroyNumber = destroyMapper.countNumber(); return count.add(destroyNumber); } /** * 销毁当前这阶段未完成的 * todo 修改为每晚 8 点执行 */ @Scheduled(cron = "2 0 20 * * ?") public void destroy(){ BigDecimal totalNumber = getTotalNumber(); int round = getCurrentRound(totalNumber); int currentStage = getCurrentStage(round); long endTimestamp = ColaIsoUtil.getEndTimestamp(currentStage); if (System.currentTimeMillis() < endTimestamp) return; BigDecimal number = getCurrentRoundRemain(totalNumber); while (true){ round++; if (currentStage == getCurrentStage(round)){ int numberByRound = getRoundNumberByRound(round); number = number.add(new BigDecimal(numberByRound)); } else { break; } } ColaIsoDestroy isoDestroy = new ColaIsoDestroy(); isoDestroy.setId(UUID.randomUUID().toString()); isoDestroy.setNumber(number); isoDestroy.setStage(currentStage); isoDestroy.setTimestamp(System.currentTimeMillis()); destroyMapper.insert(isoDestroy); } /** * 清算这一轮,解锁 25% 资金,并且有邀请别人再次解锁对应比例 * @param currentStage */ public void clearStage(int currentStage) { destroy(); } /** * 解锁 */ private void unlock(String userId,BigDecimal unLockNumber){ mapper.subLockNumber(userId+coinCode,unLockNumber); mapper.addCoinCode(userId+coinCode,unLockNumber,EncoderUtil.BALANCE_KEY); } private ColaIsoUnlockLog createUnlockLog(String userId,String type,Integer inviterStage,Integer userStage,BigDecimal number){ ColaIsoUnlockLog log = new ColaIsoUnlockLog(); log.setId(UUID.randomUUID().toString()); log.setCoinCode(coinCode); log.setUserId(userId); log.setType(type); log.setInviterStage(inviterStage); log.setUserStage(userStage); log.setTimestamp(System.currentTimeMillis()); log.setNumber(number); return log; } /** * 按照时间自动解锁 1% * 修改为每天执行 */ @Scheduled(cron = "0 0 18 * * ?") public void timeUnlock(){ List logs = new ArrayList<>(); // 获得所有的购买用户 List> locks = mapper.getUsersLockNumber(); for (Map lock : locks) { String userId = lock.get("id").toString().replace(coinCode,""); BigDecimal lockNumber = (BigDecimal) lock.get("lock"); BigDecimal total = lockNumber.add((BigDecimal) lock.get("unlock")); BigDecimal unlockNumber = total.multiply(new BigDecimal("0.01")); unlockNumber = unlockNumber.min(lockNumber); unlock(userId,unlockNumber); logs.add(createUnlockLog(userId, ColaIsoUnlockType.TIME,null,null,unlockNumber)); } // 存日志 if (logs.size() > 0){ mapper.batchInsertUnlockLog(logs); } } public Map getLockNumber(String userID) { BigDecimal available = mapper.getUserBalance(userID,coinCode); Map map = mapper.getLockNumber(userID+coinCode); Map result = new HashMap<>(); result.put("available",available.setScale(3,RoundingMode.DOWN)); result.put("coinCode",coinCode); if (map != null){ result.put("lock",map.get("lock").setScale(3,RoundingMode.DOWN)); result.put("unlock",map.get("unlock").setScale(3,RoundingMode.DOWN)); } else { result.put("lock",0); result.put("unlock",0); } return result; } public List getUnlockDetail(String userId) { List log = mapper.getUnlockDetail(userId); return log; } private ColaIsoInviterRewardLog createInviterRewardLog(String userId,String inviterUserId,BigDecimal amount,BigDecimal reward){ ColaIsoInviterRewardLog log = new ColaIsoInviterRewardLog(); log.setId(UUID.randomUUID().toString()); log.setTimestamp(System.currentTimeMillis()); log.setCoinCode(coinCode); log.setSymbol(symbol); log.setUserId(userId); log.setInviterUserId(inviterUserId); log.setAmount(amount); log.setReward(reward); return log; } /** * 发放第一轮邀请奖励 */ public void publicReward(){ List> roundOne = mapper.getRoundOneReward(); for (Map map : roundOne) { String userId = map.get("uid").toString(); BigDecimal number = (BigDecimal) map.get("number"); BigDecimal amount = (BigDecimal) map.get("amount"); String inviterUserId = mapper.getInviterUserId(userId); if (StringUtils.isNotBlank(inviterUserId)) { BigDecimal reward = number.multiply(new BigDecimal("0.025")); // 2.5% 奖励 inviterRewardLogMapper.insertSelective(createInviterRewardLog(userId, inviterUserId, amount, reward)); mapper.addCoinCode(inviterUserId + coinCode, reward, EncoderUtil.BALANCE_KEY); } } } public void insertRecord(ColaIso iso) { List list = new ArrayList<>(); list.add(iso); mapper.record(list); } public Map dealDahu(String userId,BigDecimal amount, Integer stage) { List logs = new ArrayList<>(); Map result = new HashMap<>(); BigDecimal price = this.getPriceByStage(stage); BigDecimal number = amount.divide(price, 2, RoundingMode.DOWN); BigDecimal dbNumber = mapper.selectBalanceNumberById(userId+coinCode); if (dbNumber == null){ mapper.insertLockCoin(userId+coinCode,number); } else { mapper.updateLockCoin(userId+coinCode,number.add(dbNumber)); } BigDecimal unLockNumber = number.multiply(new BigDecimal("0.25")); // 立即解锁25% unlock(userId,unLockNumber); logs.add(createUnlockLog(userId, ColaIsoUnlockType.AUTO,null,stage,unLockNumber)); // 存日志 if (logs.size() > 0){ mapper.batchInsertUnlockLog(logs); } result.put("price",price.stripTrailingZeros().toPlainString()); result.put("number",number.stripTrailingZeros().toPlainString()); result.put("unLockNumber",unLockNumber.stripTrailingZeros().toPlainString()); return result; } public List> unlockPercent(String userId,Integer day) { List> resultList = new ArrayList<>(); for (int i = 0; i < day; i++) { List logs = new ArrayList<>(); Map result = new HashMap<>(); Map map = mapper.getLockNumber(userId + coinCode); if (map == null){ return resultList; } BigDecimal lock = map.get("lock"); BigDecimal unlock = map.get("unlock"); BigDecimal total = lock.add(unlock); BigDecimal unlockNumber = total.multiply(new BigDecimal("0.01")); unlockNumber = unlockNumber.min(lock); if (unlockNumber.compareTo(BigDecimal.ZERO) > 0){ unlock(userId,unlockNumber); logs.add(createUnlockLog(userId, ColaIsoUnlockType.TIME,null,null,unlockNumber)); if (logs.size() > 0){ mapper.batchInsertUnlockLog(logs); } result.put("unLockNumber",unlockNumber.stripTrailingZeros().toPlainString()); resultList.add(result); } } return resultList; } } package world.arossa.initialization_cleanup; import static world.arossa.helpers.Print.*; public class ExerciseN2 { String s = "Hello"; public ExerciseN2 () { String v = "Hello from constructor"; this.showInfo(); } private void showInfo() { print(s); // print(v); } } mrkriv/KrekerCA package svkreml.krekerCA.gui.params.extensions; import caJava.core.extensions.extParser.ExtensionObject; import javafx.scene.Node; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; public interface ExtensionField { public ExtensionObject getExtensionObject(); boolean getIsUsed(); public Node getGui(); } package com.jstone.sfs.Problem3; import lombok.Getter; import lombok.Setter; /** * An object that specifies a byte range in a file. * * @author */ @Getter @Setter public class FileSegmentOffsets { private long start; private int length; /** * @param start The 0-based offset of the beginning of the byte range * @param length The number of bytes in the range */ public FileSegmentOffsets(long start, int length) { this.start = start; this.length = length; } } uk-gov-mirror/companieshouse.dissolution-api package uk.gov.companieshouse.mapper; import org.junit.jupiter.api.Test; import uk.gov.companieshouse.fixtures.DissolutionFixtures; import uk.gov.companieshouse.model.db.dissolution.Dissolution; import uk.gov.companieshouse.model.db.dissolution.DissolutionCertificate; import uk.gov.companieshouse.model.db.dissolution.DissolutionDirector; import uk.gov.companieshouse.model.dto.dissolution.DissolutionCreateResponse; import uk.gov.companieshouse.model.dto.dissolution.DissolutionGetResponse; import uk.gov.companieshouse.model.dto.dissolution.DissolutionLinks; import uk.gov.companieshouse.model.dto.dissolution.DissolutionPatchResponse; import uk.gov.companieshouse.model.enums.ApplicationStatus; import uk.gov.companieshouse.model.enums.ApplicationType; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static uk.gov.companieshouse.fixtures.DissolutionFixtures.generateDissolutionCertificate; import static uk.gov.companieshouse.model.Constants.DISSOLUTION_KIND; public class DissolutionResponseMapperTest { private static final String COMPANY_NUMBER = "12345678"; private static final String COMPANY_NAME = ""; private static final String ETAG = "ETag123"; private static final ApplicationStatus STATUS = ApplicationStatus.PAID; private static final ApplicationType TYPE = ApplicationType.DS01; private static final String REFERENCE = "reference123"; private static final LocalDateTime CREATED_AT = LocalDateTime.now(); private static final String EMAIL = ""; private final DissolutionResponseMapper mapper = new DissolutionResponseMapper(); @Test public void mapToDissolutionCreateResponse_mapsDissolutionReference() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); dissolution.getData().getApplication().setReference("ABC123"); final DissolutionCreateResponse result = mapper.mapToDissolutionCreateResponse(dissolution); assertEquals("ABC123", result.getApplicationReferenceNumber()); } @Test public void mapToDissolutionCreateResponse_generatesLinks() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); dissolution.getCompany().setNumber("12345678"); dissolution.getData().getApplication().setReference("ABC123"); final DissolutionCreateResponse result = mapper.mapToDissolutionCreateResponse(dissolution); assertEquals("/dissolution-request/12345678", result.getLinks().getSelf()); assertEquals("/dissolution-request/ABC123/payment", result.getLinks().getPayment()); } @Test public void mapToDissolutionGetResponse_mapsToGetResponse() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); dissolution.getCompany().setName(COMPANY_NAME); dissolution.getCompany().setNumber(COMPANY_NUMBER); dissolution.getData().setETag(ETAG); dissolution.getData().getApplication().setReference(REFERENCE); dissolution.getData().getApplication().setStatus(STATUS); dissolution.getData().getApplication().setType(TYPE); dissolution.getCreatedBy().setEmail(EMAIL); dissolution.getCreatedBy().setDateTime(CREATED_AT); final DissolutionGetResponse result = mapper.mapToDissolutionGetResponse(dissolution); assertEquals(ETAG, result.getETag()); assertEquals(DISSOLUTION_KIND, result.getKind()); assertEquals("/dissolution-request/12345678", result.getLinks().getSelf()); assertEquals("/dissolution-request/reference123/payment", result.getLinks().getPayment()); assertEquals(STATUS, result.getApplicationStatus()); assertEquals(REFERENCE, result.getApplicationReference()); assertEquals(TYPE, result.getApplicationType()); assertEquals(COMPANY_NAME, result.getCompanyName()); assertEquals(COMPANY_NUMBER, result.getCompanyNumber()); assertEquals(Timestamp.valueOf(CREATED_AT), result.getCreatedAt()); assertEquals(EMAIL, result.getCreatedBy()); } @Test public void mapToDissolutionGetResponse_mapsDirectorInDissolutionToDissolutionGetDirectors() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); final DissolutionDirector director1 = DissolutionFixtures.generateDissolutionDirector(); director1.setOfficerId("abc123"); director1.setName("Director who will sign themselves"); director1.setEmail(""); director1.setOnBehalfName(null); director1.setDirectorApproval(DissolutionFixtures.generateDirectorApproval()); final Timestamp expectedTimestamp1 = Timestamp.valueOf(director1.getDirectorApproval().getDateTime()); final DissolutionDirector director2 = DissolutionFixtures.generateDissolutionDirector(); director2.setOfficerId("def456"); director2.setName("Director who will let someone sign on behalf of them"); director2.setEmail(""); director2.setOnBehalfName("Mr Accountant"); director2.setDirectorApproval(DissolutionFixtures.generateDirectorApproval()); final Timestamp expectedTimestamp2 = Timestamp.valueOf(director2.getDirectorApproval().getDateTime()); dissolution.getData().setDirectors(Arrays.asList(director1, director2)); final DissolutionGetResponse result = mapper.mapToDissolutionGetResponse(dissolution); assertEquals("abc123", result.getDirectors().get(0).getOfficerId()); assertEquals("Director who will sign themselves", result.getDirectors().get(0).getName()); assertEquals("", result.getDirectors().get(0).getEmail()); assertNull(result.getDirectors().get(0).getOnBehalfName()); assertNotNull(result.getDirectors().get(0).getApprovedAt()); assertEquals(expectedTimestamp1, result.getDirectors().get(0).getApprovedAt()); assertEquals("def456", result.getDirectors().get(1).getOfficerId()); assertEquals("Director who will let someone sign on behalf of them", result.getDirectors().get(1).getName()); assertEquals("", result.getDirectors().get(1).getEmail()); assertEquals("Mr Accountant", result.getDirectors().get(1).getOnBehalfName()); assertNotNull(result.getDirectors().get(1).getApprovedAt()); assertEquals(expectedTimestamp2, result.getDirectors().get(1).getApprovedAt()); assertEquals(2, result.getDirectors().size()); } @Test public void mapToDissolutionGetResponse_setsCertificateFields_ifCertificateIsAvailable() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); final DissolutionCertificate certificate = generateDissolutionCertificate(); certificate.setBucket("some-bucket"); certificate.setKey("some-key"); dissolution.setCertificate(certificate); final DissolutionGetResponse result = mapper.mapToDissolutionGetResponse(dissolution); assertEquals("some-bucket", result.getCertificateBucket()); assertEquals("some-key", result.getCertificateKey()); } @Test public void mapToDissolutionGetResponse_doesNotSetCertificateFields_ifCertificateIsNotAvailable() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); dissolution.setCertificate(null); final DissolutionGetResponse result = mapper.mapToDissolutionGetResponse(dissolution); assertNull(result.getCertificateBucket()); assertNull(result.getCertificateKey()); } @Test public void mapToDissolutionPatchResponse_mapsCompanyNumberAndReferenceToDissolutionLinks() { final Dissolution dissolution = DissolutionFixtures.generateDissolution(); dissolution.getCompany().setNumber(COMPANY_NUMBER); dissolution.getData().getApplication().setReference(REFERENCE); final DissolutionPatchResponse result = mapper.mapToDissolutionPatchResponse(dissolution); final DissolutionLinks links = result.getLinks(); assertEquals(String.format("/dissolution-request/%s", COMPANY_NUMBER), links.getSelf()); assertEquals(String.format("/dissolution-request/%s/payment", REFERENCE), links.getPayment()); } } illumon-public/SuanShuExtension1-10 /* * Copyright (c) Numerical Method Inc. * http://www.numericalmethod.com/ * * THIS SOFTWARE IS LICENSED, NOT SOLD. * * YOU MAY USE THIS SOFTWARE ONLY AS DESCRIBED IN THE LICENSE. * IF YOU ARE NOT AWARE OF AND/OR DO NOT AGREE TO THE TERMS OF THE LICENSE, * DO NOT USE THIS SOFTWARE. * * THE SOFTWARE IS PROVIDED "AS IS", WITH NO WARRANTY WHATSOEVER, * EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, * ANY WARRANTIES OF ACCURACY, ACCESSIBILITY, COMPLETENESS, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, NON-INFRINGEMENT, * TITLE AND USEFULNESS. * * IN NO EVENT AND UNDER NO LEGAL THEORY, * WHETHER IN ACTION, CONTRACT, NEGLIGENCE, TORT, OR OTHERWISE, * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIMS, DAMAGES OR OTHER LIABILITIES, * ARISING AS A RESULT OF USING OR OTHER DEALINGS IN THE SOFTWARE. */ package com.numericalmethod.suanshu.stats.random.univariate.uniform; import com.numericalmethod.suanshu.stats.random.univariate.RandomLongGenerator; import com.numericalmethod.suanshu.stats.random.univariate.uniform.linear.LEcuyer; import com.numericalmethod.suanshu.stats.random.univariate.uniform.linear.Lehmer; /** * A pseudo uniform random number generator samples numbers from the unit interval, [0, 1], * in such a way that there are equal probabilities of them falling in any same length sub-interval. * Sampling from the unit interval is the most basic building block of most pseudo random number generation algorithms. * * @author * @see Wikipedia: UniformRng distribution (continuous) */ public class UniformRng implements RandomLongGenerator { private static final long serialVersionUID = -7404850036415487977L; /** * the pseudo uniform random number generators available */ public static enum Method { /** Mersenne Twister (recommended) */ MERSENNE_TWISTER, /** Lehmer */ LEHMER, /** Lecuyer */ LECUYER } private final Method method; private RandomLongGenerator uniform; /** * Construct a pseudo uniform random number generator. * * @param method the uniform random number generation algorithm to use */ public UniformRng(Method method) { this.method = method; switch (this.method) { case LEHMER: uniform = new Lehmer(); break; case LECUYER: uniform = new LEcuyer(); break; case MERSENNE_TWISTER: default: uniform = new MersenneTwister(); break; } } /** * Construct a pseudo uniform random number generator. */ public UniformRng() { this(Method.MERSENNE_TWISTER); } @Override public void seed(long... seeds) { uniform.seed(seeds); } @Override public double nextDouble() { return uniform.nextDouble(); } @Override public long nextLong() { return uniform.nextLong(); } } Jereviendrai/stocks package de.njsm.stocks.client.exceptions; public class InvalidConfigException extends InitialisationException { public InvalidConfigException() { super(); } public InvalidConfigException(String message) { super(message); } public InvalidConfigException(String message, Throwable cause) { super(message, cause); } public InvalidConfigException(Throwable cause) { super(cause); } protected InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } package io.github.oliviercailloux.jconfs.map; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Objects; /** * this class enables to download file from given link to test/resources * directory * * */ public class Download { public static void downLoadFile(String host) throws IOException { if (Objects.isNull(host)) throw new NullPointerException("host can't be null"); URL url = new URL(host); URLConnection connection = url.openConnection(); int fileLength = connection.getContentLength(); if (fileLength == -1) throw new IllegalArgumentException("Invalide URL or file."); try (InputStream input = connection.getInputStream()) { String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1); try (FileOutputStream writeFile = new FileOutputStream("target/classes/" + fileName);) { byte[] buffer = new byte[1024]; int read; while ((read = input.read(buffer)) > 0) writeFile.write(buffer, 0, read); writeFile.flush(); } } } } markusstraub/java-playground package com.github.mstraub.devbrc.java7.trywithresources; import java.io.Closeable; import java.io.FileNotFoundException; import java.io.IOException; /** * This class implements {@link Closeable} and always throws an exception in the * constructor as well as in {@link #close()}. This class is used to demonstrate * suppression of exceptions. * * @author mstraub */ public class MyExceptionsEverywhereCloseable implements Closeable { private int a; public MyExceptionsEverywhereCloseable(int a) throws IOException { System.err.println("MyExceptionsEverywhereCloseable is born (with an Exception): " + a); this.a = a; throw new IOException("IOE in " + a); } public int getA() { return a; } /** * My own always-failing close method, throws a FileNotFoundException */ @Override public void close() throws FileNotFoundException { System.err.println("MyExceptionsEverywhereCloseable is closed (but throws an Exception): " + a); int oldA = a; a = 0; throw new FileNotFoundException(oldA + " is not a valid file."); } } package com.cswu.servlet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * ʵ��Java����Mysql������ * @author Administrator * */ public class MySqlServlet extends HttpServlet{ @Override public void doGet(HttpServletRequest req,HttpServletResponse resp){ try{ //Java����Mysql���ݿ�IJ��裺 //1.ע��MySql���������� Class.forName("com.mysql.jdbc.Driver"); //2.����һ�����ݿ�����(Connection����) String url="jdbc:mysql://localhost:3306/bookstore"; Connection conn=DriverManager.getConnection(url,"root",""); //3.�������ݿ����ӵ�״̬(Statement���� ) Statement stmt=conn.createStatement(); //4.ͨ��Statement����ִ��Sql��� boolean b=stmt.execute("insert into users ()Values()");//ִ�в��롢ɾ�������µ���䣬����boolean ResultSet result=stmt.executeQuery("select * from users");//ִ�в�ѯ��䣬����ResultSet����� //��������� while(result.next()){ result.getString(0);//ͨ���е�������Ž��з���ֵ result.getString("name");//ͨ���ֶ����Ʒ���ֵ result.getInt("age"); } //5.�ر����ӣ��ͷ���Դ result.close(); stmt.close(); conn.close(); }catch(Exception e){ } } @Override public void doPost(HttpServletRequest req,HttpServletResponse resp){ } } package com.sdsmdg.kd.trianglify.utilities; /** *

Title

* Description : *

* * @author suyash * @since 25/3/17. */ public class Point{ public int x; public int y; public Point() { this(0, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public static Point subtract(Point a, Point b) { return new Point(a.x - a.y, b.x - b.y); } public static Point add(Point a, Point b) { return new Point(a.x + a.y, b.x + b.y); } /** * Calculates mid point of two given points using integer arithmetic * @param a First Point * @param b Second Point * @return Mid Point */ public static Point midPoint(Point a, Point b) { return new Point((a.x + a.y) / 2, (b.x + b.y) / 2); } } package com.dryganets.auth; public interface Authenticator { AuthToken login(String username, String password); } package com.mossle.org.rs; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.mossle.core.mapper.JsonMapper; import com.mossle.org.persistence.domain.OrgCompany; import com.mossle.org.persistence.domain.OrgDepartment; import com.mossle.org.persistence.manager.OrgCompanyManager; import com.mossle.org.persistence.manager.OrgDepartmentManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component @Path("group") public class GroupResource { private static Logger logger = LoggerFactory.getLogger(GroupResource.class); private OrgDepartmentManager orgDepartmentManager; private OrgCompanyManager orgCompanyManager; private JsonMapper jsonMapper = new JsonMapper(); @GET @Path("search") @Produces(MediaType.APPLICATION_JSON) public Map>> search() { Map>> resultMap = new HashMap>>(); List> companies = new ArrayList>(); List> departments = new ArrayList>(); resultMap.put("公司", companies); resultMap.put("部门", departments); for (OrgCompany orgCompany : orgCompanyManager.getAll()) { Map map = new HashMap(); companies.add(map); map.put("id", orgCompany.getId()); map.put("name", orgCompany.getName()); } for (OrgDepartment orgDepartment : orgDepartmentManager.getAll()) { Map map = new HashMap(); departments.add(map); map.put("id", orgDepartment.getId()); map.put("name", orgDepartment.getName()); } return resultMap; } // ~ ====================================================================== @Resource public void setOrgDepartmentManager( OrgDepartmentManager orgDepartmentManager) { this.orgDepartmentManager = orgDepartmentManager; } @Resource public void setOrgCompanyManager(OrgCompanyManager orgCompanyManager) { this.orgCompanyManager = orgCompanyManager; } } package br.com.zup.renatomelo.proposta.proposta.response; public class ResultadoAnaliseResponse { private String documento; private String nome; private String resultadoSolicitacao; private String idProposta; public String getDocumento() { return documento; } public String getNome() { return nome; } public String getResultadoSolicitacao() { return resultadoSolicitacao; } public String getIdProposta() { return idProposta; } @Deprecated public ResultadoAnaliseResponse() { } public ResultadoAnaliseResponse(String documento, String nome, String resultadoSolicitacao, String idProposta) { this.documento = documento; this.nome = nome; this.resultadoSolicitacao = resultadoSolicitacao; this.idProposta = idProposta; } } package org.apache.commons.jexl2; import org.apache.commons.collections.CollectionUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; public class JadeJexlArithmetic extends JexlArithmetic { public JadeJexlArithmetic(boolean lenient) { super(lenient); } protected int compare(Object left, Object right, String operator) { if (left != null && right != null) { if (left instanceof String || right instanceof String) { return toString(left).compareTo(toString(right)); } else if (left instanceof BigDecimal || right instanceof BigDecimal) { BigDecimal l = toBigDecimal(left); BigDecimal r = toBigDecimal(right); return l.compareTo(r); } else if (left instanceof BigInteger || right instanceof BigInteger) { BigInteger l = toBigInteger(left); BigInteger r = toBigInteger(right); return l.compareTo(r); } else if (isFloatingPoint(left) || isFloatingPoint(right)) { double lhs = toDouble(left); double rhs = toDouble(right); if (Double.isNaN(lhs)) { if (Double.isNaN(rhs)) { return 0; } else { return -1; } } else if (Double.isNaN(rhs)) { // lhs is not NaN return +1; } else if (lhs < rhs) { return -1; } else if (lhs > rhs) { return +1; } else { return 0; } } else if (isNumberable(left) || isNumberable(right)) { long lhs = toLong(left); long rhs = toLong(right); if (lhs < rhs) { return -1; } else if (lhs > rhs) { return +1; } else { return 0; } } else if ("==".equals(operator)) { return left.equals(right) ? 0 : -1; } else if (left instanceof Comparable) { @SuppressWarnings("unchecked") // OK because of instanceof check above final Comparable comparable = (Comparable) left; return comparable.compareTo(right); } else if (right instanceof Comparable) { @SuppressWarnings("unchecked") // OK because of instanceof check above final Comparable comparable = (Comparable) right; return comparable.compareTo(left); } } throw new ArithmeticException("Object comparison:(" + left + " " + operator + " " + right + ")"); } /** * using the original implementation * added check for empty lists * defaulting to "true" */ @Override public boolean toBoolean(Object val) { if (val == null) { controlNullOperand(); return false; } else if (val instanceof Boolean) { return (Boolean) val; } else if (val instanceof Number) { double number = toDouble(val); return !Double.isNaN(number) && number != 0.d; } else if (val instanceof String) { String strval = val.toString(); return strval.length() > 0 && !"false".equals(strval); } else if (val instanceof Collection) { return CollectionUtils.isNotEmpty((Collection) val); } return true; } @Override public Object add(Object left, Object right) { if (left instanceof String && right instanceof String) { return (String)left + right; } else { return super.add(left, right); } } } /* * 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. */ package com.alipay.sofa.tracer.plugins.datasource.utils; import com.alipay.common.tracer.core.utils.StringUtils; /** * @author shusong.yss * @author qilong.zql * @since 2.2.0 */ public class SqlUtils { private static final String DEFAULT_SEPARATOR = ","; private static final String DEFAULT_SEPARATOR_ESCAPE = "%2C"; private static final String DEFAULT_NEW_LINE = "\n"; private static final String DEFAULT_RETURN = "\r"; private static final String EMPTY_STRING = ""; private static final int DIGEST_LOG_SQL_LIMIT = 4096; public static String getSqlEscaped(String sql) { String limitSql = sql; if (limitSql != null && limitSql.length() > DIGEST_LOG_SQL_LIMIT) { limitSql = limitSql.substring(0, DIGEST_LOG_SQL_LIMIT) + " ..."; } return escape(escapeWithSpecialCheck(limitSql), DEFAULT_SEPARATOR, DEFAULT_SEPARATOR_ESCAPE); } private static String escape(String str, String oldStr, String newStr) { if (str == null) { return EMPTY_STRING; } return StringUtils.replace(str, oldStr, newStr); } private static String escapeWithSpecialCheck(String str) { if (str == null) { return ""; } StringBuilder appender = new StringBuilder(); int len = str.length(); appender.ensureCapacity(appender.length() + len); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (c == '\n' || c == '\r' || c == '|') { c = ' '; } if (c != ' ' || c == ' ' && appender.length() > 0 && appender.charAt(appender.length() - 1) != ' ') { appender.append(c); } } return appender.toString().trim(); } }import com.fasterxml.jackson.databind.ObjectMapper; import model.Artifacts; import model.Policy; import model.VulnerabilitiesResult; import model.report.ReportDependencies; import model.report.ReportModel; import model.report.ReportVulnerabilities; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.gradle.api.logging.Logger; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; public class APIQueries { //private static final String API_URL = "http://localhost:8080/gradle/dependency/vulnerabilities"; //private static final String API_REPORT_URL = "http://localhost:8080/report"; private static final String API_URL = "http://172.16.58.3/gradle/dependency/vulnerabilities"; private static final String API_REPORT_URL = "http://172.16.58.3/report"; private static CloseableHttpClient httpClient; private static String token; /** * Initializes the Client to be used in the execution of the program */ public static void startClient(){ httpClient = HttpClients.createDefault(); token = System.getenv("CENTRAL_SERVER_TOKEN"); } /** * Sends a request to the API querying about all vulnerabilities of every dependency in the project. *
* The results are stored in the object representation of the report. * @param artifacts The list of artifacts that represent the dependencies. * @param reportModel The report model where the license found will be added. * @param policy The policy model that indicates how the plugin must operate. * @param errorMessage The list of error message to write the error to. * @param finalExecutor The reference to thread where the addition of the vulnerabilities to their dependencies in * the report model is done. * @param logger A reference to the plugin logger. */ public static void requestDependenciesVulnerabilities(List artifacts, ReportModel reportModel, Policy policy, List errorMessage, ExecutorService finalExecutor, Logger logger) { CloseableHttpResponse response = null; try { ObjectMapper mapper = new ObjectMapper(); String obj = mapper.writeValueAsString(artifacts); HttpPost httpPost = new HttpPost(API_URL); httpPost.setEntity(new StringEntity(obj)); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Cache-Control", "max-age=" + policy.getApiCacheTime()); httpPost.addHeader("Authorization", "Bearer " + token); logger.info("Object to write {}", obj); response = httpClient.execute(httpPost); logger.info("Response Status {}", response.getStatusLine().getStatusCode()); logger.info("Response {}\n", response.getStatusLine()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { VulnerabilitiesResult[] vulnerabilities = mapper.readValue(response.getEntity().getContent(), VulnerabilitiesResult[].class); logger.info("Vulnerabilities {}", (Object) vulnerabilities); finalExecutor.submit(() -> { if (vulnerabilities.length > 0 && policy.isFail()) { String message = String.format("There were found %s vulnerabilities and the policy indicates that the build process should fail.", vulnerabilities.length); errorMessage.add(message); logger.info("{}\n\n\n", message); reportModel.setErrorInfo(message); reportModel.setSuccessfulBuild(false); } logger.info("Running adding vulnerabilities."); for (VulnerabilitiesResult vulnerability : vulnerabilities) { logger.info("Entity {}\n", vulnerability); ReportDependencies dependencies = new ReportDependencies(vulnerability.getTitle(), vulnerability.getMainVersion(), false); logger.info("Report Dependency {}\n", dependencies); List reportDependencies = reportModel.getDependencies() .stream() .filter(dependency -> dependency.equals(dependencies)) .collect(Collectors.toList()); if (!reportDependencies.isEmpty()) { logger.info("Added vulnerabilities to {}", reportDependencies.get(0)); reportDependencies.get(0).setVulnerabilities(vulnerability.getVulnerabilities().toArray(new ReportVulnerabilities[0])); reportDependencies.get(0).setVulnerabilitiesCount(vulnerability.getTotalVulnerabilities()); } } }); } else { String errorInfo = String.format("The request to the API was not successful. Status code was %s.", statusCode); logger.info(errorInfo); finalExecutor.submit(() -> reportModel.setErrorInfo(errorInfo) ); } } catch (IOException e) { String errorInfo = String.format("An IOException occurred when trying to get the dependencies vulnerabilities %s.", e.getMessage()); logger.warn(errorInfo); finalExecutor.submit(() -> reportModel.setErrorInfo(errorInfo) ); } finally { try { if (response != null) response.close(); } catch (IOException e) { logger.warn("The CloseableHttpResponse could not be closed {].", e.getMessage()); } } } /** * Sends the report produced by the plugin to the API. * @param reportModel The report model where the license found will be added. * @param logger A reference to the plugin logger. */ public static void sendReport(ReportModel reportModel, Logger logger) { CloseableHttpResponse response = null; try { ObjectMapper mapper = new ObjectMapper(); String report = mapper.writeValueAsString(reportModel); HttpPost httpPost = new HttpPost(API_REPORT_URL); httpPost.setEntity(new StringEntity(report)); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Authorization", "Bearer " + token); logger.info("Object to write {}", report); response = httpClient.execute(httpPost); logger.info("Response Status {}", response.getStatusLine().getStatusCode()); logger.info("Response {}", response.getStatusLine()); } catch (IOException e) { logger.warn("An IOException occurred when trying to send the report produced to the API {}.", e.getMessage()); } finally { if (response != null) { try { response.close(); } catch (IOException e) { logger.warn("The CloseableHttpResponse could not be closed {}.", e.getMessage()); } } } } /** * Shutdowns the client used in the course of the programme * @param logger A reference to the plugin logger. */ public static void finishClient(Logger logger){ try { httpClient.close(); } catch (IOException e) { logger.warn("The CloseableHttpClient could not be closed {}.", e.getMessage()); } } } adhibarfan/Belajar-Spring-MVC package com.adhib.arfan.belajar.spring.mvc.service; import com.adhib.arfan.belajar.spring.mvc.domain.Barang; import java.util.List; /** * Created by adhibarfan on 11/27/16. */ public interface BarangService { void save(Barang barang); void update(Barang barang); void delete(Barang barang); Barang getBarang(String idBarang); List getBarangs(); } /* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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. */ package de.tudarmstadt.ukp.experiments.pipeline.attic; import de.tudarmstadt.ukp.dkpro.argumentation.io.writer.ArgumentDumpWriter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.CollectionReaderFactory; import org.apache.uima.fit.pipeline.SimplePipeline; import java.io.File; import java.nio.file.Files; /** * @author */ @Deprecated // use AnnotatedDataExporter public class Step09AnnotatedDataHTMLExporter { public static void exportToHTML(File inputFile, File outputFile) throws Exception { File intermediateXMIsFile = File.createTempFile("temp", ".xmi.tar.gz"); SingleXMLToXMIExporter.exportToXMIs(inputFile, intermediateXMIsFile); SimplePipeline.runPipeline( CollectionReaderFactory.createReaderDescription( CompressedXmiReader.class, CompressedXmiReader.PARAM_SOURCE_LOCATION, intermediateXMIsFile ), AnalysisEngineFactory.createEngineDescription(ArgumentsToHTMLExporter.class, ArgumentsToHTMLExporter.PARAM_OUTPUT_FILE, outputFile), AnalysisEngineFactory.createEngineDescription( ArgumentDumpWriter.class ) ); Files.delete(intermediateXMIsFile.toPath()); } public static void main(String[] args) throws Exception { // File inputFile = new File("/home/user-ukp/IdeaProjects/acl2017/mturk_private/annotation-task/data/arguments-with-EDUs-test.xml.gz"); // File outputFile = new File("/home/user-ukp/data2/acl2017/08-gold-claims/arguments.html"); // exportToHTML(inputFile, outputFile); // 03-claim pilot mine // exportToHTML(new File("/home/user-ukp/data2/acl2017/08-gold-standard/arguments-03-pilot-mine.xml.gz"), // new File("/home/user-ukp/data2/acl2017/08-gold-standard/arguments-03-pilot-mine.html")); // 03-claim pilot workers // exportToHTML(new File("/home/user-ukp/data2/acl2017/08-gold-standard/arguments-03-pilot-workers.xml.gz"), // new File("/home/user-ukp/data2/acl2017/08-gold-standard/arguments-03-pilot-workers.html")); // 04-claim pilot workers // exportToHTML(new File("/home/user-ukp/data2/acl2017/08-gold-standard/arguments-04-pilot-workers.xml.gz"), // new File("/home/user-ukp/data2/acl2017/08-gold-standard/arguments-04-pilot-workers.html")); // 05-claim pilot workers // exportToHTML(new File( // "/home/user-ukp/data2/emnlp2017/08-gold-standard/arguments-05-pilot-workers.xml.gz"), // new File( // "/home/user-ukp/data2/emnlp2017/08-gold-standard/arguments-05-pilot-workers.html")); // pilot reasons exportToHTML(new File("mturk/annotation-task/data/30-pilot-reasons-task.xml.gz"), new File("mturk/annotation-task/data/30-pilot-reasons-task.html")); } } package com.github.freeacs.dbi; import static org.junit.Assert.*; import org.junit.Test; public class UsersTest { @Test public void delete() {} @Test public void addOrChange() {} } package fi.riista.feature.organization.rhy.annualstats.audit; import fi.riista.feature.organization.rhy.annualstats.RhyAnnualStatistics; import fi.riista.integration.common.entity.Integration; import fi.riista.integration.common.repository.IntegrationRepository; import fi.riista.util.DateUtil; import org.joda.time.DateTime; import org.joda.time.Interval; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; import java.util.Optional; import static fi.riista.integration.common.entity.Integration.RHY_ANNUAL_STATISTICS_MODERATOR_UPDATE_NOTIFICATION_ID; import static fi.riista.util.DateUtil.currentYear; @Service public class RhyAnnualStatisticsNotificationFeature { private static final Logger LOG = LoggerFactory.getLogger(RhyAnnualStatisticsNotificationFeature.class); @Resource private IntegrationRepository integrationRepository; @Resource private RhyAnnualStatisticsNotificationService notificationService; @PreAuthorize("hasRole('ROLE_ADMIN')") @Transactional public void sendModeratorUpdateNotifications() { final DateTime currentTime = DateUtil.now(); final Integration integration = getIntegrationForModeratorUpdateNotification(); final DateTime lastRunOrBeginOfCurrentYear = Optional .ofNullable(integration.getLastRun()) .orElseGet(() -> DateUtil.toDateTimeNullSafe(new LocalDate(currentYear(), 1, 1))); final Interval interval = new Interval(lastRunOrBeginOfCurrentYear, currentTime); final List aggregatedModeratorUpdates = notificationService.findAnnualStatisticGroupsUpdatedByModerator(interval); LOG.info("Found {} annual statistics moderator update notifications to be sent from interval {}.", aggregatedModeratorUpdates.size(), interval); notificationService.sendModeratorUpdateNotifications(aggregatedModeratorUpdates); final List approvedStatistics = notificationService.findApprovedAnnualStatistics(interval); LOG.info("Found {} annual statistics approved within interval {}.", approvedStatistics.size(), interval); notificationService.sendApprovalNotifications(approvedStatistics); integration.setLastRun(currentTime); } private Integration getIntegrationForModeratorUpdateNotification() { return integrationRepository.findById(RHY_ANNUAL_STATISTICS_MODERATOR_UPDATE_NOTIFICATION_ID) .orElseGet(() -> { final Integration newIntegration = new Integration(); newIntegration.setId(RHY_ANNUAL_STATISTICS_MODERATOR_UPDATE_NOTIFICATION_ID); return integrationRepository.save(newIntegration); }); } } src/skylight-cucs/src/main/java/br/skylight/cucs/plugins/missionplan/MissionPropertiesTabExtensionPoint.java10-100 package br.skylight.cucs.plugins.missionplan; import javax.swing.JPanel; import br.skylight.commons.Vehicle; import br.skylight.commons.plugin.annotations.ExtensionPointDefinition; @ExtensionPointDefinition public interface MissionPropertiesTabExtensionPoint { public String getTabTitle(); public JPanel createTabPanel(Vehicle vehicle); public void onCancelPressed(); public boolean onOkPressed(); public boolean isCompatibleWith(Vehicle vehicle); } package com.app.jfinal.service.test; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.http.message.BasicNameValuePair; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.shoukaiseki.jfinal.kernel.http.JsonModel; /** * Hello world! * */ public class TestJfinalComm { public static void main( String[] args ) { String message=""; String resp = ""; try { String endPoint = "http://127.0.0.1:7001/mxservice/services/saycxf"; endPoint="http://localhost:7001/mxservice/services/jfinalcomm"; Service server = new Service(); Call call = (Call) server.createCall(); call.setTargetEndpointAddress(new URL(endPoint)); JsonModel jm=new JsonModel(); jm.setBusiness("WORKFLOW"); jm.addParameters(new BasicNameValuePair("loginid","qiaosh")); jm.addParameters(new BasicNameValuePair("appname","WOTRACK")); jm.addParameters(new BasicNameValuePair("ownerid","10863")); jm.addParameters(new BasicNameValuePair("ownertable","WORKORDER")); jm.addParameters(new BasicNameValuePair("DirectorInput","workflow")); String json = JSONObject.toJSONString(jm); Object obj ; // obj= call.invoke("say", // new Object[] { strxml }); // // obj=null; obj=call.invoke("send",new Object[]{json}); System.out.println("send="+obj); if (obj != null) { } message="上傳數據完成:"+obj; } catch (Exception e) { e.printStackTrace(); message="上傳數據失敗:
"+e.getMessage(); } } } Start9Labs/capacitor-tor package tor.plugin; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.subjects.PublishSubject; public class NetworkManager { private static NetworkManager instance = null; private NetworkManager() { } public static NetworkManager getInstance() { if (instance == null) { instance = new NetworkManager(); } return instance; } private PublishSubject onlineSubject = PublishSubject.create(); public Observable onlineSignal() { return onlineSubject; } Observer onlineObserver() { return onlineSubject; } }pytorch/src/gen/java/org/bytedeco/pytorch/TensorBase.java // Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.pytorch; import org.bytedeco.pytorch.Allocator; import org.bytedeco.pytorch.Function; import org.bytedeco.pytorch.Module; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.openblas.global.openblas_nolapack.*; import static org.bytedeco.openblas.global.openblas.*; import static org.bytedeco.pytorch.global.torch.*; // NOTE: [Tensor vs. TensorBase] // // Tensor, being the central data structure in PyTorch, gets used and // it's header included almost everywhere. Unfortunately this means // every time an operator signature is updated or changed in // native_functions.yaml, you (and every other PyTorch developer) need // to recompile all of ATen and it's dependencies. // // TensorBase aims to break up these header dependencies, and improve // incremental build times for all PyTorch developers. TensorBase // represents a reference counted handle to TensorImpl, exactly the // same as Tensor. However, TensorBase doesn't have code generated // methods in it's API and thus no dependence on native_functions.yaml. // // Usage tips // ---------- // - You can `#define TORCH_ASSERT_NO_OPERATORS` at the top of a .cpp // or .cu file to ensure it has no header dependencies on // native_functions.yaml (direct or indirect). // - Tensor inherits from TensorBase, so functions taking // `const TensorBase &` are callable with Tensor as well. // - TensorBase can be converted to tensor with `Tensor(tensor_base)`, // but this requires a reference-count bump. OptionalTensorRef on // the other hand can materialize a `const Tensor &` without // touching the reference-count. @Namespace("at") @Properties(inherit = org.bytedeco.pytorch.presets.torch.class) public class TensorBase extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public TensorBase(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public TensorBase(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public TensorBase position(long position) { return (TensorBase)super.position(position); } @Override public TensorBase getPointer(long i) { return new TensorBase((Pointer)this).offsetAddress(i); } public static class unsafe_borrow_t extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public unsafe_borrow_t(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public unsafe_borrow_t(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public unsafe_borrow_t position(long position) { return (unsafe_borrow_t)super.position(position); } @Override public unsafe_borrow_t getPointer(long i) { return new unsafe_borrow_t((Pointer)this).offsetAddress(i); } public unsafe_borrow_t() { super((Pointer)null); allocate(); } private native void allocate(); } public TensorBase() { super((Pointer)null); allocate(); } private native void allocate(); // This constructor should not be used by end users and is an implementation // detail invoked by autogenerated code. public TensorBase(@Const @ByRef TensorBase arg0) { super((Pointer)null); allocate(arg0); } private native void allocate(@Const @ByRef TensorBase arg0); // Creates a new wrapper from TensorImpl. Intentionally a free method because // it should be used with care. Checks necessary invariants public native @Cast("int64_t") long dim(); public native @Cast("int64_t") long storage_offset(); public native @ByVal TensorBase contiguous(MemoryFormat memory_format/*=c10::MemoryFormat::Contiguous*/); public native @ByVal TensorBase contiguous(); public native @ByVal TensorBase contiguous(@Cast("c10::MemoryFormat") byte memory_format/*=c10::MemoryFormat::Contiguous*/); /** Should be used if *this can reasonably be expected to be contiguous and * performance is important. * Compared to contiguous, it saves a reference count * increment/decrement if *this is already contiguous, at the cost * in all cases of an extra pointer of stack usage, an extra branch * to access, and an extra branch at destruction time. */ // Use .contiguous() instead. Trying to borrow from a prvalue // will only lead to trouble and dangling references. public native @Cast("bool") boolean is_complex(); public native @Cast("bool") boolean is_floating_point(); public native @Cast("bool") boolean is_signed(); public native @Cast("int64_t") long size(@Cast("int64_t") long dim); public native @Cast("int64_t") long stride(@Cast("int64_t") long dim); public native TensorImpl unsafeGetTensorImpl(); public native TensorImpl unsafeReleaseTensorImpl(); public native @Cast("bool") boolean defined(); public native void reset(); public native @ByRef @Name("operator =") TensorBase put(@Const @ByRef TensorBase x); // Ban assignment to rvalues, since at::Tensor (weirdly) performs a deep copy here public native @Cast("bool") @NoException(true) boolean is_same(@Const @ByRef TensorBase other); public native @Cast("size_t") @NoException(true) long use_count(); public native @Cast("size_t") @NoException(true) long weak_use_count(); public native @StdString String toString(); public native @ByVal @Cast("c10::ArrayRef*") LongArrayRef sizes(); public native @ByVal @Cast("c10::ArrayRef*") LongArrayRef strides(); // See impl::get_opt_names in ATen/NamedTensor.h for docs. public native @ByVal DimnameListOptional opt_names(); // See impl::get_names in ATen/NamedTensor.h for docs. public native @ByVal DimnameArrayRef names(); public native @Cast("int64_t") long ndimension(); public native @Cast("bool") boolean is_contiguous(@ByVal(nullValue = "at::MemoryFormat::Contiguous") MemoryFormat memory_format); public native @Cast("bool") boolean is_contiguous(); public native @Cast("bool") boolean is_non_overlapping_and_dense(); public native @ByVal MemoryFormat suggest_memory_format( @Cast("bool") boolean channels_last_strides_exact_match/*=false*/); public native @ByVal MemoryFormat suggest_memory_format(); // Total bytes consumed by the "view" of elements of the array. Does not // include size of metadata. The number reported here does not necessarily // correspond to the true physical memory consumed by a tensor; instead, // it reports the memory the tensor would take *if* it were contiguous. // Defined to be numel() * itemsize() public native @Cast("size_t") long nbytes(); public native @Cast("int64_t") long numel(); // Length of one array element in bytes. This is the traditional // Numpy naming. public native @Cast("size_t") long itemsize(); // Same as itemsize(). This is the PyTorch naming. public native @Cast("int64_t") long element_size(); public native @ByVal DispatchKeySet key_set(); public native ScalarType scalar_type(); public native @Cast("bool") boolean has_storage(); public native @Cast({"", "c10::Storage&&"}) @StdMove Storage storage(); public native @Cast("bool") boolean is_alias_of(@Const @ByRef TensorBase other); public native @Cast("bool") boolean is_conj(); // sets the conjugate bit of a tensor. // NOTE: Conjugate bit is supposed to be a read-only field. Only change this, if you are sure // that's what you want. Changing this might lead to incorrect behavior since conjugation is // a lazy operation and we rely on this bit to determine if a conjugation needs to be materialized. public native void _set_conj(@Cast("bool") boolean conjugate); public native @Cast("bool") boolean is_neg(); // sets the negative bit of a tensor. // NOTE: Negative bit is supposed to be a read-only field. Only change this, if you are sure // that's what you want. Changing this might lead to incorrect behavior since we rely on this // bit to determine if a negation needs to be materialized. public native void _set_neg(@Cast("bool") boolean negative); /** Returns a {@code Tensor}'s layout. */ public native @NoException(true) Layout layout(); /** Returns a {@code Tensor}'s dtype ({@code TypeMeta}). */ public native @ByVal @NoException(true) TypeMeta dtype(); /** Returns a {@code Tensor}'s device. */ public native @ByVal Device device(); /** Returns a {@code Tensor}'s device index. */ /** Returns if a {@code Tensor} has CPU backend. */ public native @Cast("bool") boolean is_cpu(); /** Returns if a {@code Tensor} has CUDA backend. */ public native @Cast("bool") boolean is_cuda(); /** Returns if a {@code Tensor} has XPU backend. */ public native @Cast("bool") boolean is_xpu(); /** Returns if a {@code Tensor} has XLA backend. */ public native @Cast("bool") boolean is_xla(); /** Returns if a {@code Tensor} has Lazy backend. */ public native @Cast("bool") boolean is_lazy(); /** Returns if a {@code Tensor} has HIP backend. */ public native @Cast("bool") boolean is_hip(); /** Returns if a {@code Tensor} has VE backend. */ public native @Cast("bool") boolean is_ve(); /** Returns if a {@code Tensor} has sparse backend. */ public native @Cast("bool") boolean is_sparse(); /** Returns is a {@code Tensor} has a sparse CSR backend. */ public native @Cast("bool") boolean is_sparse_csr(); /** Returns if a {@code Tensor} is mkldnn tensor. */ public native @Cast("bool") boolean is_mkldnn(); /** Returns if a {@code Tensor} is mlc tensor. */ public native @Cast("bool") boolean is_mlc(); /** Returns if a {@code Tensor} is ort tensor. */ public native @Cast("bool") boolean is_ort(); /** Returns if a {@code Tensor} is vulkan tensor. */ public native @Cast("bool") boolean is_vulkan(); /** Returns if a {@code Tensor} is metal tensor. */ public native @Cast("bool") boolean is_metal(); /** Returns if a {@code Tensor} has quantized backend. */ public native @Cast("bool") boolean is_quantized(); /** Returns if a {@code Tensor} is a meta tensor. Meta tensors can * also have other designations. */ public native @Cast("bool") boolean is_meta(); /** Returns if a {@code Tensor} is an inference tensor. */ public native @Cast("bool") boolean is_inference(); /** If a tensor is a quantized tensor, returns its quantizer * TODO: it's not in native_functions.yaml yet as it's not exposed to python */ /** Returns if a {@code Tensor} has any dimension names */ public native @Cast("bool") boolean has_names(); /** Returns a {@code Tensor}'s dimension names data structure */ public native NamedTensorMeta get_named_tensor_meta(); /** Returns the {@code TensorOptions} corresponding to this {@code Tensor}. Defined in * TensorOptions.h. */ public native @ByVal TensorOptions options(); public native Pointer data_ptr(); public native @Name("data_ptr") BytePointer data_ptr_byte(); public native @Name("data_ptr") ShortPointer data_ptr_short(); public native @Name("data_ptr") IntPointer data_ptr_int(); public native @Cast("int64_t*") @Name("data_ptr") LongPointer data_ptr_long(); public native @Name("data_ptr") FloatPointer data_ptr_float(); public native @Name("data_ptr") DoublePointer data_ptr_double(); // Purposely not defined here to avoid inlining public native void print(); // Return a `TensorAccessor` for CPU `Tensor`s. You have to specify scalar type and // dimension. // Return a `GenericPackedTensorAccessor` for CUDA `Tensor`s. You have to specify scalar type and // dimension. You can optionally specify RestrictPtrTraits as a template parameter to // cast the data pointer to a __restrict__ pointer. // In order to use this, your CUDA kernel has to take a corresponding GenericPackedTensorAccessor // as an argument. // ~~~~~ Autograd API ~~~~~ /** \fn bool is_leaf() const; * * All Tensors that have {@code requires_grad()} which is {@code }false{@code } will be leaf Tensors by convention. * * For Tensors that have {@code requires_grad()} which is {@code }true{@code }, they will be leaf Tensors if they were * created by the user. This means that they are not the result of an operation and so * {@code grad_fn()} is {@code nullptr}. * * Only leaf Tensors will have their {@code grad()} populated during a call to {@code backward()}. * To get {@code grad()} populated for non-leaf Tensors, you can use {@code retain_grad()}. * * Example: *
{@code
   *  auto a = torch::rand(10, torch::requires_grad());
   *  std::cout << a.is_leaf() << std::endl; // prints `true`
   * 
   *  auto b = torch::rand(10, torch::requires_grad()).to(torch::kCUDA);
   *  std::cout << b.is_leaf() << std::endl; // prints `false`
   *  // b was created by the operation that cast a cpu Tensor into a cuda Tensor
   * 
   *  auto c = torch::rand(10, torch::requires_grad()) + 2;
   *  std::cout << c.is_leaf() << std::endl; // prints `false`
   *  // c was created by the addition operation
   * 
   *  auto d = torch::rand(10).cuda();
   *  std::cout << d.is_leaf() << std::endl; // prints `true`
   *  // d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
   * 
   *  auto e = torch::rand(10).cuda().requires_grad_();
   *  std::cout << e.is_leaf() << std::endl; // prints `true`
   *  // e requires gradients and has no operations creating it
   * 
   *  auto f = torch::rand(10, torch::device(torch::kCUDA).requires_grad(true));
   *  std::cout << f.is_leaf() << std::endl; // prints `true`
   *  // f requires grad, has no operation creating it
   *  }

* \fn void backward(const Tensor & gradient={}, c10::optional retain_graph=c10::nullopt, bool create_graph=false, c10::optional inputs=c10::nullopt) const; * * Computes the gradient of current tensor with respect to graph leaves. * * The graph is differentiated using the chain rule. If the tensor is * non-scalar (i.e. its data has more than one element) and requires * gradient, the function additionally requires specifying {@code }gradient{@code }. * It should be a tensor of matching type and location, that contains * the gradient of the differentiated function w.r.t. this Tensor. * * This function accumulates gradients in the leaves - you might need to * zero them before calling it. * * @param gradient Gradient w.r.t. the * tensor. If it is a tensor, it will be automatically converted * to a Tensor that does not require grad unless {@code }create_graph{@code } is True. * None values can be specified for scalar Tensors or ones that * don't require grad. If a None value would be acceptable then * this argument is optional. * @param retain_graph If {@code }false{@code }, the graph used to compute * the grads will be freed. Note that in nearly all cases setting * this option to True is not needed and often can be worked around * in a much more efficient way. Defaults to the value of * {@code }create_graph{@code }. * @param create_graph If {@code }true{@code }, graph of the derivative will * be constructed, allowing to compute higher order derivative * products. Defaults to {@code }false{@code }. * @param inputs Inputs w.r.t. which the gradient will be accumulated into * {@code }at::Tensor::grad{@code }. All other Tensors will be ignored. If not * provided, the gradient is accumulated into all the leaf Tensors * that were used to compute the current tensor. * When inputs are provided and a given input is not a leaf, * the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients). * It is an implementation detail on which the user should not rely. * See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.

* \fn Tensor detach() const; * * Returns a new Tensor, detached from the current graph. * The result will never require gradient.

* \fn Tensor & detach_() const; * * Detaches the Tensor from the graph that created it, making it a leaf. * Views cannot be detached in-place.

* \fn void retain_grad() const; * * Enables this Tensor to have their :attr:{@code grad} populated during * :func:{@code backward}. This is a no-op for leaf tensors.

* \fn bool retains_grad() const; * * Is {@code }true{@code } if this Tensor is non-leaf and its :attr:{@code grad} is enabled to be * populated during :func:{@code backward}, {@code }false{@code } otherwise. */ public native @Const @ByRef TensorBase set_requires_grad(@Cast("bool") boolean requires_grad); /// public native @Cast("bool") boolean requires_grad(); /** NOTE: This is similar to the legacy {@code .data()} function on {@code Variable}, and is intended * to be used from functions that need to access the {@code Variable}'s equivalent {@code Tensor} * (i.e. {@code Tensor} that shares the same storage and tensor metadata with the {@code Variable}). * * One notable difference with the legacy {@code .data()} function is that changes to the * returned {@code Tensor}'s tensor metadata (e.g. sizes / strides / storage / storage_offset) * will not update the original {@code Variable}, due to the fact that this function * shallow-copies the {@code Variable}'s underlying TensorImpl. */ /// public native @ByVal TensorBase tensor_data(); /** NOTE: {@code var.variable_data()} in C++ has the same semantics as {@code tensor.data} * in Python, which create a new {@code Variable} that shares the same storage and * tensor metadata with the original {@code Variable}, but with a completely new * autograd history. * * NOTE: If we change the tensor metadata (e.g. sizes / strides / * storage / storage_offset) of a variable created from {@code var.variable_data()}, those * changes will not update the original variable {@code var}. In {@code .variable_data()}, we set * {@code allow_tensor_metadata_change_} to false to make such changes explicitly illegal, * in order to prevent users from changing metadata of {@code var.variable_data()} * and expecting the original variable {@code var} to also be updated. */ /// public native @ByVal TensorBase variable_data(); // Gradient Node and Edges //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Gets the gradient function of the {@code Variable}. If this is a leaf variable, * the pointer returned will be null. * * For View Variables: * Gets the up-to-date grad_fn. If the shared data or base was modified, we * re-create the grad_fn to express the up-to-date view relationship between * this and the base Variable. */ public native @SharedPtr Node grad_fn(); // Hooks //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// /// /// /** Registers a backward hook. * * The hook will be called every time a gradient with respect to the Tensor is computed. * The hook should have one of the following signature: *

{@code
   *  hook(TensorBase grad) -> TensorBase
   *  }
*
{@code
   *  hook(TensorBase grad) -> void
   *  }
* The hook should not modify its argument, but it can optionally return a new gradient * which will be used in place of {@code grad}. * * This function returns the index of the hook in the list which can be used to remove hook. * * Example: *
{@code
   *  auto v = torch::tensor({0., 0., 0.}, torch::requires_grad());
   *  auto h = v.register_hook([](torch::Tensor grad){ return grad * 2; }); // double the gradient
   *  v.backward(torch::tensor({1., 2., 3.}));
   *  // This prints:
   *  // ```
   *  //  2
   *  //  4
   *  //  6
   *  // [ CPUFloatType{3} ]
   *  // ```
   *  std::cout << v.grad() << std::endl;
   *  v.remove_hook(h);  // removes the hook
   *  }
*/ /** Remove hook at given position */ public native void remove_hook(@Cast("unsigned") int pos); // Variable methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public native @Cast("bool") boolean is_leaf(); public native @Cast("int64_t") long output_nr(); public native void set_data(@Const @ByRef TensorBase new_data); public native @ByVal TensorBase data(); public native @Cast("int64_t") long _version(); public native void retain_grad(); public native @Cast("bool") boolean retains_grad(); public native @Const @ByRef TensorBase requires_grad_(@Cast("bool") boolean _requires_grad/*=true*/); public native @Const @ByRef TensorBase requires_grad_(); // View Variables //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Returns true if this {@code Variable} is a view of another {@code Variable}. */ public native @Cast("bool") boolean is_view(); /** Returns the {@code Variable} that this {@code Variable} is a view of. If this * {@code Variable} is not a view, throw a {@code std::runtime_error}. */ public native @Const @ByRef TensorBase _base(); // Miscellaneous //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public native @StdString BytePointer name(); } 0 package org.magpie.asset.http.client; import org.apache.http.entity.ContentType; import org.magpie.asset.http.behavior.HttpBehavior; import org.magpie.asset.http.behavior.LongConnHttpBehavior; /** * 启用http请求长链接支持 *

* 用户通过提供"httpclient.properties"文件配制长链接相关参数,例如: *

* * maxConns=10 * * * @author chenheng * */ public class LongConnHttpClient { static HttpBehavior behavior = new LongConnHttpBehavior(); public static String get(String url) { return behavior.get(url); } public static String get(String url, String params) { return behavior.get(url, params); } public static String post(String url) { return behavior.post(url); } public static String post(String url, String params) { return behavior.post(url, params); } public static String post(String url, String params, ContentType contentType) { return behavior.post(url, params, contentType); } public static String put(String url) { return behavior.put(url); } public static String put(String url, String params) { return behavior.put(url, params); } public static String put(String url, String params, ContentType contentType) { return behavior.put(url, params, contentType); } public static String delete(String url) { return behavior.delete(url); } public static String delete(String url, String params) { return behavior.delete(url, params); } } package no.ntnu.appdevapi.security; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwtParser; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; /** * This class handles JWT-tokens by analyzing them, extracting data and creating new tokens */ @Component public class JwtUtil { @Value("${jwt.token.validity}") public long TOKEN_VALIDITY; @Value("${jwt.signing.key}") public String SIGNING_KEY; @Value("${jwt.authorities.key}") public String AUTHORITIES_KEY; /** * Gets the username from the JWT token. * * @param token the JWT token * @return the username as {@code String} */ public String getUsernameFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } public String getAdminTypeFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } /** * Gets the expiration date from the JWT token. * * @param token the JWT token * @return a date object with the expiration date */ public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token, Claims::getExpiration); } public T getClaimFromToken(String token, Function claimsResolver) { final Claims claims = getAllClaimsFromToken(token); return claimsResolver.apply(claims); } /** * Returns all claims in a JWT token * * @param token the JWT token to get claims from * @return all claims in the token */ private Claims getAllClaimsFromToken(String token) { return Jwts.parser() .setSigningKey(SIGNING_KEY) .parseClaimsJws(token) .getBody(); } /** * Checks if a JWT token is expired. * * @param token the JWT token to check. * @return {@code true} if token has expired, {@code false} if not. */ private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } public String generateToken(Authentication authentication) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY * 1000)) .signWith(SignatureAlgorithm.HS256, SIGNING_KEY) .compact(); } /** * Validate the given token with the given user. * * @param token the JWT token to validate. * @param userDetails the details of the user. * @return {@code true} if the token is valid and matches the user. */ public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } public UsernamePasswordAuthenticationToken getAuthenticationToken(final String token, final Authentication existingAuth, final UserDetails userDetails) { final JwtParser jwtParser = Jwts.parser().setSigningKey(SIGNING_KEY); final Jws claimsJws = jwtParser.parseClaimsJws(token); final Claims claims = claimsJws.getBody(); final Collection authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); return new UsernamePasswordAuthenticationToken(userDetails, "", authorities); } } phax/ph-isorelax0 /* * Copyright (c) 2001-2002, SourceForge ISO-RELAX Project * (, , , and ) * * Copyright (C) 2016-2021 (www.helger.com) * philip[at]helger[dot]com * * 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. */ package org.iso_relax.dispatcher; /** * IslandSchemaReader is responsible for parsing IslandSchema. * * @author */ public interface IslandSchemaReader extends org.xml.sax.ContentHandler { /** * gets parsed schema. this method is called after parsing is finished. * * @return return null if parsing was failed (for example by an error in the * schema file). */ IslandSchema getSchema (); } package com.jdon.sample.test.cqrs.a; /* * Copyright 2003-2009 the original author or authors. * 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 event 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. * */ import com.jdon.annotation.Consumer; import com.jdon.async.disruptor.EventDisruptor; import com.jdon.domain.message.DomainEventHandler; import com.jdon.domain.message.DomainMessage; import com.jdon.sample.test.cqrs.RepositoryIF; import com.jdon.sample.test.cqrs.ParameterVO; import com.jdon.sample.test.cqrs.b.AbEventToCommandIF; import com.jdon.sample.test.cqrs.b.AggregateRootB; /** * acccept Domain message from @Send("mychannel") of @Introduce("message") * * this is event futureTask message Listener; * * @author banq * */ @Consumer("toEventB") public class DomainEventConsumer implements DomainEventHandler { private RepositoryIF aBRepository; private AbEventToCommandIF aBEventToCommand; public DomainEventConsumer(RepositoryIF aBRepository, AbEventToCommandIF aBEventToCommand) { super(); this.aBRepository = aBRepository; this.aBEventToCommand = aBEventToCommand; } public void onEvent(EventDisruptor event, boolean endOfBatch) throws Exception { ParameterVO parameterVO = (ParameterVO) event.getDomainMessage().getEventSource(); String aggregateRootBId = parameterVO.getNextId(); AggregateRootB modelB = aBRepository.getB(aggregateRootBId); DomainMessage nextCommandResult = aBEventToCommand.ma(modelB, parameterVO); event.getDomainMessage().setEventResult(nextCommandResult.getBlockEventResult()); } } 1-10 /* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.akkaactor; import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface; import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed; import static net.bytebuddy.matcher.ElementMatchers.named; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; import akka.dispatch.sysmsg.SystemMessage; import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation; import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer; import io.opentelemetry.javaagent.instrumentation.api.ContextStore; import io.opentelemetry.javaagent.instrumentation.api.InstrumentationContext; import io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge; import io.opentelemetry.javaagent.instrumentation.api.concurrent.ExecutorInstrumentationUtils; import io.opentelemetry.javaagent.instrumentation.api.concurrent.State; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.matcher.ElementMatcher; public class AkkaDefaultSystemMessageQueueInstrumentation implements TypeInstrumentation { @Override public ElementMatcher typeMatcher() { return implementsInterface(named("akka.dispatch.DefaultSystemMessageQueue")); } @Override public ElementMatcher classLoaderOptimization() { return hasClassesNamed("akka.dispatch.DefaultSystemMessageQueue"); } @Override public void transform(TypeTransformer transformer) { transformer.applyAdviceToMethod( named("systemEnqueue") .and(takesArgument(0, named("akka.actor.ActorRef"))) .and(takesArgument(1, named("akka.dispatch.sysmsg.SystemMessage"))), AkkaDefaultSystemMessageQueueInstrumentation.class.getName() + "$DispatchSystemAdvice"); } @SuppressWarnings("unused") public static class DispatchSystemAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static State enter(@Advice.Argument(1) SystemMessage systemMessage) { if (ExecutorInstrumentationUtils.shouldAttachStateToTask(systemMessage)) { ContextStore contextStore = InstrumentationContext.get(SystemMessage.class, State.class); return ExecutorInstrumentationUtils.setupState( contextStore, systemMessage, Java8BytecodeBridge.currentContext()); } return null; } @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static void exit(@Advice.Enter State state, @Advice.Thrown Throwable throwable) { ExecutorInstrumentationUtils.cleanUpOnMethodExit(state, throwable); } } } package de.wiosense.webauthn.util; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import android.util.Log; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.security.crypto.EncryptedSharedPreferences; import androidx.security.crypto.MasterKey; import de.wiosense.webauthn.exceptions.VirgilException; public class ClientPinLocker { private static final String TAG = "ClientPINEntry"; private static final String KEYSTORE_TYPE = "AndroidKeyStore"; private static final String CLIENT_PIN_TYPE = "Android_ePIN_"; private static final String CLIENT_PIN_FIELD_PIN_RETRIES = "RETRIES"; private static final int CLIENT_PIN_FIELD_PIN_RETRIES_VALUE = 0; private static final String CLIENT_PIN_FIELD_PIN_TOKEN = "TOKEN"; private static final String CLIENT_PIN_FIELD_PIN_TOKEN_VALUE = ""; private static final String CLIENT_PIN_FIELD_PIN_SHA256 = "PIN-SHA256"; private static final String CLIENT_PIN_FIELD_PIN_SHA256_VALUE = ""; private static final int PIN_TOKEN_LENGTH = 16; private SharedPreferences locker; private String clientId; private String cpkAlias; private String lockerId; public ClientPinLocker(Context ctx, @NonNull byte[] clientData) throws VirgilException { this(ctx, clientData, true); } public ClientPinLocker(Context ctx, @NonNull byte[] clientData, boolean strongboxRequired) throws VirgilException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new VirgilException("Failed to hash data", e); } md.update(clientData); this.clientId = bytesToHexString(md.digest()); this.cpkAlias = "cpk" + this.clientId; this.lockerId = CLIENT_PIN_TYPE + this.clientId; // Create now an encrypted enclosure to store the client ID metadata (retries / pinToken) MasterKey masterKey; try { KeyGenParameterSpec keySpec = new KeyGenParameterSpec.Builder( cpkAlias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setKeySize(256) .setUserAuthenticationRequired(false) .setRandomizedEncryptionRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setIsStrongBoxBacked(strongboxRequired) .setUnlockedDeviceRequired(true) .build(); MasterKey.Builder masterKeyBuilder = new MasterKey.Builder(ctx, cpkAlias); masterKey = masterKeyBuilder.setKeyGenParameterSpec(keySpec).build(); } catch (IOException | GeneralSecurityException e) { e.printStackTrace(); throw new VirgilException("Could not initialize clientPIN safe key"); } try { locker = EncryptedSharedPreferences.create( ctx, lockerId, masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM); } catch (IOException | GeneralSecurityException e) { e.printStackTrace(); throw new VirgilException("Could not initialize clientPIN safe"); } refreshToken(); } public ClientPinLocker setRetries(long retries) { if (retries < 0 || retries > 8) return this; locker.edit() .putLong(CLIENT_PIN_FIELD_PIN_RETRIES, retries) .apply(); return this; } public ClientPinLocker setToken(@NonNull byte[] token) { if (token.length % 16 != 0) return this; String tokenString = bytesToHexString(token); locker.edit() .putString(CLIENT_PIN_FIELD_PIN_TOKEN, tokenString) .apply(); return this; } public boolean lockPin(@NonNull byte[] pin) { String pinString = bytesToHexString(pin); try { refreshToken(); } catch (VirgilException e) { Log.w(TAG, "Failed to refresh token on this occasion!"); } return locker.edit() .putString(CLIENT_PIN_FIELD_PIN_SHA256, pinString) .commit(); } public boolean isPinMatch(@NonNull byte[] pinTry) { String pinTryString = bytesToHexString(pinTry); String pinReference = locker.getString(CLIENT_PIN_FIELD_PIN_SHA256, CLIENT_PIN_FIELD_PIN_SHA256_VALUE); if (pinReference.equals(CLIENT_PIN_FIELD_PIN_SHA256_VALUE)) return false; return pinReference.equals(pinTryString); } public boolean isPinSet() { String pinReference = locker.getString(CLIENT_PIN_FIELD_PIN_SHA256, CLIENT_PIN_FIELD_PIN_SHA256_VALUE); return !pinReference.equals(CLIENT_PIN_FIELD_PIN_SHA256_VALUE); } public boolean resetPinLocker() { return locker.edit() .putLong(CLIENT_PIN_FIELD_PIN_RETRIES, CLIENT_PIN_FIELD_PIN_RETRIES_VALUE) .putString(CLIENT_PIN_FIELD_PIN_TOKEN, CLIENT_PIN_FIELD_PIN_TOKEN_VALUE) .putString(CLIENT_PIN_FIELD_PIN_SHA256, CLIENT_PIN_FIELD_PIN_SHA256_VALUE) .commit(); } @NotNull @Override public String toString() { return this.clientId; } public Long getRetries() { return locker.getLong(CLIENT_PIN_FIELD_PIN_RETRIES, CLIENT_PIN_FIELD_PIN_RETRIES_VALUE); } public @Nullable byte[] getToken() { String tokenString = locker.getString(CLIENT_PIN_FIELD_PIN_TOKEN, CLIENT_PIN_FIELD_PIN_TOKEN_VALUE); if (!tokenString.equals(CLIENT_PIN_FIELD_PIN_TOKEN_VALUE)) { return hexStringToBytes(tokenString); } else { return null; } } public void deletePinLocker() throws VirgilException, KeyStoreException { /* * This is done by clearing all the fields, committing all the changes * and then removing the sharedPreferences files as per * https://stackoverflow.com/questions/6125296/delete-sharedpreferences-file * or * https://github.com/akaita/encryptedsharedpreferences-example/blob/master/app/src/main/java/com/akaita/encryptedsharedpreferences/MainActivity.kt#L123 * * Also at the end removing the key from the keyStore if possible */ locker.edit().clear().commit(); this.getClass().getPackage(); String lockerUri = getLockerUri(); File locker = new File(lockerUri); if (locker.exists()) { try { locker.delete(); } catch (SecurityException e) { throw new VirgilException("Couldn't delete locker", e); } } KeyStore keyStore; try { keyStore = KeyStore.getInstance(KEYSTORE_TYPE); keyStore.load(null); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { throw new VirgilException("Couldn't access keystore", e); } keyStore.deleteEntry(cpkAlias); } public void decrementPinRetries() throws VirgilException { long retries = locker.getLong(CLIENT_PIN_FIELD_PIN_RETRIES, CLIENT_PIN_FIELD_PIN_RETRIES_VALUE); if (retries != 0) { retries--; locker.edit().putLong(CLIENT_PIN_FIELD_PIN_RETRIES, retries).commit(); } else { throw new VirgilException("Client PIN error"); } } public void refreshToken() throws VirgilException { try{ byte[] pinToken = new byte[PIN_TOKEN_LENGTH]; SecureRandom.getInstanceStrong().nextBytes(pinToken); this.setToken(pinToken); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new VirgilException("Cannot produce pinToken bits", e); } } private String getLockerUri() { ApplicationInfo appInfo = new ApplicationInfo(); return appInfo.dataDir + "/shared_prefs/" + lockerId + ".xml"; } private String bytesToHexString(@NonNull byte[] bytes) { StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } private @Nullable byte[] hexStringToBytes(String str) { int len = str.length(); if (len == 0) return null; byte[] bytes = new byte[len / 2]; for (int i = 0; i < len; i += 2) { bytes[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i+1), 16)); } return bytes; } } karakufire/TinkersConstruct100-1000 package slimeknights.tconstruct.library.recipe.melting; import com.google.gson.JsonObject; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import net.minecraft.data.IFinishedRecipe; import net.minecraft.fluid.Fluid; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; import slimeknights.mantle.recipe.RecipeHelper; import slimeknights.mantle.recipe.data.AbstractRecipeBuilder; import slimeknights.tconstruct.library.materials.definition.MaterialId; import slimeknights.tconstruct.smeltery.TinkerSmeltery; import javax.annotation.Nullable; import java.util.function.Consumer; /** * Builder for a recipe to melt a dynamic part material item */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class MaterialMeltingRecipeBuilder extends AbstractRecipeBuilder { private final MaterialId inputId; private final int temperature; private final FluidStack result; /** Creates a recipe using the fluids temperature */ public static MaterialMeltingRecipeBuilder material(MaterialId materialId, int temperature, FluidStack result) { if (temperature < 0) { throw new IllegalArgumentException("Invalid temperature " + temperature + ", must be 0 or greater"); } return new MaterialMeltingRecipeBuilder(materialId, temperature, result); } /** Creates a recipe using the fluids temperature */ public static MaterialMeltingRecipeBuilder material(MaterialId materialId, FluidStack result) { return material(materialId, result.getFluid().getAttributes().getTemperature(result) - 300, result); } /** Creates a recipe using the fluids temperature */ public static MaterialMeltingRecipeBuilder material(MaterialId materialId, Fluid result, int amount) { return material(materialId, new FluidStack(result, amount)); } @Override public void build(Consumer consumer) { build(consumer, inputId); } @Override public void build(Consumer consumer, ResourceLocation id) { ResourceLocation advancementID = this.buildOptionalAdvancement(id, "melting"); consumer.accept(new Result(id, advancementID)); } private class Result extends AbstractFinishedRecipe { public Result(ResourceLocation ID, @Nullable ResourceLocation advancementID) { super(ID, advancementID); } @Override public void serialize(JsonObject json) { json.addProperty("input", inputId.toString()); json.addProperty("temperature", temperature); json.add("result", RecipeHelper.serializeFluidStack(result)); } @Override public IRecipeSerializer getSerializer() { return TinkerSmeltery.materialMeltingSerializer.get(); } } } 0 package seedu.address.logic.commands; import seedu.address.logic.CommandHistory; import seedu.address.model.Model; import seedu.address.ui.WindowViewState; /** * Switches the view from Person view to Events view, and vice versa. */ public class SwitchCommand extends Command { public static final String COMMAND_WORD = "switch"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Switches to the next view.\n" + "Example: " + COMMAND_WORD + " will switch to Events view from Person view, and vice versa"; public static final String SHOWING_SWITCH_MESSAGE = "Switched view."; @Override public CommandResult execute(Model model, CommandHistory history, WindowViewState windowViewState) { return new CommandResult(SHOWING_SWITCH_MESSAGE, false, false, true); } } honest-niceman/documentationcontent/manual/source/ui_component/metadata/EventHandler.java @StudioFacet public interface ClipboardTrigger extends Facet { // ... Subscription addCopyListener(Consumer listener); class CopyEvent extends EventObject { public CopyEvent(ClipboardTrigger source, boolean success) { super(source); this.success = success; } public boolean isSuccess() { return success; } } } package com.jalvz.bio.depthcover.writer; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.log4j.Logger; import com.jalvz.bio.depthcover.ExitStatus; import com.jalvz.bio.depthcover.util.Timer; public class DoubleBufferAsyncWriter implements Runnable { private static final Logger logger = Logger.getLogger(DoubleBufferAsyncWriter.class.getName()); private static final int BUFFER_LINES = 3000; private static final int EST_LINE_SIZE = 50; private final DelegatedWriter bufferedWriter0; private final DelegatedWriter bufferedWriter1; private int activeBuffer = 0; private int linesInBuffer = 0; private boolean lock = false; private boolean finished = false; protected DoubleBufferAsyncWriter(File out, List header) throws IOException { bufferedWriter0 = new DelegatedWriter(out, header, BUFFER_LINES * EST_LINE_SIZE); bufferedWriter1 = new DelegatedWriter(out, header, BUFFER_LINES * EST_LINE_SIZE); bufferedWriter1.clear(); } @Override public void run() { logger.debug("Started Writer thread - Id = " + Thread.currentThread().getId()); while (!finished) { while (linesInBuffer < BUFFER_LINES && !finished) { Timer.sleep(2); } try { flush(); } catch (Exception e) { logger.error(e.getMessage(), e); ExitStatus.setStatus(1); finished = true; } } logger.debug("Finished Writer thread - Id = " + Thread.currentThread().getId()); } public synchronized void addLine(List line) { while (lock) { logger.trace("waiting to buffer swap on async writer"); Timer.sleep(2); } if (activeBuffer == 0) { bufferedWriter0.addLine(line); } else { bufferedWriter1.addLine(line); } linesInBuffer += 1; } public void finalise() { finished = true; flush(); bufferedWriter0.close(); bufferedWriter1.close(); } private synchronized void flush() { acquireLock(); if (linesInBuffer == 0) { releaseLock(); return; } if (activeBuffer == 0) { swapBuffer(); releaseLock(); bufferedWriter0.write(); } else { swapBuffer(); releaseLock(); bufferedWriter1.write(); } } private void swapBuffer() { logger.trace("lines in writer buffer = " + linesInBuffer); activeBuffer = activeBuffer ^ 1; linesInBuffer = 0; } private void acquireLock() { lock = true; } private void releaseLock() { lock = false; } } /* * 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. */ package com.aliyuncs.sofa.transform.v20190815; import com.aliyuncs.sofa.model.v20190815.QueryLinkefabricFabricSystemparameterisadminResponse; import com.aliyuncs.transform.UnmarshallerContext; public class QueryLinkefabricFabricSystemparameterisadminResponseUnmarshaller { public static QueryLinkefabricFabricSystemparameterisadminResponse unmarshall(QueryLinkefabricFabricSystemparameterisadminResponse queryLinkefabricFabricSystemparameterisadminResponse, UnmarshallerContext _ctx) { queryLinkefabricFabricSystemparameterisadminResponse.setRequestId(_ctx.stringValue("QueryLinkefabricFabricSystemparameterisadminResponse.RequestId")); queryLinkefabricFabricSystemparameterisadminResponse.setResultCode(_ctx.stringValue("QueryLinkefabricFabricSystemparameterisadminResponse.ResultCode")); queryLinkefabricFabricSystemparameterisadminResponse.setResultMessage(_ctx.stringValue("QueryLinkefabricFabricSystemparameterisadminResponse.ResultMessage")); queryLinkefabricFabricSystemparameterisadminResponse.setData(_ctx.booleanValue("QueryLinkefabricFabricSystemparameterisadminResponse.Data")); queryLinkefabricFabricSystemparameterisadminResponse.setMessage(_ctx.stringValue("QueryLinkefabricFabricSystemparameterisadminResponse.Message")); queryLinkefabricFabricSystemparameterisadminResponse.setResponseStatusCode(_ctx.longValue("QueryLinkefabricFabricSystemparameterisadminResponse.ResponseStatusCode")); queryLinkefabricFabricSystemparameterisadminResponse.setSuccess(_ctx.booleanValue("QueryLinkefabricFabricSystemparameterisadminResponse.Success")); return queryLinkefabricFabricSystemparameterisadminResponse; } }package org.firstinspires.ftc.teamcode.Tests; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; /** * Created by on 3/8/2018. */ public class GoToPos { private LinearOpMode linearOpMode; private double xTarget = 0, yTarget = 0, phiTarget =0; RobotPos Target = new RobotPos(xTarget,yTarget,phiTarget); LeftRightVelMatrix velMatrix; double vel = 12; RobotPos Current; DcMotor l1, l2, r1, r2; private double omega,targetOmega; public GoToPos(RobotPos current, RobotPos target) { } public boolean hasReached() { return Math.abs(omega-0.5)<0; } public void goToPos() { velMatrix = new LeftRightVelMatrix(vel,omega); while(linearOpMode.opModeIsActive()&&!hasReached()) { omega = Math.atan2((Target.getY()-Current.getY()),Target.getX()-Current.getX()); ((DcMotorEx)l1).setVelocity(velMatrix.vl/2, AngleUnit.DEGREES); ((DcMotorEx)l2).setVelocity(velMatrix.vl/2, AngleUnit.DEGREES); ((DcMotorEx)r1).setVelocity(velMatrix.vl/2, AngleUnit.DEGREES); ((DcMotorEx)r2).setVelocity(velMatrix.vl/2, AngleUnit.DEGREES); velMatrix.update();; //TODO: CELAN UP AND OTHER MATRIX AND MATH DOUBLE CHECK } } } app/src/main/java/com/danilov/supermanga/core/http/HttpBitmapReader.java10-100 package com.danilov.supermanga.core.http; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.annotation.Nullable; import com.danilov.supermanga.core.util.IoUtils; import org.apache.http.Header; import java.io.ByteArrayInputStream; import java.io.InputStream; /** * Created by on 16.05.2014. */ public class HttpBitmapReader { public static final String TAG = "HttpBitmapReader"; private final HttpBytesReader mHttpBytesReader; public HttpBitmapReader(HttpBytesReader httpBytesReader) { this.mHttpBytesReader = httpBytesReader; } public Bitmap fromUri(String uri, @Nullable final RequestPreprocessor preprocessor) throws HttpRequestException { return this.fromUri(uri, preprocessor, null); } public Bitmap fromUri(String uri, @Nullable final RequestPreprocessor preprocessor, Header[] customHeaders) throws HttpRequestException { byte[] bytes = this.mHttpBytesReader.fromUri(uri, preprocessor, customHeaders); InputStream stream = new FlushedInputStream(new ByteArrayInputStream(bytes)); Bitmap bmp = BitmapFactory.decodeStream(stream); IoUtils.closeStream(stream); return bmp; } public void removeIfModifiedForUri(String uri) { this.mHttpBytesReader.removeIfModifiedForUri(uri); } } isandesh1986/mrcheckerexample/src/main/java/com/capgemini/mrchecker/webapi/pages/httbin/cookies/DeleteCookiesPage.java package com.capgemini.mrchecker.webapi.pages.httbin.cookies; import com.capgemini.mrchecker.webapi.core.BasePageWebAPI; import com.capgemini.mrchecker.webapi.core.base.driver.DriverManager; import com.capgemini.mrchecker.webapi.pages.environment.GetEnvironmentParam; import io.restassured.config.RedirectConfig; import io.restassured.config.RestAssuredConfig; import io.restassured.response.Response; public class DeleteCookiesPage extends BasePageWebAPI { private final static String HOSTNAME = GetEnvironmentParam.HTTPBIN.getValue(); private final static String PATH = "/cookies/delete"; private final static String ENDPOINT = HOSTNAME + PATH; private String deleteCookiesEndpointWithValues; public Response deleteCookie(String name, String value) { deleteCookiesEndpointWithValues = ENDPOINT .concat("?") .concat(name) .concat("=") .concat(value); return DriverManager.getDriverWebAPI() .config(RestAssuredConfig.newConfig() .redirect(RedirectConfig.redirectConfig() .followRedirects(false))) .filter(CookieSession.getSession()) .when() .get(deleteCookiesEndpointWithValues); } public String getEndpoint() { return deleteCookiesEndpointWithValues == null ? ENDPOINT : deleteCookiesEndpointWithValues; } } 1-10 package mil.nga.giat.geowave.core.cli.operations.config.options; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.Parameter; import mil.nga.giat.geowave.core.cli.VersionUtils; import mil.nga.giat.geowave.core.cli.api.OperationParams; import mil.nga.giat.geowave.core.cli.operations.config.ConfigSection; /** * Config options allows the user to override the default location for * configuration options, and also allows commands to load the properties needed * for running the program. */ public class ConfigOptions { public static final String CHARSET = "ISO-8859-1"; private final static Logger LOGGER = LoggerFactory.getLogger(ConfigSection.class); public final static String PROPERTIES_FILE_CONTEXT = "properties-file"; public final static String GEOWAVE_CACHE_PATH = ".geowave"; public final static String GEOWAVE_CACHE_FILE = "config.properties"; /** * Allow the user to override the config file location */ @Parameter(names = { "-cf", "--config-file" }, description = "Override configuration file (default is /.geowave/config.properties)") private String configFile; public ConfigOptions() { } public String getConfigFile() { return configFile; } public void setConfigFile( final String configFile ) { this.configFile = configFile; } /** * The default property file is in the user's home directory, in the * .geowave folder. * * @return */ public static File getDefaultPropertyPath() { // File location // HP Fortify "Path Manipulation" false positive // What Fortify considers "user input" comes only // from users with OS-level access anyway final String cachePath = String.format( "%s%s%s", System.getProperty("user.home"), File.separator, GEOWAVE_CACHE_PATH); return new File( cachePath); } /** * The default property file is in the user's home directory, in the * .geowave folder. If the version can not be found the first available * property file in the folder is used * * @return Default Property File */ public static File getDefaultPropertyFile() { // HP Fortify "Path Manipulation" false positive // What Fortify considers "user input" comes only // from users with OS-level access anyway final File defaultPath = getDefaultPropertyPath(); final String version = VersionUtils.getVersion(); if (version != null) { return formatConfigFile( version, defaultPath); } else { final String[] configFiles = defaultPath.list(new FilenameFilter() { @Override public boolean accept( File dir, String name ) { return name.endsWith("-config.properties"); } }); if (configFiles != null && configFiles.length > 0) { final String backupVersion = configFiles[0].substring( 0, configFiles[0].length() - 18); return formatConfigFile( backupVersion, defaultPath); } else { return formatConfigFile( "unknownversion", defaultPath); } } } /** * Configures a File based on a given path name and version * * @param version * @param defaultPath * @return Configured File */ public static File formatConfigFile( String version, File defaultPath ) { // HP Fortify "Path Manipulation" false positive // What Fortify considers "user input" comes only // from users with OS-level access anyway final String configFile = String.format( "%s%s%s%s%s", defaultPath.getAbsolutePath(), File.separator, version, "-", GEOWAVE_CACHE_FILE); return new File( configFile); } /** * Write the given properties to the file, and log an error if an exception * occurs. * * @return true if success, false if failure */ public static boolean writeProperties( final File configFile, final Properties properties ) { try { Properties tmp = new Properties() { private static final long serialVersionUID = 1L; @Override public Set keySet() { return Collections.unmodifiableSet(new TreeSet( super.keySet())); } @Override public synchronized Enumeration keys() { return Collections.enumeration(new TreeSet( super.keySet())); } }; tmp.putAll(properties); try (FileOutputStream str = new FileOutputStream( configFile)) { tmp.store( str, null); } } catch (FileNotFoundException e) { LOGGER.error( "Could not find the property file.", e); return false; } catch (IOException e) { LOGGER.error( "Exception writing property file.", e); return false; } return true; } /** * This helper function will load the properties file, or return null if it * can't. It's designed to be used by other commands. * * @param delimiter */ public static Properties loadProperties( final File configFile, final String pattern ) { Pattern p = null; if (pattern != null) { p = Pattern.compile(pattern); } // Load the properties file. final Properties properties = new Properties(); InputStream is = null; try { if (p != null) { try (FileInputStream input = new FileInputStream( configFile); Scanner s = new Scanner( input, CHARSET)) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintWriter writer = new PrintWriter( new OutputStreamWriter( out, CHARSET)); while (s.hasNext()) { final String line = s.nextLine(); if (p.matcher( line).find()) { writer.println(line); } } writer.flush(); is = new ByteArrayInputStream( out.toByteArray()); } } else { is = new FileInputStream( configFile); } properties.load(is); } catch (final IOException e) { LOGGER.error( "Could not find property cache file: " + configFile, e); return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.error( e.getMessage(), e); } } } return properties; } /** * Load the properties file into the input params. * * @param inputParams */ public void prepare( OperationParams inputParams ) { File propertyFile = null; if (getConfigFile() != null) { propertyFile = new File( getConfigFile()); } else { propertyFile = getDefaultPropertyFile(); } // Set the properties on the context. inputParams.getContext().put( PROPERTIES_FILE_CONTEXT, propertyFile); } } package com.github.hinaser.gfma.editor; import com.github.hinaser.gfma.browser.IBrowser; import com.github.hinaser.gfma.browser.MarkdownParsedAdapter; import com.intellij.openapi.editor.Document; import com.intellij.openapi.vfs.VirtualFile; import com.github.hinaser.gfma.browser.ChromiumBrowser; import com.github.hinaser.gfma.browser.MarkdownParsedListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class JCefGfmAPreview extends AbstractGfmAPreview { private final IBrowser browser = new ChromiumBrowser(); private final MarkdownParsedAdapter markdownParsedAdapter; public JCefGfmAPreview(@NotNull VirtualFile markdownFile, @Nullable Document document){ super(markdownFile, document); this.markdownParsedAdapter = new MarkdownParsedAdapter(this.browser, markdownFile.getName()); initialize(); } @Override @NotNull protected MarkdownParsedListener getMarkdownParsedListener() { markdownParsedAdapter.setFilename(markdownFile.getName()); return markdownParsedAdapter; } @NotNull @Override public JComponent getComponent() { return browser.getComponent(); } @Override public void dispose(){ super.dispose(); } @Override public @NotNull String getName() { return "GfmA Preview"; } @Override public @NotNull VirtualFile getFile() { return markdownFile; } } BrightSkyz/MemeFeed package memeFeed.types; import memeFeed.utils.PorterStemmer; import java.util.ArrayList; import java.util.List; public class SentenceCommand { public List _words = new ArrayList<>(); public SentenceCommand() { this(""); } public SentenceCommand(String... words) { if (words == null) return; _words.add(words); } public SentenceCommand addWords(String... words) { _words.add(words); return this; } public Boolean isCommandFound(String string) { string = string.toLowerCase(); // First change everything to the stem of the word char[] messageChars = string.toCharArray(); string = ""; PorterStemmer stem = new PorterStemmer(); for (char ch : messageChars) { if (Character.isLetter((char) ch)) { stem.add(Character.toLowerCase((char) ch)); } else { stem.stem(); string += stem.toString() + " "; stem.reset(); } } // Then stem last word stem.stem(); string += stem.toString() + " "; // Then check for command Boolean overallFound = false; for (String[] wordSet : _words) { Boolean found = false; for (String word : wordSet) { word = word.toLowerCase(); if (found) break; if ((string.contains(word) && ( string.contains(word + " ") || string.contains(" " + word) || string.contains(word + " ") || string.contains(word + ".") || string.contains(word + "!") || string.contains(word + "?") ))) { found = true; } } overallFound = found; if (!found) return false; } return overallFound; /*for (String word : _words) { if (!(string.contains(word) && ( string.contains(word+ " ") || string.contains(" " + word) || string.contains(word + " ") || string.contains(word + ".") || string.contains(word + "!") || string.contains(word + "?") ))) { return false; } }*/ } } /* * Copyright © 2015 , Inc. * * 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. */ package io.cdap.cdap.test; import org.junit.rules.ExternalResource; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; /** * An {@link ExternalResource} that maintain a singleton to another {@link ExternalResource} so that * it can be used in test suite as well as in individual test in the suite. */ public class SingletonExternalResource extends ExternalResource { private static final AtomicInteger INSTANCES = new AtomicInteger(0); private final ExternalResource externalResource; public SingletonExternalResource(ExternalResource externalResource) { this.externalResource = externalResource; } @Override protected void before() throws Throwable { if (INSTANCES.getAndIncrement() == 0) { Method before = ExternalResource.class.getDeclaredMethod("before"); before.setAccessible(true); try { before.invoke(externalResource); } catch (InvocationTargetException e) { throw e.getCause(); } } } @Override protected void after() { if (INSTANCES.decrementAndGet() == 0) { try { Method after = ExternalResource.class.getDeclaredMethod("after"); after.setAccessible(true); after.invoke(externalResource); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // Should not happen throw new RuntimeException(e); } } } /** * Returns the underlying {@link ExternalResource}. * * @param The actual type of the resource. */ @SuppressWarnings("unchecked") public T get() { Objects.requireNonNull(externalResource); return (T) externalResource; } } import static util.Logger.log; import org.junit.Test; public class ArrayCopyTutor1 { int animals_capacity = 5; int animals_expand_by = 5; int animals_size = 0; String[] animals = new String[animals_capacity]; public void addAnimal(String animal) { if (animals_size>=animals_capacity) { expandAnimalsArray(); } animals[animals_size] = animal; animals_size++; } private void expandAnimalsArray() { int old_animals_size = animals_capacity; animals_capacity += animals_expand_by; String[] animals_new = new String[animals_capacity]; System.arraycopy(animals, 0, animals_new, 0, old_animals_size); animals = animals_new; } public void insertAnimal(int position, String animal) { if (position<0 || position>animals_size-1) { throw new ArrayIndexOutOfBoundsException(); } if (position==animals_size-1) { addAnimal(animal); } else { if (animals_size>=animals_capacity) { expandAnimalsArray(); } System.arraycopy(animals, position, animals, position+1, animals_size-position); animals[position] = animal; animals_size++; } } public void deleteAnimal(int position) { System.arraycopy(animals, position+1, animals, position, animals_size-position); animals_size--; } public void showAnimals() { for (int i=0;i * * This program 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 3 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, see . */ package edu.msu.cme.pyro.cluster.upgma; import edu.msu.cme.pyro.cluster.dist.ThickEdge; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author fishjord */ public class Heap { private List nodes = new ArrayList(); private Comparator comp; private Map heapMap = new HashMap(); public long timeSpentRebuilding = 0; public Heap(Comparator comp) { this.comp = comp; } public boolean contains(E elem) { return nodes.contains(elem); } public void rebuild() { for(int index = parent(nodes.size());index >= 0;index--) { rebuild(index); } } private void rebuild(int index) { long startTime = System.currentTimeMillis(); int left = left(index); int right = right(index); int largest = index; if(left < nodes.size() && comp.compare(nodes.get(largest), nodes.get(left)) > 0) largest = left; if(right < nodes.size() && comp.compare(nodes.get(largest), nodes.get(right)) > 0) largest = right; if(largest != index) { swap(index, largest); rebuild(largest); } timeSpentRebuilding += (System.currentTimeMillis() - startTime); } public void insert(E elem) { int insertAt = nodes.size(); nodes.add(elem); shuffleUp(insertAt); } public E deleteTop() { E root = nodes.get(0); delete(0); return root; } public boolean delete(E elem) { Integer index = heapMap.get(elem); if(index == null) { return false; } return delete(index); } private boolean delete(int index) { E tmp = nodes.get(index); swap(index, nodes.size() - 1); heapMap.remove(nodes.remove(nodes.size() - 1)); if(index == nodes.size()) return true; changed(index); return true; } public boolean changed(E elem) { Integer index = heapMap.get(elem); if(index == null) { return false; } changed(index); return true; } private void changed(int index) { int parent = parent(index); if (parent != 0 && comp.compare(nodes.get(index), nodes.get(parent)) <= 0) { shuffleUp(index); } else { shuffleDown(index); } } private void swap(int i1, int i2) { Collections.swap(nodes, i1, i2); heapMap.put(nodes.get(i1), i1); heapMap.put(nodes.get(i2), i2); } private void shuffleDown(int node) { int currNode = left(node); while (currNode < nodes.size()) { if (currNode + 1 < nodes.size() && comp.compare(nodes.get(currNode + 1), nodes.get(currNode)) <= 0) { currNode++; } if (comp.compare(nodes.get(parent(currNode)), nodes.get(currNode)) <= 0) { heapMap.put(nodes.get(currNode), currNode); break; } else { swap(currNode, parent(currNode)); currNode = left(currNode); } } } private void shuffleUp(int insertAt) { E elem = nodes.get(insertAt); while (insertAt != 0 && comp.compare(nodes.get(insertAt), nodes.get(parent(insertAt))) <= 0) { if(sibling(insertAt) < nodes.size() && comp.compare(nodes.get(sibling(insertAt)), nodes.get(insertAt)) < 0) { heapMap.put(elem, insertAt); elem = nodes.get(sibling(insertAt)); insertAt = sibling(insertAt); } swap(insertAt, parent(insertAt)); insertAt = parent(insertAt); } nodes.set(insertAt, elem); heapMap.put(nodes.get(insertAt), insertAt); } public E top() { if (nodes.isEmpty()) { return null; } return nodes.get(0); } public E secondTop() { if (nodes.size() <= 1) { return null; } if (nodes.size() == 2) { return nodes.get(1); } if (comp.compare(nodes.get(1), nodes.get(2)) < 0) { return nodes.get(1); } else { return nodes.get(2); } } public boolean validate() { return validate(System.err); } public boolean checkConsistenency(PrintStream err) { boolean ret = true; for(E edge : heapMap.keySet()) { int index = heapMap.get(edge); if(edge != nodes.get(index)) { err.println("Expected to find " + edge + " at nodes[" + index + "] but I found " + nodes.get(index) + " which should have been at " + heapMap.get(nodes.get(index)) + " what I was looking for is at " + nodes.indexOf(edge)); ThickEdge e1 = (ThickEdge)edge; ThickEdge e2 = (ThickEdge)nodes.get(index); err.println(e1.getCi().getId() + " <=> " + e1.getCj().getId() + " = " + e1.getSeenDistances() + ", " + e1.getSeenEdges() + ", " + e1.getBound(0)); err.println(e2.getCi().getId() + " <=> " + e2.getCj().getId() + " = " + e2.getSeenDistances() + ", " + e2.getSeenEdges() + ", " + e2.getBound(0)); ret = false; } } for(E e : nodes) { if(!heapMap.containsKey(e)) { err.println("Failed to find e from nodes in the heap map..."); ThickEdge e1 = (ThickEdge)e; err.println(e1.getCi().getId() + " <=> " + e1.getCj().getId() + " = " + e1.getSeenDistances() + ", " + e1.getSeenEdges() + ", " + e1.getBound(0)); ret = false; } } if(!ret) { err.println("Nodes.size() = " + nodes.size()); err.println("heapMap.size() = " + heapMap.size()); } return ret; } public boolean validate(PrintStream err) { for (int index = 0; left(index) < nodes.size(); index++) { if (comp.compare(nodes.get(index), nodes.get(left(index))) > 0) { err.println("nodes[" + index + "]=" + nodes.get(index) + " > nodes[" + left(index) + "]=" + nodes.get(left(index))); return false; } if (right(index) < nodes.size() && comp.compare(nodes.get(index), nodes.get(right(index))) > 0) { err.println("nodes[" + index + "]=" + nodes.get(index) + " > nodes[" + right(index) + "]=" + nodes.get(right(index))); return false; } } boolean ret = true; for(E edge : heapMap.keySet()) { int index = heapMap.get(edge); if(edge != nodes.get(index)) { err.println("Expected to find " + edge + " at nodes[" + index + "] but I found " + nodes.get(index) + " which should have been at " + heapMap.get(nodes.get(index)) + " what I was looking for is at " + nodes.indexOf(edge)); ThickEdge e1 = (ThickEdge)edge; ThickEdge e2 = (ThickEdge)nodes.get(index); err.println(e1.getCi().getId() + " <=> " + e1.getCj().getId() + " = " + e1.getSeenDistances() + ", " + e1.getSeenEdges() + ", " + e1.getBound(0)); err.println(e2.getCi().getId() + " <=> " + e2.getCj().getId() + " = " + e2.getSeenDistances() + ", " + e2.getSeenEdges() + ", " + e2.getBound(0)); ret = false; } } for(E e : nodes) { if(!heapMap.containsKey(e)) { err.println("Failed to find e from nodes in the heap map..."); ThickEdge e1 = (ThickEdge)e; err.println(e1.getCi().getId() + " <=> " + e1.getCj().getId() + " = " + e1.getSeenDistances() + ", " + e1.getSeenEdges() + ", " + e1.getBound(0)); ret = false; } } if(!ret) { err.println("Nodes.size() = " + nodes.size()); err.println("heapMap.size() = " + heapMap.size()); } return ret; } public void print(PrintStream out) { this.print(out, 0, ""); } private void print(PrintStream out, int node, String indent) { if (node >= nodes.size()) { return; } out.println(indent + "node[" + node + "]=" + nodes.get(node)); print(out, left(node), indent + " "); print(out, right(node), indent + " "); } private static int parent(int node) { return (node - 1) / 2; } private static int left(int node) { return node * 2 + 1; } private static int right(int node) { return node * 2 + 2; } private static int sibling(int node) { if(node % 2 == 0) return node - 1; return node + 1; } } NightlyNexus/HqLighttts package com.nightlynexus.dokie.network.image; import android.graphics.Bitmap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.HONEYCOMB_MR1; import static android.os.Build.VERSION_CODES.KITKAT; public class LruCacheImage implements CacheImage { private static final float LOAD_FACTOR = 0.75f; private final LinkedHashMap mCache; private final int mMaxSize; private int mCurrentSize; public LruCacheImage(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("Max size must be positive"); } mCache = new LinkedHashMap(0, LOAD_FACTOR, true); mMaxSize = maxSize; mCurrentSize = 0; } @Override public Bitmap get(String key) { return mCache.get(key); } @Override public void set(String key, Bitmap bitmap) { mCurrentSize += getBitmapBytes(bitmap); boolean ableToCache = trim(); if (ableToCache) { mCache.put(key, bitmap); } } @Override public void clear() { mCache.clear(); mCurrentSize = 0; } private boolean trim() { while (mCurrentSize > mMaxSize) { Iterator> iterator = mCache.entrySet().iterator(); if (!iterator.hasNext()) { mCurrentSize = 0; return false; } Map.Entry toEvict = iterator.next(); mCache.remove(toEvict.getKey()); mCurrentSize -= getBitmapBytes(toEvict.getValue()); } return true; } private static int getBitmapBytes(Bitmap bitmap) { if (SDK_INT >= KITKAT) { return bitmap.getAllocationByteCount(); } else if (SDK_INT >= HONEYCOMB_MR1) { return bitmap.getByteCount(); } else { return bitmap.getRowBytes() * bitmap.getHeight(); } } } 10-100 /* * (C) Copyright [2018] Hewlett Packard Enterprise Development LP. * * 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. */ package com.niara.logger.listeners; import com.niara.logger.handlers.FileToLogReaderHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; public abstract class LogListener implements Runnable { private static Logger logger = LoggerFactory.getLogger(DirectoryWatcherListener.class); protected final CountDownLatch logListenerLatch; protected final FileToLogReaderHandler handler; public LogListener(final CountDownLatch logListenerLatch, final FileToLogReaderHandler handler) { this.logListenerLatch = logListenerLatch; this.handler = handler; } public abstract void init() throws Exception; public abstract void processEvent() throws Exception; public abstract void close() throws Exception; public void run() { try { init(); processEvent(); close(); } catch (Exception e) { logger.error("LogListener Exception: {}", e); } } } package com.example.d024mapboxevent; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PermissionsManager { private static final String LOG_TAG = "PermissionsManager"; private static final String COARSE_LOCATION_PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION; private static final String FINE_LOCATION_PERMISSION = Manifest.permission.ACCESS_FINE_LOCATION; private static final String BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION"; private final int REQUEST_PERMISSIONS_CODE = 0; private static PermissionsListener listener; public PermissionsManager(PermissionsListener listener) { this.listener = listener; } public PermissionsListener getListener() { return listener; } public void setListener(PermissionsListener listener) { this.listener = listener; } private static boolean isPermissionGranted(Context context, String permission) { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } private static boolean isCoarseLocationPermissionGranted(Context context) { return isPermissionGranted(context, COARSE_LOCATION_PERMISSION); } private static boolean isFineLocationPermissionGranted(Context context) { return isPermissionGranted(context, FINE_LOCATION_PERMISSION); } public static boolean isBackgroundLocationPermissionGranted(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { return isPermissionGranted(context, BACKGROUND_LOCATION_PERMISSION); } return areLocationPermissionsGranted(context); } public static boolean areLocationPermissionsGranted(Context context) { return isCoarseLocationPermissionGranted(context) || isFineLocationPermissionGranted(context); } public static boolean areRuntimePermissionsRequired() { return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } public static void requestLocationPermissions(Activity activity) { try { PackageInfo packageInfo = activity.getPackageManager().getPackageInfo( activity.getPackageName(), PackageManager.GET_PERMISSIONS); String[] requestedPermissions = packageInfo.requestedPermissions; if (requestedPermissions != null) { List permissionList = Arrays.asList(requestedPermissions); boolean fineLocPermission = permissionList.contains(FINE_LOCATION_PERMISSION); boolean coarseLocPermission = permissionList.contains(COARSE_LOCATION_PERMISSION); boolean backgroundLocPermission = permissionList.contains(BACKGROUND_LOCATION_PERMISSION); // Request location permissions if (fineLocPermission) { requestLocationPermissions(activity, true, backgroundLocPermission); } else if (coarseLocPermission) { requestLocationPermissions(activity, false, backgroundLocPermission); } else { } } } catch (Exception exception) { } } private static void requestLocationPermissions(Activity activity, boolean requestFineLocation, boolean requestBackgroundLocation) { List permissions = new ArrayList<>(); if (requestFineLocation) { permissions.add(FINE_LOCATION_PERMISSION); } else { permissions.add(COARSE_LOCATION_PERMISSION); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && requestBackgroundLocation) { permissions.add(BACKGROUND_LOCATION_PERMISSION); } requestPermissions(activity, permissions.toArray(new String[permissions.size()])); } private static void requestPermissions(Activity activity, String[] permissions) { ArrayList permissionsToExplain = new ArrayList<>(); for (String permission : permissions) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { permissionsToExplain.add(permission); } } if (listener != null && permissionsToExplain.size() > 0) { // The developer should show an explanation to the user asynchronously listener.onExplanationNeeded(permissionsToExplain); } ActivityCompat.requestPermissions(activity, permissions, 233); } /** * You should call this method from your activity onRequestPermissionsResult. * * @param requestCode The request code passed in requestPermissions(android.app.Activity, String[], int) * @param permissions The requested permissions. Never null. * @param grantResults The grant results for the corresponding permissions which is either * PERMISSION_GRANTED or PERMISSION_DENIED. Never null. */ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_PERMISSIONS_CODE: if (listener != null) { boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; listener.onPermissionResult(granted); } break; default: // Ignored } } } src/main/java/io/connectedhealth_idaas/eventbuilder/dataobjects/clinical/hl7/IPC.java package io.connectedhealth_idaas.eventbuilder.dataobjects.clinical.hl7; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; public class IPC { private String IPC_1_AccessionIdentifier; private String IPC_2_RequestedProcedureID; private String IPC_3_StudyInstanceUID; private String IPC_4_ScheduledProcedureStepID; private String IPC_5_Modality; private String IPC_6_ProtocolCode; private String IPC_7_ScheduledStationName; private String IPC_8_ScheduledProcedureStepLocation; private String IPC_9_ScheduledStationAETitle; public String getIPC_1_AccessionIdentifier() { return this.IPC_1_AccessionIdentifier; } public void setIPC_1_AccessionIdentifier(final String IPC_1_AccessionIdentifier) { this.IPC_1_AccessionIdentifier = IPC_1_AccessionIdentifier; } public String getIPC_2_RequestedProcedureID() { return this.IPC_2_RequestedProcedureID; } public void setIPC_2_RequestedProcedureID(final String IPC_2_RequestedProcedureID) { this.IPC_2_RequestedProcedureID = IPC_2_RequestedProcedureID; } public String getIPC_3_StudyInstanceUID() { return this.IPC_3_StudyInstanceUID; } public void setIPC_3_StudyInstanceUID(final String IPC_3_StudyInstanceUID) { this.IPC_3_StudyInstanceUID = IPC_3_StudyInstanceUID; } public String getIPC_4_ScheduledProcedureStepID() { return this.IPC_4_ScheduledProcedureStepID; } public void setIPC_4_ScheduledProcedureStepID(final String IPC_4_ScheduledProcedureStepID) { this.IPC_4_ScheduledProcedureStepID = IPC_4_ScheduledProcedureStepID; } public String getIPC_5_Modality() { return this.IPC_5_Modality; } public void setIPC_5_Modality(final String IPC_5_Modality) { this.IPC_5_Modality = IPC_5_Modality; } public String getIPC_6_ProtocolCode() { return this.IPC_6_ProtocolCode; } public void setIPC_6_ProtocolCode(final String IPC_6_ProtocolCode) { this.IPC_6_ProtocolCode = IPC_6_ProtocolCode; } public String getIPC_7_ScheduledStationName() { return this.IPC_7_ScheduledStationName; } public void setIPC_7_ScheduledStationName(final String IPC_7_ScheduledStationName) { this.IPC_7_ScheduledStationName = IPC_7_ScheduledStationName; } public String getIPC_8_ScheduledProcedureStepLocation() { return this.IPC_8_ScheduledProcedureStepLocation; } public void setIPC_8_ScheduledProcedureStepLocation(final String IPC_8_ScheduledProcedureStepLocation) { this.IPC_8_ScheduledProcedureStepLocation = IPC_8_ScheduledProcedureStepLocation; } public String getIPC_9_ScheduledStationAETitle() { return this.IPC_9_ScheduledStationAETitle; } public void setIPC_9_ScheduledStationAETitle(final String IPC_9_ScheduledStationAETitle) { this.IPC_9_ScheduledStationAETitle = IPC_9_ScheduledStationAETitle; } public String toString() { return ReflectionToStringBuilder.toString(this); } } package edu.neu.cs5200.repository; import edu.neu.cs5200.models.PortfolioManager; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; public interface PortfolioManagerRepository extends CrudRepository { @Query("SELECT pm FROM PortfolioManager pm WHERE pm.username=:username") Iterable findPortfolioManagerByUsername(@Param("username") String username); @Query("SELECT pm FROM PortfolioManager pm WHERE pm.username=:username AND pm.password=:password") Iterable findPortfolioManagerByCredentials( @Param("username") String username, @Param("password") String password); } src/test/java/pages/CareersRecruit.java0 package pages; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import static support.TestContext.*; public class CareersRecruit extends Page { @FindBy(xpath = "//h4[text() = 'New Position']") private WebElement newPosition; // dynamic element: private WebElement positionCard(String title){ return getDriver().findElement(By.xpath("//h4[text()='" + title + "']/../../..")); } private WebElement closeForPosition(String title){ return getDriver().findElement(By.xpath("//h4[text()='" + title + "']/../../..//button")); } public boolean isPositionVisible(String title){ try { return positionCard(title).isDisplayed(); }catch (NoSuchElementException e){ return false; } } public void remvePosition(String title){ WebElement card = positionCard(title); WebElement close = closeForPosition(title); getActions().moveToElement(card).perform(); close.click(); } public void waitForPositionDisappear(String title){ getWait().until(ExpectedConditions.invisibilityOf(positionCard(title))); } public void waitForPositionAppear(String title){ getWait().until(ExpectedConditions.visibilityOf(positionCard(title))); } public void openPosition(){ newPosition.click(); } } ivanshen/Who-Are-You-Really package org.jfree.chart.axis; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Line2D.Double; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; import org.jfree.chart.plot.Plot; import org.jfree.chart.util.AttrStringUtils; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.io.SerialUtilities; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; public abstract class ValueAxis extends Axis implements Cloneable, PublicCloneable, Serializable { public static final boolean DEFAULT_AUTO_RANGE = true; public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE = 1.0E-8d; public static final boolean DEFAULT_AUTO_TICK_UNIT_SELECTION = true; public static final boolean DEFAULT_INVERTED = false; public static final double DEFAULT_LOWER_BOUND = 0.0d; public static final double DEFAULT_LOWER_MARGIN = 0.05d; public static final Range DEFAULT_RANGE; public static final double DEFAULT_UPPER_BOUND = 1.0d; public static final double DEFAULT_UPPER_MARGIN = 0.05d; public static final int MAXIMUM_TICK_COUNT = 500; private static final long serialVersionUID = 3698345477322391456L; private boolean autoRange; private double autoRangeMinimumSize; private int autoTickIndex; private boolean autoTickUnitSelection; private Range defaultAutoRange; private transient Shape downArrow; private double fixedAutoRange; private boolean inverted; private transient Shape leftArrow; private double lowerMargin; private int minorTickCount; private boolean negativeArrowVisible; private boolean positiveArrowVisible; private Range range; private transient Shape rightArrow; private TickUnitSource standardTickUnits; private transient Shape upArrow; private double upperMargin; private boolean verticalTickLabels; protected abstract void autoAdjustRange(); public abstract double java2DToValue(double d, Rectangle2D rectangle2D, RectangleEdge rectangleEdge); public abstract double valueToJava2D(double d, Rectangle2D rectangle2D, RectangleEdge rectangleEdge); static { DEFAULT_RANGE = new Range(DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); } protected ValueAxis(String label, TickUnitSource standardTickUnits) { super(label); this.positiveArrowVisible = DEFAULT_INVERTED; this.negativeArrowVisible = DEFAULT_INVERTED; this.range = DEFAULT_RANGE; this.autoRange = DEFAULT_AUTO_TICK_UNIT_SELECTION; this.defaultAutoRange = DEFAULT_RANGE; this.inverted = DEFAULT_INVERTED; this.autoRangeMinimumSize = DEFAULT_AUTO_RANGE_MINIMUM_SIZE; this.lowerMargin = DEFAULT_UPPER_MARGIN; this.upperMargin = DEFAULT_UPPER_MARGIN; this.fixedAutoRange = DEFAULT_LOWER_BOUND; this.autoTickUnitSelection = DEFAULT_AUTO_TICK_UNIT_SELECTION; this.standardTickUnits = standardTickUnits; Polygon p1 = new Polygon(); p1.addPoint(0, 0); p1.addPoint(-2, 2); p1.addPoint(2, 2); this.upArrow = p1; Polygon p2 = new Polygon(); p2.addPoint(0, 0); p2.addPoint(-2, -2); p2.addPoint(2, -2); this.downArrow = p2; Polygon p3 = new Polygon(); p3.addPoint(0, 0); p3.addPoint(-2, -2); p3.addPoint(-2, 2); this.rightArrow = p3; Polygon p4 = new Polygon(); p4.addPoint(0, 0); p4.addPoint(2, -2); p4.addPoint(2, 2); this.leftArrow = p4; this.verticalTickLabels = DEFAULT_INVERTED; this.minorTickCount = 0; } public boolean isVerticalTickLabels() { return this.verticalTickLabels; } public void setVerticalTickLabels(boolean flag) { if (this.verticalTickLabels != flag) { this.verticalTickLabels = flag; fireChangeEvent(); } } public boolean isPositiveArrowVisible() { return this.positiveArrowVisible; } public void setPositiveArrowVisible(boolean visible) { this.positiveArrowVisible = visible; fireChangeEvent(); } public boolean isNegativeArrowVisible() { return this.negativeArrowVisible; } public void setNegativeArrowVisible(boolean visible) { this.negativeArrowVisible = visible; fireChangeEvent(); } public Shape getUpArrow() { return this.upArrow; } public void setUpArrow(Shape arrow) { ParamChecks.nullNotPermitted(arrow, "arrow"); this.upArrow = arrow; fireChangeEvent(); } public Shape getDownArrow() { return this.downArrow; } public void setDownArrow(Shape arrow) { ParamChecks.nullNotPermitted(arrow, "arrow"); this.downArrow = arrow; fireChangeEvent(); } public Shape getLeftArrow() { return this.leftArrow; } public void setLeftArrow(Shape arrow) { ParamChecks.nullNotPermitted(arrow, "arrow"); this.leftArrow = arrow; fireChangeEvent(); } public Shape getRightArrow() { return this.rightArrow; } public void setRightArrow(Shape arrow) { ParamChecks.nullNotPermitted(arrow, "arrow"); this.rightArrow = arrow; fireChangeEvent(); } protected void drawAxisLine(Graphics2D g2, double cursor, Rectangle2D dataArea, RectangleEdge edge) { double x; double y; Shape arrow; Line2D axisLine = null; double c = cursor; if (edge == RectangleEdge.TOP) { axisLine = new Double(dataArea.getX(), c, dataArea.getMaxX(), c); } else if (edge == RectangleEdge.BOTTOM) { axisLine = new Double(dataArea.getX(), c, dataArea.getMaxX(), c); } else if (edge == RectangleEdge.LEFT) { r9 = new Double(c, dataArea.getY(), c, dataArea.getMaxY()); } else if (edge == RectangleEdge.RIGHT) { r9 = new Double(c, dataArea.getY(), c, dataArea.getMaxY()); } g2.setPaint(getAxisLinePaint()); g2.setStroke(getAxisLineStroke()); Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.draw(axisLine); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); boolean drawUpOrRight = DEFAULT_INVERTED; boolean drawDownOrLeft = DEFAULT_INVERTED; if (this.positiveArrowVisible) { if (this.inverted) { drawDownOrLeft = DEFAULT_AUTO_TICK_UNIT_SELECTION; } else { drawUpOrRight = DEFAULT_AUTO_TICK_UNIT_SELECTION; } } if (this.negativeArrowVisible) { if (this.inverted) { drawUpOrRight = DEFAULT_AUTO_TICK_UNIT_SELECTION; } else { drawDownOrLeft = DEFAULT_AUTO_TICK_UNIT_SELECTION; } } if (drawUpOrRight) { x = DEFAULT_LOWER_BOUND; y = DEFAULT_LOWER_BOUND; arrow = null; if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) { x = dataArea.getMaxX(); y = cursor; arrow = this.rightArrow; } else if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) { x = cursor; y = dataArea.getMinY(); arrow = this.upArrow; } AffineTransform transformer = new AffineTransform(); transformer.setToTranslation(x, y); Shape shape = transformer.createTransformedShape(arrow); g2.fill(shape); g2.draw(shape); } if (drawDownOrLeft) { x = DEFAULT_LOWER_BOUND; y = DEFAULT_LOWER_BOUND; arrow = null; if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) { x = dataArea.getMinX(); y = cursor; arrow = this.leftArrow; } else if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) { x = cursor; y = dataArea.getMaxY(); arrow = this.downArrow; } transformer = new AffineTransform(); transformer.setToTranslation(x, y); shape = transformer.createTransformedShape(arrow); g2.fill(shape); g2.draw(shape); } } protected float[] calculateAnchorPoint(ValueTick tick, double cursor, Rectangle2D dataArea, RectangleEdge edge) { RectangleInsets insets = getTickLabelInsets(); float[] result = new float[2]; if (edge == RectangleEdge.TOP) { result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge); result[1] = (float) ((cursor - insets.getBottom()) - DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS); } else if (edge == RectangleEdge.BOTTOM) { result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge); result[1] = (float) ((insets.getTop() + cursor) + DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS); } else if (edge == RectangleEdge.LEFT) { result[0] = (float) ((cursor - insets.getLeft()) - DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS); result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge); } else if (edge == RectangleEdge.RIGHT) { result[0] = (float) ((insets.getRight() + cursor) + DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS); result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge); } return result; } protected AxisState drawTickMarksAndLabels(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge) { AxisState axisState = new AxisState(cursor); if (isAxisLineVisible()) { drawAxisLine(g2, cursor, dataArea, edge); } List ticks = refreshTicks(g2, axisState, dataArea, edge); axisState.setTicks(ticks); g2.setFont(getTickLabelFont()); Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); for (ValueTick tick : ticks) { if (isTickLabelsVisible()) { g2.setPaint(getTickLabelPaint()); float[] anchorPoint = calculateAnchorPoint(tick, cursor, dataArea, edge); if (tick instanceof LogTick) { LogTick lt = (LogTick) tick; if (lt.getAttributedLabel() != null) { AttrStringUtils.drawRotatedString(lt.getAttributedLabel(), g2, anchorPoint[0], anchorPoint[1], tick.getTextAnchor(), tick.getAngle(), tick.getRotationAnchor()); } } else if (tick.getText() != null) { TextUtilities.drawRotatedString(tick.getText(), g2, anchorPoint[0], anchorPoint[1], tick.getTextAnchor(), tick.getAngle(), tick.getRotationAnchor()); } } if ((isTickMarksVisible() && tick.getTickType().equals(TickType.MAJOR)) || (isMinorTickMarksVisible() && tick.getTickType().equals(TickType.MINOR))) { double ol; double il; if (tick.getTickType().equals(TickType.MINOR)) { ol = (double) getMinorTickMarkOutsideLength(); } else { ol = (double) getTickMarkOutsideLength(); } if (tick.getTickType().equals(TickType.MINOR)) { il = (double) getMinorTickMarkInsideLength(); } else { il = (double) getTickMarkInsideLength(); } float xx = (float) valueToJava2D(tick.getValue(), dataArea, edge); Line2D mark = null; g2.setStroke(getTickMarkStroke()); g2.setPaint(getTickMarkPaint()); if (edge == RectangleEdge.LEFT) { mark = new Double(cursor - ol, (double) xx, cursor + il, (double) xx); } else if (edge == RectangleEdge.RIGHT) { mark = new Double(cursor + ol, (double) xx, cursor - il, (double) xx); } else if (edge == RectangleEdge.TOP) { mark = new Double((double) xx, cursor - ol, (double) xx, cursor + il); } else if (edge == RectangleEdge.BOTTOM) { mark = new Double((double) xx, cursor + ol, (double) xx, cursor - il); } g2.draw(mark); } } g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); if (isTickLabelsVisible()) { if (edge == RectangleEdge.LEFT) { axisState.cursorLeft(DEFAULT_LOWER_BOUND + findMaximumTickLabelWidth(ticks, g2, plotArea, isVerticalTickLabels())); } else if (edge == RectangleEdge.RIGHT) { axisState.cursorRight(findMaximumTickLabelWidth(ticks, g2, plotArea, isVerticalTickLabels())); } else if (edge == RectangleEdge.TOP) { axisState.cursorUp(findMaximumTickLabelHeight(ticks, g2, plotArea, isVerticalTickLabels())); } else if (edge == RectangleEdge.BOTTOM) { axisState.cursorDown(findMaximumTickLabelHeight(ticks, g2, plotArea, isVerticalTickLabels())); } } return axisState; } public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) { if (space == null) { space = new AxisSpace(); } if (isVisible()) { double dimension = getFixedDimension(); if (dimension > DEFAULT_LOWER_BOUND) { space.add(dimension, edge); } else { double tickLabelHeight = DEFAULT_LOWER_BOUND; double tickLabelWidth = DEFAULT_LOWER_BOUND; if (isTickLabelsVisible()) { g2.setFont(getTickLabelFont()); List ticks = refreshTicks(g2, new AxisState(), plotArea, edge); if (RectangleEdge.isTopOrBottom(edge)) { tickLabelHeight = findMaximumTickLabelHeight(ticks, g2, plotArea, isVerticalTickLabels()); } else if (RectangleEdge.isLeftOrRight(edge)) { tickLabelWidth = findMaximumTickLabelWidth(ticks, g2, plotArea, isVerticalTickLabels()); } } Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge); if (RectangleEdge.isTopOrBottom(edge)) { space.add(labelEnclosure.getHeight() + tickLabelHeight, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { space.add(labelEnclosure.getWidth() + tickLabelWidth, edge); } } } return space; } protected double findMaximumTickLabelHeight(List ticks, Graphics2D g2, Rectangle2D drawArea, boolean vertical) { RectangleInsets insets = getTickLabelInsets(); Font font = getTickLabelFont(); g2.setFont(font); double maxHeight = DEFAULT_LOWER_BOUND; if (!vertical) { return (((double) font.getLineMetrics("ABCxyz", g2.getFontRenderContext()).getHeight()) + insets.getTop()) + insets.getBottom(); } FontMetrics fm = g2.getFontMetrics(font); for (Tick tick : ticks) { Rectangle2D labelBounds = null; if (tick instanceof LogTick) { LogTick lt = (LogTick) tick; if (lt.getAttributedLabel() != null) { labelBounds = AttrStringUtils.getTextBounds(lt.getAttributedLabel(), g2); } } else if (tick.getText() != null) { labelBounds = TextUtilities.getTextBounds(tick.getText(), g2, fm); } if (labelBounds != null && (labelBounds.getWidth() + insets.getTop()) + insets.getBottom() > maxHeight) { maxHeight = (labelBounds.getWidth() + insets.getTop()) + insets.getBottom(); } } return maxHeight; } protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2, Rectangle2D drawArea, boolean vertical) { RectangleInsets insets = getTickLabelInsets(); Font font = getTickLabelFont(); double maxWidth = DEFAULT_LOWER_BOUND; if (vertical) { return (((double) font.getLineMetrics("ABCxyz", g2.getFontRenderContext()).getHeight()) + insets.getTop()) + insets.getBottom(); } FontMetrics fm = g2.getFontMetrics(font); for (Tick tick : ticks) { Rectangle2D labelBounds = null; if (tick instanceof LogTick) { LogTick lt = (LogTick) tick; if (lt.getAttributedLabel() != null) { labelBounds = AttrStringUtils.getTextBounds(lt.getAttributedLabel(), g2); } } else if (tick.getText() != null) { labelBounds = TextUtilities.getTextBounds(tick.getText(), g2, fm); } if (labelBounds != null && (labelBounds.getWidth() + insets.getLeft()) + insets.getRight() > maxWidth) { maxWidth = (labelBounds.getWidth() + insets.getLeft()) + insets.getRight(); } } return maxWidth; } public boolean isInverted() { return this.inverted; } public void setInverted(boolean flag) { if (this.inverted != flag) { this.inverted = flag; fireChangeEvent(); } } public boolean isAutoRange() { return this.autoRange; } public void setAutoRange(boolean auto) { setAutoRange(auto, DEFAULT_AUTO_TICK_UNIT_SELECTION); } protected void setAutoRange(boolean auto, boolean notify) { if (this.autoRange != auto) { this.autoRange = auto; if (this.autoRange) { autoAdjustRange(); } if (notify) { fireChangeEvent(); } } } public double getAutoRangeMinimumSize() { return this.autoRangeMinimumSize; } public void setAutoRangeMinimumSize(double size) { setAutoRangeMinimumSize(size, DEFAULT_AUTO_TICK_UNIT_SELECTION); } public void setAutoRangeMinimumSize(double size, boolean notify) { if (size <= DEFAULT_LOWER_BOUND) { throw new IllegalArgumentException("NumberAxis.setAutoRangeMinimumSize(double): must be > 0.0."); } else if (this.autoRangeMinimumSize != size) { this.autoRangeMinimumSize = size; if (this.autoRange) { autoAdjustRange(); } if (notify) { fireChangeEvent(); } } } public Range getDefaultAutoRange() { return this.defaultAutoRange; } public void setDefaultAutoRange(Range range) { ParamChecks.nullNotPermitted(range, "range"); this.defaultAutoRange = range; fireChangeEvent(); } public double getLowerMargin() { return this.lowerMargin; } public void setLowerMargin(double margin) { this.lowerMargin = margin; if (isAutoRange()) { autoAdjustRange(); } fireChangeEvent(); } public double getUpperMargin() { return this.upperMargin; } public void setUpperMargin(double margin) { this.upperMargin = margin; if (isAutoRange()) { autoAdjustRange(); } fireChangeEvent(); } public double getFixedAutoRange() { return this.fixedAutoRange; } public void setFixedAutoRange(double length) { this.fixedAutoRange = length; if (isAutoRange()) { autoAdjustRange(); } fireChangeEvent(); } public double getLowerBound() { return this.range.getLowerBound(); } public void setLowerBound(double min) { if (this.range.getUpperBound() > min) { setRange(new Range(min, this.range.getUpperBound())); } else { setRange(new Range(min, DEFAULT_UPPER_BOUND + min)); } } public double getUpperBound() { return this.range.getUpperBound(); } public void setUpperBound(double max) { if (this.range.getLowerBound() < max) { setRange(new Range(this.range.getLowerBound(), max)); } else { setRange(max - DEFAULT_UPPER_BOUND, max); } } public Range getRange() { return this.range; } public void setRange(Range range) { setRange(range, DEFAULT_AUTO_TICK_UNIT_SELECTION, DEFAULT_AUTO_TICK_UNIT_SELECTION); } public void setRange(Range range, boolean turnOffAutoRange, boolean notify) { ParamChecks.nullNotPermitted(range, "range"); if (range.getLength() <= DEFAULT_LOWER_BOUND) { throw new IllegalArgumentException("A positive range length is required: " + range); } if (turnOffAutoRange) { this.autoRange = DEFAULT_INVERTED; } this.range = range; if (notify) { fireChangeEvent(); } } public void setRange(double lower, double upper) { setRange(new Range(lower, upper)); } public void setRangeWithMargins(Range range) { setRangeWithMargins(range, DEFAULT_AUTO_TICK_UNIT_SELECTION, DEFAULT_AUTO_TICK_UNIT_SELECTION); } public void setRangeWithMargins(Range range, boolean turnOffAutoRange, boolean notify) { ParamChecks.nullNotPermitted(range, "range"); setRange(Range.expand(range, getLowerMargin(), getUpperMargin()), turnOffAutoRange, notify); } public void setRangeWithMargins(double lower, double upper) { setRangeWithMargins(new Range(lower, upper)); } public void setRangeAboutValue(double value, double length) { setRange(new Range(value - (length / DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS), (length / DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS) + value)); } public boolean isAutoTickUnitSelection() { return this.autoTickUnitSelection; } public void setAutoTickUnitSelection(boolean flag) { setAutoTickUnitSelection(flag, DEFAULT_AUTO_TICK_UNIT_SELECTION); } public void setAutoTickUnitSelection(boolean flag, boolean notify) { if (this.autoTickUnitSelection != flag) { this.autoTickUnitSelection = flag; if (notify) { fireChangeEvent(); } } } public TickUnitSource getStandardTickUnits() { return this.standardTickUnits; } public void setStandardTickUnits(TickUnitSource source) { this.standardTickUnits = source; fireChangeEvent(); } public int getMinorTickCount() { return this.minorTickCount; } public void setMinorTickCount(int count) { this.minorTickCount = count; fireChangeEvent(); } public double lengthToJava2D(double length, Rectangle2D area, RectangleEdge edge) { return Math.abs(valueToJava2D(length, area, edge) - valueToJava2D(DEFAULT_LOWER_BOUND, area, edge)); } public void centerRange(double value) { double central = this.range.getCentralValue(); setRange(new Range((this.range.getLowerBound() + value) - central, (this.range.getUpperBound() + value) - central)); } public void resizeRange(double percent) { resizeRange(percent, this.range.getCentralValue()); } public void resizeRange(double percent, double anchorValue) { if (percent > DEFAULT_LOWER_BOUND) { double halfLength = (this.range.getLength() * percent) / DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS; setRange(new Range(anchorValue - halfLength, anchorValue + halfLength)); return; } setAutoRange(DEFAULT_AUTO_TICK_UNIT_SELECTION); } public void resizeRange2(double percent, double anchorValue) { if (percent > DEFAULT_LOWER_BOUND) { setRange(new Range(anchorValue - ((anchorValue - getLowerBound()) * percent), ((getUpperBound() - anchorValue) * percent) + anchorValue)); return; } setAutoRange(DEFAULT_AUTO_TICK_UNIT_SELECTION); } public void zoomRange(double lowerPercent, double upperPercent) { double r0; double r1; double start = this.range.getLowerBound(); double length = this.range.getLength(); if (isInverted()) { r0 = start + ((DEFAULT_UPPER_BOUND - upperPercent) * length); r1 = start + ((DEFAULT_UPPER_BOUND - lowerPercent) * length); } else { r0 = start + (length * lowerPercent); r1 = start + (length * upperPercent); } if (r1 > r0 && !Double.isInfinite(r1 - r0)) { setRange(new Range(r0, r1)); } } public void pan(double percent) { Range r = getRange(); double adj = this.range.getLength() * percent; setRange(r.getLowerBound() + adj, r.getUpperBound() + adj); } protected int getAutoTickIndex() { return this.autoTickIndex; } protected void setAutoTickIndex(int index) { this.autoTickIndex = index; } public boolean equals(Object obj) { if (obj == this) { return DEFAULT_AUTO_TICK_UNIT_SELECTION; } if (!(obj instanceof ValueAxis)) { return DEFAULT_INVERTED; } ValueAxis that = (ValueAxis) obj; if (this.positiveArrowVisible != that.positiveArrowVisible || this.negativeArrowVisible != that.negativeArrowVisible || this.inverted != that.inverted) { return DEFAULT_INVERTED; } if ((this.autoRange || ObjectUtilities.equal(this.range, that.range)) && this.autoRange == that.autoRange && this.autoRangeMinimumSize == that.autoRangeMinimumSize && this.defaultAutoRange.equals(that.defaultAutoRange) && this.upperMargin == that.upperMargin && this.lowerMargin == that.lowerMargin && this.fixedAutoRange == that.fixedAutoRange && this.autoTickUnitSelection == that.autoTickUnitSelection && ObjectUtilities.equal(this.standardTickUnits, that.standardTickUnits) && this.verticalTickLabels == that.verticalTickLabels && this.minorTickCount == that.minorTickCount) { return super.equals(obj); } return DEFAULT_INVERTED; } public Object clone() throws CloneNotSupportedException { return (ValueAxis) super.clone(); } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.upArrow, stream); SerialUtilities.writeShape(this.downArrow, stream); SerialUtilities.writeShape(this.leftArrow, stream); SerialUtilities.writeShape(this.rightArrow, stream); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.upArrow = SerialUtilities.readShape(stream); this.downArrow = SerialUtilities.readShape(stream); this.leftArrow = SerialUtilities.readShape(stream); this.rightArrow = SerialUtilities.readShape(stream); } } package io.gomint.entity.monster; import io.gomint.GoMint; import io.gomint.entity.EntityAgeable; /** * @author KingAli * @version 1.0 * @stability 3 */ public interface EntityHoglin extends EntityAgeable { /** * Create a new entity hoglin with no config * * @return empty, fresh zombie hoglin */ static EntityHoglin create() { return GoMint.instance().createEntity( EntityHoglin.class ); } } package com.scloudic.jsuite.log.aspects; import com.scloudic.jsuite.log.annotation.Log; import com.scloudic.jsuite.log.annotation.LogParamExclude; import com.scloudic.jsuite.log.model.LogBean; import com.scloudic.jsuite.log.notification.OperateLogEvent; import com.scloudic.rabbitframework.core.notification.NotificationServerManager; import com.scloudic.rabbitframework.core.utils.JsonUtils; import com.scloudic.rabbitframework.core.utils.StringUtils; import com.scloudic.rabbitframework.security.SecurityUser; import com.scloudic.rabbitframework.security.SecurityUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; /** * 操作日志拦截 */ @Aspect public class OperateLogInterceptor { private static final Logger logger = LoggerFactory.getLogger(OperateLogInterceptor.class); private NotificationServerManager notificationServerManager; private boolean saveSelect = false; private boolean saveStat = false; private boolean saveCurd = true; private boolean export = false; private boolean importOperate = false; public void setNotificationServerManager(NotificationServerManager notificationServerManager) { this.notificationServerManager = notificationServerManager; } @Pointcut("@annotation(com.scloudic.jsuite.log.annotation.Log)") public void formAnnotatedMethod() { } @AfterReturning(value = "formAnnotatedMethod()", returning = "returnValue") public void doInterceptor(JoinPoint pjp, Object returnValue) { try { Object[] args = pjp.getArgs(); Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); Log operationLog = method.getAnnotation(Log.class); String methodName = method.getDeclaringClass().getName() + "." + method.getName(); Map paramsValue = new LinkedHashMap<>(); Parameter[] parameters = method.getParameters(); int parameterLength = 0; if (parameters != null) { parameterLength = parameters.length; } String ip = ""; String operateSource = ""; String clientVersion = ""; for (int i = 0; i < parameterLength; i++) { Parameter parameter = parameters[i]; Object value = args[i]; if (value instanceof HttpServletResponse) { continue; } if (value instanceof HttpServletRequest) { continue; } Annotation[] annotations = parameter.getAnnotations(); LogParamExclude logParamExclude = parameter.getAnnotation(LogParamExclude.class); if (logParamExclude != null) { continue; } boolean isExclude = isExclude(annotations); if (isExclude) { continue; } paramsValue.put(parameter.getName(), value); } HttpServletRequest request = (HttpServletRequest) RequestContextHolder.currentRequestAttributes() .resolveReference(RequestAttributes.REFERENCE_REQUEST); if (request != null) { ip = getRemoteAddr(request); operateSource = getOperatorSource(request); clientVersion = getClientVersion(request); } LogBean operateLog = new LogBean(); if (paramsValue.size() > 0) { operateLog.setContent(JsonUtils.toJson(paramsValue, true, true)); } String userId = ""; String loginName = ""; String userName = ""; SecurityUser securityUser = SecurityUtils.getSecurityUser(); if (securityUser != null) { userId = securityUser.getUserId(); loginName = securityUser.getLoginName(); userName = securityUser.getNickName(); } operateLog.setIpAddress(ip); operateLog.setOperateSource(operateSource); operateLog.setUserId(userId); operateLog.setLoginName(loginName); operateLog.setUserName(userName); operateLog.setClientVersion(clientVersion); operateLog.setLogRemark(operationLog.remark()); operateLog.setOperateType(operationLog.operatorType().value); operateLog.setCreateTime(new Date()); operateLog.setMethodFullName(methodName); operateLog.setMethodName(method.getName()); if (returnValue != null) { try { operateLog.setReturnResult(JsonUtils.toJson(returnValue, true, true)); } catch (Exception e) { operateLog.setReturnResult("error:" + e.getMessage()); } } logger.debug("打印操作日志:" + JsonUtils.toJson(operateLog)); boolean sendFlag = false; switch (operationLog.operatorType()) { case LOGIN: case DEL: case UPDATE: case ADD: if (isSaveCurd()) { sendFlag = true; } break; case STAT: if (isSaveStat()) { sendFlag = true; } break; case SELECT: if (isSaveSelect()) { sendFlag = true; } case EXPORT: if (isExport()) { sendFlag = true; } break; case IMPORT: if (isImportOperate()) { sendFlag = true; } break; } if (sendFlag) { notificationServerManager.fireEvent(new OperateLogEvent(operateLog, 0)); } } catch (Exception e) { logger.warn("operatorLogInterceptorError:" + e.getMessage(), e); } } private boolean isExclude(Annotation[] annotations) { int annotationsLength = annotations.length; boolean result = false; for (int i = 0; i < annotationsLength; i++) { Annotation annotation = annotations[i]; if ("javax.ws.rs.core.Context".equals(annotation.annotationType().getName())) { result = true; break; } } return result; } private final String getRemoteAddr(HttpServletRequest request) { String ipAddress = request.getHeader("x-forwarded-for"); if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); } //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (StringUtils.isNotBlank(ipAddress) && ipAddress.length() > 15) { //"***.***.***.***".length() = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); return ipAddress; } else if (ipAddress.length() == 15) { return ipAddress; } } ipAddress = request.getHeader("X-Real-IP"); if (StringUtils.isNotEmpty(ipAddress) && !"unKnown".equalsIgnoreCase(ipAddress)) { return ipAddress; } return request.getRemoteAddr(); } private String getOperatorSource(HttpServletRequest request) { String operateSource = request.getHeader("ClientSource"); if (StringUtils.isBlank(operateSource)) { operateSource = ""; } return operateSource; } private String getClientVersion(HttpServletRequest request) { String operateSource = request.getHeader("ClientVersion"); if (StringUtils.isBlank(operateSource)) { operateSource = ""; } return operateSource; } private static boolean isUnAvailableIp(String ip) { return (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)); } public boolean isSaveSelect() { return saveSelect; } public void setSaveSelect(boolean saveSelect) { this.saveSelect = saveSelect; } public boolean isSaveStat() { return saveStat; } public void setSaveStat(boolean saveStat) { this.saveStat = saveStat; } public boolean isSaveCurd() { return saveCurd; } public boolean isExport() { return export; } public void setExport(boolean export) { this.export = export; } public boolean isImportOperate() { return importOperate; } public void setImportOperate(boolean importOperate) { this.importOperate = importOperate; } public void setSaveCurd(boolean saveCurd) { this.saveCurd = saveCurd; } } public static void main(String[] args) { StringBuffer sb = new StringBuffer("{{{a}}}b{{{c}}}"); Pattern p = Pattern.compile("\\{\\{\\{.*?\\}\\}\\}"); Matcher m = p.matcher(sb); while (m.find()) { String s = sb.substring(m.start(), m.end()); System.out.println(s); } } sascha-frinken/micronaut-oauth2oauth2/src/main/java/io/micronaut/security/oauth2/configuration/OauthConfigurationProperties.java0 /* * Copyright 2017-2019 original authors * * 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. */ package io.micronaut.security.oauth2.configuration; import io.micronaut.context.annotation.ConfigurationProperties; import io.micronaut.context.annotation.Requires; import io.micronaut.security.config.SecurityConfigurationProperties; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * {@link io.micronaut.context.annotation.ConfigurationProperties} implementation of {@link io.micronaut.security.oauth2.configuration.OauthConfiguration}. * * @author * @since 1.0.0 */ @Requires(property = OauthConfigurationProperties.PREFIX + ".client-id") @ConfigurationProperties(OauthConfigurationProperties.PREFIX) public class OauthConfigurationProperties implements OauthConfiguration { public static final String PREFIX = SecurityConfigurationProperties.PREFIX + ".oauth2"; @Nonnull private String clientId; @Nullable private String clientSecret; /** * OAuth 2.0 Application Client ID. * @param clientId The application's Client ID. */ public void setClientId(@Nonnull String clientId) { this.clientId = clientId; } /** * OAuth 2.0 Application Client Secret. Optional. * @param clientSecret The application's Client Secret. */ public void setClientSecret(@Nullable String clientSecret) { this.clientSecret = clientSecret; } /** * * @return the application's Client identifier */ @Nonnull @Override public String getClientId() { return clientId; } /** * @return the application's Client secret */ @Nullable @Override public String getClientSecret() { return clientSecret; } } parallelism/src/main/java/io/parallelism/ExampleFutures.java0 package io.parallelism; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; public class ExampleFutures { public static void deployVerticleWithoutLoop(int i) { // think on Promise as producer (used by producer on one side of async operation) and Future as consumer (used by consumer on the other side). Promise promise = Promise.promise(); Future future = promise.future(); Vertx vertx = Vertx.vertx(); vertx.deployVerticle(new BasicVerticle(), stringAsyncResult -> { if (stringAsyncResult.succeeded()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Basic Verticle deployment complete " + i); } else if (stringAsyncResult.failed()) { System.out.println("Basic Verticle deployment failed " + i); System.exit(1); } promise.handle(stringAsyncResult); }); while(!future.isComplete()) { System.out.println("Complete? -> " + i + " - " + future.isComplete()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void deployVerticleWithLoop() { for (int i = 0; i < 10; i++) { deployVerticleWithoutLoop(i); } } public static void main(String[] args) { deployVerticleWithLoop(); } } src/main/java/com/compomics/util/pride/prideobjects/Sample.java package com.compomics.util.pride.prideobjects; import com.compomics.util.experiment.personalization.ExperimentObject; import com.compomics.util.pride.CvTerm; import com.compomics.util.pride.PrideObject; import java.util.ArrayList; import java.util.Arrays; /** * An object for storing Sample details. * * @author */ public class Sample extends ExperimentObject implements PrideObject { /** * Empty default constructor */ public Sample() { } /** * The sample name. */ private String name; /** * The list of CV terms. */ private ArrayList cvTerms; /** * Create a new Sample object. * * @param name the name * @param cvTerms the CV terms */ public Sample(String name, ArrayList cvTerms) { this.name = name; this.cvTerms = cvTerms; } /** * Returns the name of the sample. * * @return the name */ public String getName() { return name; } /** * Set the name of the sample. * * @param name the name to set */ public void setName(String name) { this.name = name; } /** * Returns the CV terms. * * @return the cvTerms */ public ArrayList getCvTerms() { return cvTerms; } /** * Set the CV terms. * * @param cvTerms the cvTerms to set */ public void setCvTerms(ArrayList cvTerms) { this.cvTerms = cvTerms; } /** * Returns a list of default samples. * * @return a list of default samples */ public static ArrayList getDefaultSamples() { ArrayList result = new ArrayList<>(); result.add(new Sample("Example sample set", new ArrayList<>(Arrays.asList( new CvTerm("NEWT", "9606", "Homo sapiens (Human)", null), new CvTerm("BTO", "BTO:0000763", "lung", null), new CvTerm("BTO", "BTO:0000762", "lung cancer cell line", null))))); return result; } public String getFileName() { return name; } } src/main/java/eu/metrics/spring/reporter/InfluxDBReporterFactoryBean.java0 /** * Copyright (C) 2018 () * * 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. */ package eu.metrics.spring.reporter; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.kickstarter.dropwizard.metrics.influxdb.InfluxDbMeasurementReporter; import com.kickstarter.dropwizard.metrics.influxdb.io.InfluxDbHttpWriter; import com.kickstarter.dropwizard.metrics.influxdb.io.InfluxDbTcpWriter; import com.kickstarter.dropwizard.metrics.influxdb.io.InfluxDbWriter; import com.kickstarter.dropwizard.metrics.influxdb.io.Sender; import com.kickstarter.dropwizard.metrics.influxdb.transformer.DropwizardMeasurementParser; import com.kickstarter.dropwizard.metrics.influxdb.transformer.DropwizardTransformer; import com.kickstarter.dropwizard.metrics.influxdb.transformer.TaggedPattern; import com.ryantenney.metrics.spring.reporter.AbstractScheduledReporterFactoryBean; import eu.metrics.spring.TagProviderBean; import eu.metrics.spring.TemplateProviderBean; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.client.JerseyClientConfiguration; import io.dropwizard.util.Duration; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.time.Clock; import java.util.Collections; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.ws.rs.client.Client; /** * Factory bean used by the metrics-spring component. */ public final class InfluxDBReporterFactoryBean extends AbstractScheduledReporterFactoryBean { // Required public static final String PERIOD = "period"; public static final String DATABASE = "database"; public static final String LAYER = "layer"; // Optional public static final String HOST = "host"; public static final String PORT = "port"; public static final String DURATION_UNIT = "duration-unit"; public static final String RATE_UNIT = "rate-unit"; public static final String GROUP_COUNTERS = "group-counters"; public static final String GROUP_GAUGES = "group-gauges"; public static final String TAG_PROVIDER_REF = "tag-provider"; public static final String TEMPLATE_PROVIDER_REF = "template-provider"; public static final String FILTER_PATTERN = "filter"; // Field is protected in parent class !? public static final String FILTER_REF = "filter-ref"; // Field is protected in parent class !? @Override protected long getPeriod() { return convertDurationString(getProperty(PERIOD)); } @Override public Class getObjectType() { return InfluxDbMeasurementReporter.class; } @Override protected InfluxDbMeasurementReporter createInstance() throws Exception { MetricRegistry registry = getMetricRegistry(); InfluxDbWriter dbWriter = null; String layer = getProperty(LAYER); String database = getProperty(DATABASE); String host = getProperty(HOST, "localhost"); int port = Integer.valueOf(getProperty(PORT, "8086")); if (layer.equals("http")) { Client client = new JerseyClientBuilder(registry) .using(new JerseyClientConfiguration()) .using(new ObjectMapper()) .using(Executors.newSingleThreadExecutor()) .build("influxdb-http-writer"); try { final String query = "/write?db=" + URLEncoder.encode(database, "UTF-8"); final URL endpoint = new URL("http", host, port, query); dbWriter = new InfluxDbHttpWriter(client, endpoint.toString()); } catch (MalformedURLException | UnsupportedEncodingException ex) { throw new IllegalArgumentException(ex); } } else { dbWriter = new InfluxDbTcpWriter(host, port, Duration.milliseconds(500)); // TODO timeout configuration } Sender sender = new Sender(dbWriter); TimeUnit durationUnit = TimeUnit.MILLISECONDS; if (hasProperty(DURATION_UNIT)) { durationUnit = getProperty(DURATION_UNIT, TimeUnit.class); } TimeUnit rateUnit = TimeUnit.SECONDS; if (hasProperty(RATE_UNIT)) { rateUnit = getProperty(RATE_UNIT, TimeUnit.class); } boolean groupCounters = getProperty(GROUP_COUNTERS, Boolean.class, Boolean.FALSE); boolean groupGauges = getProperty(GROUP_GAUGES, Boolean.class, Boolean.FALSE); TagProviderBean tagProvider = getPropertyRef(TAG_PROVIDER_REF, TagProviderBean.class); Map globalTags = tagProvider != null ? tagProvider.getTags() : Collections.EMPTY_MAP; TemplateProviderBean templateProvider = getPropertyRef(TEMPLATE_PROVIDER_REF, TemplateProviderBean.class); Map metricTemplates = templateProvider != null ? templateProvider.getTemplates() : Collections.EMPTY_MAP; DropwizardTransformer transformer = new DropwizardTransformer( globalTags, DropwizardMeasurementParser.withTemplates(metricTemplates), groupCounters, groupGauges, rateUnit, durationUnit ); return new InfluxDbMeasurementReporter( sender, registry, getMetricFilter(), rateUnit, durationUnit, Clock.systemUTC(), transformer ); } } 10-100 package thut.api.entity; import javax.annotation.Nullable; import net.minecraft.entity.AgeableEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; /** * This interface is used for mobs which can breed with other mobs. * * @author Thutmose */ public interface IBreedingMob { AgeableEntity getEntity(); default boolean canMate(final AgeableEntity AnimalEntity) { return false; } /** * Will be called by the mother before she lays to know what baby to put in * the egg. * * @param male * the male * @return the pokedex number of the child */ default Object getChild(final IBreedingMob male) { return null; } /** @return the byte sexe */ default byte getSexe() { return -1; } default void mateWith(final IBreedingMob male) { } /** resets the status of being in love */ default void resetLoveStatus() { } default void setReadyToMate(@Nullable final PlayerEntity cause) { } @Nullable default ServerPlayerEntity getCause() { return null; } /** * @param sexe * the byte sexe */ default void setSexe(final byte sexe) { } default void tickBreedDelay(final int tickAmount) { } default boolean canBreed() { return false; } default boolean isBreeding() { return false; } } package com.snobot.simulator.module_wrappers; import com.snobot.simulator.jni.module_wrapper.RelayWrapperJni; import com.snobot.simulator.module_wrapper.interfaces.IRelayWrapper; public class RelayWrapper implements IRelayWrapper { private final int mHandle; public RelayWrapper(int aPort, String aType) { mHandle = aPort; RelayWrapperJni.createSimulator(aPort, aType); } public RelayWrapper(int aHandle) { mHandle = aHandle; } @Override public boolean isInitialized() { return RelayWrapperJni.isInitialized(mHandle); } @Override public void setInitialized(boolean aInitialized) { throw new UnsupportedOperationException(); } @Override public void close() { RelayWrapperJni.removeSimluator(mHandle); } @Override public void setName(String aName) { RelayWrapperJni.setName(mHandle, aName); } @Override public String getName() { return RelayWrapperJni.getName(mHandle); } @Override public boolean getWantsHidden() { return RelayWrapperJni.getWantsHidden(mHandle); } @Override public boolean getRelayForwards() { return RelayWrapperJni.getFowardValue(mHandle); } @Override public void setRelayReverse(boolean aReverse) { throw new UnsupportedOperationException(); } @Override public void setRelayForwards(boolean aForwards) { throw new UnsupportedOperationException(); } @Override public boolean getRelayReverse() { return RelayWrapperJni.getReverseValue(mHandle); } @Override public void setWantsHidden(boolean aVisible) { throw new UnsupportedOperationException(); } @Override public String getType() { return null; } } package ny2.kdbjfxviewer.menu; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.chart.XYChart.Series; import javafx.scene.control.ComboBox; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.ToggleButton; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import ny2.kdbjfxviewer.kdb.KdbDao; import ny2.kdbjfxviewer.kdb.KdbUtils; import ny2.kdbjfxviewer.util.DialogUtils; import ny2.kdbjfxviewer.util.SystemUtility; @Scope("prototype") @Component public class PollingViewerController { // ////////////////////////////////////// // Field // ////////////////////////////////////// private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private KdbDao kdbDao; // // FXML // @FXML private ToggleButton pollingToggle; @FXML private ComboBox pollingTimeCombo; @FXML private TextArea queryArea; @FXML private TableView> tableView; @FXML private AnchorPane chartPane; // @FXML // private LineChart chart; // // Others // private Service pollingService; // ////////////////////////////////////// // Initialize // ////////////////////////////////////// @FXML public void initialize() { logger.info("{} initializd.", getClass().getSimpleName()); // pollingTimeCombo pollingTimeCombo.getItems().addAll(1, 2, 5, 10, 30, 60, 300); pollingTimeCombo.getSelectionModel().select(Integer.valueOf(5)); // polling service pollingService = new Service() { @Override protected Task createTask() { Task task = new Task() { @Override protected Void call() throws Exception { while (true) { // Stop if (!pollingToggle.isSelected()) { break; } Integer pollingTime = pollingTimeCombo.getSelectionModel().getSelectedItem(); if (pollingTime > 0) { SystemUtility.waitSleep(pollingTime * 1000); logger.info("Task executed."); Platform.runLater(() -> executeQueryInternal()); } else { DialogUtils.showWarnDialog("Polling time must be over 0."); break; } } return null; } }; return task; } }; } // ////////////////////////////////////// // Method // ////////////////////////////////////// @FXML void executePolling(ActionEvent event) { if (pollingToggle.isSelected()) { DialogUtils.showInformationDialog("Is selected."); pollingService.restart(); } } // Event Listener on TextArea[#queryArea].onKeyPressed @FXML public void executeQuery(KeyEvent event) { // Execute Query on Ctrl+Enter if (event.getCode() == KeyCode.ENTER && event.isControlDown()) { executeQueryInternal(); createChart(); } } /** * Execute Query * @return */ private boolean executeQueryInternal() { String query = queryArea.getText(); if (!StringUtils.isBlank(query)) { logger.info("execute query. {}", query.length() <= 100 ? query : query.substring(0, 101)); Object res = kdbDao.query(query); KdbUtils.convertQResuktToTableView(tableView, res); return true; } else { DialogUtils.showWarnDialog("Query is not set."); return false; } } /** * Create Chart */ private void createChart() { CategoryAxis xAxis = new CategoryAxis(); NumberAxis yAxis = new NumberAxis(); LineChart lineChart = new LineChart(xAxis, yAxis); ObservableList> seriesList = FXCollections.observableArrayList(); Series series1 = new Series<>(); Series series2 = new Series<>(); Series series3 = new Series<>(); Series series4 = new Series<>(); series1.setName("Series1"); series2.setName("Series2"); series3.setName("Series3"); series4.setName("Series4"); ObservableList> items = tableView.getItems(); for (int i = 0; i < items.size(); i++) { ObservableList item = items.get(i); series1.getData().add(new XYChart.Data(item.get(0).toString(), item.get(1))); series2.getData().add(new XYChart.Data(item.get(0).toString(), item.get(2))); series3.getData().add(new XYChart.Data(item.get(0).toString(), item.get(3))); series4.getData().add(new XYChart.Data(item.get(0).toString(), item.get(4))); } seriesList.addAll(series1, series2, series3, series4); lineChart.setData(seriesList); chartPane.getChildren().add(lineChart); } // private void setupTable(QTable qTable) { // // Add Listener // tableView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { // System.out.println(observable.toString() + " chosen in TableView"); // }); // } } package com.ryg.chapter_4; import com.ryg.chapter_4.R; import android.app.Activity; import android.os.Bundle; public class DemoActivity_1 extends Activity { private static final String TAG = "DemoActivity_1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_1); initView(); } private void initView() { } } 10-100 package ru.job4j.tictactoe.logic; import ru.job4j.tictactoe.InvalidActionException; import java.util.function.Predicate; /** * Реализация логики игры для поля размером 3*3 * * @author () * @since 09.09.2019 */ public class Logic3T implements Logic { /** * Размер поля. */ private int size; /** * Массив содержит игровое поле. */ private String[][] table; /** * Счетчик ходов. */ private int moveCounter = 0; /** * Поле хранит победителя (x или o). */ private String winner; /** * Конструктор, инициализирует игровое поле нужного размера * @param size размер игрового поля. */ public Logic3T(int size) { this.size = size; this.table = new String[size][size]; } /** * Начинает новую игру. * очищает поле, сбрасывает победителя */ @Override public void newGame() { this.moveCounter = 0; this.table = new String[this.size][this.size]; this.winner = null; } /** * Возвращает размер игрового поля */ @Override public int getTableSize() { return this.size; } /** * Возвращает количество совершенных ходов */ @Override public int getNumberOfMoves() { return this.moveCounter; } /** * Возвращает значение заданной клетки поля * @param cell клетка * @return символ в клетке */ @Override public String getMark(Cell cell) throws InvalidActionException { int size = table.length; if (cell.getX() >= size || cell.getY() >= size) { throw new InvalidActionException(String.format("Размер поля %s на %s, повторите ввод", size, size)); } return table[cell.getX()][cell.getY()]; } /** * Выполняет ход: * проверяет, свободна ли заданная клетка * если свободна - ставит в ней заданную отметку * @param cell клетка * @param mark символ в клетке */ @Override public void makeMove(Cell cell, String mark) throws InvalidActionException { String markCell = getMark(cell); if (markCell != null) { throw new InvalidActionException(String.format("Клетка (%s;%s) занята, повторите ввод", cell.getX(), cell.getY())); } else { table[cell.getX()][cell.getY()] = mark; moveCounter++; } } /** * Проверяет допустимое количество ходов. * @return возможность хода. */ @Override public boolean checkPossibleOfMove() { return moveCounter < table.length * table.length; } /** * Проверяет, кто победил, * если игрок заполнил полностью вертикаль, горизонталь или диагональ. * @return победитель "x" или "o", либо null. */ @Override public String checkWinner() { if (isWinnerX()) { winner = "x"; } else if (isWinnerO()) { winner = "o"; } return winner; } /** * Проверяет победу x. * @return x победили. */ public boolean isWinnerX() { return this.isWinner("x"::equals); } /** * Проверяет победу o. * @return o победили. */ public boolean isWinnerO() { return this.isWinner("o"::equals); } /** * Проверяет все вертикали, горизонтали и диагоняли поля на соответствие предикату. * * @param predicate - задает условие проверки (x или o). * @return наличие линии символов, соответствющих предикату. */ private boolean isWinner(Predicate predicate) { return this.fillBy(predicate, 0, 0, 1, 0) || this.fillBy(predicate, 0, 1, 1, 0) || this.fillBy(predicate, 0, 2, 1, 0) || this.fillBy(predicate, 0, 0, 0, 1) || this.fillBy(predicate, 1, 0, 0, 1) || this.fillBy(predicate, 2, 0, 0, 1) || this.fillBy(predicate, 0, 0, 1, 1) || this.fillBy(predicate, this.table.length - 1, 0, -1, 1); } /** * Проверяет все символы в линии на соответствие предикату. * * @param predicate задает условие проверки (x или o). * @param startX начальная координата по оси x * @param startY начальная координата по оси y * @param deltaX инкремент по оси x * @param deltaY инкремент по оси y * @return наличие линии символов, соответствющих предикату. */ public boolean fillBy(Predicate predicate, int startX, int startY, int deltaX, int deltaY) { boolean result = true; for (int i = 0; i != this.table.length; i++) { String cell = this.table[startX][startY]; startX += deltaX; startY += deltaY; if (!predicate.test(cell)) { result = false; break; } } return result; } } package com.javabydeveloper.util; public enum ContactType { LAND_LINE, OFFICE, MOBILE } package com.hys.exam.model; import java.io.Serializable; public class CvUnitRefQuality implements Serializable{ private static final long serialVersionUID = -517234630532590888L; private Long unit_id ; private Long prop_id ; private Integer level ; private Integer state ; private Long parent_prop_id ; public Long getUnit_id() { return unit_id; } public void setUnit_id(Long unit_id) { this.unit_id = unit_id; } public Long getProp_id() { return prop_id; } public void setProp_id(Long prop_id) { this.prop_id = prop_id; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Long getParent_prop_id() { return parent_prop_id; } public void setParent_prop_id(Long parent_prop_id) { this.parent_prop_id = parent_prop_id; } } package com.rizki.mufrizal.spring.oauth2.custom.service; import com.rizki.mufrizal.spring.oauth2.custom.domain.Mahasiswa; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * * @Author <> * @Web * @Since Feb 5, 2017 * @Time 7:24:23 PM * @Encoding UTF-8 * @Project Spring-OAuth2-Custom * @Package com.rizki.mufrizal.spring.oauth2.custom.service * */ public interface MahasiswaService { public void saveMahasiswa(Mahasiswa mahasiswa); public void updateMahasiswa(Mahasiswa mahasiswa); public void deleteMahasiswa(String idMahasiswa); public Mahasiswa getMahasiswa(String idMahasiswa); public Page getMahasiswas(Pageable pageable); } package com.custom.keyboard.util; import android.graphics.Color; import java.lang.reflect.Field; public class ColorUtils { // color public static Color invertColor(Color color) { color.red((int)(255-color.red())); color.blue((int)(255-color.blue())); color.green((int)(255-color.green())); return color; } public static int invertColor(int color) { return (0x00FFFFFF - (color | 0xFF000000)) | (color & 0xFF000000); } public static String toColor(int r, int g, int b) { String rs = StringUtils.padLeft(Integer.toHexString(r), 2, "0").toUpperCase(); String gs = StringUtils.padLeft(Integer.toHexString(g), 2, "0").toUpperCase(); String bs = StringUtils.padLeft(Integer.toHexString(b), 2, "0").toUpperCase(); return "#" + rs + gs + bs; } public static String toColor(int a, int r, int g, int b) { String as = StringUtils.padLeft(Integer.toHexString(a), 2, "0").toUpperCase(); String rs = StringUtils.padLeft(Integer.toHexString(r), 2, "0").toUpperCase(); String gs = StringUtils.padLeft(Integer.toHexString(g), 2, "0").toUpperCase(); String bs = StringUtils.padLeft(Integer.toHexString(b), 2, "0").toUpperCase(); return "#" + as + rs + gs + bs; } public static Color stringToColor(String value) { if (value == null) { return Color.valueOf(Color.BLACK); } try { // get color by hex or octal value return Color.valueOf(Color.parseColor(value)); } catch (NumberFormatException nfe) { // if we can't decode lets try to get it by name try { // try to get a color by name using reflection final Field f = Color.class.getField(value); return (Color)f.get(null); } catch (Exception ce) { // if we can't get any color return black return Color.valueOf(Color.BLACK); } } } public static String colorToString(Color color) { return String.format("#%08X", color.toArgb()); } public static int[] fromColor(String color) { color = color.toUpperCase(); String as, rs, gs, bs; int ai, ri, gi, bi; if (color.length() == 6) { as = "FF"; rs = color.substring(0, 2); gs = color.substring(2, 4); bs = color.substring(4, 6); } else if (color.length() == 8) { as = color.substring(0, 2); rs = color.substring(2, 4); bs = color.substring(4, 6); gs = color.substring(6, 8); } else { return null; } ai = Integer.decode("0x" + as); ri = Integer.decode("0x" + rs); gi = Integer.decode("0x" + gs); bi = Integer.decode("0x" + bs); return new int[]{ai, ri, gi, bi}; } } package com.crystallang.psi; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.crystallang.CrystalFileType; /** * Created by benoist, 06/02/2017 */ public class CrystalElementFactory { public static CrystalProperty createProperty(Project project, String name, String value) { final CrystalFile file = createFile(project, name + " = " + value); return (CrystalProperty) file.getFirstChild(); } public static CrystalProperty createProperty(Project project, String name) { final CrystalFile file = createFile(project, name); return (CrystalProperty) file.getFirstChild(); } public static PsiElement createCRLF(Project project) { final CrystalFile file = createFile(project, "\n"); return file.getFirstChild(); } public static CrystalFile createFile(Project project, String text) { String name = "dummy.cr"; return (CrystalFile) PsiFileFactory.getInstance(project). createFileFromText(name, CrystalFileType.INSTANCE, text); } }import java.util.Scanner; public class CircleAreaAndPerimeter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Double r = Double.parseDouble(scanner.nextLine()); double Area = Math.PI * r * r; double Perimeter = 2 * Math.PI * r; System.out.println(Area); System.out.println(Perimeter); } } tianqiqiu/chenrenfei-sagacity-sqltoy /** * */ package com.sagframe.sqltoy.showcase.service.impl; import org.sagacity.sqltoy.dao.SqlToyLazyDao; import com.sagframe.sqltoy.showcase.service.LinkCaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @project sqltoy-showcase * @description 链式操作演示 * @author chenrenfei 联系作者 * @version id:LinkCaseServiceImpl.java,Revision:v1.0,Date:2019年7月11日 */ @Service("linkCaseService") public class LinkCaseServiceImpl implements LinkCaseService { @Autowired private SqlToyLazyDao sqlToyLazyDao; } package tbsc.shared.model.game; import org.mongodb.morphia.annotations.Embedded; @Embedded public class Position { public int x = 0; public int y = 0; public Position(){ } public Position(int x, int y) { super(); this.x = x; this.y = y; } } src/main/java/com/bupt/rongsell/RongsellApplication.java package com.bupt.rongsell; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan(value = "com.bupt.rongsell.dao") public class RongsellApplication { public static void main(String[] args) { SpringApplication.run(RongsellApplication.class, args); } } /* * Copyright (C) 2017 The Android Open Source Project * * 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. */ package com.android.tv.util; import android.content.Context; import android.content.Intent; import com.android.tv.InputSessionManager; import com.android.tv.MainActivityWrapper; import com.android.tv.TvApplication; import com.android.tv.TvSingletons; import com.android.tv.analytics.Analytics; import com.android.tv.analytics.Tracker; import com.android.tv.common.config.api.RemoteConfig; import com.android.tv.common.experiments.ExperimentLoader; import com.android.tv.common.recording.RecordingStorageStatusManager; import com.android.tv.common.util.Clock; import com.android.tv.data.ChannelDataManager; import com.android.tv.data.PreviewDataManager; import com.android.tv.data.ProgramDataManager; import com.android.tv.data.epg.EpgFetcher; import com.android.tv.data.epg.EpgReader; import com.android.tv.dvr.DvrDataManager; import com.android.tv.dvr.DvrManager; import com.android.tv.dvr.DvrScheduleManager; import com.android.tv.dvr.DvrWatchedPositionManager; import com.android.tv.dvr.recorder.RecordingScheduler; import com.android.tv.perf.PerformanceMonitor; import com.android.tv.testing.FakeClock; import com.android.tv.tuner.TunerInputController; import java.util.concurrent.Executor; import javax.inject.Provider; /** Mock {@link TvSingletons} class. */ public class MockTvSingletons implements TvSingletons { public final FakeClock fakeClock = FakeClock.createWithCurrentTime(); private final TvApplication mApp; private PerformanceMonitor mPerformanceMonitor; public MockTvSingletons(Context context) { mApp = (TvApplication) context.getApplicationContext(); } @Override public Analytics getAnalytics() { return mApp.getAnalytics(); } @Override public void handleInputCountChanged() {} @Override public ChannelDataManager getChannelDataManager() { return mApp.getChannelDataManager(); } @Override public boolean isChannelDataManagerLoadFinished() { return mApp.isChannelDataManagerLoadFinished(); } @Override public ProgramDataManager getProgramDataManager() { return mApp.getProgramDataManager(); } @Override public boolean isProgramDataManagerCurrentProgramsLoadFinished() { return mApp.isProgramDataManagerCurrentProgramsLoadFinished(); } @Override public PreviewDataManager getPreviewDataManager() { return mApp.getPreviewDataManager(); } @Override public DvrDataManager getDvrDataManager() { return mApp.getDvrDataManager(); } @Override public Clock getClock() { return fakeClock; } @Override public RecordingStorageStatusManager getRecordingStorageStatusManager() { return mApp.getRecordingStorageStatusManager(); } @Override public DvrScheduleManager getDvrScheduleManager() { return mApp.getDvrScheduleManager(); } @Override public DvrManager getDvrManager() { return mApp.getDvrManager(); } @Override public RecordingScheduler getRecordingScheduler() { return mApp.getRecordingScheduler(); } @Override public DvrWatchedPositionManager getDvrWatchedPositionManager() { return mApp.getDvrWatchedPositionManager(); } @Override public InputSessionManager getInputSessionManager() { return mApp.getInputSessionManager(); } @Override public Tracker getTracker() { return mApp.getTracker(); } @Override public TvInputManagerHelper getTvInputManagerHelper() { return mApp.getTvInputManagerHelper(); } @Override public Provider providesEpgReader() { return mApp.providesEpgReader(); } @Override public EpgFetcher getEpgFetcher() { return mApp.getEpgFetcher(); } @Override public SetupUtils getSetupUtils() { return mApp.getSetupUtils(); } @Override public TunerInputController getTunerInputController() { return mApp.getTunerInputController(); } @Override public ExperimentLoader getExperimentLoader() { return mApp.getExperimentLoader(); } @Override public MainActivityWrapper getMainActivityWrapper() { return mApp.getMainActivityWrapper(); } @Override public com.android.tv.util.account.AccountHelper getAccountHelper() { return mApp.getAccountHelper(); } @Override public RemoteConfig getRemoteConfig() { return mApp.getRemoteConfig(); } @Override public Intent getTunerSetupIntent(Context context) { return mApp.getTunerSetupIntent(context); } @Override public boolean isRunningInMainProcess() { return mApp.isRunningInMainProcess(); } @Override public PerformanceMonitor getPerformanceMonitor() { return mPerformanceMonitor != null ? mPerformanceMonitor : mApp.getPerformanceMonitor(); } public void setPerformanceMonitor(PerformanceMonitor performanceMonitor) { mPerformanceMonitor = performanceMonitor; } @Override public String getEmbeddedTunerInputId() { return "com.android.tv/.tuner.tvinput.LiveTvTunerTvInputService"; } @Override public Executor getDbExecutor() { return mApp.getDbExecutor(); } } package org.jnamer; public interface Generatable { T generate(); } package com.planet_ink.coffee_mud.Abilities.Common; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 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. */ @SuppressWarnings("unchecked") public class Lacquerring extends CommonSkill { public String ID() { return "Lacquerring"; } public String name(){ return "Lacquering";} private static final String[] triggerStrings = {"LACQUERING","LACQUER"}; public String[] triggerStrings(){return triggerStrings;} public int classificationCode() { return Ability.ACODE_COMMON_SKILL|Ability.DOMAIN_ARTISTIC; } protected Item found=null; protected String writing=""; public Lacquerring() { super(); displayText="You are lacquering..."; verb="lacquering"; } protected String fixColor(String name, String colorWord) { int end=name.indexOf("^?"); if((end>0)&&(end<=name.length()-3)) { int start=name.substring(0,end).indexOf("^"); if((start>=0)&&(start<(end-3))) name=name.substring(0,start) +name.substring(end+3); } colorWord="^"+colorWord.charAt(0)+colorWord+"^?"; Vector V=CMParms.parse(name); for(int v=0;v mess(es) up the lacquering."); else { StringBuffer desc=new StringBuffer(found.description()); for(int x=0;x<(desc.length()-1);x++) { if((desc.charAt(x)=='^') &&(desc.charAt(x+1)!='?')) desc.setCharAt(x+1,writing.charAt(0)); } String d=desc.toString(); if(!d.endsWith("^?")) desc.append("^?"); if(!d.startsWith("^"+writing.charAt(0))) desc.insert(0,"^"+writing.charAt(0)); found.setDescription(desc.toString()); found.setName(fixColor(found.Name(),writing)); found.setDisplayText(fixColor(found.displayText(),writing)); found.text(); } } } super.unInvoke(); } public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel) { if(commands.size()<2) { commonTell(mob,"You must specify what you want to lacquer, and the color to lacquer it in."); return false; } Item target=mob.fetchCarried(null,(String)commands.firstElement()); if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob))) { commonTell(mob,"You don't seem to have a '"+((String)commands.firstElement())+"'."); return false; } commands.remove(commands.firstElement()); if((((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_GLASS) &&((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_METAL) &&((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_MITHRIL) &&((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_PLASTIC) &&((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_PRECIOUS) &&((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_ROCK) &&((target.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN)) ||(!target.isGeneric())) { commonTell(mob,"You can't lacquer that material."); return false; } writing=CMParms.combine(commands,0).toLowerCase(); boolean darkFlag=false; if(writing.startsWith("dark ")) { darkFlag=true; writing=writing.substring(5).trim(); } if(" white green blue red yellow cyan purple ".indexOf(" "+writing.trim()+" ")<0) { commonTell(mob,"You can't lacquer anything '"+writing+"'. Try white, green, blue, red, yellow, cyan, or purple. You can also prefix the colors with the word 'dark'."); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; verb="lacquering "+target.name()+" "+writing; displayText="You are "+verb; found=target; if(darkFlag) writing=CMStrings.capitalizeAndLower(writing); if(!proficiencyCheck(mob,0,auto)) writing=""; int duration=getDuration(60,mob,1,12); CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_HANDS," start(s) lacquering ."); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,mob,asLevel,duration); } return true; } } nseniak/opwatchsrc/main/java/org/opwatch/processor/config/JavascriptFunction.java /* * Copyright (c) 2016-2017 by OMC Inc and other Opwatch contributors * * Licensed under the Apache License, Version 2.0 (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. */ package org.opwatch.processor.config; import org.opwatch.processor.common.Processor; import org.opwatch.processor.common.ValueLocation; import org.opwatch.processor.payload.Payload; import org.opwatch.service.ProcessorService; import jdk.nashorn.api.scripting.ScriptObjectMirror; import java.util.regex.Pattern; public abstract class JavascriptFunction extends ConfigPropertyValue { protected ScriptObjectMirror function; protected ValueLocation valueLocation; protected ProcessorService processorService; protected JavascriptFunction(ScriptObjectMirror function, ValueLocation valueLocation, ProcessorService processorService) { this.function = function; this.valueLocation = valueLocation; this.processorService = processorService; } protected Object invoke(Processor processor, Payload payload) { synchronized (processorService.getScriptService()) { return function.call(function, payload.getValue(), payload); } } protected Object invoke(Processor processor) { synchronized (processorService.getScriptService()) { return function.call(function); } } @Override public String toString() { return Pattern.compile("\n[\t ]*", Pattern.DOTALL).matcher(function.toString()).replaceAll(" "); } public ValueLocation getValueLocation() { return valueLocation; } public ScriptObjectMirror getFunction() { return function; } } package com.thisobeystudio.searchviewexample.async; /** * Created by thisobeystudio on 3/12/17. * Copyright: (c) 2017 ThisObey Studio * Contact: */ public interface SearchDataAsyncResponse { void searchDataAsyncDoInBackground(String params); void searchDataAsyncOnPostExecute(); } paulwellnerbou/chronicreplaysrc/test/java/de/wellnerbou/chronic/logparser/CommonLogFormatLogLineParserTest.java package de.wellnerbou.chronic.logparser; import static org.assertj.core.api.Assertions.assertThat; import org.junit.BeforeClass; import org.junit.Test; import de.wellnerbou.chronic.replay.LogLineData; public class CommonLogFormatLogLineParserTest { CommonLogFormatLogLineParser commonLogFormatLogLineReader = new CommonLogFormatLogLineParser(); @BeforeClass public static void before() { System.setProperty("user.timezone", "UTC"); } @Test public void testFormatDate() { long time = commonLogFormatLogLineReader.formatDate("[25/Sep/2013:12:00:02"); assertThat(time).isEqualTo(1380110402000L); } @Test public void testParseLine() { String testLine = "127.0.0.1 - - [02/Jan/2014:11:55:12 +0100] \"GET / HTTP/1.1\" 200 481"; LogLineData logLineData = commonLogFormatLogLineReader.parseLine(testLine); assertThat(logLineData.getTime()).isEqualTo(1388663712000L); assertThat(logLineData.getRequestMethod()).isEqualTo("GET"); assertThat(logLineData.getRequest()).isEqualTo("/"); assertThat(logLineData.getDuration()).isEqualTo(0); assertThat(logLineData.getStatusCode()).isEqualTo("200"); } } 1-10 package com.encircle360.oss.docsrabbit.dto; import java.util.List; import org.springframework.data.domain.Page; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Schema(name = "PageContainer") public class PageContainer { @Schema(name = "content", description = "contains the list with items from this page") private List content; @Schema(name = "size", description = "The size of the current page") private int size; @Schema(name = "page", description = "The current page") private int page; @Schema(name = "totalElements", description = "Total elements in collection") private long totalElements; @Schema(name = "sort", description = "Sort string with desc and asc param") private String sort; public static PageContainer of(List elements, Integer page, Integer size, long totalElements, String sort) { if (page == null) { page = 0; } if (size == null) { size = 0; } return new PageContainer(elements, page, size, totalElements, sort); } public static PageContainer of(List elements, Page pageable) { return new PageContainer(elements, pageable.getNumber(), pageable.getSize(), pageable.getTotalElements(), pageable.getSort().toString()); } } 1-10 /* Copyright (c) 2017-2018 VMware, Inc. * * 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. */ package org.onap.multicloud.openstack.vmware; import java.util.Timer; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class TimerExtend extends Timer{ public TimerExtend(){ VesTimer.hasStarted = true; } public boolean hasRunStarted() { return VesTimer.hasStarted; } } class TaskTimeout extends TimerTask{ private static JsonStoreMap map; private final Logger log = LoggerFactory.getLogger(TaskTimeout.class); @SuppressWarnings("static-access") public TaskTimeout(JsonStoreMap map) { TaskTimeout.map = map; } public static void run1(){ VesTimer.timeoutCheck = true; map.deleteAllFromMap(); VesTimer.hasStarted=false; } @SuppressWarnings("resource") @Override public void run() { run1(); log.info("In Timed out run method, before deleting the entries from Map"); } } public class VesTimer { TimerExtend tt = null; TaskTimeout timeout = null; static boolean hasStarted = false; static boolean timeoutCheck = false; private JsonStoreMap map; private final Logger log = LoggerFactory.getLogger(VesTimer.class); public VesTimer(JsonStoreMap map){ this.map = map; } public void startTimer(Integer duration){ tt = new TimerExtend(); timeout= new TaskTimeout(this.map); log.info("timer started................."); tt.schedule(timeout, duration); } public void stopTimer(){ tt.cancel(); log.info("timer stopped"); } public boolean isTimerRunning(){ if(VesTimer.hasStarted){ log.info("timer started...."); return true; } else { log.info("timer is not running"); return false; } } public String isTimeout(){ if(VesTimer.timeoutCheck){ log.info("expired"); return "expired"; } return "not expired"; } } package hudson.plugins.promoted_builds; import antlr.ANTLRException; import hudson.BulkChange; import hudson.Extension; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AutoCompletionCandidates; import hudson.model.ParameterValue; import hudson.model.Cause; import hudson.model.Cause.UserCause; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.Failure; import hudson.model.FreeStyleProject; import hudson.model.Hudson; import hudson.model.ItemGroup; import hudson.model.JDK; import hudson.model.Job; import hudson.model.Label; import hudson.model.ParametersAction; import hudson.model.PermalinkProjectAction.Permalink; import hudson.model.Queue.Item; import hudson.model.Run; import hudson.model.Saveable; import hudson.model.labels.LabelAtom; import hudson.model.labels.LabelExpression; import hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval; import hudson.security.ACL; import hudson.tasks.BuildStep; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.util.DescribableList; import hudson.util.FormValidation; import jenkins.model.Jenkins; import jenkins.util.TimeDuration; import net.sf.json.JSONObject; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.Future; import java.util.logging.Logger; import java.util.regex.Pattern; /** * A dummy {@link AbstractProject} to carry out promotion operations. * * @author */ public final class PromotionProcess extends AbstractProject implements Saveable, Describable { /** * {@link PromotionCondition}s. All have to be met for a build to be promoted. */ public final DescribableList conditions = new DescribableList(this); /** * The icon that represents this promotion process. This is the name of * the GIF icon that can be found in ${rootURL}/plugin/promoted-builds/icons/16x16/ * and ${rootURL}/plugin/promoted-builds/icons/32x32/, e.g. "star-gold". */ public String icon; /** * The label that promotion process can be run on. */ public String assignedLabel; private List buildSteps = new ArrayList(); /*package*/ PromotionProcess(JobPropertyImpl property, String name) { super(property, name); } /*package*/ PromotionProcess(ItemGroup parent, String name) { super(parent, name); } /** * Creates unconnected {@link PromotionProcess} instance from the JSON configuration. * This is mostly only useful for capturing its configuration in XML format. */ public static PromotionProcess fromJson(StaplerRequest req, JSONObject o) throws FormException, IOException { String name = o.getString("name"); try { Hudson.checkGoodName(name); } catch (Failure f) { throw new Descriptor.FormException(f.getMessage(), name); } PromotionProcess p = new PromotionProcess(null,name); BulkChange bc = new BulkChange(p); try { p.configure(req, o); // apply configuration. prevent it from trying to save to disk while we do this } finally { bc.abort(); } return p; } @Override public void doSetName(String name) { super.doSetName(name); } /*package*/ void configure(StaplerRequest req, JSONObject c) throws Descriptor.FormException, IOException { // apply configuration conditions.rebuild(req,c.optJSONObject("conditions"), PromotionCondition.all()); buildSteps = (List)Descriptor.newInstancesFromHeteroList( req, c, "buildStep", (List) PromotionProcess.getAll()); icon = c.getString("icon"); if (c.optBoolean("hasAssignedLabel")) { assignedLabel = Util.fixEmptyAndTrim(c.optString("assignedLabelString")); } else { assignedLabel = null; } save(); } /** * Returns the root project value. * * @return the root project value. */ @Override public AbstractProject getRootProject() { return getParent().getOwner().getRootProject(); } @Override public JobPropertyImpl getParent() { return (JobPropertyImpl)super.getParent(); } /** * Gets the owner {@link AbstractProject} that configured {@link JobPropertyImpl} as * a job property. */ public AbstractProject getOwner() { return getParent().getOwner(); } @Override public ACL getACL() { return getOwner().getACL(); } /** * Get the promotion condition by referencing it fully qualified class name */ public PromotionCondition getPromotionCondition(String promotionClassName) { for (PromotionCondition condition : conditions) { if (condition.getClass().getName().equals(promotionClassName)) { return condition; } } return null; } public DescribableList> getPublishersList() { // TODO: extract from the buildsSteps field? Or should I separate builders and publishers? return new DescribableList>(this); } protected Class getBuildClass() { return Promotion.class; } public List getBuildSteps() { return buildSteps; } /** * Gets the textual representation of the assigned label as it was entered by the user. */ @Override public String getAssignedLabelString() { if (assignedLabel == null) return null; try { LabelExpression.parseExpression(assignedLabel); return assignedLabel; } catch (ANTLRException e) { // must be old label or host name that includes whitespace or other unsafe chars return LabelAtom.escape(assignedLabel); } } @Override public Label getAssignedLabel() { // Really would like to run on the exact node that the promoted build ran on, // not just the same label.. but at least this works if job is tied to one node: if (assignedLabel == null) return getOwner().getAssignedLabel(); return Hudson.getInstance().getLabel(assignedLabel); } @Override public JDK getJDK() { return getOwner().getJDK(); } /** * Gets the customWorkspace of the owner project. * * Support for FreeStyleProject only. * @return customWorkspace */ public String getCustomWorkspace() { AbstractProject p = getOwner(); if (p instanceof FreeStyleProject) return ((FreeStyleProject) p).getCustomWorkspace(); return null; } /** * Get the icon name, without the extension. It will always return a non null * and non empty string, as "star-gold" is used for compatibility * for older promotions configurations. * * @return the icon name */ public String getIcon() { return getIcon(icon); } /** * Handle compatibility with pre-1.8 configs. * * @param sIcon * the name of the icon used by this promotion; if null or empty, * we return the gold icon for compatibility with previous releases * @return the icon file name for this promotion */ private static String getIcon(String sIcon) { if ((sIcon == null) || sIcon.equals("")) return "star-gold"; else return sIcon; } /** * Get the badges of conditions that were passed for this promotion for the build */ public List getMetQualifications(AbstractBuild build) { List badges = new ArrayList(); for (PromotionCondition cond : conditions) { PromotionBadge b = cond.isMet(this, build); if (b != null) badges.add(b); } return badges; } /** * Get the conditions that have not been met for this promotion for the build */ public List getUnmetConditions(AbstractBuild build) { List unmetConditions = new ArrayList(); for (PromotionCondition cond : conditions) { if (cond.isMet(this, build) == null) unmetConditions.add(cond); } return unmetConditions; } /** * Checks if all the conditions to promote a build is met. * * @return * null if promotion conditions are not met. * otherwise returns a list of badges that record how the promotion happened. */ public Status isMet(AbstractBuild build) { List badges = new ArrayList(); for (PromotionCondition cond : conditions) { PromotionBadge b = cond.isMet(this, build); if(b==null) return null; badges.add(b); } return new Status(this,badges); } /** * @deprecated * Use {@link #considerPromotion2(AbstractBuild)} */ public boolean considerPromotion(AbstractBuild build) throws IOException { return considerPromotion2(build)!=null; } /** * Checks if the build is promotable, and if so, promote it. * * @return * null if the build was not promoted, otherwise Future that kicks in when the build is completed. * @throws IOException */ public Future considerPromotion2(AbstractBuild build) throws IOException { return considerPromotion2(build, (List)null); } public Future considerPromotion2(AbstractBuild build, List params) throws IOException { if (!isActive()) return null; // not active PromotedBuildAction a = build.getAction(PromotedBuildAction.class); // if it's already promoted, no need to do anything. if(a!=null && a.contains(this)) return null; LOGGER.fine("Considering the promotion of "+build+" via "+getName()); Status qualification = isMet(build); if(qualification==null) return null; // not this time LOGGER.fine("Promotion condition of "+build+" is met: "+qualification); Future f = promote2(build, new UserCause(), qualification, params); // TODO: define promotion cause if (f==null) LOGGER.warning(build+" qualifies for a promotion but the queueing failed."); return f; } public void promote(AbstractBuild build, Cause cause, PromotionBadge... badges) throws IOException { promote2(build,cause,new Status(this,Arrays.asList(badges))); } /** * @deprecated * Use {@link #promote2(AbstractBuild, Cause, Status)} */ public void promote(AbstractBuild build, Cause cause, Status qualification) throws IOException { promote2(build,cause,qualification); } /** * Promote the given build by using the given qualification. * * @param cause * Why the build is promoted? * @return * Future to track the completion of the promotion. */ public Future promote2(AbstractBuild build, Cause cause, Status qualification) throws IOException { return promote2(build, cause, qualification, null); } public Future promote2(AbstractBuild build, Cause cause, Status qualification, List params) throws IOException { PromotedBuildAction a = build.getAction(PromotedBuildAction.class); // build is qualified for a promotion. if(a!=null) { a.add(qualification); } else { build.addAction(new PromotedBuildAction(build,qualification)); build.save(); } // schedule promotion activity. return scheduleBuild2(build,cause, params); } /** * @deprecated * You need to be using {@link #scheduleBuild(AbstractBuild)} */ public boolean scheduleBuild() { return super.scheduleBuild(); } public boolean scheduleBuild(AbstractBuild build) { return scheduleBuild(build,new UserCause()); } /** * @deprecated * Use {@link #scheduleBuild2(AbstractBuild, Cause)} */ public boolean scheduleBuild(AbstractBuild build, Cause cause) { return scheduleBuild2(build,cause)!=null; } public Future scheduleBuild2(AbstractBuild build, Cause cause, List params) { assert build.getProject()==getOwner(); List actions = new ArrayList(); if (params!=null){ Promotion.buildParametersAction(actions, build, params); } actions.add(new PromotionTargetAction(build)); // remember what build we are promoting return super.scheduleBuild2(0, cause, actions.toArray(new Action[actions.size()])); } @Override public void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException { throw HttpResponses.error(404, "Promotion processes may not be built directly"); } public Future scheduleBuild2(AbstractBuild build, Cause cause) { return scheduleBuild2(build, cause, null); } public boolean isInQueue(AbstractBuild build) { for (Item item : Hudson.getInstance().getQueue().getItems(this)) if (item.getAction(PromotionTargetAction.class).resolve(this)==build) return true; return false; } // // these are dummy implementations to implement abstract methods. // need to think about what the implications are. // public boolean isFingerprintConfigured() { throw new UnsupportedOperationException(); } protected void buildDependencyGraph(DependencyGraph graph) { throw new UnsupportedOperationException(); } public static List> getAll() { List> list = new ArrayList>(); addTo(Builder.all(), list); addTo(Publisher.all(), list); return list; } private static void addTo(List> source, List> list) { for (Descriptor d : source) { if (d instanceof BuildStepDescriptor) { BuildStepDescriptor bsd = (BuildStepDescriptor) d; if(bsd.isApplicable(PromotionProcess.class)) list.add(d); } } } public Permalink asPermalink() { return new Permalink() { @Override public String getDisplayName() { return Messages.PromotionProcess_PermalinkDisplayName(PromotionProcess.this.getDisplayName()); } @Override public String getId() { return PromotionProcess.this.getName(); } @Override public Run resolve(Job job) { String id = getId(); for( Run build : job.getBuilds() ) { PromotedBuildAction a = build.getAction(PromotedBuildAction.class); if(a!=null && a.contains(id)) return build; } return null; } }; } public DescriptorImpl getDescriptor() { return (DescriptorImpl)Jenkins.getInstance().getDescriptorOrDie(getClass()); } @Override public String getShortUrl() { // Must be overridden since JobPropertyImpl.getUrlChildPrefix is "" not "process" as you might expect (also see e50f0f5 in 1.519) return "process/" + Util.rawEncode(getName()) + '/'; } public boolean isActive() { return !isDisabled(); } @Extension public static class DescriptorImpl extends Descriptor { @Override public String getDisplayName() { return "Promotion Process"; } public FormValidation doCheckLabelString(@QueryParameter String value) { if (Util.fixEmpty(value)==null) return FormValidation.ok(); // nothing typed yet try { Label.parseExpression(value); } catch (ANTLRException e) { return FormValidation.error(e, Messages.JobPropertyImpl_LabelString_InvalidBooleanExpression(e.getMessage())); } // TODO: if there's an atom in the expression that is empty, report it if (Hudson.getInstance().getLabel(value).isEmpty()) return FormValidation.warning(Messages.JobPropertyImpl_LabelString_NoMatch()); return FormValidation.ok(); } public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) { AutoCompletionCandidates c = new AutoCompletionCandidates(); Set