text
stringlengths
10
2.72M
package ru.moneydeal.app.pages; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import ru.moneydeal.app.CheckViewModel; import ru.moneydeal.app.IRouter; import ru.moneydeal.app.R; import ru.moneydeal.app.checks.CheckEntity; import ru.moneydeal.app.checks.CheckRepo; public class GroupChecksFragment extends Fragment { private static String GROUP_ID = "GROUP_ID"; private CheckViewModel mCheckViewModel; private String mGroupId; private RecyclerView mRecyclerView; private MyDataAdapter mDataAdapter; public static GroupChecksFragment getInstance(String groupId) { Bundle bundle = new Bundle(); bundle.putString(GROUP_ID, groupId); GroupChecksFragment fragment = new GroupChecksFragment(); fragment.setArguments(bundle); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mCheckViewModel = new ViewModelProvider(getActivity()).get(CheckViewModel.class); View view = inflater.inflate( R.layout.group_checks_fragment, container, false ); Bundle bundle = getArguments(); if (bundle == null) { return view; } mGroupId = bundle.getString(GROUP_ID); if (mGroupId == null) { return view; } bindRecyclerView(view); view.findViewById(R.id.group_checks_add_btn).setOnClickListener(v -> { IRouter activity = (IRouter) getActivity(); if (activity == null) { return; } activity.showCheckCreate(mGroupId); }); return view; } private void bindRecyclerView(View view) { mRecyclerView = view.findViewById(R.id.group_checks_list); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mDataAdapter = new MyDataAdapter(mCheckViewModel); mRecyclerView.setAdapter(mDataAdapter); } class MyDataAdapter extends RecyclerView.Adapter<MyViewHolder> { CheckRepo.GroupChecks mData; public MyDataAdapter(CheckViewModel viewModel) { if (viewModel == null) { return; } mCheckViewModel.getChecks().observe(getViewLifecycleOwner(), data -> { mData = data; this.notifyDataSetChanged(); }); mCheckViewModel.fetchChecks(mGroupId); } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater .from(parent.getContext()) .inflate(R.layout.group_check_list_item, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { CheckEntity data = mData.entities.get(position); holder.mNameView.setText(data.name); holder.mDescriptionView.setText(data.description); holder.mAmountView.setText(getString(R.string.amount_string, data.amount)); } @Override public int getItemCount() { return mData == null || mData.entities == null ? 0 : mData.entities.size(); } } class MyViewHolder extends RecyclerView.ViewHolder { private final TextView mNameView; private final TextView mDescriptionView; private final TextView mAmountView; public MyViewHolder(View itemView) { super(itemView); mNameView = itemView.findViewById(R.id.group_check_name); mDescriptionView = itemView.findViewById(R.id.group_check_description); mAmountView = itemView.findViewById(R.id.group_check_amount); itemView.setOnClickListener(v -> { int position = getAdapterPosition(); CheckRepo.GroupChecks data = mDataAdapter.mData; if (data == null) { return; } List<CheckEntity> entities = data.entities; if (entities == null || position > entities.size()) { return; } CheckEntity entity = entities.get(position); if (entity == null) { return; } IRouter activity = (IRouter) getActivity(); if (activity == null) { return; } activity.showCheck(entity.id); }); } } }
package com.company; public class HeronsFormula { public static void main(String[] args) { double area; area=Triangle(3,3,3); System.out.println("A triangle with sides 3,3,3 has an area of "+ area); area=Triangle(3,4,5); System.out.println("A triangle with sides 3,4,5 has an area of "+area); area=Triangle(7,8,9); System.out.println("A triangle with sides 7,8,9 has an area of "+area); area=Triangle(5,12,13 ); System.out.println("A triangle with sides 5,12,13 has an area of "+area); area=Triangle(10,9,11); System.out.println("A triangle with sides 10,9,11 has an area of "+area); area=Triangle(8,15,17); System.out.println("A triangle with sides 8,15,17 has an area of "+area); area=Triangle(9,9,9); System.out.println("A triangle with sides 9,9,9 has an area of "+area); } public static double Triangle (int a, int b, int c) { double area; double U; U = (a + b + c) / 2; area=Math.sqrt(U*(U-a)*(U-b)*(U-c)); return area; } }
package hdfs.daemon; import java.io.Serializable; import java.util.Collection; import hdfs.FileDescriptionI; public interface FragmentDataI extends Serializable, Iterable<Integer> { FileDescriptionI getFile(); String getFragmentsPath(); void setFragmentsPath(String path); String getFragmentName(int fragment); int getNumberFragments(); Collection<Integer> getFragments(); boolean hasFragment(int fragment); void addFragment(int fragment, String fragmentName); void removeFragment(int fragment); void clear(); }
package com.sameer.springdemo; public class TrackCoach implements Coach { @Override public String getDetailWorkout() { // TODO Auto-generated method stub return "Run Run"; } }
package com.laychv.module_arch.mvc.controller; import com.laychv.module_arch.R; import com.laychv.module_arch.mvc.Book; import com.laychv.module_arch.mvc.module.BookModel; import java.util.List; /** * 控制器层 * 处理业务逻辑,调用模型层的操作,并对外暴露接口 * 根据Model层的方法,加上我们的业务逻辑处理,对外提供方法并暴露接口 * 看delete这个方法,判断List是否为空(业务逻辑),使用mode.deleteBook()(Model层方法),通过listener.onComplete()(暴露接口) */ public class BookController { private BookModel mode; public BookController() { mode = new BookModel(); } /** * 添加书本 * * @param listener */ public void add(onAddBookListener listener) { mode.addBook("JavaWeb从入门到精通", R.drawable.javaweb); if (listener != null) { listener.onComplete(); } } /** * 删除书本 * * @param listener */ public void delete(onDeleteBookListener listener) { if (mode.query().isEmpty()) { return; } else { mode.deleteBook(); } if (listener != null) { listener.onComplete(); } } /** * 查询所有书本 * * @return */ public List<Book> query() { return mode.query(); } /** * 添加成功的回调接口 */ public interface onAddBookListener { void onComplete(); } /** * 删除成功的回调接口 */ public interface onDeleteBookListener { void onComplete(); } }
package cd.com.a.daoImpl; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import cd.com.a.dao.MemberDao; import cd.com.a.model.memberDto; @Repository public class MemberDaoImpl implements MemberDao { @Autowired SqlSession sqlSession; String ns = "Member."; @Override public boolean idCheck(memberDto dto) { int result = sqlSession.selectOne(ns+"idCheck",dto); System.out.println("result=" + result); return result>0?true:false; } @Override public boolean nickCheck(String nick_name) { int result = sqlSession.selectOne(ns+"nickCheck",nick_name); System.out.println("result=" + result); return result>0?true:false; } @Override public boolean newRegi(memberDto dto) { int result = sqlSession.insert(ns+"newRegi",dto); System.out.println("newRegi Result = " + result); return result>0?true:false; } @Override public memberDto login(memberDto dto) { memberDto mem = sqlSession.selectOne(ns+"login",dto); return mem; } @Override public String findId(memberDto dto) { String id = sqlSession.selectOne(ns+"findId",dto); return id; } @Override public String findPwd(memberDto dto) { String pwd = sqlSession.selectOne(ns+"findPwd",dto); return pwd; } @Override public memberDto snsLogin(memberDto dto) { memberDto mem = sqlSession.selectOne(ns+"snsLogin",dto); return mem; } @Override public memberDto loginId(int mem_seq) { memberDto mem = sqlSession.selectOne(ns+"loginId",mem_seq); return mem; } @Override public boolean snsFirstUpdate(memberDto dto) { int result = sqlSession.update(ns+"snsFirstUpdate",dto); return result>0?true:false; } @Override public boolean pwdCheck(memberDto dto) { int result = sqlSession.selectOne(ns+"pwdCheck",dto); return result>0?true:false; } @Override public memberDto resvMem(int mem_seq) { return sqlSession.selectOne(ns+"resvMem", mem_seq); } @Override public boolean userUpdate(memberDto dto) { int result = sqlSession.update(ns+"userUpdate", dto); return result>0?true:false; } @Override public boolean snsUserUpdate(memberDto dto) { int result = sqlSession.update(ns+"snsUserUpdate", dto); return result>0?true:false; } @Override public boolean sellerAccess(int mem_seq) { int result = sqlSession.update(ns+"sellerAccess",mem_seq); return result>0?true:false; } @Override public boolean sellerAccessPass(int[] mem_seq) { int result = sqlSession.update(ns+"sellerAccessPass",mem_seq); return result>0?true:false; } @Override public boolean sellerAccessFail(int[] mem_seq) { int result = sqlSession.update(ns+"sellerAccessFail",mem_seq); return result>0?true:false; } @Override public void memberEscape(int mem_seq) { sqlSession.update(ns+"memberEscape",mem_seq); } @Override public void recoveryId(int mem_seq) { sqlSession.update(ns+"recoveryId",mem_seq); } @Override public int findSeq(memberDto dto) { return sqlSession.selectOne(ns+"findSeq",dto); } @Override public boolean recoveryCheck(memberDto dto) { int result = sqlSession.selectOne(ns+"recoveryCheck",dto); return result>0?true:false; } @Override public List<memberDto> getSellerAccessList() { return sqlSession.selectList(ns+"sellerAccessList"); } }
package sarong; import sarong.util.StringKit; import java.io.Serializable; /** * One of Mark Overton's subcycle generators from <a href="http://www.drdobbs.com/tools/229625477">this article</a> * (specifically, an un-investigated generator mentioned in the code attached to the article), a lera^lera^lera with * three 32-bit states; it has high quality, passing PractRand's 32TB battery with one anomaly, uses no * multiplication in its core operations, and is optimized for GWT. It has a period of somewhat under 2 to the 96, * 0xF8DB896393AF9CD31D8B69BA, which is roughly 2 to the 95.959176, and allows 2 to the 32 initial seeds. It is not * especially fast on desktop JVMs, but may do better on GWT in some browsers because it avoids multiplication. You may * want {@link Mover32RNG} for a faster "chaotic" generator that does well in 32-bit environments, though its period is * certainly shorter at roughly 2 to the 63.999691. * <br> * This seems to do well in PractRand testing (32 TB passed), but this is not a generator Overton tested. "Chaotic" * generators like this one tend to score well in PractRand, but it isn't clear if they will fail other tests (the * fairly-high period means that it is likely to produce most long values at some point, though possibly not all, and * definitely not with equal likelihood). * <br> * Its period is 0xF8DB896393AF9CD31D8B69BA for the largest cycle, which it always initializes into if * {@link #setState(int)} is used. setState() only allows 2 to the 32 starting states, but many more states are possible * if the generator runs for long enough. The generator has three similar parts, each updated without needing to read * from another part. Each is a 32-bit LERA generator, which adds together the current state left-shifted by a constant * amount and the current state rotated by another constant, and stores that as the next state. The particular constants * used here were found by exhaustively searching all possible combinations of left-shift added to a rotation; the three * selected LERA generators have period lengths that are coprime and are the longest three periods with that property. * <br> * This is a RandomnessSource but not a StatefulRandomness because it has 96 bits of state. It uses three generators * with different cycle lengths, and skips at most 65536 times into each generator's cycle independently when seeding. * It uses constants to store 128 known midpoints for each generator, which ensures it calculates an advance for each * generator at most 511 times. * <br> * The name comes from M. Overton, who discovered this category of subcycle generators, and the "lera" type of generator * this uses, which Overton found and noted but hadn't yet investigated. Some species of mole-rats are especially social * animals and need to work in groups to thrive, much like how one or two lera generators aren't enough to pass tests, * but three will do quite well when combined. * <br> * Created by Tommy Ettinger on 11/23/2018. * @author Mark Overton * @author Tommy Ettinger */ public final class Molerat32RNG implements RandomnessSource, Serializable { private static final long serialVersionUID = 1L; private int stateA, stateB, stateC; public Molerat32RNG() { setState((int)((Math.random() * 2.0 - 1.0) * 0x80000000)); } public Molerat32RNG(final int state) { setState(state); } /** * Not advised for external use; prefer {@link #Molerat32RNG(int)} because it guarantees a good subcycle. This * constructor allows all subcycles to be produced, including ones with a shorter period. * @param stateA * @param stateB */ public Molerat32RNG(final int stateA, final int stateB, final int stateC) { this.stateA = stateA == 0 ? 1 : stateA; this.stateB = stateB == 0 ? 1 : stateB; this.stateC = stateC == 0 ? 1 : stateC; } private static final int[] startingA = { 0x7E7A773E, 0x278C3D74, 0x3F1DE6F5, 0x0C581399, 0x414F083A, 0x74211C70, 0x42203026, 0x0724F7DB, 0x42C95E0C, 0xAEC08514, 0x30FE969A, 0xDC76E210, 0x2695EE44, 0x1CEC3584, 0x58EB49F1, 0x5162DBA6, 0x9A1ECDB2, 0x6CF2DCF3, 0xA52A2CD5, 0x78DD9006, 0x0E16D9BB, 0xEDCBE912, 0x4A262BE5, 0x1C6AE304, 0xAB094E45, 0xB5258CA8, 0xAA45EBFA, 0x499F9D80, 0x52F48F2D, 0x0AD1CF16, 0x9276A067, 0x02F98701, 0xAFCA8D8B, 0xE880DC36, 0x72868424, 0x58B91703, 0x6C596A1B, 0x5B612409, 0xA4C28B07, 0x9B683C0F, 0xCAC56556, 0xC6329F6F, 0xFCE3D058, 0x41B790CA, 0xA441288B, 0xF0437135, 0x5B54B564, 0x2512DF84, 0x755896B2, 0x59BF4FE6, 0xCAD40046, 0xAA5425D1, 0x3C95CE27, 0xC6F5B3D9, 0x9ED089C4, 0x2835D51F, 0x31D1BB97, 0x64D44BC2, 0xADB98517, 0x1EFCF0BF, 0xA6E97356, 0x68EE8F8A, 0x6121C448, 0x63E4755D, 0xB9F92D37, 0xC18BDDF7, 0x4649E686, 0xFE0DF92E, 0x1EFD5CEC, 0xE1838727, 0xF5C77CE5, 0x3291666E, 0x07096AFC, 0x1B96EDEC, 0xD9464D89, 0xC433196D, 0x2678D3FB, 0x4F0A5B4F, 0xD2071036, 0x790F31D2, 0xE6D16700, 0xF2EB1862, 0xA4C9417A, 0x319116D0, 0x853F9F2F, 0x4FB8C94E, 0xF5E26F09, 0x250996DC, 0x9EBC8D9A, 0x245A4C99, 0xB555C221, 0x72F23EF0, 0x84BBE96D, 0xDB0A2348, 0xE63297B0, 0x04FBB001, 0xD088B549, 0xA71D7895, 0x4C3B5598, 0x87B0B80F, 0x613DD55A, 0xFD5CABE0, 0xF43E0219, 0x3983FE43, 0x8ABB4A1F, 0x2FC8556A, 0x3D167F14, 0x19CA2125, 0xB3DC2407, 0x8277A7B9, 0xD3228CE7, 0xA12CE097, 0xB866E4B9, 0xB08E7C46, 0x56E44B12, 0x5922D76E, 0x6395D7AF, 0x52459BA9, 0x2F417A87, 0x7C61E1C9, 0x2C90106C, 0x7CABE916, 0x1DBA3BAE, 0xCB9503C4, 0x6F14E967, 0x13FEAB39, 0x3A310CED, 0xD7423A2F, }, startingB = { 0x90D7C575, 0xC8234ADB, 0xBCF5CC6A, 0x2786854F, 0x11D961DC, 0x89BFBF62, 0x02D30705, 0x01EB0E17, 0x440A8BE4, 0xA2ABC105, 0x4F7F3723, 0xD9E7F475, 0x69EAC2D2, 0xD28CC26F, 0x51372436, 0xA19B19C3, 0x73B52150, 0xFB8630B6, 0xC10B5FD1, 0x9F598DE7, 0x07DF4FEA, 0x822F5B8F, 0x6F66D5F8, 0x569C0D65, 0x717E5F48, 0xFCAF67A7, 0x4DB18F99, 0x81A0C864, 0x97FA2990, 0xDFCDD00C, 0x097C1093, 0x5B4B08E1, 0x38564F43, 0xBE4C4595, 0x9A158F54, 0x4FA96613, 0x133A5ACA, 0x0B4687B9, 0x1C78AB16, 0x9CF6B047, 0x4CC61CC9, 0x5CA71348, 0x428C07A1, 0xD97DDFAC, 0x7B422BA5, 0xF100CA05, 0x07B7E271, 0xAB036BC7, 0x43736C2B, 0x3373EF92, 0xA4017CB1, 0x82AD92F9, 0x85BEBEF7, 0x63C5B357, 0xACC98C93, 0x186B8003, 0xD96FA7FA, 0x22A5B1DC, 0x6F965545, 0x4D14096B, 0x30CCBAF0, 0xDE58A0A7, 0x1BCBB0A5, 0xAF878228, 0x5483DB7E, 0xF3E0C1E8, 0xD64D3ECB, 0xED5CD1BA, 0x92E0AC26, 0x467CF6CE, 0x31AFE688, 0x151A7D50, 0x5AB0FE0D, 0x495FF933, 0x39E2FE6A, 0xB52C6EA3, 0xD8879EE8, 0x2CADB7E0, 0x621EAAC2, 0x716884F5, 0xE9EF714A, 0x79E0C4E6, 0x880659B8, 0xB1964FC1, 0xA7899261, 0xB69EAB1A, 0x5D856906, 0xE5E8FA44, 0x33D54582, 0x0C40C021, 0x933BF6BF, 0x88639094, 0xDA61A98B, 0xBB5F1211, 0xA8333A75, 0x99C5F20A, 0x0823C2D7, 0x27394C15, 0x897C2CF6, 0xF12B7787, 0xE6EAA1F1, 0xC4876536, 0xE4F3BDCD, 0x92562433, 0x4EE84624, 0xE89BEC88, 0x57D89B30, 0xC4CBAB76, 0x38DACE13, 0x886C4DD2, 0xC2B69665, 0xECC5B3E4, 0x607F1FEC, 0xC498CAFF, 0xCE5CB3CE, 0x3CD0CCDF, 0xFF315E5A, 0xDCDD4968, 0x137427C6, 0x6FB2D50E, 0x7338E7CD, 0xFC94439D, 0x6F3557F7, 0x3EDC3154, 0xFD576DA6, 0xC44AD5C7, 0xE8E88178, 0x34DE4D5A, }, startingC = { 0x52CC878D, 0x4F1B13A2, 0xC3A42350, 0xC6E34D4E, 0x47161468, 0xC8B6B338, 0x6B7E278D, 0x6730BB1E, 0xCD6E54C6, 0x71F94D24, 0x88543159, 0x8772668A, 0x72BBB3DD, 0xEBCDBCFE, 0xF9B9594B, 0x382FADB2, 0x83E04D9F, 0x6E3E9ECC, 0x1CA5B60F, 0xE8701491, 0x8F881C35, 0x82889773, 0xFF49A3DD, 0x09736772, 0x35051411, 0xC81938C6, 0x1D7A8447, 0x38699825, 0x389DAEFF, 0x8D6A9E48, 0x76266923, 0x7A5364BD, 0x2C626D0A, 0x03FEF32F, 0x07BC6CDB, 0xAC8FEEBA, 0x146EC179, 0x71808FCE, 0x7EA044A7, 0xA669FA5C, 0x3195791D, 0x721363D2, 0x68ED3340, 0x4054A402, 0x82FF33DC, 0xBD6D42FD, 0x2190916B, 0xB122BF9B, 0x77CE02A4, 0xBBB02870, 0x3201F65D, 0x81839EE4, 0x0D276034, 0x1241DC88, 0x434AF4FE, 0xA2B53264, 0xCE986D9E, 0xB64729D0, 0x37672F8A, 0xC3AE3AEC, 0xCC720AFC, 0x4F2A7F61, 0x9AA1B273, 0xCB022734, 0xC5036E47, 0xA341BB1D, 0x737D966E, 0xF9891AE6, 0x5051BC0C, 0xAB424333, 0xB401D6D0, 0x6FF4C8E5, 0x1E3547DB, 0x7EB85B90, 0x39DED179, 0xD74AD860, 0xCD6BDD8B, 0xAD3BE931, 0x4518795B, 0x12343B29, 0x506F12EE, 0xD3058D31, 0xF6A5F567, 0xA15EF9E5, 0xA9230AD3, 0x3D9D0241, 0x0ED724A2, 0xD5888068, 0xEA50F71B, 0x1F905E52, 0x5D2068A4, 0xB171D763, 0x1D612B8D, 0x2F333EBD, 0x0503454E, 0xE2089897, 0xCB843788, 0x049C6535, 0xB3B04C17, 0x74859310, 0x0DE84BD0, 0xF4888A64, 0x96439BB8, 0x8054FC18, 0x0C9EF5DF, 0x2F745EA5, 0x22FB9C1C, 0x42097C3B, 0x961266B3, 0xC898BDDC, 0xD1352D55, 0x6E35C940, 0x58A97AEE, 0xECD14F5A, 0xC8D1DDE9, 0x667CAE9A, 0x50F5976F, 0x527E9ACA, 0xB356FCB0, 0xC751469A, 0xF7618145, 0x092930BD, 0xFB26DCD8, 0xDE9A1D14, 0xB48C5650, 0x5F35DAB4, 0x26712B87, 0xAB0453E0, }; public final void setState(final int s) { stateA = startingA[s >>> 9 & 0x7F]; for (int i = s & 0x1FF; i > 0; i--) { stateA = (stateA << 9) + (stateA << 8 | stateA >>> 24); } stateB = startingB[s >>> 17 & 0x7F]; for (int i = s >>> 8 & 0x1FF; i > 0; i--) { stateB = (stateB << 5) + (stateB << 1 | stateB >>> 31); } stateC = startingC[s >>> 25]; for (int i = s >>> 16 & 0x1FF; i > 0; i--) { stateC = (stateC << 27) + (stateC << 20 | stateC >>> 12); } } public final int nextInt() { stateA = (stateA << 9) + (stateA << 8 | stateA >>> 24); stateB = (stateB << 5) + (stateB << 1 | stateB >>> 31); stateC = (stateC << 27) + (stateC << 20 | stateC >>> 12); return stateA ^ stateB ^ stateC; } @Override public final int next(final int bits) { stateA = (stateA << 9) + (stateA << 8 | stateA >>> 24); stateB = (stateB << 5) + (stateB << 1 | stateB >>> 31); stateC = (stateC << 27) + (stateC << 20 | stateC >>> 12); return (stateA ^ stateB ^ stateC) >>> (32 - bits); } @Override public final long nextLong() { stateA = (stateA << 9) + (stateA << 8 | stateA >>> 24); stateB = (stateB << 5) + (stateB << 1 | stateB >>> 31); stateC = (stateC << 27) + (stateC << 20 | stateC >>> 12); final long t = (stateA ^ stateB ^ stateC) & 0xFFFFFFFFL; stateA = (stateA << 9) + (stateA << 8 | stateA >>> 24); stateB = (stateB << 5) + (stateB << 1 | stateB >>> 31); stateC = (stateC << 27) + (stateC << 20 | stateC >>> 12); return t << 32 | ((stateA ^ stateB ^ stateC) & 0xFFFFFFFFL); } /** * Produces a copy of this Mover32RNG that, if next() and/or nextLong() are called on this object and the * copy, both will generate the same sequence of random numbers from the point copy() was called. This just need to * copy the state so it isn't shared, usually, and produce a new value with the same exact state. * * @return a copy of this Mover32RNG */ @Override public Molerat32RNG copy() { return new Molerat32RNG(stateA, stateB, stateC); } /** * Gets the "A" part of the state; if this generator was set with {@link #Molerat32RNG()}, * {@link #Molerat32RNG(int)}, or {@link #setState(int)}, then this will be on the optimal subcycle, otherwise it * may not be. * @return the "A" part of the state, an int */ public int getStateA() { return stateA; } /** * Gets the "A" part of the state; if this generator was set with {@link #Molerat32RNG()}, * {@link #Molerat32RNG(int)}, or {@link #setState(int)}, then this will be on the optimal subcycle, otherwise it * may not be. * @return the "B" part of the state, an int */ public int getStateB() { return stateB; } /** * Gets the "C" part of the state; if this generator was set with {@link #Molerat32RNG()}, * {@link #Molerat32RNG(int)}, or {@link #setState(int)}, then this will be on the optimal subcycle, otherwise it * may not be. * @return the "C" part of the state, an int */ public int getStateC() { return stateC; } /** * Sets the "A" part of the state to any int, which may put the generator in a low-period subcycle. * Use {@link #setState(int)} to guarantee a good subcycle. * @param stateA any int except 0, which this changes to 1 */ public void setStateA(final int stateA) { this.stateA = stateA == 0 ? 1 : stateA; } /** * Sets the "B" part of the state to any int, which may put the generator in a low-period subcycle. * Use {@link #setState(int)} to guarantee a good subcycle. * @param stateB any int except 0, which this changes to 1 */ public void setStateB(final int stateB) { this.stateB = stateB == 0 ? 1 : stateB; } /** * Sets the "C" part of the state to any int, which may put the generator in a low-period subcycle. * Use {@link #setState(int)} to guarantee a good subcycle. * @param stateC any int except 0, which this changes to 1 */ public void setStateC(final int stateC) { this.stateC = stateC == 0 ? 1 : stateC; } @Override public String toString() { return "Mover32RNG with stateA 0x" + StringKit.hex(stateA) + ", stateB 0x" + StringKit.hex(stateB) + ", and stateC 0x" + StringKit.hex(stateC); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Molerat32RNG molerat32RNG = (Molerat32RNG) o; return stateA == molerat32RNG.stateA && stateB == molerat32RNG.stateB && stateC == molerat32RNG.stateC; } @Override public int hashCode() { return 31 * (31 * stateA + stateB) + stateC | 0; } // public static void main(String[] args) // { // int stateA = 0x90D7C575, stateB = 0x7E7A773E, stateC = 0x52CC878D; // System.out.println("int[] startingA = {"); // for (int ctr = 0; ctr < 128; ctr++) { // System.out.printf("0x%08X, ", stateA); // if((ctr & 7) == 7) // System.out.println(); // for (int i = 0; i < 512; i++) { // stateA = (stateA << 9) + (stateA << 8 | stateA >>> 24); // } // } // System.out.println("}, startingB = {"); // for (int ctr = 0; ctr < 128; ctr++) { // System.out.printf("0x%08X, ", stateB); // if((ctr & 7) == 7) // System.out.println(); // for (int i = 0; i < 512; i++) { // stateB = (stateB << 5) + (stateB << 1 | stateB >>> 31); // } // } // System.out.println("}, startingC = {"); // for (int ctr = 0; ctr < 128; ctr++) { // System.out.printf("0x%08X, ", stateC); // if((ctr & 7) == 7) // System.out.println(); // for (int i = 0; i < 512; i++) { // stateC = (stateC << 27) + (stateC << 20 | stateC >>> 12); // } // } // System.out.println("};"); // } }
package com.huawei.esdk.demo.common; public interface Constant { /** * session无效 */ int SESSION_NOT_CORRECT = 1351614476; /** * siteUri为空 */ int SITEURI_IS_NULL = 570789891; /** * */ int ERROR_CODE_DEVICE_CONN_ERROR = 2130000012; }
package com.semester_project.smd_project.Activities; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.semester_project.smd_project.R; public class HomePage extends AppCompatActivity { private Button signup, signin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_page); signup = findViewById(R.id.signuphomepage); signin = findViewById(R.id.signinhomepage); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent signupintent = new Intent(HomePage.this, SignUp.class); startActivity(signupintent); finish(); } }); signin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent signinintent = new Intent(HomePage.this, SignIn.class); startActivity(signinintent); finish(); } }); } }
package example.jamesb.moviessample.util.concurrency; import android.os.Handler; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import javax.inject.Inject; import androidx.annotation.NonNull; public class ExecutionContext { private final MainThreadContext mainThreadContext; private final BackgroundContext backgroundContext; public ExecutionContext(MainThreadContext mainThreadContext, BackgroundContext backgroundContext) { this.mainThreadContext = mainThreadContext; this.backgroundContext = backgroundContext; } public static class MainThreadContext implements Executor { private final Handler mMainThreadHandler; @Inject MainThreadContext(Handler mainThreadHandler) { this.mMainThreadHandler = mainThreadHandler; } @Override public void execute(@NonNull Runnable command) { mMainThreadHandler.post(command); } } public static class BackgroundContext implements Executor { private final ExecutorService mExecutorService; @Inject BackgroundContext(ExecutorService executorService) { this.mExecutorService = executorService; } @Override public void execute(@NonNull Runnable command) { mExecutorService.execute(command); } } public MainThreadContext getMainThreadContext() { return mainThreadContext; } public BackgroundContext getBackgroundContext() { return backgroundContext; } }
package com.ace.production.test; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import android.test.AndroidTestCase; import com.ace.production.text.SMSContent; import com.ace.production.text.SMSContentParser; public class SMSContentParserTest extends AndroidTestCase { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void should_get_the_correct_SMSContent_of_gdbbank() { SMSContentParser parser = new SMSContentParser(); String testData = "您尾号8436广发卡12月人民币账单金额647.69," + "最低还款100.00,还款到期01月12日。请留意电子账单," + "若已还勿理会【广发银行】"; SMSContent content = parser.parse(testData); Assert.assertEquals("广发银行", content.getBankName()); Assert.assertEquals(12, content.getBillingMonth()); Assert.assertEquals(true, 647.69f - content.getPayMoney("人民币").floatValue() < Float.MIN_VALUE); Assert.assertEquals(true, 100.00f - content.getTheLeastPayMoney() < Float.MIN_VALUE); Assert.assertEquals(1, content.getPayTime().getMonth()); Assert.assertEquals(12, content.getPayTime().getDate()); } @Test public void should_get_the_correct_SMSContent_of_cmbbank(){ SMSContentParser parser = new SMSContentParser(); String testData = "李斌先生,您招行个人信用卡02月" + "账单金额人民币1,580.10,美金58.34。" + "到期还款日02月25日[招商银行]" ; SMSContent content = parser.parse(testData); Assert.assertEquals("招商银行", content.getBankName()); Assert.assertEquals(2, content.getBillingMonth()); Assert.assertEquals(true, 1580.10f - content.getPayMoney("人民币").floatValue() < Float.MIN_VALUE); Assert.assertEquals(true, 58.34f - content.getPayMoney("美金").floatValue() < Float.MIN_VALUE); Assert.assertEquals(2, content.getPayTime().getMonth()); Assert.assertEquals(25, content.getPayTime().getDate()); } }
package com.cognizant.springlearn04.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Shiyam * */ @Entity public class Country { @NotNull @Size(min=2, max=2, message="Country code should be 2 characters") @Id String code; @Column String name; private static final Logger LOGGER = LoggerFactory.getLogger(Country.class); public Country() { LOGGER.debug("Inside Country Class"); } public String getName() { LOGGER.info("START"); return name; } public void setName(String name) { LOGGER.info("START"); this.name = name; LOGGER.info("End"); } public String getCode() { LOGGER.info("START"); return code; } public void setCode(String code) { LOGGER.info("START"); this.code = code; LOGGER.info("End"); } @Override public String toString() { return "Country [name=" + name + ", code=" + code + "]"; } }
package problem18; /** * @author Jackid * JDK-version:1.8 * Problem:牛客网-剑指offer《数组中重复的数字》 * Result:已通过了所有的测试用例 */ /*题目描述: 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 */ public class Solution { // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number,length of // duplication array is 1,so using duplication[0] = ? in implementation; // Here duplication like pointor in C/C++, duplication[0] equal *duplication in // C/C++ // 这里要特别注意~返回任意重复的一个,赋值duplication[0] // Return value: true if the input is valid, and there are some duplications in // the array number // otherwise false public boolean duplicate(int numbers[], int length, int[] duplication) { for (int i = 0; i < length; i++) {// 遍历数组中的每一个数 while (numbers[i] != i)// 直到这个数的值和它自己的位置相对应,否则一直做替换 { if (numbers[numbers[i]] != numbers[i]) {// 在替换过程中,如果两个数不相同,则正常替换 int temporary = numbers[numbers[i]]; numbers[numbers[i]] = numbers[i]; numbers[i] = temporary; } else { // 如果出现两个数相同的情况,则表示在数组中出现了重复的数字,将该数赋值给duplication[0],同时返回true duplication[0] = numbers[i]; return true; } } } return false;// 找不到就返回false } }
package ars.ramsey.interviewhelper.widget.Calendar; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.TimePicker; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import ars.ramsey.interviewhelper.R; /** * Created by Ramsey on 2017/4/22. */ public class DateTimePickDialog implements DatePicker.OnDateChangedListener,TimePicker.OnTimeChangedListener{ private EditText mEditText; private Context mContext; private DatePicker mDatePicker; private TimePicker mTimePicker; private int mYear; private int mMonth; private int mDay; private int mHour; private int mMinute; public DateTimePickDialog(Context context,EditText editText) { this.mContext = context; this.mEditText = editText; } public void showDialog() { View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_datetime,null); mDatePicker = (DatePicker)view.findViewById(R.id.datePicker); mTimePicker = (TimePicker)view.findViewById(R.id.timePicker); init(); mDatePicker.init(mYear,mMonth,mDay,this); mTimePicker.setCurrentHour(mHour); mTimePicker.setCurrentMinute(mMinute); mTimePicker.setOnTimeChangedListener(this); mTimePicker.setIs24HourView(true); resizePikcer(mDatePicker); resizePikcer(mTimePicker); new AlertDialog.Builder(mContext).setTitle("请选择日期").setView(view).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); GregorianCalendar gregorianCalendar = new GregorianCalendar(mYear,mMonth,mDay,mHour,mMinute); String result = format.format(gregorianCalendar.getTime()); mEditText.setText(result); dialogInterface.dismiss(); } }).create().show(); } private void init(){ Calendar calendar = Calendar.getInstance(); if(!mEditText.getText().toString().equals("")) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { Date date = sdf.parse(mEditText.getText().toString()); calendar.setTime(date); } catch (ParseException e) { e.printStackTrace(); } } mYear = calendar.get(Calendar.YEAR); mMonth = calendar.get(Calendar.MONTH); mDay = calendar.get(Calendar.DAY_OF_MONTH); mHour = calendar.get(Calendar.HOUR_OF_DAY); mMinute = calendar.get(Calendar.MINUTE); } @Override public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) { mYear = i; mMonth = i1; mDay = i2; } @Override public void onTimeChanged(TimePicker timePicker, int i, int i1) { mHour = i; mMinute = i1; } private void resizePikcer(FrameLayout tp){ List<NumberPicker> npList = findNumberPicker(tp); for(NumberPicker np:npList){ resizeNumberPicker(np); } } /** * 得到viewGroup里面的numberpicker组件 * @param viewGroup * @return */ private List<NumberPicker> findNumberPicker(ViewGroup viewGroup){ List<NumberPicker> npList = new ArrayList<NumberPicker>(); View child = null; if(viewGroup != null){ for(int i = 0; i < viewGroup.getChildCount(); i++){ child = viewGroup.getChildAt(i); if(child instanceof NumberPicker){ npList.add((NumberPicker)child); } else if(child instanceof LinearLayout){ List<NumberPicker> result = findNumberPicker((ViewGroup)child); if(result.size()>0){ return result; } } } } return npList; } /* * 调整numberpicker大小 */ private void resizeNumberPicker(NumberPicker np){ LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); np.setLayoutParams(params); } }
package com.wisape.android.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.RectF; import android.graphics.Shader; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.widget.ImageView; import com.wisape.android.R; /** * @author Duke */ public class RoundImageView extends ImageView { public static final int ROUND_TOP_LEFT = 0x0001; public static final int ROUND_TOP_RIGHT = 0x0010; public static final int ROUND_BOTTOM_RIGHT = 0x0100; public static final int ROUND_BOTTOM_LEFT = 0x1000; protected BitmapShader mShader; protected Paint mBitmapPaint; private DisplayMetrics mDm; protected float mBitmapWidth, mBitmapHeight; private PaintFlagsDrawFilter mPaintFilter; private int mRoundType = 0x0000; private int radius; public RoundImageView(Context context) { super(context); init(); } public RoundImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaintFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); ; mDm = getContext().getResources().getDisplayMetrics(); mBitmapPaint = new Paint(); mBitmapPaint.setFlags(Paint.ANTI_ALIAS_FLAG); mBitmapPaint.setAntiAlias(true); radius = getContext().getResources().getDimensionPixelSize(R.dimen.app_dialog_radius); } /** * * @param point {@link #ROUND_TOP_LEFT},{@link #ROUND_TOP_RIGHT},{@link #ROUND_BOTTOM_RIGHT},{@link #ROUND_BOTTOM_LEFT} */ public void setOrthogonal(int point) { this.mRoundType = point; } public void setImageBitmap(Bitmap bitmap) { mShader = null; if (null == bitmap || bitmap.isRecycled()) { mBitmapPaint.setShader(null); } else { mBitmapWidth = bitmap.getWidth(); mBitmapHeight = bitmap.getHeight(); mShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setShader(mShader); } this.invalidate(); } @Override public void draw(Canvas canvas) { if (null != mShader) { Matrix matrix = new Matrix(); mShader.getLocalMatrix(matrix); matrix.setScale(getWidth() / mBitmapWidth, getHeight() / mBitmapHeight); mShader.setLocalMatrix(matrix); } canvas.save(); canvas.setDrawFilter(mPaintFilter); RectF rectF = new RectF(0, 0, this.getWidth(), this.getHeight()); canvas.drawRoundRect(rectF, radius, radius, mBitmapPaint); if(0x0000 != mRoundType) { if ((mRoundType & ROUND_TOP_LEFT) != 0) { canvas.drawRect(0, 0, radius, radius, mBitmapPaint); } if ((mRoundType & ROUND_TOP_RIGHT) != 0) { canvas.drawRect(rectF.right - radius, 0, rectF.right, radius, mBitmapPaint); } if ((mRoundType & ROUND_BOTTOM_LEFT) != 0) { canvas.drawRect(0, rectF.bottom - radius, radius, rectF.bottom, mBitmapPaint); } if ((mRoundType & ROUND_BOTTOM_RIGHT) != 0) { canvas.drawRect(rectF.right - radius, rectF.bottom - radius, rectF.right, rectF.bottom, mBitmapPaint); } } canvas.restore(); } }
package com.tencent.mm.plugin.wallet_payu.create.ui; import android.text.Editable; import android.text.TextWatcher; class WalletPayUStartOpenUI$1 implements TextWatcher { final /* synthetic */ WalletPayUStartOpenUI pES; WalletPayUStartOpenUI$1(WalletPayUStartOpenUI walletPayUStartOpenUI) { this.pES = walletPayUStartOpenUI; } public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } public final void afterTextChanged(Editable editable) { WalletPayUStartOpenUI.a(this.pES); } }
package rjm.romek.awscourse.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk; import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalkClientBuilder; import com.amazonaws.services.rds.AmazonRDS; import com.amazonaws.services.rds.AmazonRDSClientBuilder; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; @Profile({"prod", "dev"}) @Configuration public class AwsConfiguration { @Bean public AmazonS3 amazonS3() { return AmazonS3ClientBuilder.standard().build(); } @Bean public AmazonEC2 amazonEC2() { return AmazonEC2ClientBuilder.standard().build(); } @Bean public AWSElasticBeanstalk amazonElasticBeanstalk() { return AWSElasticBeanstalkClientBuilder.standard().build(); } @Bean public AWSSecurityTokenService amazonSTS() { return AWSSecurityTokenServiceClientBuilder.standard().build(); } @Bean public AmazonRDS amazonRDS() { return AmazonRDSClientBuilder.standard().build(); } }
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Scanner; public class ClientCommandListener implements Runnable, KeyListener { Client client; Scanner sc; public ClientCommandListener(Client client) { this.client = client; sc = new Scanner(System.in); Thread commandListener = new Thread(this); commandListener.start(); } public void run() { while(true) { String fullCommand = sc.nextLine(); String[] commandList = fullCommand.split(" "); String args = ""; for(int i = 1; i < commandList.length; i++) { args += commandList[i] + " "; } String firstCommand = commandList[0].toLowerCase(); switch(firstCommand) { case "/t": client.getClientOutput().sendEnvelope(new Envelope(client.getClientPlayer().toString() + ": " + args, "String")); break; case "/exit": client.getClientOutput().sendEnvelope(new Envelope(client.getClientPlayer().toString() + " disconnected! ", "String")); client.getClientOutput().sendEnvelope(new Envelope(client.getSpaceStats(), "SpaceStats")); System.exit(0); break; case "/help": System.out.println("\nCommand List:"); System.out.println("/t Sends a message. "); System.out.println("/exit Leaves the game. "); System.out.println(); break; } } } public void keyPressed(KeyEvent arg0) { int key = arg0.getKeyCode(); if(key == KeyEvent.VK_ESCAPE) { client.getClientOutput().sendEnvelope(new Envelope(client.getClientPlayer().toString() + " has left the server! ", "String")); //client.getClientOutput().sendEnvelope(new Envelope(client.getClientPlayer().toString() + " has left the server! " ,"String")); client.getClientOutput().sendEnvelope(new Envelope(client.getSpaceStats(), "SpaceStats")); } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }
package com.company; import Jama.Matrix; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class ReadFileCSV { public ReadFileCSV() { } public Matrix ReadFileTrain() { String csvFile = "/home/nghia/Desktop/hoc may/1-prostate-training-data.csv"; String line = ""; String cvsSplitBy = ","; ArrayList<double[]> m = new ArrayList<double[]>(); try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { boolean x = false; while ((line = br.readLine()) != null) { // bo dong dau if (x == true) { String[] index = line.split(cvsSplitBy); double row[] = new double[9]; row[0] = 1; for (int i = 0; i < 8; ++i) { double a = Double.valueOf(index[i]); row[i + 1] = a; } m.add(row); } x = true; } } catch (IOException e) { e.printStackTrace(); } // can phai bat ngoai le double[][] matrix = new double[m.size()][]; for (int i = 0; i < m.size(); ++i) { matrix[i] = m.get(i); } return new Matrix(matrix); } public Matrix ReadFileTrainCreateMatrixY() { String csvFile = "src/1-prostate-training-data.csv"; String line = ""; String cvsSplitBy = ","; double[][] m = new double[1][67]; try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { boolean x = false; int i = 0; while ((line = br.readLine()) != null) { // bo dong dau if (x == true) { String[] index = line.split(cvsSplitBy); m[0][i] = Double.valueOf(index[8]); i++; } x = true; } } catch (IOException e) { e.printStackTrace(); } Matrix matrix = new Matrix(m); return matrix.transpose(); } public Matrix ReadFileMSSV() { String csvFile = "src/20143186-test.csv"; String line = ""; String cvsSplitBy = ","; ArrayList<double[]> m = new ArrayList<double[]>(); try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) { while ((line = br.readLine()) != null) { String[] index = line.split(cvsSplitBy); double row[] = new double[8]; for (int i = 0; i < 8; ++i) { double a = Double.valueOf(index[i]); row[i] = a; } m.add(row); } } catch (IOException e) { e.printStackTrace(); } // can phai bat ngoai le double[][] matrix = new double[m.size()][]; for (int i = 0; i < m.size(); ++i) { matrix[i] = m.get(i); } return new Matrix(matrix); } }
package c.t.m.g; import android.content.IntentFilter; final class v implements Runnable { v() { } public final void run() { try { p.e(); m.a().registerReceiver(p.m(), new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); } catch (Throwable th) { } } }
package org.alienideology.jcord.event.handler; import org.alienideology.jcord.event.channel.group.user.GroupUserJoinEvent; import org.alienideology.jcord.internal.object.IdentityImpl; import org.alienideology.jcord.internal.object.ObjectBuilder; import org.alienideology.jcord.internal.object.channel.Group; import org.alienideology.jcord.internal.object.client.Client; import org.alienideology.jcord.internal.object.user.User; import org.alienideology.jcord.util.log.LogLevel; import org.json.JSONObject; /** * @author AlienIdeology */ public class ChannelRecipientAddEventHandler extends EventHandler { public ChannelRecipientAddEventHandler(IdentityImpl identity) { super(identity); } @Override public void dispatchEvent(JSONObject json, int sequence) { Client client = identity.getClient(); Group group = (Group) client.getGroup(json.getString("channel_id")); if (group == null) { logger.log(LogLevel.FETAL, "[UNKNOWN GROUP] [CHANNEL_RECIPIENT_ADD_EVENT_HANDLER] ID: " + json.getString("channel_id")); return; } User user = new ObjectBuilder(identity.getClient()).buildUser(json.getJSONObject("user")); group.getRecipients().add(user); dispatchEvent(new GroupUserJoinEvent(identity, sequence, group, user)); } }
package com.example.pangrett.astroweather.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; public class Database extends SQLiteOpenHelper { private static final String dataBaseName = "Weather"; private static final String tableName = "City"; public Database(Context context) { super(context, dataBaseName, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + tableName + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "CITY TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + tableName); } public boolean insertData(String city) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("CITY", city); if ((db.insertWithOnConflict(tableName, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE)) == -1) { return false; } else { return true; } } public boolean deleteData(String city) { SQLiteDatabase db = this.getWritableDatabase(); if (db.delete(tableName, "CITY=?", new String[]{city}) == -1) { return false; } else { return true; } } public Cursor getListContents() { SQLiteDatabase db = this.getWritableDatabase(); Cursor data = db.rawQuery("SELECT * FROM " + tableName, null); return data; } }
/* * Copyright 2010-2013 Robert J. Buck * * 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.buck.jsql.sample.collections; import com.buck.jsql.Query; import com.buck.jsql.QueryException; import org.junit.Assert; import org.junit.Test; import java.util.Collection; import java.util.Random; import java.util.Vector; /** * Tests querying a collection of person objects. * * @author Robert J. Buck */ public class PersonTestCase { @Test public void testPerformanceOfApplies() throws QueryException { final int count = 1000; final int repeat = 1000; long nres = 0; Vector<Person> people = new Vector<Person>(); Random r = new Random(); for (int i = 0; i < count; i++) { Person person = new Person(); person.setAge(r.nextInt(100)); people.add(person); } final long start = System.currentTimeMillis(); Query<Person> query = new Query<Person>(Person.class, "age >= 50"); Query.Apply<Person> fire = new Query.Apply<Person>() { public void action(Person employee) { employee.yourFired(); } }; Query.Apply<Person> hire = new Query.Apply<Person>() { public void action(Person employee) { employee.yourHired(); } }; for (int i = 0; i < repeat; i++) { query.apply(people, fire); query.apply(people, hire); } final long end = System.currentTimeMillis(); final long elapsed = end - start; final double rate = ((double) count * repeat) * 1000 / ((double) elapsed); System.out.println("Apply Performance: "); System.out.println("\trate: " + rate); } @Test public void testPerformanceOfQueries() throws QueryException { final int count = 1000; final int repeat = 1000; long nres = 0; Vector<Person> people = new Vector<Person>(); Random r = new Random(); for (int i = 0; i < count; i++) { Person person = new Person(); person.setAge(r.nextInt(100)); people.add(person); } final long start = System.currentTimeMillis(); Query<Person> squery = new Query<Person>(Person.class, "age >= 50 AND firedNearRetirement IS FALSE"); for (int i = 0; i < repeat; i++) { Collection<Person> results = squery.select(people); nres += results.size(); for (Person p : results) { p.getAge(); } } final long end = System.currentTimeMillis(); final long elapsed = end - start; final double rate = ((double) count * repeat) * 1000 / ((double) elapsed); System.out.println("Query Performance: "); System.out.println("\trate: " + rate); System.out.println("\tnres: " + nres); } @Test public void testQueryOfPersons() throws QueryException { final int count = 1000; // generate seed data Vector<Person> people = new Vector<Person>(); Random r = new Random(); for (int i = 0; i < count; i++) { Person person = new Person(); person.setAge(r.nextInt(100)); people.add(person); } // create query // US companies fire all employees approaching retirement age for cost // savings reasons. Query<Person> query = new Query<Person>(Person.class, "age >= 50"); Query.Apply<Person> apply = new Query.Apply<Person>() { public void action(Person employee) { employee.yourFired(); } }; query.apply(people, apply); // benchmark // US companies check to make sure there are no stragglers. Query<Person> squery = new Query<Person>(Person.class, "age < 50 AND firedNearRetirement IS TRUE"); Collection<Person> stragglers = squery.select(people); Assert.assertEquals(0, stragglers.size()); } @Test public void testLikePredicate() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); p.setName("bob"); people.add(p); Query<Person> query = new Query<Person>(Person.class, "name LIKE '_ob'"); Collection<Person> results = query.select(people); Assert.assertEquals(1, results.size()); } @Test public void testNullPredicate() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); people.add(p); Query<Person> query = new Query<Person>(Person.class, "name is NULL"); Collection<Person> results = query.select(people); Assert.assertEquals(1, results.size()); } @Test public void testNotNullPredicate() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); people.add(p); Query<Person> query = new Query<Person>(Person.class, "name is not NULL"); Collection<Person> results = query.select(people); Assert.assertEquals(0, results.size()); } @Test public void testBetweenPredicate() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); p.setAge(54); people.add(p); Query<Person> query = new Query<Person>(Person.class, "age between 50 and 60"); Collection<Person> results = query.select(people); Assert.assertEquals(1, results.size()); } @Test public void testNotBetweenPredicate() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); p.setAge(54); people.add(p); Query<Person> query = new Query<Person>(Person.class, "age not between 50 and 60"); Collection<Person> results = query.select(people); Assert.assertEquals(0, results.size()); } @Test public void testBooleanTest() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); people.add(p); Query<Person> query = new Query<Person>(Person.class, "firedNearRetirement is false"); Collection<Person> results = query.select(people); Assert.assertEquals(1, results.size()); } @Test public void testNotBooleanTest() throws QueryException { Vector<Person> people = new Vector<Person>(); Person p = new Person(); people.add(p); Query<Person> query = new Query<Person>(Person.class, "firedNearRetirement is not false"); Collection<Person> results = query.select(people); Assert.assertEquals(0, results.size()); } }
package ca.mohawk.jdw.shifty.server.utils; /* I, Josh Maione, 000320309 certify that this material is my original work. No other person's work has been used without due acknowledgement. I have not made my work available to anyone else. Module: server Developed By: Josh Maione (000320309) */ import ca.mohawk.jdw.shifty.companyapi.Company; import ca.mohawk.jdw.shifty.companyapi.creator.CompanyCreator; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.Optional; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Stream; public final class CompanyLoader { private CompanyLoader(){} public static Company load(final File jarFile) throws Exception { final JarFile jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); final URLClassLoader cl = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}); while(entries.hasMoreElements()){ final JarEntry entry = entries.nextElement(); if(!entry.getName().endsWith(".class")) continue; final Class clazz = cl.loadClass(entry.getName().replace(".class", "").replace('/', '.')); if(clazz.isInterface()) continue; final Optional<Class> loaderClassOpt = Stream.of(clazz.getInterfaces()) .filter(CompanyCreator.class::equals) .findFirst(); if(!loaderClassOpt.isPresent()) continue; final CompanyCreator creator = (CompanyCreator) clazz.newInstance(); return creator.create(); } return null; } }
package com.example.spendingtrackerandroid.ui.transactions; import android.content.Context; import android.os.Bundle; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.example.spendingtrackerandroid.CustomAdapter; import com.example.spendingtrackerandroid.R; import android.view.View; import android.widget.ListView; import org.json.JSONArray; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.widget.Toast; public class TransactionFragment extends Fragment { Context con; ListView list; JSONArray data; CustomAdapter cust_adapater; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_transactions, container, false); list = root.findViewById(R.id.listview); getDataFromDB(); return root; } public void onResume() { super.onResume(); getDataFromDB(); } public void getDataFromDB() { String url ="http://192.168.1.69/SpendingMoney/getAllTransactions.php"; RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext()); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { data = response; cust_adapater = new CustomAdapter(getActivity().getApplicationContext(), data); list.setAdapter(cust_adapater); }}, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO: Handle error Toast.makeText(getActivity().getApplicationContext(), "Error:" + error.toString(), Toast.LENGTH_SHORT).show(); } }); queue.add(jsonArrayRequest); } }
package com.lazypanda.algorithms.greedy; import java.util.Arrays; /** * Union-Find algorithm implementation to detect a cycle in a graph with no self loops. * * A disjoint-set data structure is a data structure that keeps track of a set of elements * partitioned into a number of disjoint (non-overlapping) subsets. * * A union-find algorithm is an algorithm that performs two useful operations on such a data structure: * * Find: Determine which subset a particular element is in. This can be used for determining * if two elements are in the same subset. * * Union: Join two subsets into a single subset. */ public class UnionFind { int [] parent; /** * @param graph is an instance of class Graph * parent[] is a 1D array to keep track of subsets of vertices. * */ public UnionFind(Graph graph){ parent = new int[graph.numVertices]; Arrays.fill(parent,-1); } /** * Finds the subset of element * @param element * @return integer subset to which element belongs */ private int find(int element){ if(parent[element] == -1){ return element; } return find(parent[element]); } /** * Performs union of two subsets to which element1 and element2 belong * @param element1 integer vertice * @param element2 integer vertice */ private void union(int element1, int element2){ int set1 = find(element1); int set2 = find(element2); parent[element1] = element2; } /** * Checks if a graph contains cycle * @param graph instance of class Graph * @return integer 1 is graph is a cycle 0 otherwise */ public int isCycle(Graph graph){ for(int i=0; i<graph.numEdges; i++){ int element1 = find(graph.edges[i].source); int element2 = find(graph.edges[i].destination); if(element1 == element2) return 1; union(element1, element2); } return 0; } }
package cordova.plugin.zk.plugin; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Handler; import android.os.Message; import com.alipay.sdk.app.PayTask; import com.ewell.guahao.nanjingchildren.MainActivity; import com.ewell.guahao.nanjingchildren.wxapi.WXPayEntryActivity; import com.ewell.guahao.nanjingchildren.AndroidUnionPayPluginActivity; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.HashMap; import java.util.Map; /** * This class echoes a string called from JavaScript. */ public class ZkPlugin extends CordovaPlugin { private static final String VERSION_NUMBER = "getVersionNumber"; private static final String Map = "openMap"; private static final String ALIPAY = "alipay"; private static final String WXPAY = "wxpay"; private static final String UNPay = "unionPay"; private static final String BAIDUPUSH = "baidupush"; private static final int SDK_PAY_FLAG = 1; private static final String KEEPALIVE = "keepAlive"; public static CallbackContext keepCallbackContext; private CallbackContext wxCallbackContext; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { switch (action) { case VERSION_NUMBER: this.getVersionNumber(callbackContext); break; case Map: this.openMap((JSONObject) args.get(0), callbackContext); break; case ALIPAY: this.alipay((String)args.get(0), callbackContext); break; case WXPAY: this.wxpay((JSONObject) args.get(0), callbackContext); break; case UNPay: this.unionPay((String) args.get(0), callbackContext); break; case BAIDUPUSH: this.baidupush((String) args.get(0), callbackContext); break; case KEEPALIVE: this.keepAlive(callbackContext); break; } return true; } public void getVersionNumber(CallbackContext callbackContext) { try { PackageManager packageManager = this.cordova.getActivity().getPackageManager(); callbackContext.success(packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName); } catch (Exception e) { callbackContext.success("N/A"); } } /** * 打开地图 * @param json * @param callbackContext */ public void openMap(JSONObject json, CallbackContext callbackContext) { try { String hospital = String.valueOf(json.get("hospital")); String lat = String.valueOf(json.get("lat")); String lon = String.valueOf(json.get("lon")); String address = String.valueOf(json.get("address")); if(isInstallByread("com.baidu.BaiduMap")){ Intent intent = Intent.getIntent("intent://map/marker?location="+ lat + "," + lon +"&title=" + hospital + "&content="+ address + "&src=zhicall|zhicall#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"); this.cordova.getActivity().startActivity(intent); callbackContext.success(); } else if(isInstallByread("com.autonavi.minimap")){ Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("androidamap://viewMap?sourceApplication=appname&poiname=" + hospital +"&lat="+ lat +"&lon="+ lon + "&dev=1")); intent.setPackage("com.autonavi.minimap"); this.cordova.getActivity().startActivity(intent); callbackContext.success(); } else { String invalidUrl = "http://app.zhicall.com/mobile-web/baidumap/baidumap.html?x=" + lat + "&y=" + lon; Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); Uri content_url = Uri.parse(invalidUrl); intent.setData(content_url); this.cordova.getActivity().startActivity(intent); } } catch (Exception e) { } } private void alipay(String info, final CallbackContext callbackContext) { final String orderInfo = info; // 订单信息 Runnable payRunnable = new Runnable() { @Override public void run() { PayTask alipay = new PayTask(cordova.getActivity()); Map<String, String> result = alipay.payV2(orderInfo, true); Map obj = new HashMap(); obj.put("result", result); obj.put("callbackContext", callbackContext); Message msg = new Message(); msg.what = SDK_PAY_FLAG; msg.obj = obj; payHandler.sendMessage(msg); } }; // 必须异步调用 Thread payThread = new Thread(payRunnable); payThread.start(); } private void wxpay(JSONObject object, final CallbackContext callbackContext) throws JSONException{ String appId = object.getString("payAppId"); String nonceStr = object.getString("payNonceStr"); String packageValue = object.getString("payPackage"); String partnerId = object.getString("payPartnerid"); String prepayId = object.getString("payPrepayid"); String sign = object.getString("paySign"); String timeStamp = object.getString("payTimestamp"); String zhicallSerial = object.getString("zhicallSerial"); try { Intent intent = new Intent().setClass(cordova.getActivity(), WXPayEntryActivity.class); intent.putExtra("appId", appId); intent.putExtra("nonceStr", nonceStr); intent.putExtra("packageValue", packageValue); intent.putExtra("partnerId", partnerId); intent.putExtra("prepayId", prepayId); intent.putExtra("sign", sign); intent.putExtra("timeStamp", timeStamp); intent.putExtra("zhicallSerial", zhicallSerial); this.cordova.startActivityForResult(this, intent, 1); this.wxCallbackContext = callbackContext; } catch (Exception e) { } } private void unionPay(String object, final CallbackContext callbackContext) throws JSONException{ try { Intent intent = new Intent().setClass(cordova.getActivity(), AndroidUnionPayPluginActivity.class); intent.putExtra("tn", object); this.cordova.startActivityForResult(this, intent, 1); this.wxCallbackContext = callbackContext; } catch (Exception e) { } } private void baidupush(String object, final CallbackContext callbackContext) throws JSONException{ Map map = new HashMap(); map.put("channelId", MainActivity.channelId); map.put("userId", MainActivity.userId); JSONObject o = new JSONObject(map); callbackContext.success(o); } private void keepAlive(CallbackContext callbackContext){ ZkPlugin.keepCallbackContext = callbackContext; // ZkPlugin.CourseCallback(); } @SuppressLint("HandlerLeak") private Handler payHandler = new Handler() { @SuppressWarnings("unused") public void handleMessage(Message msg) { switch (msg.what) { case SDK_PAY_FLAG: { Map obj = (Map)msg.obj; CallbackContext callbackContext = (CallbackContext)obj.get("callbackContext"); @SuppressWarnings("unchecked") PayResult payResult = new PayResult((Map<String, String>) obj.get("result")); /** 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。 */ String resultInfo = payResult.getResult();// 同步返回需要验证的信息 String resultStatus = payResult.getResultStatus(); // 判断resultStatus 为9000则代表支付成功 if (resultStatus.equals("9000")) { // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。 callbackContext.success("9000"); } else { // 该笔订单真实的支付结果,需要依赖服务端的异步通知。 callbackContext.error(resultStatus); } break; } default: break; } }; }; /** * 判断是否安装目标应用 * @param packageName 目标应用安装后的包名 * @return 是否已安装目标应用 */ private boolean isInstallByread(String packageName) { return new File("/data/data/" + packageName).exists(); } // onActivityResult为第二个Activity执行完后的回调接收方法 @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (resultCode) { // resultCode为回传的标记,我在第二个Activity中回传的是RESULT_OK case Activity.RESULT_OK: if(intent.getStringExtra("WXFlag").equals("false")){ wxCallbackContext.error("2000"); //2000为未安装微信 } else { String msg = intent.getStringExtra("msg"); if ("9000".equals(msg)) { wxCallbackContext.success(msg); } else { wxCallbackContext.error(msg); } } break; case -2: String msg = intent.getStringExtra("msg"); if ("9000".equals(msg)) { wxCallbackContext.success(msg); } else { wxCallbackContext.error(msg); } break; default: break; } } }
/* This file was generated by SableCC (http://www.sablecc.org/). */ package node; import analysis.*; @SuppressWarnings("nls") public final class AIfelseLogic extends PLogic { private PTerm _if_; private TQuery _query_; private TLBrace _thenin_; private PImpl _then_; private TColon _colon_; private TLBrace _elsein_; private PImpl _else_; public AIfelseLogic() { // Constructor } public AIfelseLogic( @SuppressWarnings("hiding") PTerm _if_, @SuppressWarnings("hiding") TQuery _query_, @SuppressWarnings("hiding") TLBrace _thenin_, @SuppressWarnings("hiding") PImpl _then_, @SuppressWarnings("hiding") TColon _colon_, @SuppressWarnings("hiding") TLBrace _elsein_, @SuppressWarnings("hiding") PImpl _else_) { // Constructor setIf(_if_); setQuery(_query_); setThenin(_thenin_); setThen(_then_); setColon(_colon_); setElsein(_elsein_); setElse(_else_); } @Override public Object clone() { return new AIfelseLogic( cloneNode(this._if_), cloneNode(this._query_), cloneNode(this._thenin_), cloneNode(this._then_), cloneNode(this._colon_), cloneNode(this._elsein_), cloneNode(this._else_)); } @Override public void apply(Switch sw) { ((Analysis) sw).caseAIfelseLogic(this); } public PTerm getIf() { return this._if_; } public void setIf(PTerm node) { if(this._if_ != null) { this._if_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._if_ = node; } public TQuery getQuery() { return this._query_; } public void setQuery(TQuery node) { if(this._query_ != null) { this._query_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._query_ = node; } public TLBrace getThenin() { return this._thenin_; } public void setThenin(TLBrace node) { if(this._thenin_ != null) { this._thenin_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._thenin_ = node; } public PImpl getThen() { return this._then_; } public void setThen(PImpl node) { if(this._then_ != null) { this._then_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._then_ = node; } public TColon getColon() { return this._colon_; } public void setColon(TColon node) { if(this._colon_ != null) { this._colon_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._colon_ = node; } public TLBrace getElsein() { return this._elsein_; } public void setElsein(TLBrace node) { if(this._elsein_ != null) { this._elsein_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._elsein_ = node; } public PImpl getElse() { return this._else_; } public void setElse(PImpl node) { if(this._else_ != null) { this._else_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._else_ = node; } @Override public String toString() { return "" + toString(this._if_) + toString(this._query_) + toString(this._thenin_) + toString(this._then_) + toString(this._colon_) + toString(this._elsein_) + toString(this._else_); } @Override void removeChild(@SuppressWarnings("unused") Node child) { // Remove child if(this._if_ == child) { this._if_ = null; return; } if(this._query_ == child) { this._query_ = null; return; } if(this._thenin_ == child) { this._thenin_ = null; return; } if(this._then_ == child) { this._then_ = null; return; } if(this._colon_ == child) { this._colon_ = null; return; } if(this._elsein_ == child) { this._elsein_ = null; return; } if(this._else_ == child) { this._else_ = null; return; } throw new RuntimeException("Not a child."); } @Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._if_ == oldChild) { setIf((PTerm) newChild); return; } if(this._query_ == oldChild) { setQuery((TQuery) newChild); return; } if(this._thenin_ == oldChild) { setThenin((TLBrace) newChild); return; } if(this._then_ == oldChild) { setThen((PImpl) newChild); return; } if(this._colon_ == oldChild) { setColon((TColon) newChild); return; } if(this._elsein_ == oldChild) { setElsein((TLBrace) newChild); return; } if(this._else_ == oldChild) { setElse((PImpl) newChild); return; } throw new RuntimeException("Not a child."); } }
/** * Copyright (C) 2010 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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.beust.jcommander.shell; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.UsageReporter; import jline.Completor; import jline.ConsoleReader; import jline.Terminal; import jline.UnsupportedTerminal; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; import java.io.*; import java.lang.reflect.Method; import java.util.List; /** * <p>Implements a jline base shell for executing JCommander commands.</p> * <p/> * This is code is original based on the Karaf Console code. * * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ abstract public class Shell implements Runnable, UsageReporter { final private InputStream in = System.in; final private PrintStream out = System.out; final private PrintStream err = System.err; protected String prompt = "\u001B[1m>\u001B[0m "; protected Throwable lastException; protected boolean printStackTraces; protected boolean bellEnabled = true; protected File history; @Parameter(description = "a sub command to execute, if not specified, you will be placed into an interactive shell.") public List<String> cliArgs; private Completor completer = createCompleter(); public static class CloseShellException extends RuntimeException { } static final private ThreadLocal<JCommander> CURRENT_JCOMMANDER = new ThreadLocal<JCommander>(); static final private ThreadLocal<Session> CURRENT_SESSION = new ThreadLocal<Session>(); /** * @return the currently executing shell session. */ static public Session getCurrentSession() { return CURRENT_SESSION.get(); } /** * @return the currently executing JCommander */ static public JCommander getCurrentJCommander() { return CURRENT_JCOMMANDER.get(); } public class Session { public Shell getShell() { return Shell.this; } private final JCommander jcommander = getCurrentJCommander(); private ConsoleReader reader; public JCommander getJCommander() { return jcommander; } public ConsoleReader getConsoleReader() { return reader; } private void execute() { Session original = CURRENT_SESSION.get(); CURRENT_SESSION.set(this); Terminal terminal = null; try { terminal = openTerminal(); try { this.reader = new ConsoleReader(System.in, new PrintWriter(out), getClass().getResourceAsStream("keybinding.properties"), terminal); } catch (IOException e) { throw new RuntimeException(e); } if (history != null) { try { // to setup history file support history.getParentFile().mkdirs(); reader.getHistory().setHistoryFile(history); } catch (IOException ignore) { } } reader.setBellEnabled(bellEnabled); if (completer != null) { reader.addCompletor(completer); } try { while (true) { String line = null; try { line = reader.readLine(prompt); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { break; } executeLine(line); } } catch (CloseShellException e) { } } finally { reader = null; closeTerminal(terminal); CURRENT_SESSION.set(original); } } private Terminal openTerminal() { if ("jline.UnsupportedTerminal".equals(System.getProperty("jline.terminal"))) { return new UnsupportedTerminal(); } boolean windows = System.getProperty("os.name").toLowerCase().contains("windows"); try { if (windows) { AnsiWindowsTerminal t = new AnsiWindowsTerminal(); t.setDirectConsole(true); t.initializeTerminal(); return t; } NoInterruptUnixTerminal t = new NoInterruptUnixTerminal(); t.initializeTerminal(); return t; } catch (Throwable e) { return new UnsupportedTerminal(); } } private void closeTerminal(Terminal term) { if (term != null) { try { term.restoreTerminal(); } catch (Exception ignore) { } } } } /** * Override to customize command line parsing, should call {@link #executeCommand(String, String[])} */ public void executeLine(String line) { // implementing a really simple command line parser.. // TODO: replace with something that can handle quoted args etc. String[] args = line.split(" +"); if (args.length > 0) { String[] commandArgs = new String[args.length - 1]; System.arraycopy(args, 1, commandArgs, 0, args.length - 1); executeCommand(args[0], commandArgs); } } public abstract String getShellName(); public abstract String[] getDisplayedCommands(); public abstract JCommander createSubCommand(String name); public void usage(StringBuilder out) { out.append("\n"); out.append(" Commands:\n"); int ln = longestName(getDisplayedCommands()) + 3; for (String name : getDisplayedCommands()) { int spaceCount = ln - name.length(); JCommander jc = createSubCommand(name); if( jc!=null ) { String description = jc.getCommandDescription(); if (description == null) { description = jc.getMainParameterDescription(); } out.append(" " + name + s(spaceCount) + description + "\n"); } } } private String s(int count) { StringBuilder result = new StringBuilder(); for (int i = 0; i < count; i++) { result.append(" "); } return result.toString(); } private int longestName(String[] objects) { int result = 0; for (Object o : objects) { int l = o.toString().length(); if (l > result) result = l; } return result; } /** * Override if you want to change how the command is looked up and executed. It reports * an error if the command is not found. * This ends up calling {@link #executeCommand(String, com.beust.jcommander.JCommander)} */ protected void executeCommand(String command, String[] args) { JCommander jc = createSubCommand(command); if (jc == null) { displayNotFound(command); return; } try { jc.parse(args); } catch (ParameterException e) { err.print(Ansi.ansi().fg(Ansi.Color.RED)); err.println(command + ": invalid usage: " + e.getMessage()); err.print(Ansi.ansi().reset()); err.flush(); out.println(); jc.usage(); return; } try { executeCommand(command, jc); } catch (CloseShellException e) { throw e; } catch (Throwable t) { displayFailure(command, t); } } public void displayFailure(String command, Throwable t) { lastException = t; err.print(Ansi.ansi().fg(Ansi.Color.RED).toString()); if (printStackTraces) { t.printStackTrace(err); } else { if( command==null ) { err.println(getShellName() + ": " + t); } else { err.println(command + ": " + t); } } err.print(Ansi.ansi().fg(Ansi.Color.DEFAULT).toString()); } public void displayNotFound(String command) { err.print(Ansi.ansi().fg(Ansi.Color.RED)); err.println(getShellName() + ": " + command + ": command not found"); err.print(Ansi.ansi().reset()); return; } /** * This executes the command by looking for the first Runnable object * added to the JCommander object. Override if you want to execute * commands using a different strategy. */ protected void executeCommand(String name, JCommander command) { for (Object o : command.getObjects()) { if (o instanceof Runnable) { JCommander original = CURRENT_JCOMMANDER.get(); CURRENT_JCOMMANDER.set(command); try { ((Runnable) o).run(); } finally { CURRENT_JCOMMANDER.set(original); } return; } } throw new IllegalArgumentException("The command " + name + " is not a Runnable command."); } public void run(JCommander jc) { JCommander original = CURRENT_JCOMMANDER.get(); CURRENT_JCOMMANDER.set(jc); try { run(); } finally { CURRENT_JCOMMANDER.set(original); } } /** * Sub classes can override to implement before/after actions like * showing a banner etc. * * @throws IOException */ public void run() { if (cliArgs == null || cliArgs.isEmpty()) { new Session().execute(); } else { String command = cliArgs.remove(0); String args[] = cliArgs.toArray(new String[cliArgs.size()]); executeCommand(command, args); } } private static PrintStream wrap(PrintStream stream) { OutputStream o = AnsiConsole.wrapOutputStream(stream); if (o instanceof PrintStream) { return ((PrintStream) o); } else { return new PrintStream(o); } } private static <T> T unwrap(T stream) { try { Method mth = stream.getClass().getMethod("getRoot"); return (T) mth.invoke(stream); } catch (Throwable t) { return stream; } } protected Completor createCompleter() { return new ShellCompletor(this); } }
package it.htm.entity; import javax.persistence.*; @Entity @Table(name = "user_project") @IdClass(UserProjectPK.class) public class UserProject { @ManyToOne(cascade = CascadeType.MERGE) @Id @PrimaryKeyJoinColumn private User user; @ManyToOne(cascade = CascadeType.MERGE) @Id @PrimaryKeyJoinColumn private Project project; @Column(name = "role") private String role; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
//在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 // // 示例 1: // // 输入: [3,2,1,5,6,4] 和 k = 2 //输出: 5 // // // 示例 2: // // 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 //输出: 4 // // 说明: // // 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 // Related Topics 堆 分治算法 // 👍 1105 👎 0 package me.alvin.leetcode.editor.cn; import java.util.PriorityQueue; public class KthLargestElementInAnArray { public static void main(String[] args) { Solution solution = new KthLargestElementInAnArray().new Solution(); // System.out.println(solution.findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 2)); // System.out.println(solution.findKthLargest(new int[]{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4)); System.out.println(solution.findKthLargest(new int[]{2, 8, 3, 1, 6, 5, 9}, 3)); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int findKthLargest(int[] nums, int k) { //使用小顶堆 PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int val : nums) { if (pq.size() < k) { pq.offer(val); } else if (pq.peek() < val) { pq.poll(); pq.offer(val); } } return pq.peek(); } public int findKthLargest2(int[] nums, int k) { //使用小顶堆 PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int val : nums) { pq.offer(val); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } } //leetcode submit region end(Prohibit modification and deletion) }
package com.client; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; /** * @author Feinik * @Discription 消息处理 * @Data 2018/12/28 * @Version 1.0.0 */ public class MyStompSessionHandler extends StompSessionHandlerAdapter { @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { System.out.println("MyStompSessionHandler.afterConnected"); String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); session.send("/topic/notification", "来自stomp客户端的通知消息" + time); } @Override public Type getPayloadType(StompHeaders headers) { System.out.println("MyStompSessionHandler.getPayloadType"); return super.getPayloadType(headers); } @Override public void handleFrame(StompHeaders headers, Object payload) { System.out.println("MyStompSessionHandler.handleFrame"); super.handleFrame(headers, payload); } @Override public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) { System.err.println("MyStompSessionHandler.handleException:" + exception.getMessage()); } @Override public void handleTransportError(StompSession session, Throwable exception) { System.err.println("MyStompSessionHandler.handleTransportError:" + exception.getMessage()); } }
package com.daffatahta.go2workapp.activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.daffatahta.go2workapp.R; import com.daffatahta.go2workapp.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.r0adkll.slidr.Slidr; import org.w3c.dom.Text; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CompanyRegister extends AppCompatActivity { private Button buttonNext; private EditText usernameInput, emailInput, passwordInput, companyName, kota, websiteCompany, contact; private FirebaseAuth mAuth; private DatabaseReference mData; private static final String TAG= ""; private Pattern pattern1= Pattern.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_company_register); Slidr.attach(this); mData = FirebaseDatabase.getInstance().getReference(); usernameInput = findViewById(R.id.usernameInput); emailInput = findViewById(R.id.emailInput); passwordInput = findViewById(R.id.passInput); companyName = findViewById(R.id.companyNameInput); kota = findViewById(R.id.kotaInput); websiteCompany = findViewById(R.id.websiteInput); contact = findViewById(R.id.editTextContactPerson); buttonNext = (Button) findViewById(R.id.registerNextButton); buttonNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { nextButton(); } }); mAuth = FirebaseAuth.getInstance(); } public void nextButton(){ String username = usernameInput.getText().toString(); final String email = emailInput.getText().toString(); String password = passwordInput.getText().toString(); String name = companyName.getText().toString(); String k = kota.getText().toString(); String web = websiteCompany.getText().toString(); String nomer = contact.getText().toString(); Matcher matcher = pattern1.matcher(email); if (TextUtils.isEmpty(username)){ Toast.makeText(getApplicationContext(), "Username harus di isi!", Toast.LENGTH_SHORT).show(); usernameInput.setError("Harus di isi!"); //usernameInput.setError(Html.fromHtml("<font color = 'red'>test</font>")); usernameInput.requestFocus(); return; } if (TextUtils.isEmpty(email)){ Toast.makeText(getApplicationContext(), "Email harus di isi!", Toast.LENGTH_SHORT).show(); emailInput.setError("Harus di isi!"); emailInput.requestFocus(); return; }else if(!matcher.matches()){ Toast.makeText(getApplicationContext(),"Format email salah!",Toast.LENGTH_SHORT).show(); emailInput.setError("Format email salah!"); emailInput.requestFocus(); return; } if (TextUtils.isEmpty(password)){ Toast.makeText(getApplicationContext(),"Password harus di isi!", Toast.LENGTH_SHORT).show(); passwordInput.setError("Password harus di isi!"); passwordInput.requestFocus(); return; }else if(password.length() < 5 && password.length() > 20){ Toast.makeText(getApplicationContext(),"Panjang password tidak memenuhi kriteria!", Toast.LENGTH_SHORT).show(); passwordInput.requestFocus(); passwordInput.setError("Password salah!"); return; } if (TextUtils.isEmpty(name)){ Toast.makeText(getApplicationContext(), "Nama perusahaan harus di isi!", Toast.LENGTH_SHORT).show(); companyName.setError("Nama perusahaan harus di isi!"); companyName.requestFocus(); return; } if (TextUtils.isEmpty(k)){ Toast.makeText(getApplicationContext(),"Kota perusahaan harus di isi!", Toast.LENGTH_SHORT).show(); kota.requestFocus(); kota.setError("Kota harus di isi!"); return; } if (TextUtils.isEmpty(web)){ Toast.makeText(getApplicationContext(),"Website perusahaan harus di isi!", Toast.LENGTH_SHORT).show(); websiteCompany.setError("Website harus di isi!"); websiteCompany.requestFocus(); return; } if (TextUtils.isEmpty(nomer)){ Toast.makeText(getApplicationContext(), "Contact Person harus di isi!", Toast.LENGTH_SHORT).show(); contact.setError("Harus di isi!"); contact.requestFocus(); return; } mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(CompanyRegister.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ Log.d(TAG, "Create user companyWithEmail.success"); authSuccess(task.getResult().getUser()); Intent intent = new Intent (CompanyRegister.this, Login.class); startActivity(intent); } if (!task.isSuccessful()){ Log.w(TAG, "Create user fail!", task.getException()); Toast.makeText(getApplicationContext(), "Failed!" , Toast.LENGTH_SHORT).show(); Intent i = new Intent(CompanyRegister.this, Register.class); startActivity(i); }else if (task.getException() instanceof FirebaseAuthUserCollisionException){ emailInput.setError("Email Sudah terpakai!"); Toast.makeText(getApplicationContext(), "Email already used! Please login.", Toast.LENGTH_SHORT).show(); } } }); //if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(name) && !TextUtils.isEmpty(k) && !TextUtils.isEmpty(web) && !TextUtils.isEmpty(nomer)){ // Intent intent = new Intent (CompanyRegister.this, FormLowongan.class); // startActivity(intent); //} } public void writeToDatabase (String userId,String username, String email, String password, String namaPerusahaan, String kota, String websitePerusahaan, String contactPerson,String tipe){ User user = new User(username,email,password,namaPerusahaan,kota,websitePerusahaan,contactPerson,tipe); mData.child("User").child(userId).setValue(user); } public void authSuccess (FirebaseUser user){ String usernamee = usernameInput.getText().toString(); String emaill= emailInput.getText().toString(); String passwordd = passwordInput.getText().toString(); String namee = companyName.getText().toString(); String kotaa = kota.getText().toString(); String webb = websiteCompany.getText().toString(); String nomerr = contact.getText().toString(); String tipe = "company"; writeToDatabase(user.getUid(),usernamee, emaill, passwordd, namee, kotaa, webb, nomerr, tipe); } }
package com.yunhe.basicdata.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yunhe.basicdata.dao.CommclassMapper; import com.yunhe.basicdata.entity.Commclass; import com.yunhe.basicdata.service.ICommclassService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * <p> * 商品分类 服务实现类 * </p> * * @author 李恒奎,唐凯宽 * @since 2019-01-02 */ @Service public class CommclassServiceImpl extends ServiceImpl<CommclassMapper, Commclass> implements ICommclassService { @Resource private CommclassMapper commclassMapper; @Override public List<Commclass> query() { return commclassMapper.query(); } @Override public List<Commclass> sel(String name) { List<Commclass> list= (List<Commclass>) commclassMapper.sel(name); return list; } @Override public void add(Commclass commclass) { commclassMapper.insert(commclass); } @Override public void updateCommclass(Map map) { commclassMapper.updateCommclass(map); } @Override public void deleteCommclass(String name) { commclassMapper.deleteCommclass(name); } @Override public int selectidbyname(String name) throws Exception{ /* Commclass commclass=new Commclass(); commclass= commclassMapper.sel(name);*/ int re=0; List<Commclass> list= commclassMapper.sel(name); if (list.size()>0){ for (Commclass commclass : list) { commclass.getId(); re= commclass.getId(); } } return re; } }
package lab4; public class BinaryTree { private Node root; private int count; // Keep track of how many Nodes are in the tree private int arrayCount; // Keeps track of the position in the String array; // Explicit Constructor public BinaryTree() { this.root = null; this.count = 0; this.arrayCount = 0; } // Root Getter private Node getRoot() { return this.root; } // Root Setter private void setRoot(Node root) { this.root = root; } // Count Getter private int getCount() { return this.count; } // Count Incrementer private void incrementCount() { this.count++; } // No need for a count setter since we aren't deleting nodes from the tree // Array Count Getter private int getArrayCount() { return this.arrayCount; } // Array Count Setter private void setArrayCount(int arrayCount) { this.arrayCount = arrayCount; } // Array Count Incrementer private void incrementArrayCount() { this.arrayCount++; } // Is the tree currently empty? private boolean isEmpty() { return getRoot() == null; } // Insert method public void insert(String word) { // Create the Node Node newNode = new Node(word); // Is the tree currently empty? if(isEmpty()) { setRoot(newNode); incrementCount(); } else { // Call recursive insert method helper insert(getRoot(), newNode); } }//END insert method // Insert recursive helper method private void insert(Node current, Node newNode) { // Does the Node already exist with the same word? if(newNode.getWord().equalsIgnoreCase(current.getWord())) { // Increment the Nodes internal counter - duplicates current.incrementCounter(); } // the word is lexicographically less than the current Node's word else if(newNode.getWord().compareToIgnoreCase(current.getWord()) < 0) { // The left spot is available, insert if(current.getLeft() == null) { current.setLeft(newNode); incrementCount(); // How many Nodes in the tree } // Left spot is occupied, recursive insert through left subtree else { insert(current.getLeft(), newNode); } } // the word is lexicographically greater than the current Node's word else { // The right spot is available, insert if(current.getRight() == null) { current.setRight(newNode); incrementCount(); // How many Nodes in the tree } // Right spot is occupied, recursive insert through right subtree else { insert(current.getRight(), newNode); } } }//END insert recursive helper // Search method public boolean search(String word) { // Tree is empty if (isEmpty()) { return false; } // Otherwise recursive search within the tree else { return search(getRoot(), word); } } // Recursive search helper method private boolean search(Node current, String word) { // Did we reach a dead-end? word not found if(current == null) { return false; } // We found the word else if(word.equalsIgnoreCase(current.getWord())) { return true; } // Word is lexicographically less than the current word else if(word.compareToIgnoreCase(current.getWord()) < 0) { return search(current.getLeft(), word); } // Word is lexicographically greater than the current word else if(word.compareToIgnoreCase(current.getWord()) > 0) { return search(current.getRight(), word); } // Eclipse requires this although program would never reach here return false; } public String print() { // Is the tree empty? if(isEmpty()) { return "The tree is empty so there is nothing to print!"; } // Tree is not empty so create a temporary String array that will be used to obtain // the words at each Node String[][] temp = new String[getCount()][2]; setArrayCount(0); // Call the inorder method to traverse the Tree inorder and store the strings in the array inorder(temp, getRoot()); // Create the one String that contains the information required by the user String result = new String(); for(int i = 0; i < temp.length; i++) { result += temp[i][0] + ": " + temp[i][1] + "\n"; } return result; } private void inorder(String[][] temp, Node current) { if(current != null) { // Traverse left subtree inorder(temp, current.getLeft()); // Store the current Node word in the temp String array temp[getArrayCount()][0] = current.getWord(); temp[getArrayCount()][1] = Integer.toString(current.getCounter()); incrementArrayCount(); // Traverse right subtree inorder(temp, current.getRight()); } } // Private Node class private class Node { private String word; private int counter; private Node left; private Node right; private Node parent; // Constructor private Node(String word) { this.word = word; this.counter = 1; this.left = null; this.right = null; this.parent = null; } // Word Getter private String getWord() { return this.word; } // Word Setter private void setWord(String word) { this.word = word; } // Counter Getter private int getCounter() { return this.counter; } // Counter incrementer private void incrementCounter() { this.counter++; } // Don't need a counter setter since we aren't deleting any words // Left Getter private Node getLeft() { return this.left; } // Left Setter private void setLeft(Node left) { this.left = left; } // Right Getter private Node getRight() { return this.right; } // Right Setter private void setRight(Node right) { this.right = right; } // Parent Getter private Node getParent() { return this.parent; } // Parent Setter private void setParent(Node parent) { this.parent = parent; } // Is the node a leaf? private boolean isLeaf() { return getLeft() == null && getRight() == null; } } }
public class Star2 { public static void main(String[] args) { for(int j=4; j>0; j--) { for(int i=j; i>0; i--) { System.out.print("*"); } System.out.println(); } } }
package com.trantienptit.sev_user.chatbot23.dao; import android.content.Context; import android.util.Log; import com.trantienptit.sev_user.chatbot23.R; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.MarshalFloat; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.AndroidHttpTransport; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; /** * Created by SEV_USER on 9/26/2016. */ public class ChatMessageDAO { private Context context; public ChatMessageDAO(Context context){ this.context=context; } public String getTokenizer(String s) { String result = ""; String NAMESPACE = context.getResources().getString(R.string.NAME_SPACE); String URL = context.getResources().getString(R.string.URL); String SOAP_METHOD = "tokenizerService"; String SOAP_ACTION = NAMESPACE + SOAP_METHOD; SoapObject request = new SoapObject(NAMESPACE, SOAP_METHOD); request.addProperty("sequence", s); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); envelope.implicitTypes = true; MarshalFloat marshal = new MarshalFloat(); marshal.register(envelope); // HttpTransportSE httpTransportSE=new HttpTransportSE(URL); AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL); try { // httpTransportSE.call(SOAP_ACTION,envelope); androidHttpTransport.call(SOAP_ACTION, envelope); SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); result = response.toString(); } catch (IOException e) { Log.e("TAG", e.getMessage()); } catch (XmlPullParserException e) { Log.e("TAG", e.getMessage()); } return result; } }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class FormatConfig { @XmlAttribute private String columnName; @XmlAttribute private Format format; public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public Format getFormat() { return format; } public void setFormat(Format format) { this.format = format; } public FormatConfig(String columnName, Format format) { super(); this.columnName = columnName; this.format = format; } public FormatConfig(){} }
package controller; import java.util.ArrayList; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import model.Historial; import util.HibernateUtil; import util.UtilesLog; public class HistorialController { public static Long save(Historial historial) { Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); Long save = null; historial.setUser(UsuarioController.get(session, historial.getUser().getUser()));//traigo al user perteneciente en la db try { save = (Long) session.save(historial); tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); UtilesLog.loggerStackTrace(e, HistorialController.class); } finally { session.close(); } return save; } @SuppressWarnings("unchecked") public static List<Historial> get(String userName) { Session session = HibernateUtil.getSession(); List<Historial> list = new ArrayList<Historial>(); try { Criteria criteria = session.createCriteria(Historial.class,"historial"); criteria.createAlias("historial.user", "user"); // inner join by default criteria.add(Restrictions.like("user.user", userName)); list = criteria.list(); } catch (HibernateException e) { UtilesLog.loggerStackTrace(e, HistorialController.class); } finally { session.close(); } return list; } }
package com.zero.qa.testcases; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.zero.qa.base.TestBase; import com.zero.qa.pages.AccountSummaryPage; import com.zero.qa.pages.Home; import com.zero.qa.pages.LoginPage; import com.zero.qa.util.TestUtil; public class AccountSummaryTest extends TestBase { LoginPage loginPage; TestUtil testUtil; AccountSummaryPage asp; Home home; public AccountSummaryTest() { super(); } @BeforeMethod public void setUp() { initialization(); testUtil = new TestUtil(); loginPage = new LoginPage(); asp = new AccountSummaryPage(); home = new Home(); home.clickOnSignin(); loginPage.login(prop.getProperty("username"), prop.getProperty("password")); } @Test(priority=1) public void verifyAccountSummaryTitleTest(){ String title = driver.getTitle(); Assert.assertEquals(title,"Zero - Account Summary"); } @Test(priority=2) public void verifyBrokerageTest(){ asp.clickOnBrokerage(); Assert.assertEquals(driver.getTitle(), "Zero - Account Activity"); } @Test(priority = 3) public void verifyCC() { String actual = asp.getCCNumber(); Assert.assertEquals(actual, "VISA 4485-5368-3381-1879"); } @AfterMethod public void tearDown(){ driver.quit(); } }
package com.linda.framework.rpc.service; import com.linda.framework.rpc.HelloRpcService; import com.linda.framework.rpc.HelloRpcTestService; import com.linda.framework.rpc.LoginRpcService; import com.linda.framework.rpc.RpcService; import com.linda.framework.rpc.client.AbstractRpcClient; import com.linda.framework.rpc.client.MultiRpcClient; import com.linda.framework.rpc.exception.RpcException; import com.linda.framework.rpc.monitor.RpcMonitorService; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; public class RpcClientTest { private static Logger logger = Logger.getLogger(RpcClientTest.class); private String host = "127.0.0.1"; private int port = 4332; private AbstractRpcClient client; private int clientCount = 5; private LoginRpcService loginService; private HelloRpcService helloRpcService; private HelloRpcTestService testService; private RpcMonitorService monitorService; private long sleep = 10; private long time = 10000L; private int threadCount = 5; private List<Thread> threads = new ArrayList<Thread>(); private AtomicLong timeAll = new AtomicLong(); private AtomicLong callAll = new AtomicLong(); private boolean sleep() { if (sleep > 0) { try { Thread.currentThread().sleep(sleep); } catch (InterruptedException e) { return true; } } return false; } public void start() { client = new MultiRpcClient(); //client.setConnector(new RpcOioConnector()); client.setHost(host); client.setPort(port); ((MultiRpcClient) client).setConnections(clientCount); client.startService(); loginService = client.register(LoginRpcService.class); helloRpcService = client.register(HelloRpcService.class); testService = client.register(HelloRpcTestService.class); monitorService = client.register(RpcMonitorService.class); List<RpcService> rpcServices = monitorService.getRpcServices(); logger.info("rpcServices:" + rpcServices); startThreads(); } private void startThreads() { int c = 0; while (c < threadCount) { ExeThread thread = new ExeThread(); thread.start(); threads.add(thread); c++; } } public void shutdown() { for (Thread thread : threads) { thread.interrupt(); } client.stopService(); } private class ExeThread extends Thread { Random random = new Random(); @Override public void run() { boolean login = loginService.login("linda", "123456"); logger.info("login result:" + login); long start = System.currentTimeMillis(); long end = start + time; int call = 0; long begin = start; int fail = 0; while (start < end) { try { int idx = random.nextInt(100000); helloRpcService.sayHello("this is HelloRpcService " + idx, idx); String index = testService.index(idx, "index client test " + idx); String hello = helloRpcService.getHello(); int ex = helloRpcService.callException(false); } catch (RpcException e) { fail++; } start = System.currentTimeMillis(); call += 4; boolean inter = RpcClientTest.this.sleep(); if (inter) { break; } String ping = monitorService.ping(); logger.info("ping resp:" + ping); } long endTime = System.currentTimeMillis(); long cost = endTime - begin; logger.info( "thread:" + Thread.currentThread().getId() + " call:" + call + " fail:" + fail + " cost:" + cost + " sleep:" + sleep); timeAll.addAndGet(cost); callAll.addAndGet(call); } } public static void main(String[] args) throws InterruptedException { String host = "127.0.0.1"; int port = 4332; long sleep = 500; long time = 30000L; int threadCount = 3; int clients = 5; if (args != null) { for (String arg : args) { if (arg.startsWith("-h")) { host = arg.substring(2); } else if (arg.startsWith("-p")) { port = Integer.parseInt(arg.substring(2)); } else if (arg.startsWith("-s")) { sleep = Long.parseLong(arg.substring(2)); } else if (arg.startsWith("-th")) { threadCount = Integer.parseInt(arg.substring(3)); } else if (arg.startsWith("-t")) { time = Long.parseLong(arg.substring(2)); } else if (arg.startsWith("-c")) { clients = Integer.parseInt(arg.substring(2)); } } } logger.info("host:" + host + " port:" + port + " sleep:" + sleep + " thc:" + threadCount + " time:" + time + " connections:" + clients); int c = 0; long call = 0; long timeAll = 0; long myTime = time + 3000 + 200 * clients; List<RpcClientTest> tests = new ArrayList<RpcClientTest>(); while (c < 1) { RpcClientTest test = new RpcClientTest(); test.host = host; test.port = port; test.sleep = sleep; test.threadCount = threadCount; test.time = time; test.clientCount = clients; test.start(); tests.add(test); Thread.currentThread().sleep(200); c++; } try { Thread.currentThread().sleep(myTime); } catch (InterruptedException e) { } for (RpcClientTest test : tests) { call += test.callAll.get(); timeAll += (test.timeAll.get() / 1000); test.shutdown(); } long exTime = timeAll / threadCount; double tps = call / exTime; double threadTps = call / timeAll; long myExeTime = time / 1000; logger.info("callAll:" + call + " threadCount:" + threadCount + " timeAll:" + timeAll + " time:" + myExeTime + " tps:" + tps + " threadTps:" + threadTps + " connections:" + clients); System.exit(0); } }
package ogo.spec.game.model; public class Food extends Inhabitant { }
package com.example.coffemachine.repository; import com.example.coffemachine.model.InventoryItem; /** * holds InventoryItems instances * * @author siddu * */ public interface InventoryManager { public InventoryItem getInventory(String inventoryName); public InventoryItem addIngredient(InventoryItem inventory); public void replaceInventoryItem(InventoryItem inventoryItem); }
package br.udesc.controller.tablemodel; import br.udesc.model.entidade.Sala; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; /** * Classe resposável modelar a table de Sala. * Implementando todos os métodos da Interface nativa AbstractTableModel. * @author PIN2 */ public class SalaModel extends AbstractTableModel { private ArrayList<Sala> linhas = null; private String[] colunas = new String[]{"ID","Número Sala", "Limite", "Tipo"}; public SalaModel() { linhas = new ArrayList<Sala>(); } @Override public String getColumnName(int column) { return colunas[column]; } public Sala getLinha(int x) { return linhas.get(x); } @Override public int getRowCount() { return linhas.size(); } @Override public int getColumnCount() { return colunas.length; } public Object getValueAt(int numLin, int numCol) { Sala linha = linhas.get(numLin); switch (numCol) { case 0: return linha.getId(); case 1: return linha.getNumero(); case 2: return linha.getLimite(); case 3: if (linha.getTipo()) { return "Laboratorio"; } else { return "Sala"; } } return null; } public void limpar() { linhas.clear(); fireTableDataChanged(); } public void anuncioAdd(Sala a) { linhas.add(a); fireTableDataChanged(); } public ArrayList<Sala> getLinhas() { return linhas; } }
//package edu; import java.util.ArrayList; import java.util.Iterator; class LAll{ private ArrayList<LBody> arBody = new ArrayList<>(); private ArrayList<LBody> arBodiesToAdd = new ArrayList<>(); private ArrayList<LBody> arBodiesToRemove = new ArrayList<>(); private Iterator<LBody> activeIt = null;// = arBody.iterator(); private LBody currentBody = null; LAll(){} void startIteration(){//Starts iteration arBodiesToAdd.clear(); arBodiesToRemove.clear(); activeIt = arBody.iterator(); } void addBody(LBody Body){ if(activeIt == null) arBody.add(Body); else arBodiesToAdd.add(Body); } //Collection<? extends E> c void addBodies(ArrayList<? extends LBody> in_arBody){ if(activeIt == null){ arBody.addAll(in_arBody); } else arBodiesToAdd.addAll(arBody); } void removeBody(LBody Body){ if(activeIt == null) arBody.remove(Body); else{ if(Body == currentBody){ activeIt.remove(); Body.destroy(); } else arBodiesToRemove.add(Body); } } LBody getNext(){ if(activeIt!=null){ if(activeIt.hasNext()) currentBody = activeIt.next(); else{ // Iteration finished currentBody = null; activeIt = null; } return currentBody; } else return null; } boolean hasNext(){ if(activeIt != null){ if(activeIt.hasNext()){ return true; } else{ activeIt = null; return false; } } else return false; } boolean EndIteration(){ if(activeIt != null) return false; arBody.addAll(arBodiesToAdd); arBody.removeAll(arBodiesToRemove); for(LBody body : arBodiesToRemove){ body.destroy(); } arBodiesToAdd.clear(); arBodiesToRemove.clear(); //activeIt = null; return true; } //Iterator<LBody> iterator(){ // return activeIt; //} }
package Weapons; import Weapons.WeaponLibrary.Axe; import Weapons.WeaponLibrary.Dagger; import Weapons.WeaponLibrary.Sword; public class WeaponFactory { public IAttack create(WeaponType type){ if (type.equals(WeaponType.AXE)){ return new Axe(50); } else if (type.equals(WeaponType.DAGGER)){ return new Dagger(25); } else if (type.equals(WeaponType.SWORD)){ return new Sword(40); } return null; } }
package com.myatnoe.burpplefood.network; /** * Created by User on 1/15/2018. */ public interface BurppleDataAgent { void loadBurppleFeatures(); void loadBurpplePromotions(); void loadBurppleGuides(); }
package mk.petrovski.weathergurumvp.data.remote.model.error_models; import java.util.List; /** * Created by Nikola Petrovski on 2/13/2017. */ public class ErrorModel { private List<MsgErrorModel> error; public List<MsgErrorModel> getError() { return error; } public void setError(List<MsgErrorModel> error) { this.error = error; } }
package com.app.thread; public class WhatIsWrong1 extends Thread{ public static Object lock1 = new Object(); public static Object lock2 = new Object(); public void method1() { synchronized (lock1) { delay(500); //some operation System.out.println("method1: " + Thread.currentThread().getName()); synchronized (lock2) { System.out.println("method1 is executing .... "); } } } public void method2() { synchronized (lock2) { delay(500); //some operation System.out.println("method2: " + Thread.currentThread().getName()); synchronized (lock1) { System.out.println("method2 is executing .... "); } } } @Override public void run() { method1(); method2(); } public static void main(String[] args) { WhatIsWrong1 thread1 = new WhatIsWrong1(); thread1.setName("worker-thread1"); WhatIsWrong1 thread2 = new WhatIsWrong1(); thread2.setName("worker-thread2"); thread1.start(); thread2.start(); } /** * The delay is to simulate some real operation happening. * @param timeInMillis */ private void delay(long timeInMillis) { try { Thread.sleep(timeInMillis); } catch (InterruptedException e) { e.printStackTrace(); } } }
package br.com.treinar.web.servlet; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns= {"*.treinar"}) public class SegundoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SegundoServlet() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { System.out.println("Iniciando Servlet"); } /** * @see Servlet#destroy() */ public void destroy() { System.out.println("TESTE FINALIZANDO SERVLET"); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } /** * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse) */ protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doHead(HttpServletRequest, HttpServletResponse) */ protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doOptions(HttpServletRequest, HttpServletResponse) */ protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doTrace(HttpServletRequest, HttpServletResponse) */ protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
package org.webmaple.worker.config; import redis.clients.jedis.JedisPool; /** * @author lyifee * 使用worker构建爬虫时需要实现此接口 * 提供爬虫需要使用的jedispool * on 2021/2/19 */ public interface JedisSPI { JedisPool getJedisPool(); }
package com.dominion.prog2.game; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; public class CardStack implements Iterable<Card> { private ArrayList<Card> cards; private ArrayList<StackChanged> listeners = new ArrayList<>(); /** * Constructor of Card Stack * This class is an arrayList of Cards * Used mainly in CardGrid */ public CardStack() { cards = new ArrayList<>(); } /** * Constructor of Card Stack * This class is an arrayList of Cards * Copies the passed in ArrayList to the Card variable * Used mainly in CardGrid */ public CardStack(ArrayList<Card> cards) { this.cards = new ArrayList<>(); add(cards); } /** * Constructor of Card Stack * This class is an arrayList of Cards * Creates and Adds Cards based off the list of names that were passed in * Used mainly in CardGrid */ public CardStack(String[] names) { cards = new ArrayList<>(); for(String name : names) { cards.add(CardInfo.getCard(name)); } } /** * This method returns a CardStack with only cards with the passed in name * Used for playing a card within Action */ public CardStack getStackOfName(String name) { CardStack names = new CardStack(); for(Card c: cards) if(c.getName().equals(name)) names.add(c); return names; } /** * Implement Iterable interface to allow enhanced for loops */ public Iterator<Card> iterator() { return new CardStackIterator(this); } /** * Adds an ArrayList of Cards to the list of Cards that is already in the CardStack * adds to the end of the List */ public void add(ArrayList<Card> cards) { for(Card c : cards) { this.cards.add(c); } notifyListeners(); } /** * Adds a specific Card to the list of Cards that is already in the CardStack * adds to the end of the List */ public void add(Card c) { this.cards.add(c); notifyListeners(); } /** * Add a specific card to the top of the CardStack */ public void addTop(Card c) { ArrayList<Card> before = cards; cards.clear(); cards.add(c); cards.addAll(before); } /** * Adds an arbitrary number of new cards by name * Used mainly for creating the shop, and making sure there is a correct amount of each card */ public void addMultiple(String name, int number) { for(int i=0; i<number; i++) { this.cards.add(CardInfo.getCard(name)); } notifyListeners(); } /** * Removes a specific Card * Returns the card that was removed */ public Card remove(Card c) { this.cards.remove(c); notifyListeners(); return c; } /** * Removed the first Card that has the specified name * Returns the card that was removed; */ public Card remove(String name) { for(int i = 0; i < cards.size(); i ++) { if(cards.get(i).getName().equals(name)){ Card c = cards.get(i); cards.remove(c); notifyListeners(); return c; } } notifyListeners(); return null; } /** * splices the list, REMOVES the card(s) too * Returns the spliced list */ public ArrayList<Card> splice(int startIndex, int number) { ArrayList<Card> result = new ArrayList<>(); int i = 0; while(i<number) { result.add(cards.get(startIndex)); cards.remove(startIndex); i++; } notifyListeners(); return result; } /** * Shuffles all the cards * Used by Player */ public void shuffle() { Collections.shuffle(cards); notifyListeners(); } /** * Getter for the card at the specified index * return null if the Index is larger than the ArrayList within CardStack */ public Card get(int i) { if(i > cards.size()) return null; else return cards.get(i); } /** * Sees if the CardStack contains the specified card * returns false if it does not */ public boolean has(Card c) { return cards.contains(c); } /** * Sees if the CardStack contains a Card with a specific name * returns false if it does not */ public boolean has(String name) { for(Card c: cards) if(c.getName().equals(name)) return true; return false; } /** * Sees if the CardStack contains a Card with a specific Type * returns false if it does not */ public boolean has(CardType type) { for(Card c: cards) if(c.getType().equals(type)) return true; return false; } /** * Gets the first Card with the specified name * returns null if there is no card with that name */ public Card get(String name) { for(Card card : cards) { if(card.getName().equals(name)) { return card; } } return null; } /** * Gets all the cards within the CardStack that has a specific type * returns empty ArrayList if there is none with that type */ public ArrayList<Card> get(CardType type) { ArrayList<Card> result = new ArrayList<>(); for(Card c : cards) { if(c.getType() == type) { result.add(c); } } return result; } /** * Gets a CardStack that only has the Card at specified position * Used within ActionCard for one of the extra functions */ public CardStack getPosAsStack(int pos) { CardStack stack = new CardStack(); stack.add(cards.get(pos)); return stack; } /** * Gets a CardStack that only has the Card at specified position * Only if the card has a type Action * Used within ActionCard for one of the extra functions */ public CardStack getPosAsStackIfAttack(int pos) { CardStack stack = new CardStack(); if(cards.get(pos).type.equals(CardType.ACTION)) stack.add(cards.get(pos)); return stack; } /** * Gets all the cards in the CardStack */ public ArrayList<Card> getAll() { ArrayList<Card> result = new ArrayList<>(); for(Card c : cards) { result.add(c); } return result; } /** * Getter for the size of the ArrayList of Cards */ public int size() { return cards.size(); } /** * Listeners are notified whenever the cards in a stack change */ public void addListener(StackChanged listener) { listeners.add(listener); } /** * Notifies all listeners of a change to this stack */ private void notifyListeners() { for(StackChanged listener : listeners) { listener.change(); } } /** * Gets hashMap of name as key and value is the number of those cards within the cardStack */ public HashMap<String, Integer> getCounts() { HashMap<String, Integer> result = new HashMap<>(); for(Card c : cards) { result.put(c.getName(), result.getOrDefault(c.getName(), 0)+1); } return result; } /** * Gets how many different cards there are * @return types */ public int getNumberTypesOfCards() { ArrayList<String> names = new ArrayList<>(); for(Card c: cards) if(!names.contains(c.getName())) names.add(c.getName()); return names.size(); } /** * Filters a CardStack to have cards with the price or less * @param price int * @return CardStack based off Prices */ public CardStack filterPrice(int price) { CardStack filtered = new CardStack(); for(Card c: cards) if(c.getPrice() <= price) filtered.add(c); return filtered; } /** * Filters a Cardstack based off cardType * @param types Array of CardTypes * @return Cardstack which only has the CardTypes */ public CardStack filterType(ArrayList<CardType> types) { CardStack filtered = new CardStack(); for(Card c: cards) if(types.contains(c.getType())) filtered.add(c); return filtered; } /** * Clears the arrayList of Cards */ public void clear() { cards.clear(); } }
package com.example.healthmanage.ui.activity.legaladvice; import android.os.Bundle; import com.example.healthmanage.BR; import com.example.healthmanage.R; import com.example.healthmanage.base.BaseActivity; import com.example.healthmanage.databinding.ActivityLegalAdviceBinding; import com.example.healthmanage.widget.TitleToolBar; public class LegalAdviceActivity extends BaseActivity<ActivityLegalAdviceBinding, LegalAdviceViewModel> implements TitleToolBar.OnTitleIconClickCallBack { private TitleToolBar titleToolBar = new TitleToolBar(); @Override protected void initData() { titleToolBar.setTitle(getString(R.string.legal_advice)); titleToolBar.setLeftIconVisible(true); viewModel.setTitleToolBar(titleToolBar); } @Override public void initViewListener() { super.initViewListener(); titleToolBar.setOnClickCallBack(this); } @Override public void onRightIconClick() { } @Override public void onBackIconClick() { finish(); } @Override protected int initVariableId() { return BR.ViewModel; } @Override protected int setContentViewSrc(Bundle savedInstanceState) { return R.layout.activity_legal_advice; } }
package parse; import java.util.ArrayList; import java.util.Stack; import static parse.InfixToPostfix.isDouble; /** * Created by Matthew on 9/12/2016. */ public class Denominator { //public long totalTime = 0, evals = 0; private String postfix, variable; private double value, variableValue; private Token[] tokens; public Denominator(String postfix) { this(postfix, ""); } public Denominator(String postfix, String variable) { this.postfix = postfix; this.variable = variable; preprocess(); //long sTime = System.nanoTime(); fastEvaluate(); //evaluators(); //totalTime = System.nanoTime() - sTime; //evals++; } private void preprocess() { String[] split = postfix.split(" "); tokens = new Token[split.length]; for(int i = 0; i < split.length; i++) { String s = split[i]; if(isDouble(s) || s.equals(variable)) { //is number or variable if(isDouble(s)) tokens[i] = new Token(s); if(s.equals(variable)) tokens[i] = new Token(true); } else { //operator tokens[i] = new Token(getOperator(s)); } } } private void fastEvaluate() { //~5000ns vs 20,000ns for 1/x^2 Stack<String> expressions = new Stack<>(); ArrayList<String> demoninators = new ArrayList<String>(); for(Token token : tokens) { if(token.isVar || token.isNum()) { //is number or variable if(token.isNum()) expressions.push(""+token.num); if(token.isVar) expressions.push(variable); } else { //is operator if(token.operator.isUnary) { String a = expressions.pop(); switch (token.operator) { case NEG: a += " neg"; break; case SIN: a += " sin"; break; case COS: a += " cos"; break; case TAN: a += " cos"; break; case LOG: a += " cos"; break; case LN: a += " cos"; break; } expressions.push(a); } else { String b = expressions.pop(); String a = expressions.pop(); String c = a+" "+b; switch (token.operator) { case MULTIPLY: c += " *"; break; case DIVIDE: c += " /"; demoninators.add(b); break; case ADD: c += " +"; break; case SUBTRACT: c += " -"; break; case EXPONENT: //demoninators.add(a); //b is expression :| so sign = idk c += " ^"; break; } expressions.push(c); } } } } @Override public String toString() { return "Postfix: "+ getPostfix() +"\n"+ "Value: "+ getValue() +"\n"; } public String getPostfix() { return postfix; } public double getValue() { return value; } private static Operator getOperator (String s) { switch (s) { case "neg": return Operator.NEG; case "sin": return Operator.SIN; case "cos": return Operator.COS; case "tan": return Operator.TAN; case "log": return Operator.LOG; case "ln": return Operator.LN; case "*": return Operator.MULTIPLY; case "/": return Operator.DIVIDE; case "+": return Operator.ADD; case "-": return Operator.SUBTRACT; case "^": return Operator.EXPONENT; } return Operator.NONE; } private class Token { public Operator operator = Operator.NONE; public String num; public boolean isVar = false; public Token (boolean isvar) { this.isVar = isvar; } public Token (Operator operator) { this.operator = operator; } public Token (String value) { this.num = value; } public boolean isNum() { return !isVar && operator == Operator.NONE; } @Override public String toString() { if(isNum()) return num; if(isVar) return "var"; return operator.toString(); } } enum Operator { NEG(true), SIN(true), COS(true), TAN(true), LOG(true), LN(true), ADD (false), SUBTRACT(false), MULTIPLY(false), DIVIDE(false), EXPONENT(false), NONE(false); public boolean isUnary; Operator(boolean isUnary) { this.isUnary = isUnary; } } }
package it.uniroma3.siw_progetto.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import it.uniroma3.siw_progetto.model.ClinicaAccessPoint; import it.uniroma3.siw_progetto.model.TipoEsame; public class ListTipoesame implements Action { @Override public String perform(HttpServletRequest request) { ClinicaAccessPoint accessPoint = new ClinicaAccessPoint(); List<TipoEsame> Tipoesami = accessPoint.getTuttiTipoEsame(); request.setAttribute("tipoesami",Tipoesami); return "/NostriEsami.jsp"; } }
/** * @author ${Prashanth Thipparthi} */ package com.example.demo.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.model.Sample; /* * This class contains functions which performs CRUD operations on the Sample table in the database */ public interface SampleDAO extends JpaRepository<Sample, Integer> { }
package Pages; import org.openqa.selenium.WebDriver; public class HomePage extends HomeOR { public HomePage(WebDriver driver){ super(driver); } public void redirectToOtherPage(String url){ driver.navigate().to(url); } public void forword(){ driver.navigate().forward(); } public void back(){ driver.navigate().back(); } public void refresh(){ driver.navigate().refresh(); } public String checkCurrentUrl(){ return driver.getCurrentUrl(); } public String checkHomePageTitle(){ return driver.getTitle(); } public HomePage GotoFacebookHome(){ GotoFacebookHome.click(); return new HomePage(driver); } }
package com.example.parkminhyun.trackengine; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by 12aud on 2017-06-27. */ public class RVAdapterMap extends RecyclerView.Adapter<RVAdapterMap.MapViewHolder> { public class MapViewHolder extends RecyclerView.ViewHolder { CardView cv; // cardView TextView trackName; TextView tv1; TextView tv2; TextView tv3; TextView tv4; TextView tv5; TextView tv6; TextView tv7; TextView tv8; TextView tv9; TextView tv10; TextView tv11; ImageView iv1; ImageView iv2; ImageView iv3; ImageView iv4; ImageView iv5; ImageView iv6; ImageView iv7; ImageView iv8; ImageView iv9; ImageView iv10; ImageView iv11; public MapViewHolder(View itemView) { super(itemView); cv = (CardView) itemView.findViewById(R.id.cv_map); trackName = (TextView)itemView.findViewById(R.id.tv_track_map_cv); tv1 = (TextView) itemView.findViewById(R.id.tv1_map_cv); tv2 = (TextView) itemView.findViewById(R.id.tv2_map_cv); tv3 = (TextView) itemView.findViewById(R.id.tv3_map_cv); tv4 = (TextView) itemView.findViewById(R.id.tv4_map_cv); tv5 = (TextView) itemView.findViewById(R.id.tv5_map_cv); tv6 = (TextView) itemView.findViewById(R.id.tv6_map_cv); tv7 = (TextView) itemView.findViewById(R.id.tv7_map_cv); tv8 = (TextView) itemView.findViewById(R.id.tv8_map_cv); tv9 = (TextView) itemView.findViewById(R.id.tv9_map_cv); tv10 = (TextView) itemView.findViewById(R.id.tv10_map_cv); tv11 = (TextView) itemView.findViewById(R.id.tv11_map_cv); iv1 = (ImageView) itemView.findViewById(R.id.iv1_map_cv); iv2 = (ImageView) itemView.findViewById(R.id.iv2_map_cv); iv3 = (ImageView) itemView.findViewById(R.id.iv3_map_cv); iv4 = (ImageView) itemView.findViewById(R.id.iv4_map_cv); iv5 = (ImageView) itemView.findViewById(R.id.iv5_map_cv); iv6 = (ImageView) itemView.findViewById(R.id.iv6_map_cv); iv7 = (ImageView) itemView.findViewById(R.id.iv7_map_cv); iv8 = (ImageView) itemView.findViewById(R.id.iv8_map_cv); iv9 = (ImageView) itemView.findViewById(R.id.iv9_map_cv); iv10 = (ImageView) itemView.findViewById(R.id.iv10_map_cv); iv11 = (ImageView) itemView.findViewById(R.id.iv11_map_cv); } } Context context; List<MapVO> maps; private UserStudyData userStudyData; private List<String> userStudyList; public RVAdapterMap(List<MapVO> maps, Context context){ this.maps = maps; this.context = context; userStudyData = new UserStudyData(context); this.userStudyList = userStudyData.loadStudyDataList(); } @Override public MapViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.map_track, viewGroup, false); MapViewHolder mvh = new MapViewHolder(v); return mvh; } @Override public void onBindViewHolder(MapViewHolder holder, int position) { holder.trackName.setText(maps.get(position).getTrackName()); holder.tv1.setText(maps.get(position).getSub0()); holder.tv2.setText(maps.get(position).getSub1()); holder.tv3.setText(maps.get(position).getSub2()); holder.tv4.setText(maps.get(position).getSub3()); holder.tv5.setText(maps.get(position).getSub4()); holder.tv6.setText(maps.get(position).getSub5()); holder.tv7.setText(maps.get(position).getSub6()); holder.tv8.setText(maps.get(position).getSub7()); holder.tv9.setText(maps.get(position).getSub8()); holder.tv10.setText(maps.get(position).getSub9()); holder.tv11.setText(maps.get(position).getSub10()); for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub0())){ holder.tv1.setTextColor(Color.rgb(3, 153, 58)); holder.iv1.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub2())){ holder.tv2.setTextColor(Color.rgb(3, 153, 58)); holder.iv2.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub2())){ holder.tv3.setTextColor(Color.rgb(3, 153, 58)); holder.iv3.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub3())){ holder.tv4.setTextColor(Color.rgb(3, 153, 58)); holder.iv4.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub4())){ holder.tv5.setTextColor(Color.rgb(3, 153, 58)); holder.iv5.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub5())){ holder.tv6.setTextColor(Color.rgb(3, 153, 58)); holder.iv6.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub6())){ holder.tv7.setTextColor(Color.rgb(3, 153, 58)); holder.iv7.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub7())){ holder.tv8.setTextColor(Color.rgb(3, 153, 58)); holder.iv8.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub8())){ holder.tv9.setTextColor(Color.rgb(3, 153, 58)); holder.iv9.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub9())){ holder.tv10.setTextColor(Color.rgb(3, 153, 58)); holder.iv10.setImageResource(R.drawable.circle_darkgreen); } } for(int i = 0; i < userStudyList.size(); i++){ if(userStudyList.get(i).equals(maps.get(position).getSub10())){ holder.tv11.setTextColor(Color.rgb(3, 153, 58)); holder.iv11.setImageResource(R.drawable.circle_darkgreen); } } } @Override public int getItemCount() { return maps.size(); } }
/* * Created on Mar 9, 2006 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.ibm.jikesbt; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public class BT_AnnotationArray { BT_Annotation annotations[]; BT_AnnotationArray() {} public BT_AnnotationArray(BT_Annotation annotations[]) { this.annotations = annotations; } void read(String attName, DataInputStream dis, BT_ConstantPool pool) throws IOException, BT_ConstantPoolException, BT_AnnotationAttributeException, BT_DescriptorException { int numAnnotations = dis.readUnsignedShort(); // AKA number_of_classes annotations = new BT_Annotation[numAnnotations]; for(int i=0; i<annotations.length; i++) { BT_Annotation annotation = new BT_Annotation(); annotation.read(attName, dis, pool); annotations[i] = annotation; } } void write(DataOutputStream dos, BT_ConstantPool pool) throws IOException { dos.writeShort(annotations.length); // number_of_classes for (int i = 0; i < annotations.length; ++i) { // Per element annotations[i].write(dos, pool); } } void dereference(BT_Repository rep, BT_Attribute att) throws BT_DescriptorException { for (int i = 0; i < annotations.length; ++i) { // Per element annotations[i].dereference(rep, att); } } void remove(BT_Attribute att) { for (int i = 0; i < annotations.length; ++i) { // Per element annotations[i].remove(att); } } void removeReference(BT_Attribute att, BT_Item ref) { for (int i = 0; i < annotations.length; ++i) { // Per element annotations[i].removeReference(att, ref); } } public void resolve(BT_ConstantPool pool) { for (int i = 0; i < annotations.length; ++i) { // Per element annotations[i].resolve(pool); } } int getLength() { int length = 2; for(int i=0; i<annotations.length; i++) { length += annotations[i].getLength(); } return length; } }
/* * 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.pig.newplan; import java.util.Iterator; import java.util.List; import org.apache.pig.classification.InterfaceAudience; import org.apache.pig.classification.InterfaceStability; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.util.Pair; /** * An interface that defines graph operations on plans. Plans are modeled as * graphs with restrictions on the types of connections and operations allowed. */ @InterfaceAudience.Private @InterfaceStability.Unstable public interface OperatorPlan { /** * Get number of nodes in the plan. * @return number of nodes in the plan */ public int size(); /** * Get all operators in the plan that have no predecessors. * @return all operators in the plan that have no predecessors, or * an empty list if the plan is empty. */ public List<Operator> getSources(); /** * Get all operators in the plan that have no successors. * @return all operators in the plan that have no successors, or * an empty list if the plan is empty. */ public List<Operator> getSinks(); /** * For a given operator, get all operators immediately before it in the * plan. * @param op operator to fetch predecessors of * @return list of all operators immediately before op, or an empty list * if op is a root. */ public List<Operator> getPredecessors(Operator op); /** * For a given operator, get all operators immediately after it. * @param op operator to fetch successors of * @return list of all operators immediately after op, or an empty list * if op is a leaf. */ public List<Operator> getSuccessors(Operator op); /** * For a given operator, get all operators softly immediately before it in the * plan. * @param op operator to fetch predecessors of * @return list of all operators immediately before op, or an empty list * if op is a root. */ public List<Operator> getSoftLinkPredecessors(Operator op); /** * For a given operator, get all operators softly immediately after it. * @param op operator to fetch successors of * @return list of all operators immediately after op, or an empty list * if op is a leaf. */ public List<Operator> getSoftLinkSuccessors(Operator op); /** * Add a new operator to the plan. It will not be connected to any * existing operators. * @param op operator to add */ public void add(Operator op); /** * Remove an operator from the plan. * @param op Operator to be removed * @throws FrontendException if the remove operation attempts to * remove an operator that is still connected to other operators. */ public void remove(Operator op) throws FrontendException; /** * Connect two operators in the plan, controlling which position in the * edge lists that the from and to edges are placed. * @param from Operator edge will come from * @param fromPos Position in the array for the from edge * @param to Operator edge will go to * @param toPos Position in the array for the to edge */ public void connect(Operator from, int fromPos, Operator to, int toPos); /** * Connect two operators in the plan. * @param from Operator edge will come from * @param to Operator edge will go to */ public void connect(Operator from, Operator to); /** * Create an soft edge between two nodes. * @param from Operator dependent upon * @param to Operator having the dependency */ public void createSoftLink(Operator from, Operator to); /** * Remove an soft edge * @param from Operator dependent upon * @param to Operator having the dependency */ public void removeSoftLink(Operator from, Operator to); /** * Disconnect two operators in the plan. * @param from Operator edge is coming from * @param to Operator edge is going to * @return pair of positions, indicating the position in the from and * to arrays. * @throws FrontendException if the two operators aren't connected. */ public Pair<Integer, Integer> disconnect(Operator from, Operator to) throws FrontendException; /** * Get an iterator of all operators in this plan * @return an iterator of all operators in this plan */ public Iterator<Operator> getOperators(); /** * This is like a shallow comparison. * Two plans are equal if they have equivalent operators and equivalent * structure. * @param other object to compare * @return boolean if both the plans are equivalent * @throws FrontendException */ public boolean isEqual( OperatorPlan other ) throws FrontendException; /** * This method replace the oldOperator with the newOperator, make all connection * to the new operator in the place of old operator * @param oldOperator operator to be replaced * @param newOperator operator to replace * @throws FrontendException */ public void replace(Operator oldOperator, Operator newOperator) throws FrontendException; /** * This method remove a node operatorToRemove. It also Connect all its successors to * predecessor/connect all it's predecessors to successor * @param operatorToRemove operator to remove * @throws FrontendException */ public void removeAndReconnect(Operator operatorToRemove) throws FrontendException; /** * This method insert node operatorToInsert between pred and succ. Both pred and succ cannot be null * @param pred predecessor of inserted node after this method * @param operatorToInsert operato to insert * @param succ successor of inserted node after this method * @throws FrontendException */ public void insertBetween(Operator pred, Operator operatorToInsert, Operator succ) throws FrontendException; /** * check if there is a path in the plan graph between the load operator to the store operator. * @param load load operator * @param store store operator * @return true if yes, no otherwise. */ public boolean pathExists(Operator load, Operator store); }
package com.example.vineet.easybuy; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class loantypeoption extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { Bundle bundle = getIntent().getExtras(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_loantypeoption); Intent intent = getIntent(); String messge = intent.getStringExtra(signuppmoney.EXTRA_MESSAGE); TextView textView = findViewById(R.id.tv20); textView.setText(messge); } public void pocketmoney(View view) { Intent intent = new Intent(this,EasyEMI.class); startActivity(intent); } public void loan(View view) { Intent intent = new Intent(this,Pmoney.class); startActivity(intent); } }
package com.mrenesinau.tampilmeja.SearchMeja; import com.google.gson.annotations.SerializedName; public class Meja { @SerializedName("idmeja") private int idmeja; @SerializedName("nmmeja") private String nmmeja; @SerializedName("model") private String model; @SerializedName("nama_status_meja") private String nama_status_meja; public int getIdmeja() { return idmeja; } public void setIdmeja(int idmeja) { this.idmeja = idmeja; } public String getNmmeja() { return nmmeja; } public void setNmmeja(String nmmeja) { this.nmmeja = nmmeja; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getNama_status_meja() { return nama_status_meja; } public void setNama_status_meja(String nama_status_meja) { this.nama_status_meja = nama_status_meja; } }
package info.kldeng.concurrency; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSearcher implements Runnable { private String initPath; /* 待查找目录 */ private String fileName; /* 待查找文件 */ private ThreadGroup tg; /* 所属的threadGroup */ public FileSearcher(String initPath, String fileName, ThreadGroup tg) { this.initPath = initPath; this.fileName = fileName; this.tg = tg; } public void processDirectory(File f) throws InterruptedException { System.out.printf("Processing: %s\n", f.getAbsolutePath()); File[] filesList = f.listFiles(); List<File> files = new ArrayList<File>(); List<File> dirs = new ArrayList<File>(); if (filesList != null && filesList.length > 0) { for (File file : filesList) { if (file.isDirectory()) dirs.add(file); else if (file.isFile()) files.add(file); } } //广度优先搜索,先检测目录下所有文件,再搜索目录 if (! files.isEmpty()) { for (File file : files) processFile(file); } //搜索子目录 if (! dirs.isEmpty()) { //每个子目录都新开一个线程 for (File dir : dirs) { Thread thd = new Thread(new FileSearcher(dir.getAbsolutePath(), "slf4j-api-1.7.2.jar", tg)); thd.start(); } //processDirectory(dir); } if(Thread.interrupted()) { throw new InterruptedException(); } } public void processFile(File f) throws InterruptedException { //System.out.println(f.getName()); if (f.getName().equals(fileName)){ System.out.printf("Gotcha! %s is found!\n", fileName); //有一个线程找到的待查找文件,就中断同一threadgroup中的其他线程 System.exit(0); } if(Thread.interrupted()) { throw new InterruptedException(); } } @Override public void run() { File f = new File(initPath); try { System.out.printf("Thread: %s begins.\n", Thread.currentThread().getName()); processDirectory(f); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.printf("The thread %s is interrupted.", Thread.currentThread().getName()); } } /** * @param args */ public static void main(String[] args) { ThreadGroup tg = new ThreadGroup("FileSearcher"); FileSearcher fs = new FileSearcher("/home/kldeng/", "slf4j-api-1.7.2.jar", tg); Thread thd = new Thread(tg, fs); thd.start(); //thd.interrupt(); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.util.models; import de.hybris.platform.catalog.model.CatalogVersionModel; import de.hybris.platform.category.daos.CategoryDao; import de.hybris.platform.category.model.CategoryModel; import de.hybris.platform.cmsfacades.util.builder.ProductCategoryModelBuilder; import java.util.Locale; public class ProductCategoryModelMother extends AbstractModelMother<CategoryModel> { public static final String ELECTRONICS = "electronics"; public static final String CARS = "cars"; private CategoryDao categoryDao; protected CategoryModel getCategoryByCode(final String categoryCode, final CatalogVersionModel catalogVersion) { return getFromCollectionOrSaveAndReturn(() -> getCategoryDao().findCategoriesByCode(categoryCode), () -> ProductCategoryModelBuilder.aModel() // .withName(categoryCode, Locale.ENGLISH) // .withCatalogVersion(catalogVersion) // .withCode(categoryCode) .build()); } public CategoryModel createDefaultCategory(final CatalogVersionModel catalogVersion) { return getCategoryByCode(ELECTRONICS, catalogVersion); } public CategoryModel createCarsCategory(final CatalogVersionModel catalogVersion) { return getCategoryByCode(CARS, catalogVersion); } public CategoryDao getCategoryDao() { return categoryDao; } public void setCategoryDao(final CategoryDao categoryDao) { this.categoryDao = categoryDao; } }
package com.example.demo.service.imp; import com.example.demo.dao.UserDao; import com.example.demo.entity.User; import com.example.demo.service.UserInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service("UserInfoService") public class UserInfoServiceImp implements UserInfoService { @Resource private UserDao userDao; @Override public List<User> getAllUsers() { List<User> users = userDao.getAllUsers(); return userDao.getAllUsers(); } @Override public User getUserWithId(int id) { return userDao.getUserWithId(id); } @Override public int deleteUserWithId(int id) { return userDao.deleteUserWithId(id); } @Override public int updateUser(User user) { return userDao.updateUser(user); } @Override public int insertUser(User user) { return userDao.insertUser(user); } }
package edu.wpi.cs.justice.cardmaker.http; import java.util.ArrayList; public class ListImageResponse { public ArrayList<String> ImgList; public final int statusCode; public final String error; public ListImageResponse (ArrayList<String> list, int code) { this.ImgList = list; this.statusCode = code; this.error = ""; } public ListImageResponse (String errorMessage, int code) { this.ImgList = null; this.statusCode = code; this.error = errorMessage; } }
/** * Copyright © 2020 Guillermo Rebaza (grebaza@gmail.com) * Adapted from com.github.jcustenborder.kafka.connect.transform.common.ToJSON * * 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.github.jcustenborder.kafka.connect.transform.common; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; import com.github.jcustenborder.kafka.common.cache.XSynchronizedCache; import com.github.jcustenborder.kafka.connect.utils.config.Description; import com.github.jcustenborder.kafka.connect.utils.config.DocumentationTip; import com.github.jcustenborder.kafka.connect.utils.config.Title; import com.google.common.base.Charsets; import org.apache.kafka.common.cache.LRUCache; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.connect.connector.ConnectRecord; import org.apache.kafka.connect.data.Field; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaAndValue; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.json.JsonConverter; import org.apache.kafka.connect.transforms.util.SchemaUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class FieldToJSON<R extends ConnectRecord<R>> extends BaseTransformation<R> { private static final Logger log = LoggerFactory.getLogger(FieldToJSON.class); private static final Map<Schema.Type, Schema> FIELD_SCHEMA_MAPPING = new HashMap<>(); private static final Map<Schema.Type, Function<byte[], ?>> FIELD_MAPPING_FUNC = new HashMap<>(); // Handlers setup static { FIELD_SCHEMA_MAPPING.put(Schema.Type.STRING, Schema.OPTIONAL_STRING_SCHEMA); FIELD_SCHEMA_MAPPING.put(Schema.Type.BYTES, Schema.OPTIONAL_BYTES_SCHEMA); FIELD_MAPPING_FUNC.put(Schema.Type.STRING, a -> new String(a, Charsets.UTF_8)); FIELD_MAPPING_FUNC.put(Schema.Type.BYTES, Function.identity()); } FieldToJSONConfig config; //private Map<Schema, Schema> schemaCache; private XSynchronizedCache<Schema, Schema> schemaCache; JsonConverter converter = new JsonConverter(); @Override public ConfigDef config() { return FieldToJSONConfig.config(); } @Override public void close() { } @Override public void configure(Map<String, ?> settings) { this.config = new FieldToJSONConfig(settings); //this.schemaCache = new HashMap<>(); this.schemaCache = new XSynchronizedCache<>(new LRUCache<>(16)); // JsonConverter setup Map<String, Object> settingsClone = new LinkedHashMap<>(settings); settingsClone.put(FieldToJSONConfig.SCHEMAS_ENABLE_CONFIG, this.config.schemasEnable); this.converter.configure(settingsClone, false); } @Override protected SchemaAndValue processStruct(R record, Schema inputSchema, Struct input) { return schemaAndValue(inputSchema, input); } SchemaAndValue schemaAndValue(Schema inputSchema, Struct input) { final Schema outputSchema; final Struct outputValue; // Build output schema outputSchema = this.schemaCache.computeIfAbsent(inputSchema, s1 -> { final SchemaBuilder builder = SchemaUtil.copySchemaBasics(inputSchema, SchemaBuilder.struct()); // input part for (Field field : inputSchema.fields()) { builder.field(field.name(), field.schema()); } // converted fields for (Map.Entry<String, FieldToJSONConfig.FieldSettings> fieldSpec : this.config.conversions.entrySet()) { final FieldToJSONConfig.FieldSettings fieldSettings = fieldSpec.getValue(); builder.field( fieldSettings.outputName, FIELD_SCHEMA_MAPPING.computeIfAbsent( fieldSettings.outputSchema, s2 -> { throw new UnsupportedOperationException( String.format("Schema type '%s' is not supported.", fieldSettings.outputSchema)); }) ); } return builder.build(); }); // Build output value (input part) outputValue = new Struct(outputSchema); for (Field field : inputSchema.fields()) { final Object value = input.get(field); outputValue.put(field.name(), value); } // Build output value (converted fields) for (Map.Entry<String, FieldToJSONConfig.FieldSettings> fieldSpec : this.config.conversions.entrySet()) { final String field = fieldSpec.getKey(); final FieldToJSONConfig.FieldSettings fieldSettings = fieldSpec.getValue(); final Schema inputFieldSchema = input.schema().field(field).schema(); final Object inputFieldValue = input.get(field); final Object convertedFieldValue; // convert to JSON final byte[] buffer = this.converter .fromConnectData("dummy", inputFieldSchema, inputFieldValue); convertedFieldValue = FIELD_MAPPING_FUNC.computeIfAbsent( fieldSettings.outputSchema, s -> { throw new UnsupportedOperationException( String.format("Schema type '%s' is not supported.", fieldSettings.outputSchema)); }).apply(buffer); log.trace(String.format( "converted value: %s", convertedFieldValue.toString())); // update output value outputValue.put(fieldSettings.outputName, convertedFieldValue); } return new SchemaAndValue(outputSchema, outputValue); } @Title("FieldToJSON(Key)") @Description("This transformation is used to extract a field from a " + "nested struct convert into JSON string and append it to " + "the parent struct.") @DocumentationTip("This transformation is used to manipulate fields in " + "the Key of the record.") public static class Key<R extends ConnectRecord<R>> extends FieldToJSON<R> { @Override public R apply(R r) { final SchemaAndValue transformed = process(r, r.keySchema(), r.key()); return r.newRecord( r.topic(), r.kafkaPartition(), transformed.schema(), transformed.value(), r.valueSchema(), r.value(), r.timestamp() ); } } @Title("FieldToJSON(Value)") @Description("This transformation is used to extract a field from a " + "nested struct convert into JSON string and append it to " + "the parent struct.") @DocumentationTip("This transformation is used to manipulate fields in " + "the Value of the record.") public static class Value<R extends ConnectRecord<R>> extends FieldToJSON<R> { @Override public R apply(R r) { final SchemaAndValue transformed = process(r, r.valueSchema(), r.value()); return r.newRecord( r.topic(), r.kafkaPartition(), r.keySchema(), r.key(), transformed.schema(), transformed.value(), r.timestamp() ); } } }
package com.sdk4.boot.apiengine; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.sdk4.boot.bo.LoginUser; import com.sdk4.common.util.DateUtils; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import java.util.Date; import java.util.Map; /** * Created by sh on 2018/6/19. */ @Slf4j @Data public class RequestContent { /** * 应用ID */ private String appId; /** * 接口名称 */ private String method; /** * 签名类型 */ private String signType; /** * 请求参数的签名串 */ private String sign; /** * 送请求时间,格式:yyyy-MM-dd HH:mm:ss */ private String timestamp; /** * 调用接口版本,固定值:1.0 */ private String version; /** * 业务请求参数的集合,JSON格式字符串 */ private String bizContent; /** * 业务请求参数的集合,JSON格式对象 */ private JSONObject bizContentObject; /** * API 请求对象 */ private ApiRequest apiRequest; /** * 当前登录用户 */ private LoginUser loginUser; public RequestContent(ApiRequest apiRequest, Map<String, String> params) { this.apiRequest = apiRequest; this.appId = params.get(ApiConstants.APP_ID); this.method = params.get(ApiConstants.METHOD); this.signType = params.get(ApiConstants.SIGN_TYPE); this.sign = params.get(ApiConstants.SIGN); this.timestamp = params.get(ApiConstants.TIMESTAMP); this.version = params.get(ApiConstants.VERSION); this.bizContent = params.get(ApiConstants.BIZ_CONTENT); if (StringUtils.isNotEmpty(this.bizContent)) { this.bizContentObject = JSON.parseObject(this.bizContent); } else { this.bizContentObject = new JSONObject(); } } public int optInt(String key, int defaultValue) { int result = defaultValue; if (this.bizContentObject.containsKey(key)) { result = this.bizContentObject.getInteger(key); } return result; } public Integer optInteger(String key, Integer defaultValue) { Integer result = defaultValue; if (this.bizContentObject.containsKey(key)) { result = this.bizContentObject.getInteger(key); } return result; } public String optString(String key, String defaultValue) { String result = defaultValue; if (this.bizContentObject.containsKey(key)) { result = this.bizContentObject.getString(key); } return result; } public Date optDate(String key, Date defaultValue) { Date result = defaultValue; if (this.bizContentObject.containsKey(key)) { String str = this.bizContentObject.getString(key); result = DateUtils.parseDate(str); } return result; } public <T> T toJavaObject(Class<T> cls) { T result = null; if (this.bizContentObject.size() > 0) { result = this.bizContentObject.toJavaObject(cls); } return result; } }
package paqueteServlets; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/EnviaYRecibe") public class EnviaYRecibe extends HttpServlet { private static final long serialVersionUID = 1L; private LinkedHashMap<String, String> arrayPaises = new LinkedHashMap<String, String>(); //array asociativo @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Carga del array asociativo arrayPaises.put("ES", "España"); arrayPaises.put("FR", "Francia"); arrayPaises.put("IT", "Italia"); arrayPaises.put("PT", "Portugal"); // Recepción de parámetros String nombre = request.getParameter("nombre"); String clave = request.getParameter("clave"); String genero = request.getParameter("genero"); String fechaNac = request.getParameter("fechaNac"); String[] paises = request.getParameterValues("paises[]"); String acepto = request.getParameter("acepto"); String comentarios = request.getParameter("comentarios"); String foto = request.getParameter("foto"); PrintWriter out = response.getWriter(); // 1.Creación del formulario vacío inicial y lógica de negocio if (nombre == null) { // solo ocurre en la primera llamada out.println("<h1>EnviaYRecibe</h1>"); out.println("<fieldset>\n" + "<legend>FORMULARIO DE ALTA</legend> <br />"); out.println("<form name=\"f1\" action=\"EnviaYRecibe\" method=\"get\">"); out.println("<label for=\"nombre\">Nombre </label> <input type=\"text\" name=\"nombre\" /> <br /> <br />"); out.println("<label for=\"clave\">Clave </label><input type=\"password\" name=\"clave\" /> <br /> <br />"); out.println("<label>Género: </label> "); out.println("<label>Mujer</label><input type=\"radio\" value=\"F\" name=\"genero\" />"); out.println("<label>Hombre</label><input type=\"radio\" value=\"M\" name=\"genero\" /> <br /><br />"); out.println("<label for=\"fechaNac\">Fecha de nacimiento </label><input type=\"text\" name=\"fechaNac\" /> (dd/mm/aaaa) <br /> <br />"); out.println("<label>País/es de origen: </label> <br />"); out.println("<select name=\"paises[]\" multiple=\"multiple\">"); out.println("<option value=\"ES\">España</option>"); out.println("<option value=\"FR\">Francia</option>"); out.println("<option value=\"IT\">Italia</option>"); out.println("<option value=\"PT\">Portugal</option>"); out.println("</select> <br /> <br />"); out.println("<label for=\"acepto\">Acepto las condiciones del alta en el servicio</label>"); out.println("<input type=\"checkbox\" name=\"acepto\" value=\"OK\" /> <br /> <br />"); out.println("<label for=\"comentarios\">Comentarios</label> <br />"); out.println("<textarea name=\"comentarios\" rows=\"5\" cols=\"30\">Escriba sus comentarios...</textarea> <br /> <br />"); out.println("<label for=\"foto\">Fotografía: </label><input type=\"file\" name=\"foto\" /> <br /><br />"); out.println("<input type=\"submit\" value=\"Enviar\" />"); out.println("<input type=\"reset\" value=\"Reset\" />"); out.println("</form>\n" + "</fieldset>"); } // Lógica de negocio String errores = ""; // cadena que va recogiendo los posibles erorres del formulario if (nombre.equals("")) { errores += "Rellena el nombre <br/>"; } if (clave.length() < 6 || clave.length() > 12) { errores += "Clave incorrecta <br/>"; } if (genero == null) { //Los radiobutton vacíos son null errores += "Rellena el género <br/>"; } if (fechaNac.equals("") || fechaNac.length()!=10) { errores += "Rellena la fecha de nacimiento <br/>"; } else if (!mayorDeEdad(fechaNac) ) { errores += "Debes ser mayor de edad para realizar el alta <br />"; } if (paises == null) { errores += "Rellena el país/es de origen <br/>"; } if (acepto == null) { errores += "Debes aceptar las condiciones de alta en el servicio <br/>"; } // 2.Creación del formulario con errores if (errores.length() != 0) { out.println("<html>"); out.println("<body>"); out.println("<h3>Errores en el Formulario </h3>"); out.println("<p style=\"color:red\">" + errores + "</p>"); out.println("<fieldset>\n" + "<legend>FORMULARIO DE ALTA</legend> <br />"); out.println("<form name=\"f1\" action=\"EnviaYRecibe\" method=\"get\" >"); out.println("Nombre: <input type=\"text\" name=\"nombre\" value=\"" + nombre + "\" /> <br /> <br /> "); out.println("Clave: <input type=\"password\" name=\"clave\" /> <br /> <br />"); //La clave no se regenera out.println(generaButtonGenero(genero) + "<br /> <br />"); out.println("Fecha Nacimiento: <input type=\"text\" name=\"fechaNac\" value=\"" + fechaNac + "\"> (dd/mm/aaaa)<br /> <br />"); out.println(generaSelectPaises(arrayPaises, paises) + "<br />"); out.println("Acepto las condiciones del alta en el servicio: " + "<input type=\"checkbox\" name=\"acepto\" value=\"OK\" /> <br /> <br /> "); out.println("Comentarios: <br /> <textarea name=\"comentarios\" rows=\"5\" cols=\"30\"/>" + comentarios + "</textarea> <br /> <br /> "); out.println("Foto: <input type=\"file\" name=\"foto\" /> <br /> <br />"); out.println("<input type=\"submit\" value=\"Enviar\" />"); out.println("<input type=\"reset\" value=\"Reset\" />"); out.println("</form>\n" + "</fieldset>"); out.println("</body>"); out.println("</html>"); } // 3.Creación del formulario enviado con éxito else { out.println("<h1>Formulario enviado con éxito</h1>" + "<br/>"); out.println("Nombre = " + nombre + "<br />"); out.println("Clave = " + clave + "<br />"); out.println("Género = " + genero + "<br />"); out.println("Fecha de nacimiento = " + fechaNac + "<br />"); out.println("País/es de origen = " + Arrays.toString(paises) + "<br />"); out.println("Acepto = " + acepto + "<br />"); out.println("Comentarios = " + comentarios + "<br />"); out.println("Foto = " + foto + "<br />"); } } // Funciones para regenerar el formulario con errores protected String generaButtonGenero(String _genero) { String cadena = "Género: "; if (_genero==null) { cadena += "<label>Mujer</label><input type=\"radio\" name=\"genero\" value=\"F\" />"; cadena += "<label>Hombre</label><input type=\"radio\" name=\"genero\" value=\"M\" />"; } else if (_genero.equals("F")){ cadena += "<label>Mujer</label><input type=\"radio\" name=\"genero\" value=\"F\" checked=\"checked\"/>"; cadena += "<label>Hombre</label><input type=\"radio\" name=\"genero\" value=\"M\" />"; } else { cadena += "<label>Mujer</label><input type=\"radio\" name=\"genero\" value=\"F\" />"; cadena += "<label>Hombre</label><input type=\"radio\" name=\"genero\" value=\"M\" checked=\"checked\"/>"; } return cadena; } protected Boolean mayorDeEdad(String _fechaNac) { SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy"); Date fechaHoy = new Date(); String cadenaHoy = formatoFecha.format(fechaHoy); String[] dat1 = _fechaNac.split("/"); String[] dat2 = cadenaHoy.split("/"); int años = Integer.parseInt(dat2[2]) - Integer.parseInt(dat1[2]); int mes = Integer.parseInt(dat2[1]) - Integer.parseInt(dat1[1]); if (mes < 0) { años = años - 1; } else if (mes == 0) { int dia = Integer.parseInt(dat2[0]) - Integer.parseInt(dat1[0]); if (dia > 0) { años = años - 1; } } if(años<18) return false; else return true; } protected String generaSelectPaises (LinkedHashMap<String, String> arrayPaises, String[] _paises) { String cadena = "País/es de origen: <br /> <select name=\"paises[]\" multiple=\"multiple\">"; int numPaises = 0; int i=0; int cont=0; if (_paises!=null) { numPaises= _paises.length; // Si el parámetro paises recibido no es nulo se calcula su longitud } System.out.println("num"+numPaises); Iterator<String> iterador = arrayPaises.keySet().iterator(); while (iterador.hasNext()) { String clave = (String)iterador.next(); String valor = (String)arrayPaises.get(clave); if ( i<numPaises && _paises[i].equals(clave)) { cadena += "<option value=\"" + clave + "\" selected=\"selected\">" + valor + "</option>"; i++; } else { cadena += "<option value=\"" + clave + "\">" + valor + "</option>"; } cont++; System.out.println(cont+" "+i+clave+valor); // para control interno } cadena +="</select>"; return cadena; } }
package problems; import java.util.*; public class Paranthasis_balenced { public static void main(String[] args) { String s="([]){"; System.out.println(isValid(s)); } public static boolean isValid(String s) { Stack<Character> st=new Stack<>(); boolean res=false; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){ st.push(s.charAt(i)); }else{ if(st.isEmpty()){ return false; }else{ if(!check_parn(s.charAt(i),st)){ return false; }else{ res=true; } } } } if (!st.isEmpty()){ return false; } return res; } static boolean check_parn(char c,Stack<Character> st){ switch(c){ case ')': if(st.pop()=='('){ return true; } return false; case '}': if(st.pop()=='{'){ return true; } return false; case ']': if(st.pop()=='['){ return true; } return false; } return false; } }
package com.travix.medusa.busyflights.service.adapter; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; import com.travix.medusa.busyflights.domain.busyflights.BusyFlightsRequest; import com.travix.medusa.busyflights.domain.busyflights.BusyFlightsResponse; import com.travix.medusa.busyflights.domain.toughjet.ToughJetRequest; import com.travix.medusa.busyflights.domain.toughjet.ToughJetResponse; import com.travix.medusa.busyflights.service.FlightSupplier; import com.travix.medusa.busyflights.service.external.ToughJetFlightSupplier; @Component public class ToughJetFlightSupplierAdapter implements FlightSupplier { private static final String supplierName = "ToughJet"; private static final double wholePercentage = 100.00; private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; private ToughJetFlightSupplier flightSupplier; public ToughJetFlightSupplierAdapter(ToughJetFlightSupplier flightSupplier) { this.flightSupplier = flightSupplier; } @Override public List<BusyFlightsResponse> findFlight(BusyFlightsRequest busyFlightsRequest) { ToughJetRequest request = new ToughJetRequest(busyFlightsRequest.getOrigin(), busyFlightsRequest.getDestination(), busyFlightsRequest.getDepartureDate(), busyFlightsRequest.getReturnDate(), busyFlightsRequest.getNumberOfPassengers()); ToughJetResponse[] foundedFlights = flightSupplier.findFlight(request); List<BusyFlightsResponse> response = convertToBusyFlightsResponse(foundedFlights); return response; } private List<BusyFlightsResponse> convertToBusyFlightsResponse(ToughJetResponse[] foundedFlights) { List<BusyFlightsResponse> convertedFlights = new ArrayList<>(); for (ToughJetResponse foundedFlight : foundedFlights) { BusyFlightsResponse convertedFlight = new BusyFlightsResponse(); convertedFlight.setSupplier(supplierName); convertedFlight.setAirline(foundedFlight.getCarrier()); convertedFlight.setDestinationAirportCode(foundedFlight.getDepartureAirportName()); convertedFlight.setDestinationAirportCode(foundedFlight.getArrivalAirportName()); convertedFlight.setDepartureDate(getFormattedDatetime(foundedFlight.getOutboundDateTime())); convertedFlight.setArrivalDate(getFormattedDatetime(foundedFlight.getInboundDateTime())); double fare = calculateFare(foundedFlight); convertedFlight.setFare(fare); convertedFlights.add(convertedFlight); } return convertedFlights; } private String getFormattedDatetime(String unFormattedDate) { LocalDateTime date = LocalDateTime.ofInstant(Instant.parse(unFormattedDate), ZoneOffset.UTC); return date.format(formatter); } private double calculateFare(ToughJetResponse foundedFlight) { double priceWithTax = foundedFlight.getBasePrice() + foundedFlight.getTax(); double priceWithTaxAndDiscount = priceWithTax * ((wholePercentage - foundedFlight.getDiscount()) / wholePercentage); return roundDoubleTwoDigit(priceWithTaxAndDiscount); } private double roundDoubleTwoDigit(double priceWithTaxAndDiscount) { int digitCount = 2; BigDecimal bd = BigDecimal.valueOf(priceWithTaxAndDiscount); bd = bd.setScale(digitCount, RoundingMode.HALF_UP); return bd.doubleValue(); } }
package com.crewmaker.entity; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @NoArgsConstructor @Entity @Table(name="userOpinion") public class UserOpinion { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="userOpinionID") private Long userOpinionId; @ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}) @JoinColumn(name="userAuthorID") private User userAuthor; @ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}) @JoinColumn(name="userAboutID") private User userAbout; @Column(name="title") private String title; @Column(name="message") private String message; @Column(name="grade") private int grade; public UserOpinion(User userAuthor, User userAbout, String title, String message, int grade) { this.userAuthor = userAuthor; this.userAbout = userAbout; this.title = title; this.message = message; this.grade = grade; } }
package ca.ubc.cpen391team17; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import java.util.List; public class StartUpActivity extends AppCompatActivity implements SensorEventListener { private SensorManager mSensorManager; private Sensor mBarometer; public void mainMenu(View view){ Intent intent = new Intent(this, MainMenuActivity.class); this.finish(); startActivity(intent); } private void checkGooglePlayServices() { // Check if the user has the latest latest Google Play Services, and if not, prompt the // user to update it. GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance(); int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { Dialog dialog = googleApiAvailability.getErrorDialog(this, resultCode, 0); if (dialog != null) { //This dialog will help the user update to the latest GooglePlayServices dialog.show(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_up); checkGooglePlayServices(); initializeBarometer(); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mBarometer, SensorManager.SENSOR_DELAY_NORMAL); } /** * Called when the back button is pressed. */ @Override public void onBackPressed() { super.onBackPressed(); // Quit the app this.finishAffinity(); } public void initializeBarometer() { mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<Sensor> deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL); mBarometer = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); if (mBarometer != null) { System.out.println("updateAirPressure: There *is* a barometer"); } else { System.out.println("updateAirPressure: barometer not found"); } } @Override public void onSensorChanged(SensorEvent event) { double pressure = event.values[0]; TextView textView = (TextView) findViewById(R.id.barometer); textView.setText((int)pressure + " hPa"); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // we do not need to do anything if sensor accuracy changes } }
package dev.schoenberg.kicker_stats.rest.dto; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class PlayersDto { @XmlElement(name = "players") public List<PlayerDto> players; protected PlayersDto() {} public PlayersDto(List<PlayerDto> players) { this.players = players; } }
package org.cloudfoundry.vr; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class VrController { private static final Logger LOG = Logger.getLogger(VrController.class); public static final String TOKEN = "MTM5MTI1OTg5MDQwMzozNDQyZWMxZmQ5ZDliODUzMGFiMjp0ZW5hbnQ6cWV1c2VybmFtZTjYjY1ZjhiODI2OTg4ODU3M2UwOTUwOWRkMjlmYWRjNWQ4NjJkOTk1YmE3MTg1MWZhOTc2MjEyYjYxZmU3YTVhZDcwNzM3ZTg3ZDNjNDk2ZDlmNA=="; public static final String CATALOG_ID = "dc808d12-3786-4f7c-b5a1-d5f997c8ad66"; public static final String REQUEST_ID = "7aaf9baf-aa4e-47c4-997b-edd7c7983a5b"; public static final String RESOURCE_ID = "c4d3db3e-e397-44ffa1c9-0ecebdba12f4"; public static final String ACTION_ID = "02bad06d-f92b-4cf8-b964-37bb5d57be38"; @RequestMapping(value = "/identity/api/tokens ", method = RequestMethod.POST) public HttpEntity<Map<String, String>> tokens( @RequestBody Map<String, String> request) { Map<String, String> m = new HashMap<String, String>(); m.put("expires", "2015-08-01T13:09:45.619Z"); m.put("id", TOKEN); m.put("tenant", request.get("tenant").toString()); return new ResponseEntity<>(m, HttpStatus.OK); } @RequestMapping(value = "/identity/api/tokens/{token}", method = RequestMethod.GET) public HttpEntity<String> tokens(@PathVariable String token) { if (token == null || token.length() < 1 || token.trim().equalsIgnoreCase("null")) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Authorization", " Bearer " + TOKEN); return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT); } @RequestMapping(value = "/catalog-service/api/consumer/entitledCatalogItemViews", method = RequestMethod.GET) public HttpEntity<String> entitledCatalogItemViews( @RequestHeader("Authorization") String token) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } return new ResponseEntity<>(getJson("catalog.json"), HttpStatus.OK); } @RequestMapping(value = "/service/api/consumer/entitledCatalogItems/{catalogId}/requests/template", method = RequestMethod.GET) public HttpEntity<String> requestTemplate( @RequestHeader("Authorization") String token, @PathVariable String catalogId) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (catalogId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(getJson("resourceTemplate.json"), HttpStatus.OK); } @RequestMapping(value = "/service/api/consumer/entitledCatalogItems/{catalogId}/requests", method = RequestMethod.POST) public HttpEntity<String> requestCatalogItem( @RequestHeader("Authorization") String token, @PathVariable String catalogId, @RequestBody String request) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (catalogId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(getJson("request.json"), HttpStatus.CREATED); } @RequestMapping(value = "/catalog-service/api/consumer/requests/{requestId}", method = RequestMethod.GET) public HttpEntity<String> requestDetails( @RequestHeader("Authorization") String token, @PathVariable String requestId) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (requestId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(getJson("request.json"), HttpStatus.OK); } @RequestMapping(value = "/catalog-service/api/consumer/requests/{requestId}/resourceViews", method = RequestMethod.GET) public HttpEntity<String> requestResources( @RequestHeader("Authorization") String token, @PathVariable String requestId) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (requestId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(getJson("resources.json"), HttpStatus.OK); } @RequestMapping(value = "/catalog-service/api/consumer/resources/{resourceId}/actions/{actionId}/requests/template", method = RequestMethod.GET) public HttpEntity<String> actionTemplate( @RequestHeader("Authorization") String token, @PathVariable String resourceId, @PathVariable String actionId) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (resourceId == null || actionId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(getJson("actionTemplate.json"), HttpStatus.OK); } // TODO, use correct query string as per api @RequestMapping(value = "/catalogservice/api/consumer/resourceViews/{resourceId}", method = RequestMethod.GET) public HttpEntity<String> childResources( @RequestHeader("Authorization") String token, @PathVariable String resourceId) { if (token == null) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if (resourceId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(getJson("child.json"), HttpStatus.OK); } public static String getJson(String fileName) { try { URI u = new ClassPathResource(fileName).getURI(); return new String(Files.readAllBytes(Paths.get(u))); } catch (IOException e) { LOG.error(e); return e.getMessage(); } } }
package com.dazhi.config; import com.dazhi.naming.api.config.PropertySourcesUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @ConfigurationProperties("spring.cloud.nacos.config") public class NacosConfigProperties { public static final String PREFIX = "spring.cloud.nacos.config"; public static final String COMMAS = ","; public static final String SEPARATOR = "[,]"; private static final Pattern PATTERN = Pattern.compile("-(\\w)"); private static final Logger log = LoggerFactory.getLogger(NacosConfigProperties.class); @Autowired @JsonIgnore private Environment environment; private String serverAddr; private String username; private String password; private String encode; private String group = "DEFAULT_GROUP"; private String prefix; private String fileExtension = "properties"; private int timeout = 3000; private String maxRetry; private String configLongPollTimeout; private String configRetryTime; private boolean enableRemoteSyncConfig = false; private String endpoint; private String namespace; private String accessKey; private String secretKey; private String contextPath; private String clusterName; private String name; private List<Config> sharedConfigs; private List<NacosConfigProperties.Config> extensionConfigs; private boolean refreshEnabled = true; public NacosConfigProperties() { } @PostConstruct public void init() { this.overrideFromEnv(); } private void overrideFromEnv() { if (StringUtils.isEmpty(this.getServerAddr())) { String serverAddr = this.environment.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}"); if (StringUtils.isEmpty(serverAddr)) { serverAddr = this.environment.resolvePlaceholders("${spring.cloud.nacos.server-addr:localhost:8848}"); } this.setServerAddr(serverAddr); } if (StringUtils.isEmpty(this.getUsername())) { this.setUsername(this.environment.resolvePlaceholders("${spring.cloud.nacos.username:}")); } if (StringUtils.isEmpty(this.getPassword())) { this.setPassword(this.environment.resolvePlaceholders("${spring.cloud.nacos.password:}")); } } public String getServerAddr() { return this.serverAddr; } public void setServerAddr(String serverAddr) { this.serverAddr = serverAddr; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getFileExtension() { return this.fileExtension; } public void setFileExtension(String fileExtension) { this.fileExtension = fileExtension; } public String getGroup() { return this.group; } public void setGroup(String group) { this.group = group; } public int getTimeout() { return this.timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getMaxRetry() { return this.maxRetry; } public void setMaxRetry(String maxRetry) { this.maxRetry = maxRetry; } public String getConfigLongPollTimeout() { return this.configLongPollTimeout; } public void setConfigLongPollTimeout(String configLongPollTimeout) { this.configLongPollTimeout = configLongPollTimeout; } public String getConfigRetryTime() { return this.configRetryTime; } public void setConfigRetryTime(String configRetryTime) { this.configRetryTime = configRetryTime; } public Boolean getEnableRemoteSyncConfig() { return this.enableRemoteSyncConfig; } public void setEnableRemoteSyncConfig(Boolean enableRemoteSyncConfig) { this.enableRemoteSyncConfig = enableRemoteSyncConfig; } public String getEndpoint() { return this.endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public String getNamespace() { return this.namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getAccessKey() { return this.accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return this.secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getEncode() { return this.encode; } public void setEncode(String encode) { this.encode = encode; } public String getContextPath() { return this.contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getClusterName() { return this.clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Environment getEnvironment() { return this.environment; } public void setEnvironment(Environment environment) { this.environment = environment; } public List<NacosConfigProperties.Config> getSharedConfigs() { return this.sharedConfigs; } public void setSharedConfigs(List<NacosConfigProperties.Config> sharedConfigs) { this.sharedConfigs = sharedConfigs; } public List<NacosConfigProperties.Config> getExtensionConfigs() { return this.extensionConfigs; } public void setExtensionConfigs(List<NacosConfigProperties.Config> extensionConfigs) { this.extensionConfigs = extensionConfigs; } public boolean isRefreshEnabled() { return this.refreshEnabled; } public void setRefreshEnabled(boolean refreshEnabled) { this.refreshEnabled = refreshEnabled; } /** @deprecated */ @Deprecated @DeprecatedConfigurationProperty( reason = "replaced to NacosConfigProperties#sharedConfigs and not use it at the same time.", replacement = "spring.cloud.nacos.config.shared-configs[x]" ) public String getSharedDataids() { return null == this.getSharedConfigs() ? null : (String)this.getSharedConfigs().stream().map(NacosConfigProperties.Config::getDataId).collect(Collectors.joining(",")); } /** @deprecated */ @Deprecated public void setSharedDataids(String sharedDataids) { if (null != sharedDataids && sharedDataids.trim().length() > 0) { List<NacosConfigProperties.Config> list = new ArrayList(); Stream.of(sharedDataids.split("[,]")).forEach((dataId) -> { list.add(new NacosConfigProperties.Config(dataId.trim())); }); this.compatibleSharedConfigs(list); } } /** @deprecated */ @Deprecated @DeprecatedConfigurationProperty( reason = "replaced to NacosConfigProperties#sharedConfigs and not use it at the same time.", replacement = "spring.cloud.nacos.config.shared-configs[x].refresh" ) public String getRefreshableDataids() { return null == this.getSharedConfigs() ? null : (String)this.getSharedConfigs().stream().filter(NacosConfigProperties.Config::isRefresh).map(NacosConfigProperties.Config::getDataId).collect(Collectors.joining(",")); } /** @deprecated */ @Deprecated public void setRefreshableDataids(String refreshableDataids) { if (null != refreshableDataids && refreshableDataids.trim().length() > 0) { List<NacosConfigProperties.Config> list = new ArrayList(); Stream.of(refreshableDataids.split("[,]")).forEach((dataId) -> { list.add((new NacosConfigProperties.Config(dataId.trim())).setRefresh(true)); }); this.compatibleSharedConfigs(list); } } private void compatibleSharedConfigs(List<NacosConfigProperties.Config> configList) { if (null != this.getSharedConfigs()) { configList.addAll(this.getSharedConfigs()); } List<NacosConfigProperties.Config> result = new ArrayList(); // ((ConcurrentHashMap)configList.stream().collect(Collectors.groupingBy((cfg) -> { // return cfg.getGroup() + cfg.getDataId(); // }, () -> { // return new ConcurrentHashMap(new LinkedHashMap()); // }, Collectors.toList()))).forEach((key, list) -> { // list.stream().reduce((a, b) -> { // return new NacosConfigProperties.Config(a.getDataId(), a.getGroup(), a.isRefresh() || b != null && b.isRefresh()); // }).ifPresent(result::add); // }); this.setSharedConfigs(result); } /** @deprecated */ @Deprecated @DeprecatedConfigurationProperty( reason = "replaced to NacosConfigProperties#extensionConfigs and not use it at the same time .", replacement = "spring.cloud.nacos.config.extension-configs[x]" ) public List<NacosConfigProperties.Config> getExtConfig() { return this.getExtensionConfigs(); } /** @deprecated */ @Deprecated public void setExtConfig(List<NacosConfigProperties.Config> extConfig) { this.setExtensionConfigs(extConfig); } /** @deprecated */ // @Deprecated // public ConfigService configServiceInstance() { // return NacosConfigManager.createConfigService(this); // } /** @deprecated */ @Deprecated public Properties getConfigServiceProperties() { return this.assembleConfigServiceProperties(); } public Properties assembleConfigServiceProperties() { Properties properties = new Properties(); properties.put("serverAddr", Objects.toString(this.serverAddr, "")); properties.put("username", Objects.toString(this.username, "")); properties.put("password", Objects.toString(this.password, "")); properties.put("encode", Objects.toString(this.encode, "")); properties.put("namespace", Objects.toString(this.namespace, "")); properties.put("accessKey", Objects.toString(this.accessKey, "")); properties.put("secretKey", Objects.toString(this.secretKey, "")); properties.put("clusterName", Objects.toString(this.clusterName, "")); properties.put("maxRetry", Objects.toString(this.maxRetry, "")); properties.put("configLongPollTimeout", Objects.toString(this.configLongPollTimeout, "")); properties.put("configRetryTime", Objects.toString(this.configRetryTime, "")); properties.put("enableRemoteSyncConfig", Objects.toString(this.enableRemoteSyncConfig, "")); String endpoint = Objects.toString(this.endpoint, ""); if (endpoint.contains(":")) { int index = endpoint.indexOf(":"); properties.put("endpoint", endpoint.substring(0, index)); properties.put("endpointPort", endpoint.substring(index + 1)); } else { properties.put("endpoint", endpoint); } this.enrichNacosConfigProperties(properties); return properties; } private void enrichNacosConfigProperties(Properties nacosConfigProperties) { Map<String, Object> properties = PropertySourcesUtils.getSubProperties((ConfigurableEnvironment)this.environment, "spring.cloud.nacos.config"); properties.forEach((k, v) -> { nacosConfigProperties.putIfAbsent(this.resolveKey(k), String.valueOf(v)); }); } private String resolveKey(String key) { Matcher matcher = PATTERN.matcher(key); StringBuffer sb = new StringBuffer(); while(matcher.find()) { matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); } matcher.appendTail(sb); return sb.toString(); } public String toString() { return "NacosConfigProperties{serverAddr='" + this.serverAddr + '\'' + ", encode='" + this.encode + '\'' + ", group='" + this.group + '\'' + ", prefix='" + this.prefix + '\'' + ", fileExtension='" + this.fileExtension + '\'' + ", timeout=" + this.timeout + ", maxRetry='" + this.maxRetry + '\'' + ", configLongPollTimeout='" + this.configLongPollTimeout + '\'' + ", configRetryTime='" + this.configRetryTime + '\'' + ", enableRemoteSyncConfig=" + this.enableRemoteSyncConfig + ", endpoint='" + this.endpoint + '\'' + ", namespace='" + this.namespace + '\'' + ", accessKey='" + this.accessKey + '\'' + ", secretKey='" + this.secretKey + '\'' + ", contextPath='" + this.contextPath + '\'' + ", clusterName='" + this.clusterName + '\'' + ", name='" + this.name + '\'' + '\'' + ", shares=" + this.sharedConfigs + ", extensions=" + this.extensionConfigs + ", refreshEnabled=" + this.refreshEnabled + '}'; } public static class Config { private String dataId; private String group; private boolean refresh; public Config() { this.group = "DEFAULT_GROUP"; this.refresh = false; } public Config(String dataId) { this.group = "DEFAULT_GROUP"; this.refresh = false; this.dataId = dataId; } public Config(String dataId, String group) { this(dataId); this.group = group; } public Config(String dataId, boolean refresh) { this(dataId); this.refresh = refresh; } public Config(String dataId, String group, boolean refresh) { this(dataId, group); this.refresh = refresh; } public String getDataId() { return this.dataId; } public NacosConfigProperties.Config setDataId(String dataId) { this.dataId = dataId; return this; } public String getGroup() { return this.group; } public NacosConfigProperties.Config setGroup(String group) { this.group = group; return this; } public boolean isRefresh() { return this.refresh; } public NacosConfigProperties.Config setRefresh(boolean refresh) { this.refresh = refresh; return this; } public String toString() { return "Config{dataId='" + this.dataId + '\'' + ", group='" + this.group + '\'' + ", refresh=" + this.refresh + '}'; } public boolean equals(Object o) { if (this == o) { return true; } else if (o != null && this.getClass() == o.getClass()) { NacosConfigProperties.Config config = (NacosConfigProperties.Config)o; return this.refresh == config.refresh && Objects.equals(this.dataId, config.dataId) && Objects.equals(this.group, config.group); } else { return false; } } public int hashCode() { return Objects.hash(new Object[]{this.dataId, this.group, this.refresh}); } } }
package cn.xdl.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.xdl.dao.EtAdminDao; import cn.xdl.entity.EtAdmin; import java.util.List; @Service public class EtAdminService { @Autowired private EtAdminDao dao; public List<EtAdmin> getAll(){ return dao.getAll(); } }
package org.usfirst.frc.team1247.robot.commands; public class PnuematicsCommand extends BaseCommand { public PnuematicsCommand() { requires(pnuematics); } // Called just before this Command runs the first time protected void initialize() { super.initialize(); } @Override protected void execute() { if (oi.getCompressorOffButton()) pnuematics.stopCompressor(); if (oi.getCompressorOnButton()) pnuematics.startCompressor(); } @Override protected boolean isFinished() { // TODO Auto-generated method stub return super.isFinished(); } @Override protected void end() { // TODO Auto-generated method stub super.end(); } @Override protected void interrupted() { // TODO Auto-generated method stub super.interrupted(); } }
package com.ssm.wechatpro.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ssm.wechatpro.object.InputObject; import com.ssm.wechatpro.object.OutputObject; import com.ssm.wechatpro.service.WechatProductPackageService; @Controller public class WechatProductPackageController { @Resource private WechatProductPackageService wechatProductPackageService; /** * * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/selectAllPackage") @ResponseBody public void selectAllPackage(InputObject inputObject,OutputObject outputObject) throws Exception { wechatProductPackageService.selectAllPackage(inputObject, outputObject); } /** * 通过id查询套餐中的商品信息 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/selectPackageById") @ResponseBody public void selectPackageById(InputObject inputObject,OutputObject outputObject) throws Exception { wechatProductPackageService.selectPackageById(inputObject, outputObject); } /** * 添加一条套餐表单 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/insertPackage") @ResponseBody public void insertPackage(InputObject inputObject, OutputObject outputObject)throws Exception { wechatProductPackageService.insertPackage(inputObject, outputObject); } /** * 查看所有提审状态的套餐 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/selectProductByState") @ResponseBody public void selectProductByState(InputObject inputObject, OutputObject outputObject)throws Exception { wechatProductPackageService.selectProductByState(inputObject, outputObject); } /** * 修改套餐信息 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/updatePackageState") @ResponseBody public void updatePackageState(InputObject inputObject, OutputObject outputObject) throws Exception{ wechatProductPackageService.updatePackageState(inputObject, outputObject); } @RequestMapping("/post/wechatProductPackageController/updatePackageStatePass") @ResponseBody public void updatePackageStatePass(InputObject inputObject, OutputObject outputObject) throws Exception{ wechatProductPackageService.updatePackageStatePass(inputObject, outputObject); } @RequestMapping("/post/wechatProductPackageController/updatePackageStateNotPass") @ResponseBody public void updatePackageStateNotPass(InputObject inputObject, OutputObject outputObject) throws Exception{ wechatProductPackageService.updatePackageStateNotPass(inputObject, outputObject); } /** * 删除套餐信息 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/deletePackageById") @ResponseBody public void deletePackageById(InputObject inputObject,OutputObject outputObject) throws Exception { wechatProductPackageService.deletePackageById(inputObject, outputObject); } /** * 通过套餐中查询出套餐绑定产品ID,查看套餐的详细信息 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/selectPackageDetailInfoById") @ResponseBody public void selectPackageDetailInfoById(InputObject inputObject, OutputObject outputObject) throws Exception{ wechatProductPackageService.selectPackageDetailInfoById(inputObject, outputObject); } /** * 根据商品类别的id查询商品 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/selectProductByProductTypeId") @ResponseBody public void selectProductByProductTypeId(InputObject inputObject, OutputObject outputObject) throws Exception{ wechatProductPackageService.selectProductByProductTypeId(inputObject, outputObject); } /** * 更新套餐的信息 * @param inputObject * @param outputObject * @throws Exception */ @RequestMapping("/post/wechatProductPackageController/updatePackageInfo") @ResponseBody public void updatePackageInfo(InputObject inputObject, OutputObject outputObject) throws Exception{ wechatProductPackageService.updatePackageInfo(inputObject, outputObject); } }
package Servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.User; import org.apache.catalina.servlet4preview.RequestDispatcher; import Been.Userbeen; import Dao.UserDao; public class LoginServlet extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); doPost(request, response); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String nickname = request.getParameter("nickname"); int password =Integer.parseInt(request.getParameter("password")); UserDao ud=new UserDao(); Userbeen user=new Userbeen(); boolean b=ud.userenter(nickname, password); if(b==true){ request.getSession().setAttribute("user", user); request.getSession().setAttribute("nickname", nickname); response.sendRedirect("/NBAStar/Stars.jsp"); }else{ response.sendRedirect("/NBAStar/Stars.jsp"); } } }
/** * @author Paweł Włoch ©SoftLab * @date 17 sty 2019 */ package com.softlab.ubscoding.webserver.test.websocket; import static org.junit.Assert.assertTrue; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.knowm.xchange.currency.CurrencyPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.messaging.converter.MappingJackson2MessageConverter; import org.springframework.messaging.simp.stomp.StompFrameHandler; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; import org.springframework.messaging.simp.stomp.StompSessionHandler; import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.messaging.WebSocketStompClient; import org.springframework.web.socket.sockjs.client.SockJsClient; import org.springframework.web.socket.sockjs.client.Transport; import org.springframework.web.socket.sockjs.client.WebSocketTransport; import com.softlab.ubscoding.webserver.model.AlertData; import com.softlab.ubscoding.webserver.model.LimitsWrapper; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @TestPropertySource("classpath:application-test.properties") public class WebsocketIntegrationTest { private static Logger LOG = LoggerFactory.getLogger(WebsocketIntegrationTest.class); private static final CurrencyPair CURRENCY_PAIR = CurrencyPair.BTC_PLN; private static final String ALERT_TOPIC = "/topic/limit-alerts"; @Value("${server.address}") private String serverAddress; @LocalServerPort private int port; @Value("${server.servlet.context-path}") private String servletContextPath; @Autowired private LimitsWrapper limitsData; private String URL; private WebSocketStompClient stompClient; private volatile boolean dataReceived = false; @Before public void setup() throws Exception { URL = "ws://" + serverAddress + ":" + port + servletContextPath + "/monitor-websocket"; List<Transport> transports = new ArrayList<>(); transports.add(new WebSocketTransport(new StandardWebSocketClient())); SockJsClient sockJsClient = new SockJsClient(transports); this.stompClient = new WebSocketStompClient(sockJsClient); this.stompClient.setMessageConverter(new MappingJackson2MessageConverter()); // set limit to 0 for a basic currency limitsData.setLimitForCurrPair(CURRENCY_PAIR, new BigDecimal(0)); } @Test public void shouldSubscribeAndReceiveAlert() throws InterruptedException, ExecutionException, TimeoutException { StompSessionHandler handler = new StompSessionHandlerAdapter() { @Override public void afterConnected(final StompSession session, StompHeaders connectedHeaders) { session.subscribe(ALERT_TOPIC, new StompFrameHandler() { @Override public Type getPayloadType(StompHeaders headers) { return AlertData.class; } @Override public void handleFrame(StompHeaders headers, Object payload) { LOG.debug(payload.toString()); AlertData alert = (AlertData) payload; assertTrue(alert.getCurrencyPair().equals(CURRENCY_PAIR.toString())); System.out.println("received alert: " + alert.toString()); LOG.debug("received alert:" + alert.toString()); dataReceived = true; } }); LOG.debug("succesfully subscribed to topic on socket"); } }; StompSession stompSession = stompClient.connect(URL, handler).get(); assertTrue(stompSession.isConnected()); LOG.debug("succesfully connected to socket"); // TODO add automatic test failure after waiting e.g. 5 secs while (!dataReceived) { Thread.sleep(1000); } stompSession.disconnect(); } }
package com.linda.framework.rpc.aio; import com.linda.framework.rpc.Service; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * TCP连接AIO接收 * * @author lindezhi * 2016年6月13日 下午3:00:39 */ public class RpcAcceptCompletionHandlerImpl implements CompletionHandler<AsynchronousSocketChannel, AbstractRpcAioAcceptor>, Service { /** * 公共的readerhandler */ private RpcReadCompletionHandler readHandler; /** * 公共的writehandler */ private RpcWriteCompletionHandler writeHandler; /** * 新建连接回调 */ @Override public void completed(AsynchronousSocketChannel channel, AbstractRpcAioAcceptor acceptor) { //新建tcp消息通道 AbstractRpcAioConnector connector = new AbstractRpcAioConnector(acceptor.getAioWriter(), channel); try { connector.setReadHandler(readHandler); connector.setWriteHandler(writeHandler); //将上下文的listener添加到connector中 acceptor.addConnectorListeners(connector); connector.startService(); } catch (Exception e) { connector.handleConnectorException(e); } finally { //异步接受新的TCP连接 acceptor.getServerChannel().accept(acceptor, this); } } /** * 新建连接失败 */ @Override public void failed(Throwable th, AbstractRpcAioAcceptor acceptor) { acceptor.handleFail(th, acceptor); } @Override public void startService() { readHandler = new RpcReadCompletionHandler(); writeHandler = new RpcWriteCompletionHandler(); } @Override public void stopService() { readHandler = null; writeHandler = null; } }
package GameService; import Player.Player; import java.io.Serializable; public class PlayerID implements Serializable { private int playersID = 0; public PlayerID(int id){ this.playersID = id; } public int getPlayersID() { return playersID; } public void setPlayersID(int playersID) { this.playersID = playersID; } }
package com.sanqing.factory; import com.sanqing.dao.MessagePermissionDAO; import com.sanqing.daoImpl.MessagePermissionDAOImpl; /** * ╗˝╚íMessagePermissionDAOÂ嵐 * @author grass * */ public class MessagePermissionDAOFactory { public static MessagePermissionDAO getMessagePermissionDAO(){ return new MessagePermissionDAOImpl(); } }
package com.smxknife.java.ex30; import java.util.stream.Stream; /** * @author smxknife * 2019/9/8 */ public class _Demo { public static void main(String[] args) { Stream.iterate(0, i -> i + 1).limit(10) .forEach(idx -> new Thread(() -> {Bird.INSTANCE.print();}, "th_" + idx).start()); System.out.println(Bird.INSTANCE == Bird.INSTANCE); } }
package amit.chefling_amit; import android.widget.Toast; import mobi.upod.timedurationpicker.TimeDurationPicker; import mobi.upod.timedurationpicker.TimeDurationPickerDialogFragment; /** * Created by amit on 10/28/2016. */ public class PickerDialogFragment extends TimeDurationPickerDialogFragment { public interface PickerDialogFragmentListener { void onDurationPicked(Long duaration); } @Override protected long getInitialDuration() { return 15 * 60 * 1000; } @Override public void onDurationSet(TimeDurationPicker view, long duration) { Toast.makeText(getActivity(), Long.toString(duration),Toast.LENGTH_SHORT).show(); // SharedPreferences cook_time; // SharedPreferences.Editor editor; // cook_time = getActivity().getSharedPreferences("COOKING_TIME", Context.MODE_PRIVATE); //1 // editor = cook_time.edit(); //2 // // editor.putLong("COOKING_TIME_LONG", duration); //3 // editor.commit(); PickerDialogFragmentListener listener = (PickerDialogFragmentListener) getActivity(); listener.onDurationPicked(duration); } }
package sort; public class sortUtils { /** * 交换数据i和j2个位置的值 * @param array * @param i * @param j */ public static void change(int[] array, int i,int j){ int temp=array[i]; array[i]=array[j]; array[j]=temp; } /** * 数据往后移 * @param array * @param from * @param to * @return */ public static int moveFromTo(int[] array,int from,int to){ int result=array[to]; int j=to-1; do{ array[j+1]=array[j]; j--; }while(j>=from); return result; } }
package com.Collections_TreeSetUsingNavigateSetInterface; public class NoOfElement { }
package entities; import java.util.Scanner; public class Count { //Attributes private String nCount; private String nameUser; private double balance; private char ask; //Construct public Count() { Scanner sc = new Scanner(System.in); // Start to read System.out.print("Enter account number: "); this.nCount = sc.next(); System.out.print("Enter account holder: "); this.nameUser = sc.next(); // sc.hasNextLine(); Using 2 NextLine to pick compound names System.out.print("Is there na initial deposit (y/n)? "); this.ask = sc.next().charAt(0); // Using .charAt(0) and == 'y' in the next line if (this.ask == 'y') { System.out.print("Enter initial deposit value: "); this.balance = sc.nextDouble(); } System.out.println(""); System.out.println("Account Data: "); System.out.printf("Account %s, Holder: %s, Balance: $ %.2f%n", this.nCount, this.nameUser, this.balance); System.out.println(""); System.out.print("Enter a deposit value: "); this.balance += sc.nextDouble(); System.out.println("Updated account data: "); System.out.printf("Account %s, Holder: %s, Balance: $ %.2f%n", this.nCount, this.nameUser, this.balance); System.out.println(""); System.out.print("Enter a withdraw value: "); this.balance -= sc.nextDouble(); this.balance -= 5.00; System.out.println("Updated account data: "); System.out.printf("Account %s, Holder: %s, Balance: $ %.2f%n", this.nCount, this.nameUser, this.balance); sc.close(); // End to read } /* public Count(String nCount, String nameUser, double balance) { //super(); this.nCount = nCount; this.nameUser = nameUser; this.balance = balance; } */ /* public Count(String nCount, String nameUser) { //super(); this.nCount = nCount; this.nameUser = nameUser; this.balance = 0; } */ //Métodos especiais - Set and Get public String getNCount() { return nCount; } public String getNameUser() { return nameUser; } public void setNameUser(String nameUser) { this.nameUser = nameUser; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } /*public void setNCount(String nCount) { this.nCount = nCount; } Number of count can't change */ }
package telecom.executors.kostanay; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.rarfile.FileHeader; import telecom.Mailer; import telecom.executors.Execute; public class ExecuteCC8LIS extends Execute{ public ExecuteCC8LIS(String mode) throws IOException { super(mode); } @SuppressWarnings("resource") private File[] unRarFile(File file) throws RarException, IOException{ String slash = System.getProperty("file.separator"); ArrayList<File> fileList = new ArrayList<>(); Archive a = new Archive(new FileVolumeManager(file)); String extractedFile = null; if (a != null) { //a.getMainHeader().print(); FileHeader fh = a.nextFileHeader(); while (fh != null) { extractedFile = fh.getFileNameString().trim(); String strOutFile = file.getCanonicalFile().getParent() + slash + extractedFile; File out = new File(strOutFile); if (out.exists()) throw new IOException(out.getCanonicalPath() + " allready exists. JUNRAR error."); fileList.add(out); FileOutputStream os = new FileOutputStream(out); a.extractFile(fh, os); os.close(); fh = a.nextFileHeader(); } } return fileList.toArray(new File[fileList.size()]); } protected void start() throws Exception { String subj = ini.getString("email","subject",""); try { File[] files = downloadFiles(); if (files.length > 0) { uploadFilesToArch(files); List <File> aFiles = new ArrayList<File>(); for(File file : files ) { File[] unrFiles = unRarFile(file); aFiles.addAll(Arrays.asList(unrFiles)); } uploadFilesToMD(aFiles.toArray(new File[aFiles.size()])); setFilesDB(files); } } catch (Exception ex) { this.log.add("error", ex.toString()); throw ex; } finally { subj = subj + "(" + (this.mode) + ")"; if (this.log.errCount > 0) { subj = subj + "[Error]"; } else if (this.log.wrnCount > 0) { subj = subj + "[Warning]"; } (new Mailer(ini.getString("email","to",""), ini.getString("email","from",""), ini.getString("email","host",""), subj, this.log.getAllMessages())).send(); } } }
package controller; import javafx.animation.TranslateTransition; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.media.AudioClip; import javafx.stage.Stage; import javafx.util.Duration; import sun.audio.AudioPlayer; import util.DBConnection; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.xml.transform.Result; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import java.util.regex.Pattern; public class ForgetPassword { private static final AudioClip errorAlertSound = new AudioClip(AudioPlayer.class.getResource("/resource/windows_error.mp3").toString()); private static final AudioClip success = new AudioClip(AudioPlayer.class.getResource("/resource/sounds/success.mp3").toString()); private static final AudioClip informationAlertSound = new AudioClip(AudioPlayer.class.getResource("/resource/sounds/windows_10_notify.mp3").toString()); public AnchorPane forgetPassword; public TextField txtUserEmail; public Button btnSubmit; String email; public void initialize() { txtUserEmail.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { String emailValidation = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{3}$"; Pattern pattern = Pattern.compile(emailValidation); if (txtUserEmail.getText().trim().matches(String.valueOf(pattern))) { txtUserEmail.setStyle(null); btnSubmit.setDisable(false); email = "done"; } else { txtUserEmail.setStyle("-fx-border-color: red"); btnSubmit.setDisable(true); email = "null"; } } }); } public void btnSubmit_OnAction(ActionEvent event) throws SQLException, MessagingException { if (txtUserEmail.getText().trim().equals("")) { informationAlertSound.play(); new Alert(Alert.AlertType.INFORMATION, "Enter the Email Address", ButtonType.OK).show(); return; } String email = txtUserEmail.getText(); PreparedStatement statement = DBConnection.getInstance().getConnection().prepareStatement("SELECT * FROM user WHERE emailAddress = ?"); statement.setObject(1, email); ResultSet rs = statement.executeQuery(); System.out.println("done"); if (rs.next()) { String userName = rs.getString(2); String password = rs.getString(3); String to = email;//change accordingly //Get the session object Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("shahidfazaal@gmail.com", "email password must come here");//Put your email id and password here } }); //compose message String l1 = "Hi " + userName + "!,"; String l2 = "Your password for the Email ID " + email + " is " + password; String l3 = "IJSE Library \n #223A 1/2, Galle Road, Panadura. \n +94 38 2222 800 / +94 38 2244 855"; MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("shahidfazaal@gmail.com"));//change accordingly message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Your Forgot Password is"); message.setText(l1 + "\r\n" + "\r\n" + l2 + "\r\n" + "\r\n" + l3); //send message Transport.send(message); System.out.println("message sent successfully"); System.out.println("Password send to your email id successfully !"); success.play(); new Alert(Alert.AlertType.INFORMATION, "The password hass successfully sent to the email address " + email, ButtonType.OK).show(); } else { errorAlertSound.play(); new Alert(Alert.AlertType.ERROR, "there is no user with the email address " + email, ButtonType.OK).show(); } } public void navigate_onKeyPressed(KeyEvent keyEvent) throws IOException { if (keyEvent.getCode() == KeyCode.ESCAPE) { Parent root = FXMLLoader.load(this.getClass().getResource("/view/Login.fxml")); Scene subScene = new Scene(root); Stage primaryStage = (Stage) this.forgetPassword.getScene().getWindow(); primaryStage.setScene(subScene); primaryStage.centerOnScreen(); TranslateTransition tt = new TranslateTransition(Duration.millis(350), subScene.getRoot()); tt.setFromX(500); tt.setToX(0); tt.play(); } } }
package com.pa.miniEip.controller; import com.pa.miniEip.model.Answer; import com.pa.miniEip.model.Form; import com.pa.miniEip.service.AnswerService; import com.pa.miniEip.service.FormService; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class FormController { @Autowired private FormService formService; @Autowired private AnswerService answerService; @GetMapping(value = "/forms/{id}") public ResponseEntity<Form> getForm(@PathVariable ObjectId id) { Form form = formService.getForm(id); return ResponseEntity.status(HttpStatus.OK).body(form); } @GetMapping(value = "/forms/{id}/answers") public ResponseEntity<List<Answer>> getAnswersForFormId(@PathVariable ObjectId id) { List<Answer> answers = answerService.getAnswersForFormId(id); return ResponseEntity.status(HttpStatus.OK).body(answers); } @PostMapping(value = "/forms") public ResponseEntity<Form> createForm(@RequestBody Form form) { Form createdForm = formService.createForm(form); return ResponseEntity.status(HttpStatus.OK).body(createdForm); } @PutMapping(value = "/forms") public ResponseEntity<Form> updateForm(@RequestBody Form form) { Form updatedForm = formService.updateForm(form); return ResponseEntity.status(HttpStatus.OK).body(updatedForm); } @DeleteMapping(value = "/forms/{id}") public ResponseEntity<Void> deleteForm(@PathVariable ObjectId id) { formService.deleteForm(id); return ResponseEntity.noContent().build(); } }
package com.sneaker.mall.api.service; import com.sneaker.mall.api.model.Goods; import com.sneaker.mall.api.model.Order; import java.util.List; /** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ public interface GoodsService { /** * 根据公司ID读取商品信息 * * @param cid 公司ID * @param cateid 分类ID * @param ccid 客户ID * @return */ public List<Goods> getGoodsBycid(long cid, long cateid, long ccid); /** * 获取热够商品 * * @param cid * @param limit * @param ccid * @return */ public List<Goods> getHotGoodsByCid(long cid, int limit, long ccid); /** * 根据公司ID和类型获取商品列表 * * @param cid * @param typeid * @param ccid 客户ID * @return */ public List<Goods> getGoodsByTypeIdAndCid(long cid, long typeid, long ccid); /** * 根据公司ID与类型的编码获取商品列表 * * @param cid * @param code * @param ccid 客户ID * @return */ public List<Goods> getGoodsByCidAndTypeCode(int page, int limit, long cid, String code, long ccid); /** * 根据仓库与类型的编码获取商品列表 * @param page * @param limit * @param code * @param ccid * @return */ public List<Goods> getGoodsByCidAndTypeCode(int page, int limit, long cid, String code, String cctype, String sid); /** * 根据公司ID与类型统计商品个数 * * @param cid * @param code * @param ccid 客户ID * @return */ public int countGoodsByCidAndTypeCode(long cid, String code, long ccid); /** * 根据公司ID与类型统计商品个数 根据sid, cctype * * @param cid * @param code * @param ccid 客户ID * @return */ public int countGoodsByCidAndTypeCode(long cid, String code, String cctype, String sid); /** * 分页读取公司商品信息 * * @param cid * @param pageNumber * @param size * @param ccid 客户ID * @return */ public List<Goods> getGoodsByCidAndPage(long cid, int pageNumber, int size, long ccid); /** * 分页读取公司商品信息 根据cctype, sid * * @param cid * @param pageNumber * @param size * @param ccid 客户ID * @return */ public List<Goods> getGoodsByCidAndPage(long cid, int pageNumber, int size, String cctype, String sid); /** * 统计公司商品 * * @param cid * @param ccid 客户ID * @return */ public int countGoodsByCid(long cid, long ccid); /** * 统计公司商品 * * @param cid * @param ccid 客户ID * @return */ public int countGoodsByCid(long cid, String cctype, String sid); /** * 根据公司及栏目读取商品信息 * * @param cid * @param cateid * @param limit * @param ccid 客户ID * @return */ public List<Goods> getGoodsByCidAndCateidAndLimit(long cid, long cateid, int limit, long ccid); /** * 根据公司及栏目读取商品信息 cctype sid * @param cid * @param cateid * @param limit * @param cctype * @param sid * @return */ public List<Goods> getGoodsByCidAndCateidAndLimit(long cid, long cateid, int limit, String cctype, String sid); /** * 统计公司及栏目下面的商品统总数 * * @param cid * @param cateid * @param ccid 客户ID * @return */ public int countGoodsByCidAndCateid(long cid, long cateid, long ccid); /** * 统计公司及栏目下面的商品统总数 cctype sid * @param cid * @param cateid * @param cctype * @param sid * @return */ public int countGoodsByCidAndCateid(long cid, long cateid, String cctype, String sid); /** * 根据公司ID与商品ID读取商品信息 * * @param gid * @param cid * @return */ public Goods getGoodsByGidAndCid(long gid, long cid); /** * 根据ID读取商品基本信息 * * @param id * @return */ public Goods getGoodsById(long id, long cid, long ccid); /** * 根据BarCode查询商品 * * @param barcode * @return */ public Goods getGoodsByBarCode(String barcode, long cid, long ccid); /** * 根据公司ID和商品KEYWROD搜索 * * @param keywrod * @param cid * @param ccid 客户ID * @return */ public List<Goods> getGoodsByKeywordAndCid(String keywrod, long cid, long ccid); /** * 根据商品ID获取子商信息列表 * * @param id * @return */ public List<Goods> getChlidGoodsByMainGoodsId(long id, long cid, long ccid); /** * 根据供应商与自己公司获取收藏 * * @param scid * @param cid * @param page * @param limit * @return */ public List<Goods> getFavoriteGoodsCidAndScid(long scid, long cid, int page, int limit); /** * 根据用户获取收藏列表 * * @param uid * @param page * @param limit * @return */ public List<Goods> getFavoriteGoodsForUser(long uid, int page, int limit, long cid, long ccid); /** * 补充商品的绑定信息 * * @param goods */ public void paddingSingleMarket(Goods goods, long cid, long ccid); /** * 填充商品信息 * * @param goodses */ public void paddingMarket(List<Goods> goodses, long cid, long ccid); /** * 一键下单,获取该客户可以从该订单中再次下单的商品 * * @param order * @return */ public List<Goods> getOrderForAKeyOrder(Order order, long ccid, long scid); /** * 生成图片地址 * * @param goods */ public void genartePhoto(Goods goods); }
package org.simpleflatmapper.converter.joda.impl; import org.joda.time.ReadableInstant; import org.joda.time.format.DateTimeFormatter; import org.simpleflatmapper.converter.Converter; public class JodaReadableInstantToStringConverter implements Converter<ReadableInstant, String> { private final DateTimeFormatter dateTimeFormatter; public JodaReadableInstantToStringConverter(DateTimeFormatter dateTimeFormatter) { this.dateTimeFormatter = dateTimeFormatter; } @Override public String convert(ReadableInstant in) throws Exception { return dateTimeFormatter.print(in); } }
package org.alienideology.jcord.event.guild.emoji; import org.alienideology.jcord.Identity; import org.alienideology.jcord.handle.guild.IGuild; import org.alienideology.jcord.handle.guild.IGuildEmoji; /** * @author AlienIdeology */ public class GuildEmojiUploadEvent extends GuildEmojiEvent { public GuildEmojiUploadEvent(Identity identity, IGuild guild, int sequence, IGuildEmoji emoji) { super(identity, guild, sequence, emoji); } }
// Sun Certified Java Programmer // Chapter 1, P76_6 // Declarations and Access Control abstract class Phone1 extends Electronic { }
package com.dahua.design.behavioral.obsever; public abstract class AbstractTiktok { abstract void addFans(AbstractFans fans); abstract void notifyFans(String message); }
package banking.services; import framework.dto.ReportDTO; import framework.services.Report; import framework.services.ReportService; import banking.factories.ReportFactory; public class ReportServiceImp implements ReportService { private static ReportServiceImp instance; private ReportFactory factory; private ReportServiceImp(){ factory = new ReportFactory(); } public static ReportService getInstance(){ if(instance == null) instance = new ReportServiceImp(); return instance; } @Override public Report createReport(ReportDTO dto) { return factory.create(dto); } }
package sapronov.pavel.managementrestapi.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import sapronov.pavel.managementrestapi.utils.PatchAndPutReady; import javax.persistence.*; @Data @Entity @AllArgsConstructor @NoArgsConstructor @Builder(toBuilder = true) public class Address implements PatchAndPutReady<Address> { @Id @GeneratedValue(strategy = GenerationType.AUTO) @JsonIgnore Long id; String type; Integer number; String street; String unit; String city; String state; String zipCode; @JsonIgnore @ManyToOne @EqualsAndHashCode.Exclude @ToString.Exclude Identification identification; public Address(String type, Integer number, String street, String unit, String city, String state, String zipCode, Identification identification) { this(null, type, number, street, unit, city, state, zipCode, identification); } public Address(Long id, String type, Integer number, String street, String unit, String city, String state, String zipCode) { this(id, type, number, street, unit, city, state, zipCode, null); } public Address(String type, Integer number, String street, String unit, String city, String state, String zipCode) { this(null, type, number, street, unit, city, state, zipCode, null); } @Override public Address put(Address that) { return this.toBuilder() .type(that.type) .number(that.number) .street(that.street) .unit(that.unit) .city(that.city) .state(that.state) .zipCode(that.zipCode) .build(); } @Override public Address patch(Address that) { AddressBuilder b = this.toBuilder(); if (that.type != null) b.type(that.type); if (that.number != null) b.number(that.number); if (that.street != null) b.street(that.street); if (that.unit != null) b.unit(that.unit); if (that.city != null) b.city(that.city); if (that.state != null) b.state(that.state); if (that.zipCode != null) b.zipCode(that.zipCode); return b.build(); } }
import java.util.*; public class HighFive_1086 { public static int[][] highFive(int[][] items) { TreeMap<Integer, PriorityQueue<Integer>> data = new TreeMap<>(); for (int[] item : items) { int id = item[0], score = item[1]; if (!data.containsKey(id)) data.put(id, new PriorityQueue<>()); PriorityQueue<Integer> minHeap = data.get(id); minHeap.add(score); if (minHeap.size() > 5) minHeap.poll(); } int[][] output = new int[data.size()][2]; int i = 0; for (int id : data.keySet()) { PriorityQueue<Integer> pq = data.get(id); int sum = 0, size = pq.size(); while (!pq.isEmpty()) sum += pq.poll(); output[i][0] = id; output[i][1] = sum / size; i++; } return output; } public static void main(String[] args){ int[][] output = highFive(new int[][]{{1, 91}, {1, 92}, {2, 93}, {2, 97}, {1, 60}, {2, 77}, {1, 65}, {1, 87}, {1, 100}, {2, 100}, {2, 76}}); for (int[] elem: output){ System.out.println(elem[1]); } } }