text
stringlengths
10
2.72M
package com.yuecheng.yue.base; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.yuecheng.yue.R; import com.yuecheng.yue.broadcast.NetBroadcastReceiver; import com.yuecheng.yue.ui.bean.YUE_SPsave; import com.yuecheng.yue.util.CommonUtils; import com.yuecheng.yue.util.StatusBarCompat; import com.yuecheng.yue.util.YUE_SharedPreferencesUtils; import com.yuecheng.yue.util.YUE_ToastUtils; /** * Created by yuecheng on 2017/10/29. */ public abstract class YUE_BaseActivityNoSlideBack extends AppCompatActivity implements NetBroadcastReceiver.NetEvevt { /** * Screen information */ protected int mScreenWidth = 0; protected int mScreenHeight = 0; protected float mScreenDensity = 0.0f; protected boolean statusBarCompat = true; /** * context */ protected Context mContext = null; public static NetBroadcastReceiver.NetEvevt evevt; /** * 网络类型 */ private int mNetMobile; @SuppressWarnings("unchecked") public <T extends View> T findView(int id) { return (T) findViewById(id); } @Override protected void onCreate(Bundle savedInstanceState) { // overridePendingTransition(R.anim.right_in, R.anim.right_out); super.onCreate(savedInstanceState); mContext = this; String mThem = (String) YUE_SharedPreferencesUtils.getParam(this, YUE_SPsave.YUE_THEM, "默认主题"); Window window = getWindow(); switch (mThem) { case "默认主题": setTheme(R.style.AppThemeDefault); break; case "热情似火": setTheme(R.style.AppThemeRed); break; case "梦幻紫": setTheme(R.style.AppThemePurple); break; case "乌金黑": setTheme(R.style.AppThemeHardwareblack); break; default: if (Build.VERSION.SDK_INT >= 21) window.setStatusBarColor(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary)); break; } // getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); // getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); YUE_BaseAppManager.getInstance().addActivity(this); /* *获取屏幕尺寸 * */ DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); mScreenDensity = displayMetrics.density; mScreenHeight = displayMetrics.heightPixels; mScreenWidth = displayMetrics.widthPixels; if (getContentViewLayoutID() != 0) { setContentView(getContentViewLayoutID()); } else { throw new IllegalArgumentException("You must return a right contentView layout " + "resource Id"); } if (statusBarCompat) { StatusBarCompat.compat(this, CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary)); transparent19and20(); } evevt = this; inspectNet(); initViewsAndEvents(); } /** * 网络变化之后的类型 */ @Override public void onNetChange(int netMobile) { // TODO Auto-generated method stub if (netMobile == 0) Toast.makeText(mContext, "网络断开了", Toast.LENGTH_SHORT).show(); this.mNetMobile = netMobile; isNetConnect(); } private boolean inspectNet() { this.mNetMobile = CommonUtils.getNetworkType(mContext); return isNetConnect(); } protected Toolbar initToolBars(int toolBarId, String title) { Toolbar mToolBar = findView(toolBarId); setSupportActionBar(mToolBar); ActionBar ab = getSupportActionBar(); //使能app bar的导航功能 ab.setDisplayHomeAsUpEnabled(true); ab.setTitle(title); mToolBar.setTitleTextColor(getResources().getColor(R.color.white)); return mToolBar; } protected void transparent19and20() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /** * 判断有无网络 。 * * @return true 有网, false 没有网络. */ public boolean isNetConnect() { if (mNetMobile == 1) { return true; } else if (mNetMobile == 0) { return true; } else if (mNetMobile == -1) { return false; } return false; } /* *功能操作 * */ protected abstract void initViewsAndEvents(); /* *加载的布局 * */ protected abstract int getContentViewLayoutID(); @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); } @Override public void finish() { super.finish(); // YUE_BaseAppManager.getInstance().removeActivity(this); // overridePendingTransition(R.anim.right_in, R.anim.right_out); } protected void startActivity(Class a) { Intent intent = new Intent(); intent.setClass(mContext, a); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); YUE_BaseAppManager.getInstance().removeActivity(this); } protected void ShowMessage(String s) { YUE_ToastUtils.showmessage(s); } protected void showSnackBar(View v, String s) { Snackbar snackBar = Snackbar.make(v, s, Snackbar.LENGTH_SHORT); //设置SnackBar背景颜色 snackBar.getView().setBackgroundColor(CommonUtils.getColorByAttrId(mContext, R.attr.colorPrimary)); //设置按钮文字颜色 snackBar.setActionTextColor(Color.WHITE); snackBar.show(); } }
package br.com.nozinho.model; public enum FormaEncaminhamentoEnum { OFICIO_CORRESPONDENCIA("Ofício/Correspondência"), EMAIL("E-mail"), TELEFONE_CONTATO_INTERNO("Telefone/ Contato pessoal gabinete"); private String descricao; private FormaEncaminhamentoEnum(String descricao){ this.descricao = descricao; } public String getDescricao(){ return this.descricao; } }
package virtualpetsamok; public class Cat extends OrganicPet implements Poop { private static int waste; private int ticksSincePoop; public Cat(String name, String description) { super(name, description); this.waste = 0; this.ticksSincePoop = 0; } // This overloaded constructor is for testing purposes public Cat(String name, String description, int ticksSincePoop, int waste) { super(name, description); this.ticksSincePoop = ticksSincePoop; this.waste = waste; } public int getWaste() { return waste; } public void poop() { waste++; ticksSincePoop = 0; } public void catTick() { checkPoopTimer(); excessiveWasteDamage(); } private void checkPoopTimer() { if (ticksSincePoop >= 4) { poop(); } else { ticksSincePoop++; } } public int getTicksSincePoop() { return ticksSincePoop; } public void excessiveWasteDamage() { if (waste >= 10) { setHealth(getHealth() - 10); } } public void emptyLitterBox() { waste = 0; } }
//package com.sky.contract.service; // //import com.sky.contract.mapper.PermissionMapper; //import com.sky.contract.mapper.UserMapper; //import com.sky.contract.model.Permission; //import org.junit.Test; //import org.junit.runner.RunWith; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; // //import java.util.List; // // ///** // * Created by shiqm on 2018/9/13. // */ // //@RunWith(SpringJUnit4ClassRunner.class) //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //public class UserServiceTest { // // @Autowired // private UserMapper userMapper; // // @Autowired // private PermissionMapper permissionMapper; // // @Test // public void getUser(){ // // System.out.println(userMapper.selectByPrimaryKey(Long.valueOf(1)).getCreateAt()); // //// List<Permission> list=permissionMapper.getAllPermissions(); //// //// list.forEach(t->{ //// System.out.println(t.getName()); //// t.getList().forEach(p->{ //// System.out.println("---"+p.getName()); //// }); //// }); // // permissionMapper.getPermissionsByUid(1L); // // // // } // //}
package redis_test; import redis.clients.jedis.Jedis; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /** * Description: 模拟Redis客户端,向Redis服务端写入遵从RESP协议的数据 * * @author Baltan * @date 2019-10-10 16:30 */ public class RedisMockClientTest { public static void main(String[] args) { Socket socket = null; InputStream is = null; OutputStream os = null; Jedis jedis = new Jedis("127.0.0.1", 6379); try { System.out.println(jedis.keys("*")); socket = new Socket("127.0.0.1", 6379); String command = redisCommand("SET", "k2", "v2"); System.out.println(command); is = socket.getInputStream(); os = socket.getOutputStream(); byte[] buf = new byte[1024]; os.write(command.getBytes()); is.read(buf); System.out.println(new String(buf)); System.out.println(jedis.keys("*")); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); } try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } jedis.close(); } } public static String redisCommand(String... commands) { StringBuilder builder = new StringBuilder(); builder.append("*").append(commands.length).append("\r\n"); for (String command : commands) { builder.append("$").append(command.length()).append("\r\n").append(command).append("\r\n"); } return builder.toString(); } }
package com.suturease.SuturEase.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class BaseController { @RequestMapping("/crossBow") public String crossBow(){ return "crossBow"; } @RequestMapping("/securusEP") public String securusEP(){ return "securusEP"; } @RequestMapping("/company") public String company(){ return "company"; } @RequestMapping("/team") public String contact(){ return "team"; } @RequestMapping("/news") public String news(){ return "news"; } @RequestMapping("/") public String baseRoute(){ return "index"; } }
package it.unical.asd.group6.computerSparePartsCompany; import it.unical.asd.group6.computerSparePartsCompany.data.entities.Employee; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import java.util.List; import java.util.Optional; @RunWith(SpringRunner.class) @SpringBootTest public class EmployeeTest extends AbstractComputerSparePartsCompanyTest{ // SERVICE TESTs @Test public void loginServiceTest() { assert(employeeService.checkLogin("Rubie", "Mitzi")); } // DAO TESTs @Test public void testFindEmployeesByHiringDateIsLessThan_OK(){ LocalDate date=LocalDate.now(); Optional<List<Employee>> employees = employeeDao.findAllByHiringDateIsLessThan(date); assert(employees.get().size()==10); } @Test public void testFindEmployeeByTelephoneNumber_OK(){ Optional<Employee> emp=employeeDao.findEmployeeByTelephoneNumberEquals("1614827388"); assert(emp.get()!=null); assert(emp.get().getUsername().equals("Kial")); assert(emp.get().getPassword().equals("Byrne")); assert(emp.get().getFirstname().equals("Kial")); assert(emp.get().getLastname().equals("Byrne")); assert(emp.get().getEmail().equals("Kial.Byrne@mail.com")); } @Test public void testFindEmployeeByUsernameAndPassword_OK(){ Optional<Employee> e=employeeDao.findEmployeeByUsernameAndPassword("Rubie","Mitzi"); assert(e.get()!=null); assert(e.get().getFirstname().equals("Rubie")); assert(e.get().getLastname().equals("Mitzi")); assert(e.get().getEmail().equals("Rubie.Mitzi@mail.com")); assert(e.get().getTelephoneNumber().equals("1796853502")); } @Test public void testFindEmployeeByUsername(){ assert(employeeDao.findEmployeeByUsername("Aryn").get().getLastname().equals("Darbie")); } @Test public void testUpdateEmployeePassword(){ employeeDao.updateEmployeePassword("Aryn","ShocktBECAUUUUSE"); assert(employeeDao.findEmployeeByUsername("Aryn").get().getPassword().equals("ShocktBECAUUUUSE")); } }
package com.ssafy.web.dto; public class Store { private int no; //번호 private String storeName; //가게명 private String sido; //시도 private String gugun; //구군 private String dong; //동 private String juso; //전체주소 private String type; //종류 private String type2; //종류2 public Store() { // TODO Auto-generated constructor stub } public Store(int no) { this.no = no; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getDong() { return dong; } public void setDong(String dong) { this.dong = dong; } public String getJuso() { return juso; } public void setJuso(String juso) { this.juso = juso; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSido() { return sido; } public void setSido(String sido) { this.sido = sido; } public String getGugun() { return gugun; } public void setGugun(String gugun) { this.gugun = gugun; } @Override public String toString() { return "Store [no=" + no + ", storeName=" + storeName + ", sido=" + sido + ", gugun=" + gugun + ", dong=" + dong + ", juso=" + juso + ", type=" + type + "]"; } public String getType2() { return type2; } public void setType2(String type2) { this.type2 = type2; } }
package com.techathon.model.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.google.common.base.MoreObjects; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "EXERCISE") @JsonIgnoreProperties("exerciseRequest") public class Exercise extends UpdateableBaseEntity { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column @Temporal(TemporalType.TIMESTAMP) private Date date; @Column private String path; @ManyToOne private ExerciseRequest exerciseRequest; @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("super", super.toString()) .add("date", date) .add("path", path) .toString(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public ExerciseRequest getExerciseRequest() { return exerciseRequest; } public void setExerciseRequest(ExerciseRequest exerciseRequest) { this.exerciseRequest = exerciseRequest; } }
package com.nv95.ficbook; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.Spinner; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; public class ReqSearchActivity extends Activity { ArrayList<String> Fandoms = new ArrayList<String>(); ArrayList<String> Ids = new ArrayList<String>(); ArrayList<String> GenreList = new ArrayList<String>(); ArrayList<String> WarnList = new ArrayList<String>(); boolean Genres[] = new boolean[35]; boolean NoGenres[] = new boolean[35]; boolean Warns[] = new boolean[20]; boolean NoWarns[] = new boolean[20]; int cat[]={1,2,3,4,5,6,9,7,10,11}; int SelFandom=-1; int WarnId(int x){ if (x==20)return 60; return x+10; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reqsearch); if (Build.VERSION.SDK_INT>=11) this.getActionBar().setDisplayHomeAsUpEnabled(true); Spinner t = ((Spinner)findViewById(R.id.spinner_status)); t.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.status_req))); t = ((Spinner)findViewById(R.id.spinner_sort)); t.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.sort_req))); t = ((Spinner)findViewById(R.id.spinner_category)); t.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.cats_e))); t.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { findViewById(R.id.block_fandom).setVisibility(View.GONE); if (i > 0) new FandomListTask().execute("" + cat[i-1]); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); ((AutoCompleteTextView)ReqSearchActivity.this.findViewById(R.id.autoCompleteTextView_fandom)).setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { SelFandom = Fandoms.indexOf(((AutoCompleteTextView) ReqSearchActivity.this.findViewById(R.id.autoCompleteTextView_fandom)).getText().toString()); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); } }); Collections.addAll(GenreList, getResources().getStringArray(R.array.genres)); GenreList.remove(0); findViewById(R.id.button_genres).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(ReqSearchActivity.this).setMultiChoiceItems(GenreList.toArray(new String[GenreList.size()]),Genres, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { Genres[i]=b; } }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); String c = ""; for (int j = 0; j < GenreList.size(); j++) if (Genres[j]) c = c + GenreList.get(j) + ", "; if (c.length() == 0) ((Button) findViewById(R.id.button_genres)).setText(R.string.str_select); else ((Button) findViewById(R.id.button_genres)).setText(c.substring(0, c.length() - 2)); } }).setNeutralButton("Сброс", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { for (int j = 0; j < GenreList.size(); j++) Genres[j] = false; ((Button) findViewById(R.id.button_genres)).setText(R.string.str_select); } }).setTitle(R.string.es_genres).create().show(); } }); findViewById(R.id.button_nogenres).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(ReqSearchActivity.this).setMultiChoiceItems(GenreList.toArray(new String[GenreList.size()]),NoGenres, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { NoGenres[i]=b; } }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); String c = ""; for (int j = 0; j < GenreList.size(); j++) if (NoGenres[j]) c = c + GenreList.get(j) + ", "; if (c.length() == 0) ((Button) findViewById(R.id.button_nogenres)).setText(R.string.str_select); else ((Button) findViewById(R.id.button_nogenres)).setText(c.substring(0, c.length() - 2)); } }).setNeutralButton("Сброс", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { for (int j = 0; j < GenreList.size(); j++) NoGenres[j] = false; ((Button) findViewById(R.id.button_nogenres)).setText(R.string.str_select); } }).setTitle(R.string.es_nogenres).create().show(); } }); Collections.addAll(WarnList, getResources().getStringArray(R.array.warns)); findViewById(R.id.button_warns).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(ReqSearchActivity.this).setMultiChoiceItems(WarnList.toArray(new String[WarnList.size()]),Warns, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { Warns[i]=b; } }).setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); String c = ""; for (int j = 0;j<WarnList.size();j++) if (Warns[j])c=c+WarnList.get(j)+", "; if (c.length()==0) ((Button)findViewById(R.id.button_warns)).setText(R.string.str_select); else ((Button)findViewById(R.id.button_warns)).setText(c.substring(0,c.length()-2)); } }).setNeutralButton("Сброс", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { for (int j = 0; j < WarnList.size(); j++) Warns[j] = false; ((Button) findViewById(R.id.button_warns)).setText(R.string.str_select); } }).setTitle(R.string.es_warns).create().show(); } }); findViewById(R.id.button_nowarns).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(ReqSearchActivity.this).setMultiChoiceItems(WarnList.toArray(new String[WarnList.size()]),NoWarns, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { NoWarns[i]=b; } }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); String c = ""; for (int j = 0; j < WarnList.size(); j++) if (NoWarns[j]) c = c + WarnList.get(j) + ", "; if (c.length() == 0) ((Button) findViewById(R.id.button_nowarns)).setText("Выбрать"); else ((Button) findViewById(R.id.button_nowarns)).setText(c.substring(0, c.length() - 2)); } }).setNeutralButton("Сброс", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { for (int j = 0; j < WarnList.size(); j++) NoWarns[j] = false; ((Button) findViewById(R.id.button_nowarns)).setText(R.string.str_select); } }).setTitle(R.string.es_nowarns).create().show(); } }); findViewById(R.id.button_find).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(((AutoCompleteTextView)ReqSearchActivity.this.findViewById(R.id.autoCompleteTextView_fandom)).getText().length()==0){ SelFandom=-1; } //&rating_id%5B0%5D=5&rating_id%5B1%5D=6&rating_id%5B2%5D=7&rating_id%5B3%5D=8&rating_id%5B4%5D=9&genres%5B0%5D=29&genres%5B1%5D=33&genres_ignore%5B0%5D=31&warnings%5B0%5D=12&warnings_ignore%5B0%5D=13&sort=1&find=Найти%21 String q = "http://mobile.ficbook.net/requests?status="; int f = ((Spinner)findViewById(R.id.spinner_status)).getSelectedItemPosition(); switch (f){ case 0: q=q+"0"; break; case 1: q=q+"1"; break; case 2: q=q+"-1"; break; } q=q+"&fandom_group="; f = ((Spinner)findViewById(R.id.spinner_category)).getSelectedItemPosition(); if (f==0){ q=q+"&fandom_id%5B%5D="; }else{ q=q+cat[f-1]; q=q+"&fandom_id%5B%5D="; if (SelFandom!=-1) q=q+Ids.get(SelFandom); } int i; String[] gs = getResources().getStringArray(R.array.genres_u); for (i=0;i<GenreList.size();i++){ if (Genres[i])q=q+"&genres%5B%5D="+gs[i+1]; if (NoGenres[i])q=q+"&genres_ignore%5B%5D="+gs[i+1]; } for (i=0;i<WarnList.size();i++){ if (Warns[i])q=q+"&warnings%5B%5D="+WarnId(i); if (NoWarns[i])q=q+"&warnings_ignore%5B%5D="+WarnId(i); } if (((CheckBox)findViewById(R.id.checkBox_rating_g)).isChecked())q=q+"&rating_crazy%5B%5D=g"; if (((CheckBox)findViewById(R.id.checkBox_rating_pg13)).isChecked())q=q+"&rating_crazy%5B%5D=pg13"; if (((CheckBox)findViewById(R.id.checkBox_rating_r)).isChecked())q=q+"&rating_crazy%5B%5D=r"; if (((CheckBox)findViewById(R.id.checkBox_rating_nc17)).isChecked())q=q+"&rating_crazy%5B%5D=nc17"; if (((CheckBox)findViewById(R.id.checkBox_rating_nc21)).isChecked())q=q+"&rating_crazy%5B%5D=nc21"; q=q+"&sort="+((Spinner)findViewById(R.id.spinner_sort)).getSelectedItemPosition(); q=q+"&find=Найти%21"; Intent intent = new Intent(ReqSearchActivity.this, ReqListActivity.class); intent.putExtra("furl", q); intent.putExtra("ttl", "Результаты поиска"); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.esearch, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_reset: ((Spinner)findViewById(R.id.spinner_category)).setSelection(0); ((Spinner)findViewById(R.id.spinner_sort)).setSelection(0); ((Spinner)findViewById(R.id.spinner_status)).setSelection(0); for (int j = 0; j < GenreList.size(); j++) Genres[j] = false; ((Button) findViewById(R.id.button_genres)).setText(R.string.str_select); for (int j = 0; j < GenreList.size(); j++) NoGenres[j] = false; ((Button) findViewById(R.id.button_nogenres)).setText(R.string.str_select); for (int j = 0; j < WarnList.size(); j++) Warns[j] = false; ((Button) findViewById(R.id.button_warns)).setText(R.string.str_select); for (int j = 0; j < WarnList.size(); j++) NoWarns[j] = false; ((Button) findViewById(R.id.button_nowarns)).setText(R.string.str_select); ((CheckBox)findViewById(R.id.checkBox_rating_r)).setChecked(true); ((CheckBox)findViewById(R.id.checkBox_rating_g)).setChecked(true); ((CheckBox)findViewById(R.id.checkBox_rating_nc21)).setChecked(true); ((CheckBox)findViewById(R.id.checkBox_rating_nc17)).setChecked(true); ((CheckBox)findViewById(R.id.checkBox_rating_pg13)).setChecked(true); return true; default: return super.onOptionsItemSelected(item); } } class FandomListTask extends AsyncTask<String, Void, String> { ArrayList<String> lst; int r=0; FandomListTask() { } protected String doInBackground(String[] paramArrayOfString) { try { String[] arrayOfString3 = new String[2]; arrayOfString3[0] = "group_id"; arrayOfString3[1] = paramArrayOfString[0]; JSONArray entries = new JSONArray(new FbSession(getApplicationContext()).postAjax("http://mobile.ficbook.net/ajax/fandom_list",arrayOfString3)); lst = new ArrayList<String>(); for (int i=0;i<entries.length();i++) { JSONObject post = entries.getJSONObject(i); Fandoms.add(post.get("main_title").toString()); Ids.add(post.get("id").toString()); } r=4; } catch (JSONException e) { e.printStackTrace(); } return ""; } protected void onPostExecute(String paramString) { super.onPostExecute(paramString); findViewById(R.id.block_load).setVisibility(View.GONE); if (Fandoms.size()!=0) findViewById(R.id.block_fandom).setVisibility(View.VISIBLE); ((AutoCompleteTextView)ReqSearchActivity.this.findViewById(R.id.autoCompleteTextView_fandom)) .setAdapter(new ArrayAdapter<String>(ReqSearchActivity.this, android.R.layout.simple_list_item_1, Fandoms)); SelFandom=-1; } protected void onPreExecute() { super.onPreExecute(); findViewById(R.id.block_fandom).setVisibility(View.GONE); findViewById(R.id.block_load).setVisibility(View.VISIBLE); Fandoms.clear(); Ids.clear(); } } }
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.r2dbc.postgresql; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class PostgresqlSqlLexerTest { @Nested class SingleStatementTests { @Nested class SingleTokenTests { @Test void singleQuotedStringIsTokenized() { assertSingleStatementEqualsCompleteToken("'Test'", TokenizedSql.TokenType.STRING_CONSTANT); } @Test void dollarQuotedStringIsTokenized() { assertSingleStatementEqualsCompleteToken("$$test$$", TokenizedSql.TokenType.STRING_CONSTANT); } @Test void dollarQuotedTaggedStringIsTokenized() { assertSingleStatementEqualsCompleteToken("$a$test$a$", TokenizedSql.TokenType.STRING_CONSTANT); } @Test void quotedIdentifierIsTokenized() { assertSingleStatementEqualsCompleteToken("\"test\"", TokenizedSql.TokenType.QUOTED_IDENTIFIER); } @Test void lineCommentIsTokenized() { assertSingleStatementEqualsCompleteToken("--test", TokenizedSql.TokenType.COMMENT); } @Test void cStyleCommentIsTokenized() { assertSingleStatementEqualsCompleteToken("/*Test*/", TokenizedSql.TokenType.COMMENT); } @Test void nestedCStyleCommentIsTokenizedAsSingleToken() { assertSingleStatementEqualsCompleteToken("/*/*Test*/*/", TokenizedSql.TokenType.COMMENT); } @Test void windowsMultiLineCStyleCommentIsTokenizedAsSingleToken() { assertSingleStatementEqualsCompleteToken("/*Test\r\n Test*/", TokenizedSql.TokenType.COMMENT); } @Test void unixMultiLineCStyleCommentIsTokenizedAsSingleToken() { assertSingleStatementEqualsCompleteToken("/*Test\n Test*/", TokenizedSql.TokenType.COMMENT); } @Test void digitIsTokenizedAsDefaultToken() { assertSingleStatementEqualsCompleteToken("1", TokenizedSql.TokenType.DEFAULT); } @Test void alphaIsTokenizedAsDefaultToken() { assertSingleStatementEqualsCompleteToken("a", TokenizedSql.TokenType.DEFAULT); } @Test void multipleDefaultTokensAreTokenizedAsSingleDefaultToken() { assertSingleStatementEqualsCompleteToken("atest123", TokenizedSql.TokenType.DEFAULT); } @Test void parameterIsTokenized() { assertSingleStatementEqualsCompleteToken("$1", TokenizedSql.TokenType.PARAMETER); } @Test void statementEndIsTokenized() { assertSingleStatementEqualsCompleteToken(";", TokenizedSql.TokenType.STATEMENT_END); } void assertSingleStatementEqualsCompleteToken(String sql, TokenizedSql.TokenType token) { assertSingleStatementEquals(sql, new TokenizedSql.Token(token, sql)); } } @Nested class SingleTokenExceptionTests { @Test void unclosedSingleQuotedStringThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("'test")); } @Test void unclosedDollarQuotedStringThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("$$test")); } @Test void unclosedTaggedDollarQuotedStringThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("$abc$test")); } @Test void unclosedQuotedIdentifierThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("\"test")); } @Test void unclosedBlockCommentThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("/*test")); } @Test void unclosedNestedBlockCommentThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("/*/*test*/")); } @Test void invalidParameterCharacterThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("$1test")); } @Test void invalidTaggedDollarQuoteThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("$a b$test$a b$")); } @Test void unclosedTaggedDollarQuoteThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> PostgresqlSqlLexer.tokenize("$abc")); } } @Nested class MultipleTokenTests { @Test void defaultTokenIsEndedBySpecialCharacter() { assertSingleStatementEquals("abc[", new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "abc"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "[")); } @Test void defaultTokenIsEndedByOperatorCharacter() { assertSingleStatementEquals("abc-", new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "abc"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "-")); } @Test void defaultTokenIsEndedByStatementEndCharacter() { assertSingleStatementEquals("abc;", new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "abc"), new TokenizedSql.Token(TokenizedSql.TokenType.STATEMENT_END, ";")); } @Test void defaultTokenIsEndedByQuoteCharacter() { assertSingleStatementEquals("abc\"def\"", new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "abc"), new TokenizedSql.Token(TokenizedSql.TokenType.QUOTED_IDENTIFIER, "\"def\"")); } @Test void parameterTokenIsEndedByQuoteCharacter() { assertSingleStatementEquals("$1+", new TokenizedSql.Token(TokenizedSql.TokenType.PARAMETER, "$1"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "+")); } @Test void parameterIsRecognizedBetweenSpecialCharacters() { assertSingleStatementEquals("($1)", new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "("), new TokenizedSql.Token(TokenizedSql.TokenType.PARAMETER, "$1"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, ")") ); } @Test void lineCommentIsEndedAtNewline() { assertSingleStatementEquals("--abc\ndef", new TokenizedSql.Token(TokenizedSql.TokenType.COMMENT, "--abc"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "def")); } @Test void multipleOperatorsAreSeparatelyTokenized() { assertSingleStatementEquals("**", new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "*"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "*") ); } } @Nested class AssortedRealStatementTests { @Test void simpleSelectStatementIsTokenized() { assertSingleStatementEquals("SELECT * FROM /* A Comment */ table WHERE \"SELECT\" = $1", new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "SELECT"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "*"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "FROM"), new TokenizedSql.Token(TokenizedSql.TokenType.COMMENT, "/* A Comment */"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "table"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "WHERE"), new TokenizedSql.Token(TokenizedSql.TokenType.QUOTED_IDENTIFIER, "\"SELECT\""), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "="), new TokenizedSql.Token(TokenizedSql.TokenType.PARAMETER, "$1") ); } } void assertSingleStatementEquals(String sql, TokenizedSql.Token... tokens) { TokenizedSql tokenizedSql = PostgresqlSqlLexer.tokenize(sql); assertEquals(1, tokenizedSql.getStatements().size(), "Parse returned zero or more than 2 statements"); TokenizedSql.TokenizedStatement statement = tokenizedSql.getStatements().get(0); assertEquals(new TokenizedSql.TokenizedStatement(sql, Arrays.asList(tokens)), statement); } } @Nested class MultipleStatementTests { @Test void simpleMultipleStatementIsTokenized() { TokenizedSql tokenizedSql = PostgresqlSqlLexer.tokenize("DELETE * FROM X; SELECT 1;"); List<TokenizedSql.TokenizedStatement> statements = tokenizedSql.getStatements(); assertEquals(2, statements.size()); TokenizedSql.TokenizedStatement statementA = statements.get(0); TokenizedSql.TokenizedStatement statementB = statements.get(1); assertEquals(new TokenizedSql.TokenizedStatement("DELETE * FROM X;", Arrays.asList( new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "DELETE"), new TokenizedSql.Token(TokenizedSql.TokenType.SPECIAL_OR_OPERATOR, "*"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "FROM"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "X"), new TokenizedSql.Token(TokenizedSql.TokenType.STATEMENT_END, ";") )), statementA ); assertEquals(new TokenizedSql.TokenizedStatement("SELECT 1;", Arrays.asList( new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "SELECT"), new TokenizedSql.Token(TokenizedSql.TokenType.DEFAULT, "1"), new TokenizedSql.Token(TokenizedSql.TokenType.STATEMENT_END, ";") )), statementB ); } } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.GLUEHENIstdatenType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.GluehstapelIdentType; import java.io.StringWriter; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; public class GLUEHENIstdatenTypeBuilder { public static String marshal(GLUEHENIstdatenType gLUEHENIstdatenType) throws JAXBException { JAXBElement<GLUEHENIstdatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), GLUEHENIstdatenType.class , gLUEHENIstdatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private String gluehKz; private String gluehVerfahren; private GluehstapelIdentType gluehstapel; private BigInteger lageImGluehstapel; private ArbeitsvorgangTypType arbeitsvorgang; private String aggregat; private XMLGregorianCalendar zeitpunktDurchsatz; public GLUEHENIstdatenTypeBuilder setGluehKz(String value) { this.gluehKz = value; return this; } public GLUEHENIstdatenTypeBuilder setGluehVerfahren(String value) { this.gluehVerfahren = value; return this; } public GLUEHENIstdatenTypeBuilder setGluehstapel(GluehstapelIdentType value) { this.gluehstapel = value; return this; } public GLUEHENIstdatenTypeBuilder setLageImGluehstapel(BigInteger value) { this.lageImGluehstapel = value; return this; } public GLUEHENIstdatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public GLUEHENIstdatenTypeBuilder setAggregat(String value) { this.aggregat = value; return this; } public GLUEHENIstdatenTypeBuilder setZeitpunktDurchsatz(XMLGregorianCalendar value) { this.zeitpunktDurchsatz = value; return this; } public GLUEHENIstdatenType build() { GLUEHENIstdatenType result = new GLUEHENIstdatenType(); result.setGluehKz(gluehKz); result.setGluehVerfahren(gluehVerfahren); result.setGluehstapel(gluehstapel); result.setLageImGluehstapel(lageImGluehstapel); result.setArbeitsvorgang(arbeitsvorgang); result.setAggregat(aggregat); result.setZeitpunktDurchsatz(zeitpunktDurchsatz); return result; } }
package ua.www2000.yourcourses.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import ua.www2000.yourcourses.entity.Topic; @Repository public interface TopicRepository extends JpaRepository<Topic, Long> { }
package com.mateus.discordah.game; import com.mateus.discordah.cards.Card; import com.mateus.discordah.cards.CardComposite; import com.mateus.discordah.cards.PlayedCards; import com.mateus.discordah.listener.CzarListener; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.User; import java.util.*; import java.util.List; public class Game { private final List<Player> players; private final TextChannel channel; private final long creatorId; private final Set<Card> playedBlackCards = new HashSet<>(); private final Map<User, PlayedCards> votes = new HashMap<>(); private final Map<Integer, User> choose = new HashMap<>(); private final Map<User, Integer> points = new HashMap<>(); private Player czar; private int czarIdx = -1; private Card blackCard; public Game(List<User> players, TextChannel channel, long creatorId) { this.channel = channel; this.creatorId = creatorId; List<Card> decks = CardComposite.makeDecks(players.size()); int idx = 0; List<Player> playerList = new ArrayList<>(); for (User player : players) { List<Card> playerCards = new ArrayList<>(); for (int i = 0; i < 7; i++) { playerCards.add(decks.get(idx)); idx++; } playerList.add(new Player(player, playerCards)); } this.players = playerList; //System.out.println("legal 1"); } public void newRound() { //System.out.println("legal 2"); Collections.shuffle(players); nextRound(); } public void nextRound() { for (Map.Entry<User, Integer> userIntegerEntry : points.entrySet()) { int points = userIntegerEntry.getValue(); if (points >= 3) { channel.sendMessage("**The winner is: " + userIntegerEntry.getKey().getAsMention() +"!**").queue(); stop(); return; } } czarIdx++; if (czarIdx >= players.size()) { czarIdx = 0; } czar = players.get(czarIdx); blackCard = CardComposite.getRandomBlackCard(); while (playedBlackCards.contains(blackCard)) { blackCard = CardComposite.getRandomBlackCard(); } playedBlackCards.add(blackCard); for (Player player : players) { User user = player.getUser(); Card bc = blackCard; if (player.getId() == czar.getId()) { user.openPrivateChannel().queue(p -> { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setAuthor("You are the Czar!"); embedBuilder.setDescription("**The black card for this round is:**\n" + bc.getContent().replace("_", "\\_")); embedBuilder.setFooter("This card has " + bc.getSlots() + " pick(s)."); embedBuilder.setColor(0x1CBF1E); p.sendMessage(embedBuilder.build()).queue(); }); } else { user.openPrivateChannel().queue(p -> { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setAuthor("Discord Against humanity"); embedBuilder.addField("The black card:", bc.getContent().replace("_", "\\_"), false); int c = 0; for (Card card : player.getCards()) { c++; embedBuilder.addField("Card "+ c +":", card.getContent(), true); } embedBuilder.setColor(0x1CBF1E); embedBuilder.setFooter("This card has " + bc.getSlots() + " pick(s). Use `dh!play <number of the card>` to play it!"); p.sendMessage(embedBuilder.build()).queue(); }); } } } public void czarVoting(JDA jda) { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setAuthor("Discord against humanity"); StringBuilder stringBuilder = new StringBuilder(); int i = 0; embedBuilder.addField("The black card:", blackCard.getContent().replace("_", "\\_"), false); List<User> keys = new ArrayList<>(votes.keySet()); Collections.shuffle(keys); for (User key : keys) { i++; for (Card playedCard : votes.get(key).getPlayedCards()) { stringBuilder.append(playedCard.getContent()); stringBuilder.append(" | "); } embedBuilder.addField("Card(s) " + i + ":", stringBuilder.substring(0, stringBuilder.length() - 2), true); choose.put(i, key); stringBuilder.setLength(0); } embedBuilder.setColor(0x1CBF1E); embedBuilder.setFooter("Use `dh!vote <the number of your chosen card>`"); channel.sendMessage(embedBuilder.build()).queue(); channel.sendMessage(czar.getUser().getAsMention() + " choose your favorite card(s)").queue(); jda.addEventListener(new CzarListener(choose, czar.getUser())); } public List<Player> getPlayers() { return players; } public Player getPlayer(User user) { return players.stream().filter(p -> p.getId() == user.getIdLong()).findFirst().orElse(null); } public TextChannel getChannel() { return channel; } public Map<User, PlayedCards> getVotes() { return votes; } public Card getBlackCard() { return blackCard; } public boolean everyonePlayed() { if (blackCard == null) return false; int i = 0; for (Map.Entry<User, PlayedCards> userEntry : votes.entrySet()) { PlayedCards cards = userEntry.getValue(); if (cards.getPlayedCards().size() == blackCard.getSlots()) { i++; } } return i == players.size() - 1; } public boolean isCzar(Player player) { if (czar == null) return false; return player.getId() == czar.getId(); } public Map<Integer, User> getChoose() { return choose; } public Map<User, Integer> getPoints() { return points; } public long getCreatorId() { return creatorId; } public void stop() { players.clear(); playedBlackCards.clear(); GameManager.getInstance().removeGame(this); } }
package edu.nju.data.daoImpl; import edu.nju.RuanHuApplication; import edu.nju.data.dao.MessageDAO; import edu.nju.data.entity.Message; import edu.nju.data.entity.User; import edu.nju.data.util.MesType; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * Created by ss14 on 2016/7/21. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = RuanHuApplication.class) @WebAppConfiguration @Rollback public class MessageDAOImplTest { @Autowired MessageDAO messageDAO; @Test public void save_Message() throws Exception { Message message = new Message(); MesType type = MesType.voteQuestion; Long srcId = new Long (284); Long senderId = new Long(2); Long receiverId = new Long (3); message.setMesgType(type); message.setSourceId(srcId); message.setSenderId(senderId); message.setReceiverId(receiverId); Message loaded = messageDAO.save_Message(message); if(loaded==null){ fail(); }else if(loaded.getId()==null){ fail(); } } @Test public void markChecked() throws Exception { messageDAO.markChecked((long) 2); } @Test public void deleteByMesID() throws Exception { messageDAO.deleteByMesID((long) 2); } @Test public void sendMessage() throws Exception { MesType type = MesType.comment; Long srcID = new Long(283); User sender = new User(); sender.setId(new Long(2)); sender.setUserName("ss14"); User re = new User(); re.setId(new Long(3)); messageDAO.sendMessage(type,srcID,sender,re); } }
package WinGame; public class Square { private String name; private int position; Square(String namePick, int pos){ setName(namePick); setPos(pos); } private void setName(String namePick) { this.name = namePick; } private void setPos(int pos) { this.position = pos; } public String getName() { return name; } public int getPos() { return this.position; } }
package utility.model.SchemaParser.service; import static utility.model.SchemaParser.constants.Constants.CSV; import static utility.model.SchemaParser.constants.Constants.PREFIX_FILE_PATH; import static utility.model.SchemaParser.constants.Constants.SCHEMA_PATH_FILE; import static utility.model.SchemaParser.utility.SQLUtility.addForeignConstraint; import static utility.model.SchemaParser.utility.SQLUtility.createTables; import static utility.model.SchemaParser.utility.SQLUtility.dropTables; import static utility.model.SchemaParser.utility.SQLUtility.insertRecordsIntoDB; import static utility.model.SchemaParser.utility.SchemaValidator.validateSchemaTypeValue; import java.io.File; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import utility.model.SchemaParser.exception.FileValidatorException; import utility.model.SchemaParser.model.Row; import utility.model.SchemaParser.model.entity.Schemas; public class FileValidatorService { private static void validateRecord(String schemaPathFile, String extension) throws IOException { boolean foreignFlag = false; Schemas schemas = createObjectFromSchemaFile(schemaPathFile); dropTables(foreignFlag, schemas); foreignFlag = createTables(foreignFlag, schemas); addForeignConstraint(foreignFlag, schemas); schemas.tables.forEach(schema -> { String filePath = PREFIX_FILE_PATH + schema.name + extension; List<Row> parse = null; if (extension.contains(CSV)) { parse = CSVParser.parse(filePath, schema); } else { parse = TextFileParser.parse(filePath, schema); } validateSchemaTypeValue(schemas.tables.get(0), parse); String collect = parse.get(0).columns.stream().map(s1 -> s1.name).collect(Collectors.joining(",")); insertRecordsIntoDB(parse, collect); }); } private static Schemas createObjectFromSchemaFile(String SCHEMA_PATH_FILE) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); Schemas example = objectMapper.readValue(new File(SCHEMA_PATH_FILE), Schemas.class); System.out.println("Object is \n" + example); return example; } public static void main(String[] args) { try { validateRecord(SCHEMA_PATH_FILE, CSV); } catch (IOException e) { e.printStackTrace(); throw new FileValidatorException(e.getMessage()); } } }
import java.util.Scanner; public class BodyIndex { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double weight, height, bmi; System.out.println("Your weíght (in kilogram) is: "); weight = sc.nextDouble(); System.out.println("Your height (in meter) is: "); height = sc.nextDouble(); bmi = weight/Math.pow(height,2); if (bmi<18) { System.out.println("Underweight!"); } else if (bmi<25) { System.out.println("Normal!"); } else if (bmi<30) { System.out.println("Overweight!"); } else { System.out.println("Obese!"); } } }
/* * The purpose of this lab is to learn about using the for loop * inside of a method and having if statements inside of the for loop. * * Author: Victor (Zach) Johnson * Date: 10/14/17 */ package chapter6; import java.util.Scanner; public class PasswordChecking { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter a Password: "); String password = input.next(); while(isValidPassword(password) == false) { System.out.print("Please enter a Password: "); password = input.next(); } System.out.println("Valid Password"); input.close(); } public static boolean isValidPassword(String password) { if (password.length() < 8) { System.out.println("Your password must be at least 8 characters."); return false; } else { char c; int digitCount = 0; for (int i = 0; i < password.length() - 1; i++) { c = password.charAt(i); if (!Character.isLetterOrDigit(c)) { return false; } else if (Character.isDigit(c)) { digitCount++; if (digitCount < 2) { return false; } } else if (!password.contains("!") && !password.contains(",") && !password.contains("_") && !password.contains("*")) { System.out.println("Your password must contain one of the following \"! , _ *\" special characters."); return false; } } } return true; } }
package com.espendwise.manta.web.controllers; import com.espendwise.manta.model.view.SiteListView; import com.espendwise.manta.util.SelectableObjects; import com.espendwise.manta.web.forms.AbstractFilterResult; import java.util.List; public class LocateLocationFilterResultForm extends AbstractFilterResult<SelectableObjects.SelectableObject<SiteListView>> { private SelectableObjects<SiteListView> sites; private boolean multiSelected; public void setMultiSelected(boolean multiSelected) { this.multiSelected = multiSelected; } public boolean isMultiSelected() { return multiSelected; } public boolean getMultiSelected() { return multiSelected; } public LocateLocationFilterResultForm() { } public SelectableObjects<SiteListView> getSites() { return sites; } public void setSites(SelectableObjects<SiteListView> sites) { this.sites = sites; } @Override public List<SelectableObjects.SelectableObject<SiteListView>> getResult() { return sites != null ? sites.getSelectableObjects() : null; } @Override public void reset() { super.reset(); this.sites = null; } }
package com.nxtlife.mgs.jpa; import org.springframework.data.jpa.repository.JpaRepository; import com.nxtlife.mgs.entity.user.LFIN; public interface LFINRepository extends JpaRepository<LFIN , Long> { public boolean existsByCidAndActiveTrue(String cid); public boolean existsByEmailAndActiveTrue(String email); }
package com.tencent.mm.ui.chatting; import android.content.Context; import com.tencent.mm.ui.x; public interface f$c { boolean a(String str, Context context, x xVar, String str2); }
package com.tencent.mm.plugin.voip.model; import com.tencent.mm.e.b.c; import com.tencent.mm.sdk.platformtools.x; class l$a implements Runnable { private b kqa = null; private c kqt = null; final /* synthetic */ l oKN; public l$a(l lVar, b bVar, c cVar) { this.oKN = lVar; this.kqa = bVar; this.kqt = cVar; } public final void run() { if (this.kqa != null) { this.kqa.bJv(); this.kqa.bJs(); this.kqa = null; } x.i("MicroMsg.Voip.VoipDeviceHandler", "do stopRecord"); if (this.kqt != null) { this.kqt.we(); this.kqt = null; x.i("MicroMsg.Voip.VoipDeviceHandler", "finish stopRecord"); } } }
// Sun Certified Java Programmer // Chapter 6, P469_2 // Strings, I/O, Formatting, and Parsing public class Tester469_2 { public static void main(String[] args) { // TODO code application logic here } }
package classformat.cptype; public class ConstantPoolType { }
package model.validations.interfaces; public interface OnCreate { }
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.acme.travels; public class Coffee { private String coffeeType; private String creamType; private String sugarType; private String workStatus; @Override public String toString() { return "{" + " coffeeType='" + getCoffeeType() + "'" + ", creamType='" + getCreamType() + "'" + ", sugarType='" + getSugarType() + "'" + ", workStatus='" + getWorkStatus() + "'" + "}"; } public Coffee(String coffeeType, String creamType, String sugarType) { this.coffeeType = coffeeType; this.creamType = creamType; this.sugarType = sugarType; this.workStatus = "initiated"; } public String getWorkStatus() { return this.workStatus; } public void setWorkStatus(String workStatus) { this.workStatus = workStatus; } public Coffee workStatus(String workStatus) { setWorkStatus(workStatus); return this; } public Coffee() { } public String getCoffeeType() { return this.coffeeType; } public void setCoffeeType(String coffeeType) { this.coffeeType = coffeeType; } public String getCreamType() { return this.creamType; } public void setCreamType(String creamType) { this.creamType = creamType; } public String getSugarType() { return this.sugarType; } public void setSugarType(String sugarType) { this.sugarType = sugarType; } public Coffee coffeeType(String coffeeType) { setCoffeeType(coffeeType); return this; } public Coffee creamType(String creamType) { setCreamType(creamType); return this; } public Coffee sugarType(String sugarType) { setSugarType(sugarType); return this; } }
/* * [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 com.hybris.backoffice.cockpitng.dnd.handlers; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import de.hybris.platform.category.model.CategoryModel; import de.hybris.platform.core.model.product.ProductModel; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import com.hybris.backoffice.widgets.contextpopulator.ContextPopulator; import com.hybris.cockpitng.core.context.CockpitContext; import com.hybris.cockpitng.dnd.DragAndDropContext; @RunWith(MockitoJUnitRunner.class) public class ProductToCategoryDropHandlerTest { @Spy private ProductToCategoryDropHandler handler; @Mock private ProductModel product; @Mock private CategoryModel category; @Mock private CategoryModel selectedContextCategory; @Mock private DragAndDropContext context; @Mock private CockpitContext dragContext; @Before public void setUp() { when(context.getDraggedContext()).thenReturn(dragContext); when(dragContext.getParameter(ContextPopulator.SELECTED_OBJECT)).thenReturn(selectedContextCategory); } @Test public void testHandleAppend() { // given final CategoryModel supercategory = mock(CategoryModel.class); when(product.getSupercategories()).thenReturn(Arrays.asList(supercategory)); // when final ProductModel result = handler.copyProductToCategory(product, category, context); // test assertThat(result).isSameAs(product); verify(product).getSupercategories(); final ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); verify(product).setSupercategories(captor.capture()); assertThat(captor.getValue()).containsExactly(supercategory, category); verifyNoMoreInteractions(product); } @Test public void testHandleAppendWithAppend() { //given when(product.getSupercategories()).thenReturn(Collections.singleton(selectedContextCategory)); //when handler.copyProductToCategory(product, category, context); //then final ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); verify(product).getSupercategories(); verify(product).setSupercategories(captor.capture()); assertThat(captor.getValue()).contains(category, selectedContextCategory); } @Test public void testHandleReplace() { // when final ProductModel result = handler.moveProductToCategory(product, category, context); // test assertThat(result).isSameAs(product); final ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); verify(product).getSupercategories(); verify(product).setSupercategories(captor.capture()); assertThat(captor.getValue()).containsExactly(category); verifyNoMoreInteractions(product); } }
package Test; import java.util.*; public class Data { /// Helper class // to keep track on the operations applied on the document /// operation name, previous value of the variable, new value of the variable private String name; private String previousValue; private String nextValue; public Data() {} public Data(String name, String previousValue, String nextValue) { // System.out.println("Called " + previousValue); this.name = name; this.previousValue = previousValue; // System.out.println(previousValue); this.nextValue = nextValue; } /// getter - setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPreviousValue() { return this.previousValue; } public void setPreviousValue(String previousValue) { this.previousValue = previousValue; } public String getNextValue() { return this.nextValue; } public void setNextValue(String nextValue) { this.nextValue = nextValue; } }
package com.accp.pub.pojo; import java.util.Date; public class Accessory { private Integer fujianid; private String fujianname; private String fujianurl; private String fujianbianhao; private Float daxiao; private Date fujiantate; private String scname; private String scid; private Integer moid; private Integer stater; private String creationpersonid; private String creationpersonname; private Date creationdate; private String usestatus; private String standbyyi; private String standbyer; private String standbysan; public Integer getFujianid() { return fujianid; } public void setFujianid(Integer fujianid) { this.fujianid = fujianid; } public String getFujianname() { return fujianname; } public void setFujianname(String fujianname) { this.fujianname = fujianname == null ? null : fujianname.trim(); } public String getFujianurl() { return fujianurl; } public void setFujianurl(String fujianurl) { this.fujianurl = fujianurl == null ? null : fujianurl.trim(); } public String getFujianbianhao() { return fujianbianhao; } public void setFujianbianhao(String fujianbianhao) { this.fujianbianhao = fujianbianhao == null ? null : fujianbianhao.trim(); } public Float getDaxiao() { return daxiao; } public void setDaxiao(Float daxiao) { this.daxiao = daxiao; } public Date getFujiantate() { return fujiantate; } public void setFujiantate(Date fujiantate) { this.fujiantate = fujiantate; } public String getScname() { return scname; } public void setScname(String scname) { this.scname = scname == null ? null : scname.trim(); } public String getScid() { return scid; } public void setScid(String scid) { this.scid = scid == null ? null : scid.trim(); } public Integer getMoid() { return moid; } public void setMoid(Integer moid) { this.moid = moid; } public Integer getStater() { return stater; } public void setStater(Integer stater) { this.stater = stater; } public String getCreationpersonid() { return creationpersonid; } public void setCreationpersonid(String creationpersonid) { this.creationpersonid = creationpersonid == null ? null : creationpersonid.trim(); } public String getCreationpersonname() { return creationpersonname; } public void setCreationpersonname(String creationpersonname) { this.creationpersonname = creationpersonname == null ? null : creationpersonname.trim(); } public Date getCreationdate() { return creationdate; } public void setCreationdate(Date creationdate) { this.creationdate = creationdate; } public String getUsestatus() { return usestatus; } public void setUsestatus(String usestatus) { this.usestatus = usestatus == null ? null : usestatus.trim(); } public String getStandbyyi() { return standbyyi; } public void setStandbyyi(String standbyyi) { this.standbyyi = standbyyi == null ? null : standbyyi.trim(); } public String getStandbyer() { return standbyer; } public void setStandbyer(String standbyer) { this.standbyer = standbyer == null ? null : standbyer.trim(); } public String getStandbysan() { return standbysan; } public void setStandbysan(String standbysan) { this.standbysan = standbysan == null ? null : standbysan.trim(); } }
package cn.bs.zjzc; import android.content.Intent; import java.text.SimpleDateFormat; import cn.bs.zjzc.cache.DataCacheManager; public interface AllConsts { interface IndexConsts { // 广告轮播间隔 int adLoopTime = 2000; } interface cache { // 一次行缓存,退出应用后清除所有缓存 DataCacheManager onceCache = new DataCacheManager(); // 应用程序缓存,如设置,首页订单类型等 DataCacheManager cacheData = new DataCacheManager(); } interface app { //客服电话 String SEVICE_PHONE_NUMBER = "4001669856"; int gcTime = 500; // 网络连接时间 int netConnectTime = 60; // 读取网络数据时间 int netReadTime = 30; // 网络写数据时间 int netWriteTime = 60; // 验证码倒计时 long getCheckCode = 60000; //应用程序缓存根目录名 String cacheDirName = "Caches"; //一次行缓存目录 String tempDir = "/temp"; //应用缓存,如设置,订单类型等数据 String cacheDir = "/cacheDatas"; } interface location { String privinceKey = "location_privince"; String cityKey = "location_city"; String areaKey = "location_area"; } /** * 网络请求 * * @author pt-xuejj */ interface http { String successErrCode = "1"; String failedErrCode = "2"; String loadingErrCode = "3"; } interface DataFormats { SimpleDateFormat dateFormatRefresh = new SimpleDateFormat("MM-dd HH:mm"); SimpleDateFormat systemMessageItemDataFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); SimpleDateFormat discountCouplonDateFormat = new SimpleDateFormat( "yyyy.MM.dd"); SimpleDateFormat mindDateFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat orderLoadFormatRefresh = new SimpleDateFormat("HH:mm"); SimpleDateFormat ViewLineMenuItem = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } interface TaskName { // 系统消息 String systemRefreshName = "sys_msg_refresh"; String systemLoadMore = "sys_msg_load_more"; // 常用地址 String oftenAddressRefreshName = "of_ad_refresh"; String oftenAddressLoadMore = "of_ad_load_more"; // 返程车 String returnCar = "activity_return_car"; // 常用司机 String oftenDriver = "often_driver"; // 意见反馈列表 String userMindsTaskName = "user_minds"; } interface IntentAction { //修改家地址 String actionEditHomeAddress = "edit_often_address_home_address"; //修改公司地址 String actionEditCompanyAddress = "edit_often_address_company_address"; // String socketBroadcast = ""; } }
/* * Copyright (C), 2013-2014, 上海汽车集团股份有限公司 * FileName: CxjCardItemInfo.java * Author: baowenzhou * Date: 2015年08月21日 下午1:34:06 * Description: //模块目的、功能描述 * History: //修改记录 * <author> <time> <version> <desc> * 修改人姓名 修改时间 版本号 描述 */ package com.xjf.wemall.adapter.service.entity.alibabamap; import java.io.Serializable; /** * 门店技师查询-实体类 <br> * 〈功能详细描述〉 * * @author xiejiefeng * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ public class MapInfo implements Serializable{ /** * */ private static final long serialVersionUID = -6495237027339424944L; // 城市 private String a; public String getA() { return a; } public void setA(String a) { this.a = a; } }
package com.company; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; public class Main { @SuppressWarnings(value = "unused") private int a ; public static void main(String[] args) throws InterruptedException { List<String> stringList = new ArrayList<>(); // List<String> stringList = new Vector<>(); // List<String> stringList = Collections.synchronizedList(new ArrayList<>()); // List<String> stringList = new CopyOnWriteArrayList<>(); for (int i = 0; i <30 ; i++) { new Thread(()->{ stringList.add("a"); System.out.println(stringList); }).start(); } } }
package com.zjh.administrat.torchbearer_power.bag.utilsbag; import com.zjh.administrat.torchbearer_power.bag.beanbag.UserIDBean; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.Map; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PartMap; import retrofit2.http.QueryMap; import retrofit2.http.Url; public interface BaseApi<T> { @GET rx.Observable<ResponseBody> get(@Url String urlStr); @POST rx.Observable<ResponseBody> post(@Url String urlStr, @QueryMap Map<String, String> map); @Multipart @POST rx.Observable<ResponseBody> postFormBody(@Url String urlStr, @PartMap Map<String, RequestBody> requestBodyMap); }
package com.xnuminousx.elementaleffects.commands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.xnuminousx.elementaleffects.gui.IndGui; import com.xnuminousx.elementaleffects.gui.TrailGui; public class Commands implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String lable, String[] args) { String title = ChatColor.DARK_PURPLE + "" + "" + ChatColor.UNDERLINE + "" + ChatColor.BOLD + "ElementalEffects"; if (lable.equalsIgnoreCase("elementaleffects") || lable.equalsIgnoreCase("ee")) { if (args.length == 0) { sender.sendMessage(ChatColor.DARK_AQUA + "--= " + title + ChatColor.DARK_AQUA + " =--"); sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + "/ee"); sender.sendMessage(" " + ChatColor.GRAY + "Alias: " + ChatColor.ITALIC + "/elementaleffects"); sender.sendMessage(" " + ChatColor.YELLOW + "- Shows list of commands"); sender.sendMessage(""); sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + "/ee trails"); sender.sendMessage(" " + ChatColor.GRAY + "Alias: " + ChatColor.ITALIC + "/ee trail, /ee effects"); sender.sendMessage(" " + ChatColor.YELLOW + "- Opens the trail GUI."); sender.sendMessage(""); sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + "/ee indicators"); sender.sendMessage(" " + ChatColor.GRAY + "Alias: " + ChatColor.ITALIC + "/ee indicator, /ee ind"); sender.sendMessage(" " + ChatColor.YELLOW + "- Opens the indicators GUI."); return true; } else if (args.length == 1) { if (sender instanceof Player) { Player p = (Player)sender; if (args[0].equalsIgnoreCase("trails") || args[0].equalsIgnoreCase("trail") || args[0].equalsIgnoreCase("effects")) { TrailGui.openGUI(p); return true; } else if (args[0].equalsIgnoreCase("ind") || args[0].equalsIgnoreCase("indicators") || args[0].equalsIgnoreCase("indicator")) { IndGui.openGui(p); return true; } else { sender.sendMessage(ChatColor.RED + "Unknown command! Try: " + ChatColor.YELLOW + "/ee"); return true; } } else { sender.sendMessage("You're not a player!"); return false; } } return false; } return false; } }
/** * A class to handle the 'Return' option of the Main Menu. */ public class ReturnOption implements Option { private String name; private BookLister bookLister; public ReturnOption(String name, BookLister bookLister) { this.name = name; this.bookLister = bookLister; } @Override public String name() { return name; } @Override public void run() { bookLister.returnBook(); } }
package me.Streampy.minetopia.commands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.Streampy.minetopia.Main; import me.Streampy.minetopia.subcommands.Plot; public class minetopia implements CommandExecutor { public minetopia(Main main) { // TODO Auto-generated constructor stub } Plot plot = new Plot(); @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("minetopia")) { if (args.length == 0) { //help menu }else { switch(args[0]) { case "plot": plot.onCommand(sender, cmd, label, args); break; case "": break; default: //help menu } } }else { player.sendMessage(ChatColor.RED + "You dont have the right permissions!"); } } return false; } }
package io.github.rhythm2019.mawenCommunity.constant; /** * @author Rhythm-2019 * @date 2023/3/7 * @description */ public class ConfigurationConstant { public static final String TAGS_FILE_PATH = "classpath:tags.json"; public static final String TAGS_NAMESPACE = "tags"; }
package zm.gov.moh.core.model; public class IntentAction { public static final String REMOTE_SERVICE_INTERRUPTED = "zm.gov.moh.common.REMOTE_SERVICE_INTERRUPTED"; public static final String REMOTE_SERVICE_METADATA_SYNC_COMPLETE = "zm.gov.moh.common.REMOTE_SERVICE_METADATA_SYNC_COMPLETE"; public static final String REMOTE_SYNC_COMPLETE = "zm.gov.moh.common.REMOTE_SYNC_COMPLETE"; public static final String INSUFFICIENT_IDENTIFIERS_FAILED_REGISTRATION = "zm.gov.moh.common.INSUFFICIENT_IDENTIFIERS_FAILED_REGISTRATION"; }
package ejercicios.colection.list; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Integer numero1 = 1; Integer numero2 = 4; Integer numero3 = 8; Integer numero4 = 20; // ctrl + shift + o java.util.list List<Integer> listaNueva = new ArrayList<Integer>(); // lista de Integers listaNueva.add(numero1); listaNueva.add(numero2); listaNueva.add(numero3); listaNueva.add(numero4); // impresion lista System.out.println(listaNueva); } }
package hello; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class BlogFile { private BufferedReader reader; private Integer waitPeriod = 1000; private File generateBlogFile() { return new File("/tmp/spring-example/infoq-articles.txt"); } public BlogFile() throws Exception { reader = generateReader(); } public void empty() { try { PrintWriter writer = new PrintWriter(generateBlogFile()); writer.print(""); writer.close(); } catch (IOException x) { System.err.println(x); } } public void close() throws Exception { reader.close(); } public void readOrWait() throws Exception { String line = reader.readLine(); if (line == null) Thread.sleep(waitPeriod); else System.out.println(line); } private BufferedReader generateReader() throws Exception { File file = generateBlogFile(); FileReader fr = new FileReader(file); return new BufferedReader(fr); } }
package com.jst.model; public class QuestionsTagMiddle { private Questions questions; private QuestionsTag questionsTag; public Questions getQuestions() { return questions; } public void setQuestions(Questions questions) { this.questions = questions; } public QuestionsTag getQuestionsTag() { return questionsTag; } public void setQuestionsTag(QuestionsTag questionsTag) { this.questionsTag = questionsTag; } @Override public String toString() { return "QuestionsTagMiddle [questions=" + questions + ", questionsTag=" + questionsTag + "]"; } }
package ch20.ex20_11; import java.io.File; import java.io.FilenameFilter; public class FileFilterPrefix implements FilenameFilter{ private File file; // file private String prefix; // 接尾語 public FileFilterPrefix(File directory, String prefix){ file = directory; this.prefix = prefix; } public boolean accept(File dir, String name) { return name.endsWith(prefix); } public void printFileList(){ String[] filenames = file.list(this); for(String name: filenames){ System.out.println(name); } } }
package com.espendwise.manta.dao; import java.util.List; import com.espendwise.manta.model.data.UserAssocData; import com.espendwise.manta.model.data.UserData; import com.espendwise.manta.util.criteria.UserAssocCriteria; import java.util.List; public interface UserAssocDAO { public UserAssocData readAssoc(Long userId, Long storeId, String assocType); public List<UserData> findAssocUsers(Long storeId, UserAssocCriteria criteria, String assocType); public List<UserAssocData> findEntityAssoc(Long entityId, String assocType); public UserAssocData createAssoc(Long userId, Long entityId, String assocCd); public void removeEntityAssoc(Long entityId, String assocCd); public UserAssocData findAssoc(Long userId, Long entityId, String assocType); public List<UserAssocData> updateUserAssocs(Long userId, List<UserAssocData> newAssocs); public List<UserAssocData> readUserAccountAssoc(Long userId, Long storeId); public List<UserAssocData> readUserSiteAssoc(Long userId, Long storeId); public List<UserAssocData> readUserSiteAssocsForAccount(Long userId, Long accountId); public List<UserAssocData> readSiteUserAssoc(Long siteId, Long storeId); }
package iarfmoose; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import com.github.ocraft.s2client.bot.gateway.UnitInPool; import com.github.ocraft.s2client.protocol.data.UnitType; import com.github.ocraft.s2client.protocol.data.Upgrade; import com.github.ocraft.s2client.protocol.game.PlayerInfo; import com.github.ocraft.s2client.protocol.game.Race; import com.github.ocraft.s2client.protocol.unit.Alliance; public class PlayerState implements State { PlayerInfo playerInfo; private Alliance alliance; private float armySupply; private int workerCount; private Set<UnitInPool> structures; private Set<Upgrade> completedUpgrades; public PlayerState() { playerInfo = null; alliance = Alliance.NEUTRAL; armySupply = 0; workerCount = 0; structures = new HashSet<UnitInPool>(); completedUpgrades = new HashSet<Upgrade>(); } public PlayerState( PlayerInfo playerInfo, Alliance alliance, float armySupply, int workerCount, Set<UnitInPool> structures, Set<Upgrade> upgrades) { this.alliance = alliance; this.playerInfo = playerInfo; this.armySupply = armySupply; this.workerCount = workerCount; this.structures = structures; this.completedUpgrades = upgrades; } @Override public Optional<Integer> getWorkerCount() { return Optional.of(workerCount); } @Override public Optional<Integer> getBaseCount() { java.util.List<UnitType> townhallTypes = UnitData.getTownHallTypeFor(getRace()); int count = 0; for (UnitType townhallType : townhallTypes) { count += getCountForStructureType(townhallType); } return Optional.of(count); } @Override public Optional<Float> getArmySupply() { return Optional.of(armySupply); } @Override public Optional<Integer> getGasCount() { UnitType gasType = UnitData.getGasTypeFor(getRace()); return Optional.of(getCountForStructureType(gasType)); } public Race getRace() { if (playerInfo == null) { return Race.NO_RACE; } else { return playerInfo.getActualRace().orElse(playerInfo.getRequestedRace()); } } public int getPlayerID() { return playerInfo.getPlayerId(); } public Alliance getAlliance() { return alliance; } public List<UnitInPool> getBases() { java.util.List<UnitType> townhallTypes = UnitData.getTownHallTypeFor(getRace()); List<UnitInPool> bases = new ArrayList<UnitInPool>(); for (UnitType townhallType : townhallTypes) { bases.addAll(getStructuresOfType(townhallType)); } return bases; } public Set<UnitInPool> getStructures() { return structures; } public Set<UnitType> getStructureTypes() { Set<UnitType> structureTypes = new HashSet<UnitType>(); for (UnitInPool structure: structures) { structureTypes.add(structure.unit().getType()); } return structureTypes; } public int getCountForStructureType(UnitType structureType) { int count = 0; for (UnitInPool structure : structures) { if (structure.unit().getType() == structureType) { count++; } } return count; } public List<UnitInPool> getStructuresOfType(UnitType structureType) { List<UnitInPool> outputStructures = new ArrayList<UnitInPool>(); for (UnitInPool structure : structures) { if (structure.unit().getType() == structureType) { outputStructures.add(structure); } } return outputStructures; } public Set<Upgrade> getCompletedUpgrades() { return completedUpgrades; } public int getProductionFacilityCount() { int currentProductionFacilities = 0; Set<UnitType> productionFacilities = UnitData.getProductionFacilitiesForRace(getRace()); for (UnitType structureType : productionFacilities) { currentProductionFacilities += getCountForStructureType(structureType); } return currentProductionFacilities; } public boolean completedStructureExists(UnitType structureType) { for (UnitInPool structure : structures) { if (structure.unit().getType() == structureType && structure.unit().getBuildProgress() == 1.0) { return true; } } return false; } }
package com.studio.saradey.aplicationvk.ui.activity; import android.accounts.AccountManager; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import com.arellomobile.mvp.presenter.InjectPresenter; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.materialdrawer.AccountHeader; import com.mikepenz.materialdrawer.AccountHeaderBuilder; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem; import com.mikepenz.materialdrawer.model.SectionDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IProfile; import com.studio.saradey.aplicationvk.MyAplication; import com.studio.saradey.aplicationvk.R; import com.studio.saradey.aplicationvk.consts.ApiConstants; import com.studio.saradey.aplicationvk.model.Profile; import com.studio.saradey.aplicationvk.mvp.presenter.MainPresenter; import com.studio.saradey.aplicationvk.mvp.view.MainView; import com.studio.saradey.aplicationvk.rest.api.AccountApi; import com.studio.saradey.aplicationvk.rest.model.request.AccountRegisterDeviceRequest; import com.studio.saradey.aplicationvk.ui.fragment.BaseFragment; import com.studio.saradey.aplicationvk.ui.fragment.NewsFeedFragment; import com.vk.sdk.VKAccessToken; import com.vk.sdk.VKCallback; import com.vk.sdk.VKSdk; import com.vk.sdk.api.VKError; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class MainActivity extends BaseActivity implements MainView { @InjectPresenter MainPresenter presenter; private Drawer mDrawer; private AccountHeader mAccountHeader; @Inject AccountApi mAccountApi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyAplication.getApplicationComponent().inject(this); presenter.chekAuth(); } //создание Drawer public void setUpDrawer() { PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1) .withName(R.string.screen_name_news) .withIcon(GoogleMaterial.Icon.gmd_home); PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2) .withName(R.string.screen_name_my_posts) .withIcon(GoogleMaterial.Icon.gmd_list); PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3) .withName(R.string.screen_name_settings) .withIcon(GoogleMaterial.Icon.gmd_settings); PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4) .withName(R.string.screen_name_members) .withIcon(GoogleMaterial.Icon.gmd_people); PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5) .withName(R.string.screen_name_topics) .withIcon(GoogleMaterial.Icon.gmd_record_voice_over); PrimaryDrawerItem item6 = new PrimaryDrawerItem().withIdentifier(6) .withName(R.string.screen_name_info) .withIcon(GoogleMaterial.Icon.gmd_info); PrimaryDrawerItem item7 = new PrimaryDrawerItem().withIdentifier(7) .withName(R.string.screen_name_rules) .withIcon(GoogleMaterial.Icon.gmd_assignment); mAccountHeader = new AccountHeaderBuilder() .withActivity(this) .build(); mDrawer = new DrawerBuilder() .withActivity(this) //указываем активити. .withToolbar(toolbar) // указываем тулбар. .withTranslucentStatusBar(true) //если true — статусбар становится прозрачным при открытии дровера. .withActionBarDrawerToggle(true) //добавляет для дровера иконку в тулбаре (в нашем случае — гамбургер) .withAccountHeader(mAccountHeader) .addDrawerItems(item1, item2, item3, new SectionDrawerItem().withName("Группа"), item4, item5, item6, item7) .withOnDrawerItemClickListener((view, position, drawerItem) -> { presenter.drawerItemClick((int) drawerItem.getIdentifier()); return false; }) .build(); } //получаем макет этой активити @Override protected int getMainContentLayout() { return R.layout.activity_main; } //если мы еще не авторизованы @Override public void startSignIn() { VKSdk.login(this, ApiConstants.DEFAULT_LOGIN_SCOPE); //код для авторизации setUpDrawer(); setContent(new NewsFeedFragment()); } //если мы уже автризованы @Override public void signedId() { setUpDrawer(); setContent(new NewsFeedFragment()); //регистрируем устройство на сервере ВК как получатель push-сообщений mAccountApi.registerDevice(new AccountRegisterDeviceRequest(Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID)).toMap()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } //показываем в хедаре конкретного юзера @Override public void showCurrentUser(Profile profile) { List<IProfile> profileDrawerItems = new ArrayList<>(); profileDrawerItems.add(new ProfileDrawerItem().withName(profile.getFullName()).withEmail(VKAccessToken.currentToken().email) .withIcon(profile.getDisplayProfilePhoto())); profileDrawerItems.add(new ProfileSettingDrawerItem().withName(getString(R.string.screen_name_exit)) .withOnDrawerItemClickListener((view, position, drawerItem) -> { mAccountHeader.removeProfile(0); mAccountHeader.removeProfile(0); VKSdk.logout(); return false; })); mAccountHeader.setProfiles(profileDrawerItems); } //Создадим приложение, которое будет вызывать два разных Activity и получать от них результат. Как мы помним, // результат приходит в метод onActivityResult. И requestCode используется, чтобы отличать друг от друга // пришедшие результаты. А resultCode – позволяет определить успешно прошел вызов или нет. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!VKSdk.onActivityResult(requestCode, resultCode, data, new VKCallback<VKAccessToken>() { @Override public void onResult(VKAccessToken res) { // Пользователь успешно авторизовался presenter.chekAuth(); } @Override public void onError(VKError error) { // Произошла ошибка авторизации (например, пользователь запретил авторизацию) } })) { super.onActivityResult(requestCode, resultCode, data); } } //отображаем наш фрагмент @Override public void showFragmentFromDrawer(BaseFragment baseFragment) { setContent(baseFragment); } @Override public void startActivityFromDrawer(Class<?> act) { startActivity(new Intent(MainActivity.this, act)); } }
import java.awt.TextArea; import java.util.ArrayList; import java.util.Scanner; public class throwAway { private TextArea outputArea; private int numResourceTypes=0; private ArrayList resourceList = new ArrayList(); ArrayList tempAllocationList = new ArrayList(); ArrayList tempNewWorkList = new ArrayList(); ArrayList tempNewAvailableList = new ArrayList(); private ArrayList<Process> processList = new ArrayList(); private ArrayList<String> processLabels = new ArrayList(); private ArrayList availableList = new ArrayList(); private String tempProcessLabels, tempAvailable; public throwAway(TextArea outputArea){ this.outputArea = outputArea; } public void parseAndStore(String inputArea){ System.out.println("Start Parse and Store"); outputArea.append(inputArea+"\n\n"); Scanner scanner = new Scanner(inputArea); tempProcessLabels = scanner.nextLine(); outputArea.append("Available in the system:\n"); outputArea.append(tempProcessLabels+"\n"); tempAvailable = scanner.nextLine(); System.out.println("Available length "+ tempAvailable.length()); numResourceTypes=(tempAvailable.length()+1)/2; System.out.println("Resources "+ numResourceTypes); for(int i = 0; i<tempAvailable.length(); i+=2){ char s = tempAvailable.charAt(i); String str = String.valueOf(s); int n = Integer.parseInt(str); availableList.add(n); } outputArea.append(availableList+"\n"); outputArea.append("Processes\n" + " Allocation Max Need\n"); while(scanner.hasNext()){ ArrayList tempAllocationList = new ArrayList(); ArrayList tempMaxList = new ArrayList(); ArrayList tempNeedList = new ArrayList(); String tempLine = scanner.nextLine(); //create allocation list for(int i = 0; i<tempLine.length()/2; i+=2){ char s = tempLine.charAt(i); String str = String.valueOf(s); int n = Integer.parseInt(str); tempAllocationList.add(n); } //create Max list for(int i = tempLine.length()/2+1; i<tempLine.length(); i+=2){ char s = tempLine.charAt(i); String str = String.valueOf(s); int n = Integer.parseInt(str); tempMaxList.add(n); } //create need list for(int i =0; i<tempMaxList.size(); i++){ int x = (Integer)tempAllocationList.get(i); int y = (Integer)tempMaxList.get(i); tempNeedList.add(y-x); } processList.add(new Process(tempAllocationList,tempMaxList, tempNeedList)); } for(int i=0;i<processList.size();i++){ outputArea.append("** "+i+":"+processList.get(i).toString()); } } public boolean safety(){ ArrayList workList = new ArrayList(); boolean allgood = true; for(int i = 0; i<availableList.size(); i++){ int tempNum = 0; tempNum = (Integer)availableList.get(i); workList.add(tempNum); } for(int j = 0; j<processList.size(); j++){ for(int i=0; i<numResourceTypes; i++){ if((Integer)processList.get(j).getNeed().get(i) <= (Integer)workList.get(i) && processList.get(j).getIsFinished() == false){ System.out.println(processList.get(j)+" good"); }else{ allgood = false; } } if(allgood == true){ for(int i=0; i<numResourceTypes; i++){ if((Integer)processList.get(j).getNeed().get(i) <= (Integer)workList.get(i) && processList.get(j).getIsFinished() == false){ for(int k=0; k<numResourceTypes; k++){ int x = (Integer)tempAllocationList.get(i); System.out.println("x: "+x); int y = (Integer)workList.get(i); System.out.println("y: "+y); tempNewWorkList.add(y+x); if(j == processList.size()-1){ j =-1; } } } } workList.clear(); for(int i=0; i<numResourceTypes; i++){ workList.add(tempNewWorkList.get(i)); } } } for(int i=0; i<numResourceTypes; i++){ if(processList.get(i).getIsFinished() == false){return false;} } return true; } public void resourceRequest(String commandField){ boolean success = true; System.out.println("Resource Request"); System.out.println("Command Field "+ commandField); System.out.println("Char at 3:"+ commandField.charAt(2)); // ArrayList resourceList; // resourceList = new ArrayList(); for(int i=2; i<commandField.length(); i+=2){ char s = commandField.charAt(i); String str = String.valueOf(s); int n = Integer.parseInt(str); resourceList.add(n); } int tempNum = (Integer)resourceList.get(0); System.out.println(tempNum); for(int i=0; i<numResourceTypes; i++){ tempNum = (Integer)resourceList.get(i+1); int start = (Integer)resourceList.get(0); System.out.println(tempNum +(Integer) processList.get(start).getAllocation().get(i) +" <= "+ (Integer)processList.get(start).getMax().get(i)); if(tempNum +(Integer) processList.get(start).getAllocation().get(i) <= (Integer)processList.get(start).getMax().get(i)){ System.out.println("Success"); }else{success = false;} } if(success = false){System.out.println("success = "+success); }else{ for(int i=0; i<numResourceTypes; i++){ System.out.print("boom "); } } } public void addProcess(String commandField){ // ArrayList tempAllocationList = new ArrayList(); ArrayList tempMaxList = new ArrayList(); ArrayList tempNeedList = new ArrayList(); //create Allocation list for(int i = 2; i<commandField.length()/2+1; i+=2){ char s = commandField.charAt(i); String str = String.valueOf(s); int n = Integer.parseInt(str); tempAllocationList.add(n); } //create Max list for(int i = commandField.length()/2+2; i<commandField.length(); i+=2){ if(commandField.charAt(i)==('A') || commandField.charAt(i)==(' ')){ System.out.println("wrong spot"); }else{System.out.println("right spot");} char s = commandField.charAt(i); String str = String.valueOf(s); System.out.println("str "+str); int n = Integer.parseInt(str); tempMaxList.add(n); } //create need list for(int i =0; i<tempMaxList.size(); i++){ int x = (Integer)tempAllocationList.get(i); int y = (Integer)tempMaxList.get(i); tempNeedList.add(y-x); } processList.add(new Process(tempAllocationList,tempMaxList, tempNeedList)); //remove from available for(int i=0; i<numResourceTypes; i++){ int x = (Integer)tempAllocationList.get(i); System.out.println("x: "+x); int y = (Integer)availableList.get(i); System.out.println("y: "+y); tempNewAvailableList.add(y-x); } availableList.clear(); for(int i=0; i<numResourceTypes; i++){ availableList.add(tempNewAvailableList.get(i)); } System.out.println(processList.get(processList.size()-1).toString()); System.out.print(availableList.get(0)); System.out.print(availableList.get(1)); System.out.print(availableList.get(2)); printHeaders(); } public void delete(String commandField){ System.out.println("delete"); char s = commandField.charAt(2); String str = String.valueOf(s); int n = Integer.parseInt(str); for(int i=0; i<numResourceTypes; i++){ //ArrayList tempNewAvailableList = new ArrayList(); int x = (Integer)processList.get(n).getAllocation().get(i); System.out.println("x: "+x); //System.out.println("pre y: "+availableList.toString()); int y = (Integer)availableList.get(i); System.out.println("y: "+y); tempNewAvailableList.add(y+x); } processList.remove(n); availableList.clear(); for(int i=0; i<numResourceTypes; i++){ availableList.add(tempNewAvailableList.get(i)); } printHeaders(); } public void printHeaders(){ outputArea.append("Available in the system:\n"); outputArea.append(tempProcessLabels+"\n"); outputArea.append(availableList+"\n"); outputArea.append("Processes\n" + " Allocation Max Need\n"); for(int i=0;i<processList.size();i++){ outputArea.append("** "+i+":"+processList.get(i).toString()); } } }
package com.fleet.mysql.multi.service.impl; import com.fleet.mysql.multi.dao.master.MasterUserDao; import com.fleet.mysql.multi.dao.slaver.SlaverUserDao; import com.fleet.mysql.multi.entity.User; import com.fleet.mysql.multi.service.UserService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * @author April Han */ @Transactional @Service public class UserServiceImpl implements UserService { @Resource private MasterUserDao masterUserDao; @Resource private SlaverUserDao slaverUserDao; @Override public int insert(User user) { return masterUserDao.insert(user); } @Override public int delete(Long id) { return masterUserDao.delete(id); } @Override public int update(User user) { return masterUserDao.update(user); } @Override public User get(Long id) { return slaverUserDao.get(id); } @Override public List<User> list(Map<String, Object> map) { return slaverUserDao.list(map); } }
package com.drzewo97.ballotbox.panel.controller.district; import com.drzewo97.ballotbox.core.model.country.CountryRepository; import com.drzewo97.ballotbox.core.model.district.District; import com.drzewo97.ballotbox.core.model.district.DistrictRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @Controller @RequestMapping(path = "/panel/district/create") public class DistrictCreationController { @Autowired private DistrictRepository districtRepository; @Autowired private CountryRepository countryRepository; @ModelAttribute("district") private District district() { return new District(); } @GetMapping private String showDistrictCreate(Model model){ model.addAttribute("countries", StreamSupport.stream(countryRepository.findAll().spliterator(), false).collect(Collectors.toList())); return "panel/district_create"; } @PostMapping private String createDistrict(@ModelAttribute("district") District district, BindingResult result){ if(districtRepository.existsByNameAndCountry_Name(district.getName(), district.getCountry().getName())){ result.rejectValue("name", "name.exist", "District already exists."); } if(result.hasErrors()){ return "panel/district_create"; } districtRepository.save(district); return "redirect:create?success"; } }
package com.weixin.web.servlet; import com.weixin.dto.WeiXinInfo; import com.weixin.service.CoreService; import com.weixin.thread.AccessTokenThread; import com.weixin.tool.SignUtil; import com.weixin.tool.WeixinUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * 核心请求处理类 * Created by White on 2017/2/20. */ @WebServlet(urlPatterns = "/CoreServlet") public class CoreServlet extends HttpServlet { private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); @Override public void init() throws ServletException { log.info("weixin api appId:{}", WeiXinInfo.APPID); log.info("weixin api appSecret:{}", WeiXinInfo.APPSECRET); //未配置appId、appSecret时给出提示 if("".equals(WeiXinInfo.APPID) || "".equals(WeiXinInfo.APPSECRET)) { log.error("appId and appSecret configuration error, please check carefully."); } else { //启动定时获取access_token的线程 new Thread(new AccessTokenThread()).start(); } } /** * 确认请求来自微信服务器 * @param request * @param response * @throws ServletException * @throws IOException */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("开始校验签名"); // 微信加密签名 String signature = request.getParameter("signature"); // 时间戳 String timestamp = request.getParameter("timestamp"); // 随机数 String nonce = request.getParameter("nonce"); // 随机字符串 String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败 if (SignUtil.checkSignature(signature, timestamp, nonce)) { System.out.println("签名校验通过"); out.print(echostr); }else { System.out.println("签名校验失败"); } out.close(); out = null; } /** * 处理微信服务器发来的消息 * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //将请求、响应的编码均设置为UTF-8(防止中文乱码) request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); //调用核心业务类接受消息并处理 String respMessage = CoreService.processRequest(request); //响应消息 PrintWriter out = response.getWriter(); out.print(respMessage); out.close(); } }
package org.rainice.model; import java.io.Serializable; public class BaseModel implements Serializable{ private static final long serialVersionUID = 1339810983872667825L; private Integer startRow; //起始行 private Integer endRow; //结束行 private Integer pageLimit; //页面大小 private Integer pageOffset; //页面偏移量 public Integer getStartRow() { return startRow; } public void setStartRow(Integer startRow) { this.startRow = startRow; } public Integer getEndRow() { return endRow; } public void setEndRow(Integer endRow) { this.endRow = endRow; } public Integer getPageLimit() { return pageLimit; } public void setPageLimit(Integer pageLimit) { this.pageLimit = pageLimit; } public Integer getPageOffset() { return pageOffset; } public void setPageOffset(Integer pageOffset) { this.pageOffset = pageOffset; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((endRow == null) ? 0 : endRow.hashCode()); result = prime * result + ((pageLimit == null) ? 0 : pageLimit.hashCode()); result = prime * result + ((pageOffset == null) ? 0 : pageOffset.hashCode()); result = prime * result + ((startRow == null) ? 0 : startRow.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseModel other = (BaseModel) obj; if (endRow == null) { if (other.endRow != null) return false; } else if (!endRow.equals(other.endRow)) return false; if (pageLimit == null) { if (other.pageLimit != null) return false; } else if (!pageLimit.equals(other.pageLimit)) return false; if (pageOffset == null) { if (other.pageOffset != null) return false; } else if (!pageOffset.equals(other.pageOffset)) return false; if (startRow == null) { if (other.startRow != null) return false; } else if (!startRow.equals(other.startRow)) return false; return true; } @Override public String toString() { return "BaseModel [endRow=" + endRow + ", pageLimit=" + pageLimit + ", pageOffset=" + pageOffset + ", startRow=" + startRow + "]"; } }
package com.zebra.pay.utils; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 目前只应用在基础数据列表上 * @author 2013159 */ @Component public class CacheTools { public static final String CACHE_NAME="list"; public static final String CACHE_NAME_EXPORT="export"; public static final String CACHE_NAME_PROVINCE_CITY="provincecity"; @Autowired private CacheManager cacheManager; public Object get(String key){ Element element = getCache().get(key); return element == null? null:element.getObjectValue(); } public void set(String key,Object value) { Element element = new Element(key, value); getCache().put(element); } private Cache getCache(){ return cacheManager.getCache(CACHE_NAME); } private Cache getCache(String cacheKey){ return cacheManager.getCache(cacheKey); } public Object get(String cacheKey,String key){ Element element = getCache().get(key); return element == null? null:element.getObjectValue(); } public void set(String cacheKey,String key,Object value) { Element element = new Element(key, value); getCache().put(element); } public void remove(String key){ getCache().remove(key); } public void removeAll(){ getCache().removeAll(); } }
/** * Copyright 2019 bejson.com */ package com.wxapp.jsonbean; import java.util.List; /** * Auto-generated: 2019-12-31 15:56:46 * * @author bejson.com (i@bejson.com) * @website http://www.bejson.com/java2pojo/ */ public class FriendCounter { private String friendCount; private List<String> friendWxids; public void setFriendCount(String friendCount) { this.friendCount = friendCount; } public String getFriendCount() { return friendCount; } public void setFriendWxids(List<String> friendWxids) { this.friendWxids = friendWxids; } public List<String> getFriendWxids() { return friendWxids; } }
package uk.gov.companieshouse.api.testdata.model.entity; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; import java.time.Instant; import java.util.List; @Document(collection = "company_pscs") public class CompanyPscs{ @Id @Field("_id") private String id; @Field("delta_at") private String deltaAt; @Field("data.natures_of_control") private List<String> naturesOfControl; @Field("data.kind") private String kind; @Field("data.name_elements") private NameElements nameElements; @Field("data.name") private String name; @Field("data.notified_on") private Instant notifiedOn; @Field("data.nationality") private String nationality; @Field("data.address.postal_code") private String postalCode; @Field("data.address.premises") private String premises; @Field("data.address.locality") private String locality; @Field("data.address.country") private String country; @Field("data.address.address_line_1") private String addressLine1; @Field("data.address.address_line_2") private String addressLine2; @Field("data.address.care_of") private String careOf; @Field("data.address.poBox") private String poBox; @Field("data.address.region") private String region; @Field("data.country_of_residence") private String countryOfResidence; @Field("data.address_same_as_registered_office_address") private Boolean addressSameAsRegisteredOfficeAddress; @Field("data.ceased_on") private Instant ceasedOn; @Field("data.reference_etag") private String referenceEtag; @Field("data.reference_psc_id") private String referencePscId; @Field("data.register_entry_date") private Instant registerEntryDate; @Field("data.statement_action_date") private Instant statementActionDate; @Field("data.statement_type") private String statementType; @Field("data.date_of_birth") private Instant dateOfBirth; @Field("data.links") private Links links; @Field("data.etag") private String etag; @Field("company_number") private String companyNumber; @Field("psc_id") private String pscId; @Field("updated.at") private Instant updatedAt; @Field("notification_id") private String notificationId; @Field("created.at") private Instant createdAt; @Field("data.identification") private Identification identification; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeltaAt() { return deltaAt; } public void setDeltaAt(String deltaAt) {this.deltaAt = deltaAt; } public List<String> getNaturesOfControl() { return naturesOfControl; } public void setNaturesOfControl(List<String> naturesOfControl) { this.naturesOfControl = naturesOfControl; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public NameElements getNameElements() { return nameElements; } public void setNameElements(NameElements nameElements) { this.nameElements = nameElements; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Instant getNotifiedOn() { return notifiedOn; } public void setNotifiedOn(Instant notifiedOn) { this.notifiedOn = notifiedOn; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getPremises() { return premises; } public void setPremises(String premises) { this.premises = premises; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getCareOf() { return careOf; } public void setCareOf(String careOf) { this.careOf = careOf; } public String getPoBox() { return poBox; } public void setPoBox(String poBox) { this.poBox = poBox; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public Boolean getAddressSameAsRegisteredOfficeAddress() { return addressSameAsRegisteredOfficeAddress; } public void setAddressSameAsRegisteredOfficeAddress(Boolean addressSameAsRegisteredOfficeAddress) { this.addressSameAsRegisteredOfficeAddress = addressSameAsRegisteredOfficeAddress; } public Instant getCeasedOn() { return ceasedOn; } public void setCeasedOn(Instant ceasedOn) { this.ceasedOn = ceasedOn; } public String getReferenceEtag() { return referenceEtag; } public void setReferenceEtag(String referenceEtag) { this.referenceEtag = referenceEtag; } public String getReferencePscId() { return referencePscId; } public void setReferencePscId(String referencePscId) { this.referencePscId = referencePscId; } public Instant getRegisterEntryDate() { return registerEntryDate; } public void setRegisterEntryDate(Instant registerEntryDate) { this.registerEntryDate = registerEntryDate; } public Instant getStatementActionDate() { return statementActionDate; } public void setStatementActionDate(Instant statementActionDate) { this.statementActionDate = statementActionDate; } public String getStatementType() { return statementType; } public void setStatementType(String statementType) { this.statementType = statementType; } public String getCountryOfResidence() { return countryOfResidence; } public void setCountryOfResidence(String countryOfResidence) { this.countryOfResidence = countryOfResidence; } public Instant getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Instant dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Links getLinks() { return links; } public void setLinks(Links links) { this.links = links; } public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } public String getCompanyNumber() { return companyNumber; } public void setCompanyNumber(String companyNumber) { this.companyNumber = companyNumber; } public String getPscId() { return pscId; } public void setPscId(String pscId) { this.pscId = pscId; } public Instant getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } public String getNotificationId() { return notificationId; } public void setNotificationId(String notificationId) { this.notificationId = notificationId; } public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } public Identification getIdentification() { return identification; } public void setIdentification(Identification identification) { this.identification = identification; } }
import java.util.Scanner; public class ProgramaNotas { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("CALCULANDO NOTAS DA TURMA"); System.out.println("Quantos alunos há na turma?"); int numAlunos = Integer.parseInt(scan.nextLine()); String [] listaNomes = new String[numAlunos]; double [] listaNotas = new double[numAlunos]; for (int k = 0; k < numAlunos; k++) { System.out.println("Qual o nome do aluno [" + (k + 1) + "]"); listaNomes[k] = scan.nextLine(); System.out.println("Qual a nota do aluno [" + (k + 1) + "]"); listaNotas[k] = Double.parseDouble(scan.nextLine()); } if (numAlunos > 0) { System.out.println("A maior nota da turma foi:" +calculaMaiorNota(listaNotas)); System.out.println("A quantidade de notas abaixo da média é:" +contaAlunosComNotaBaixa(listaNotas)); System.out.println("Qual o nome a pesquisar?"); String nomeAPesquisar = scan.nextLine(); int quantNomes = contaAlunosComNome(listaNomes, nomeAPesquisar); System.out.println("A quantidade de alunos com o nome " + nomeAPesquisar + " é:" + quantNomes); System.out.println("Qual o prefixo a pesquisar?"); String prefixo = scan.nextLine(); imprimeNomesQueComecamCom(listaNomes, prefixo); } System.out.println("Fim do programa"); scan.close(); } public static double calculaMaiorNota(double [] listaNotas) { double maiorNota = listaNotas[0]; for (int k=1; k<listaNotas.length; k++) { if (listaNotas[k] > maiorNota) { maiorNota = listaNotas[k]; } } return maiorNota; } public static int contaAlunosComNotaBaixa(double [] listaNotas) { int contNotas = 0; for (int k=0; k<listaNotas.length; k++) { if (listaNotas[k] < 7) { contNotas +=1; } } return contNotas; } public static int contaAlunosComNome(String [] listaNomes, String nomeAPesquisar) { int quantNomes = 0; for (int k=0; k<listaNomes.length; k++) { if (listaNomes[k].equals(nomeAPesquisar)) { quantNomes +=1; } } return quantNomes; } public static void imprimeNomesQueComecamCom(String [] listaNomes, String prefixo) { for (int k=0; k<listaNomes.length; k++) { if (listaNomes[k].startsWith(prefixo)) { System.out.println(listaNomes[k]); } } } }
public class absmethodinterfaceext implements absmethodinterface { public int multiplyTwo(int num1, int num2){ return num1*num2; } public int multiplyThree(int num1, int num2, int num3){ return num1*num2*num3; } public static void main(String args[]){ absmethodinterfaceext obj = new absmethodinterfaceext(); System.out.println(obj.multiplyTwo(3, 7)); System.out.println(obj.multiplyThree(1, 9, 0)); } }
package com.allen.lightstreamdemo.fragment; import android.app.Dialog; import android.os.Bundle; import android.text.TextUtils; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.allen.lightstreamdemo.R; import com.allen.lightstreamdemo.base.BaseDialogFragment; /** * 作者: allen on 16/6/30. */ public class LoadingFragment extends BaseDialogFragment { public String Tag; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Tag = getArguments().getString("LoadingFragment"); } private View view; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity(), R.style.MyDialogStyle); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // must be called before set content LayoutInflater inflater = getActivity().getLayoutInflater(); view = inflater.inflate(R.layout.dialog_loading, null); TextView textView = (TextView) view.findViewById(R.id.tipTextView); dialog.setCanceledOnTouchOutside(true); dialog.setContentView(view); // 设置宽度为屏宽、靠近屏幕底部。 WindowManager manager = getActivity().getWindowManager(); Window window = dialog.getWindow(); Display display = manager.getDefaultDisplay(); WindowManager.LayoutParams wlp = window.getAttributes(); wlp.gravity = Gravity.CENTER; wlp.width = WindowManager.LayoutParams.WRAP_CONTENT; wlp.height = WindowManager.LayoutParams.WRAP_CONTENT; if (!TextUtils.isEmpty(Tag)){ textView.setText(Tag); } window.setAttributes(wlp); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(true); return dialog; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getDialog().getWindow() .getAttributes().windowAnimations = R.style.MyDialogStyle; } }
package com.app.thread; import java.util.LinkedList; import java.util.List; /** * Producer Class in java, Producer will allow consumer to consume only * when 10 products have been produced (i.e. when production is over). */ public class Producer implements Runnable { boolean prodInProcess; List<Integer> list; public Producer() { //initially Producer will be producing, so make this productionInProcess true. super(); prodInProcess =true; list = new LinkedList<Integer>(); } public void run() { for(int i=1;i<=20;i++) { list.add(i); System.out.println("Producer is still Producing, Produced :"+i); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* Once production is over, make this productionInProcess false. * Production is over, consumer can consume. */ } prodInProcess=false; } }
package com.tencent.d.b.f; import android.content.Context; import com.tencent.d.b.c.a; import com.tencent.d.b.e.c; import com.tencent.d.b.e.f; public final class b { public int fdx; a jgQ; Context mContext; String pIu; c vmi; public f vmj; com.tencent.d.b.c.b vmk; /* synthetic */ b(byte b) { this(); } private b() { } public final String toString() { return "AuthenticationParam{mScene=" + this.fdx + ", mChallenge='" + this.pIu + '\'' + ", mIWrapGetChallengeStr=" + this.vmi + ", mIWrapUploadSignature=" + this.vmj + ", mContext=" + this.mContext + ", mFingerprintCanceller=" + this.jgQ + ", mSoterFingerprintStateCallback=" + this.vmk + '}'; } }
package com.多线程; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import com.多线程.ext.CallableTask; import com.多线程.ext.SupplierTask; /** * future的线程池用法 * @author wicks * */ public class Futrue_CompletionService线程池同步 { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(10); CallableTask task1 = new CallableTask("task1", 1000); CallableTask task2 = new CallableTask("task2", 100); // CompletionService实现 CompletionService<String> completionService = new ExecutorCompletionService<>(executor); completionService.submit(task1); completionService.submit(task2); for(int i=0;i<2;i++) { System.out.println(completionService.take().get()); } // CompletionService实现(超时) List<Future<String>> list = new ArrayList<>(); list.add(completionService.submit(task1)); list.add(completionService.submit(task2)); for(int i=0;i<2;i++) { try { String result = completionService.poll(200, TimeUnit.MILLISECONDS).get(); System.out.println(System.currentTimeMillis() + ":" + result); } catch(Exception ex) { } } for(int i=0;i<list.size();i++) { Future<String> future = list.get(i); if(!future.isCancelled() && !future.isDone()) { future.cancel(true); } } // CompletionFture实现 SupplierTask supplierTask1 = new SupplierTask("stask1", 1000); SupplierTask supplierTask2 = new SupplierTask("stask2", 100); CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(supplierTask1, executor); CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(supplierTask2, executor); CompletableFuture.allOf(completableFuture1, completableFuture2).get(); // 自建BlockingQueue队列 Future<String> future1 = executor.submit(task1); Future<String> future2 = executor.submit(task2); BlockingQueue<String> queue = new LinkedBlockingQueue<>(); executor.execute(()->{ try { queue.put(future1.get()); } catch (Exception e) { e.printStackTrace(); } }); executor.execute(()->{ try { queue.put(future2.get()); } catch (Exception e) { e.printStackTrace(); } }); for(int i=0;i<2;i++) { System.out.println(queue.take()); } } }
package com.tkb.elearning.action.admin; import java.io.IOException; import java.util.List; import com.tkb.elearning.model.AllAssociation; import com.tkb.elearning.model.Zone; import com.tkb.elearning.service.AllAssociationService; import com.tkb.elearning.service.ZoneService; import com.tkb.elearning.util.VerifyBaseAction; /** * 各區協會資訊Dao實作類 * @author Admin * @version 創建時間:2016-04-22 */ public class AllAssociationAction extends VerifyBaseAction { private static final long serialVersionUID = 1L; private ZoneService zoneService; //地區管理服務 private AllAssociationService allAssociationService; //各區協會資訊服務 private List<Zone> zoneList; //地區管理清單 private List<AllAssociation> allAssociationList; //各區協會資訊清單 private Zone zone; //地區管理資料 private AllAssociation allAssociation; //各區協會資訊資料 private int pageNo; //頁碼 private int[] deleteList; //刪除的ID清單 /** * 清單頁面 * @return */ public String index() { if(allAssociation == null) { allAssociation = new AllAssociation(); } pageTotalCount = allAssociationService.getCount(allAssociation); pageNo = super.pageSetting(pageNo); allAssociationList = allAssociationService.getList(pageCount, pageStart, allAssociation); return "list"; } /** * 新增頁面 * @return */ public String add() { allAssociation= new AllAssociation(); zoneList = zoneService.getZoneList(); return "form"; } /** * 新增資料 * @return * @throws IOException */ public String addSubmit() throws IOException { if(zone == null){ zone = new Zone(); } zone.setZone_name(allAssociation.getZone_name()); allAssociationService.add(allAssociation); return "index"; } /** * 修改頁面 * @return */ public String update() { allAssociation = allAssociationService.getData(allAssociation); zoneList=zoneService.getZoneList(); return "form"; } /** * 修改最新消息 * @return * @throws IOException */ public String updateSubmit() throws IOException { allAssociationService.update(allAssociation); return "index"; } /** * 刪除最新消息 * @return */ public String delete() throws IOException { for(int id : deleteList) { allAssociation.setId(id); allAssociation = allAssociationService.getData(allAssociation); allAssociationService.delete(id); } return "index"; } /** * 瀏覽頁面 * @return */ public String view(){ allAssociation=allAssociationService.getData(allAssociation); return "view"; } public ZoneService getZoneService() { return zoneService; } public void setZoneService(ZoneService zoneService) { this.zoneService = zoneService; } public AllAssociationService getAllAssociationService() { return allAssociationService; } public void setAllAssociationService(AllAssociationService allAssociationService) { this.allAssociationService = allAssociationService; } public List<Zone> getZoneList() { return zoneList; } public void setZoneList(List<Zone> zoneList) { this.zoneList = zoneList; } public List<AllAssociation> getAllAssociationList() { return allAssociationList; } public void setAllAssociationList(List<AllAssociation> allAssociationList) { this.allAssociationList = allAssociationList; } public Zone getZone() { return zone; } public void setZone(Zone zone) { this.zone = zone; } public AllAssociation getAllAssociation() { return allAssociation; } public void setAllAssociation(AllAssociation allAssociation) { this.allAssociation = allAssociation; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int[] getDeleteList() { return deleteList; } public void setDeleteList(int[] deleteList) { this.deleteList = deleteList; } }
package org.fuusio.api.rest.volley; import android.util.Log; import com.android.volley.Response; import com.android.volley.VolleyError; import org.fuusio.api.rest.HttpMethod; import org.fuusio.api.rest.RequestListener; import org.fuusio.api.rest.RestRequest; public abstract class VolleyRestRequest<T_Response> extends RestRequest<T_Response, AbstractRequest<T_Response>> { protected final Response.ErrorListener mErrorListener; protected final Response.Listener<T_Response> mResponseListener; protected VolleyRestRequest(final String relativeUrl, final RequestListener<T_Response> requestListener) { this(HttpMethod.GET, relativeUrl, requestListener); } protected VolleyRestRequest(final HttpMethod method, final String relativeUrl, final RequestListener<T_Response> requestListener) { super(method, relativeUrl, requestListener); mErrorListener = createErrorListener(requestListener); mResponseListener = createResponseListener(requestListener); } protected void initializeRequest(AbstractRequest<T_Response> request) { request.setTag(getClass().getSimpleName()); // If GET method we set the params that are used to define query params. If in rare case // where POST method has query params (in addition to body) the query params are handled in // RestRequest#composeUrl(HttpParams) /* if (isGet()) { mVolleyRequest.setParams(mParams); }*/ // If POST method then add the body if (isPost()) { request.setBody(mBody); } // Set the headers request.setHeaders(getHeaders().getMap()); } protected final AbstractRequest<T_Response> createRequest() { return createRequest(mResponseListener, mErrorListener); } protected abstract AbstractRequest<T_Response> createRequest(Response.Listener<T_Response> responseListener, Response.ErrorListener errorListener); protected Response.Listener<T_Response> createResponseListener(final RequestListener<T_Response> requestListener) { return new Response.Listener<T_Response>() { @Override public void onResponse(final T_Response response) { Log.d("VolleyRestRequest", "onResponse"); requestListener.onResponse(response); } }; } protected Response.ErrorListener createErrorListener(final RequestListener<T_Response> requestListener) { return new Response.ErrorListener() { @Override public void onErrorResponse(final VolleyError error) { Log.d("VolleyRestRequest", "onError"); requestListener.onError(error); } }; } }
package Model; import javafx.scene.shape.Shape; public class Line extends Figure{ // Konstruktoren für die Klasse Line public Line(double a, double b, double x, double y) { super(a, b, x, y); } // Rückgabe Figurentyp protected String getType() { return "Linie"; } // Berechnung des Umfangs = Linienlänge public double circumference() { return (Math.sqrt(Math.pow(getA(), 2) + Math.pow(getB(), 2))); } @Override public double area() { return 0; } public Shape getShape() { double a = getWidth() / 2; double b = getHeight() / 2; Shape s = new javafx.scene.shape.Line(getX() + a, getY() + b, a, b); setShapeColors(s); return s; } }
import java.util.ArrayList; import java.util.List; import java.util.Arrays; public enum Tuning { STANDARD(Note.E, Note.A, Note.D, Note.G, Note.B, Note.E); List<Note> notes = new ArrayList<>(); Tuning(Note ... notes) { this.notes = Arrays.asList(notes); } public List<Note> getNotes() { return notes; } }
package com.e6soft.form.dao.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.e6soft.core.mybatis.BaseEntityDao; import com.e6soft.form.dao.DataSourceFieldShowRuleDao; import com.e6soft.form.dao.FormFieldDao; import com.e6soft.form.model.DataSourceFieldShowRule; @Transactional @Repository("dataSourceFieldShowRuleDao") public class DataSourceFieldShowRuleDaoImpl extends BaseEntityDao<DataSourceFieldShowRule,String> implements DataSourceFieldShowRuleDao { public DataSourceFieldShowRuleDaoImpl() { super(DataSourceFieldShowRule.class); } @Override public List<DataSourceFieldShowRule> queryByTemplateFieldId( String templateFieldId) { return this.createQuery().addFiterPro("templateFieldId",templateFieldId).list(); } @Override public void deleteByTemplateFieldId(String templateFieldId) { String stateMent = DataSourceFieldShowRuleDao.class.getName()+".deleteByTemplateFieldId"; Map<String,String> param = new HashMap<String,String>(); param.put("templateFieldId", templateFieldId); this.getSqlSession().delete(stateMent, param); } }
import java.util.Scanner; public class bus { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Students : "); double students = in.nextDouble(); in.nextLine(); System.out.println("Teachers : "); double teachers = in.nextDouble(); in.nextLine(); System.out.println("Capacity : "); double capacity = in.nextDouble(); in.nextLine(); double total = students + teachers; double numberOfBuses = total / capacity; double remainder = total % capacity; System.out.println(" "); System.out.printf("Buses required : %.0f", numberOfBuses); System.out.println(" "); System.out.printf("Overflow passengers : %.0f", remainder); in.close(); } }
package com.wechat.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import net.sf.json.JSONObject; import com.ssm.util.TokenThread; import com.ssm.wechatpro.object.OutputObject; import com.ssm.wechatpro.util.Constants; import com.ssm.wechatpro.util.WeixinUtil; public class GetActivationCard { @Resource public static OutputObject outputObject = new OutputObject(); /** * 激活会员卡接口 * @param membership_number * @param code * @throws Exception */ public static void getCrad(String membership_number,String code) throws Exception{ String result = null; String url = "https://api.weixin.qq.com/card/membercard/activate?access_token="+TokenThread.accessToken.getToken();// 请求接口地址 Map<String, Object> params = new HashMap<String, Object>();// 请求参数 params.put("membership_number", membership_number);// 会员卡编号 params.put("code", code);// 领取会员卡用户获得的code result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while(!object.getString("errcode").equals("0")){ if(object.getString("errcode").equals(Constants.TOKEINVALID)){ TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid,TokenThread.appsecret); url = "https://api.weixin.qq.com/card/membercard/activate?access_token="+TokenThread.accessToken.getToken(); result=UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); }else{ String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } } /** * 设置开卡字段 * @param cardId * @throws Exception */ public static void setCard(String cardId) throws Exception{ String result = null; String url = "https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token="+TokenThread.accessToken.getToken(); Map<String,Object> params = new HashMap<String, Object>(); Map<String,Object> required_form = new HashMap<>(); required_form.put("can_modify", false); List<String> common_field_id_list = new ArrayList<>(); common_field_id_list.add("USER_FORM_INFO_FLAG_MOBILE"); required_form.put("common_field_id_list", common_field_id_list); Map<String,Object> optional_form = new HashMap<>(); optional_form.put("can_modify", false); List<String> common_field_id_list1 = new ArrayList<>(); common_field_id_list1.add("USER_FORM_INFO_FLAG_NAME"); common_field_id_list1.add("USER_FORM_INFO_FLAG_SEX"); optional_form.put("common_field_id_list", common_field_id_list1); params.put("card_id", cardId); params.put("required_form", required_form); params.put("optional_form", optional_form); result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while(!object.getString("errcode").equals("0")){ if(object.getString("errcode").equals(Constants.TOKEINVALID)){ TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid,TokenThread.appsecret); url = "https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token="+TokenThread.accessToken.getToken(); result=UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); }else{ String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //getCrad("AAA00000001","12312313"); setCard("pSU_mt4ZKnrDcBRgD_sxiJiG2eDM"); } }
package com.tencent.mm.plugin.appbrand.launching.precondition; import android.content.Intent; import com.tencent.mm.plugin.appbrand.config.AppBrandInitConfig; import com.tencent.mm.plugin.appbrand.launching.AppBrandLaunchProxyUI; import com.tencent.mm.plugin.appbrand.launching.params.LaunchParcel; import com.tencent.mm.plugin.appbrand.report.AppBrandStatObject; import com.tencent.mm.plugin.appbrand.ui.AppBrandUI; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.bi; public final class d extends b implements h { private Intent Hq; int fDQ = 0; protected final boolean b(AppBrandInitConfig appBrandInitConfig) { Class cls; try { cls = Class.forName(bi.oV(this.Hq.getStringExtra("extra_launch_source_context"))); } catch (Exception e) { cls = null; } if (cls == null || !AppBrandUI.class.isAssignableFrom(cls)) { return super.b(appBrandInitConfig); } return false; } public d(AppBrandLaunchProxyUI appBrandLaunchProxyUI) { setBaseContext(appBrandLaunchProxyUI); } public final void w(Intent intent) { this.Hq = intent; LaunchParcel launchParcel = (LaunchParcel) intent.getParcelableExtra("extra_launch_parcel"); if (launchParcel == null) { finish(); } else { a(launchParcel); } } public final void onResume() { int i = this.fDQ + 1; this.fDQ = i; if (i > 1) { akZ(); } } public final void onPause() { akZ(); } protected final String akW() { return this.Hq.getStringExtra("extra_launch_source_context"); } protected final void e(AppBrandInitConfig appBrandInitConfig, AppBrandStatObject appBrandStatObject) { super.e(appBrandInitConfig, appBrandStatObject); 1 1 = new 1(this); if (getBaseContext() instanceof AppBrandLaunchProxyUI) { ah.A(1); } else { this.gho.offer(1); } } protected final void akX() { } private void akZ() { if (!isFinishing() && !akY()) { super.akX(); } } }
package com.codechallenge.application.services.impl; import java.time.LocalDateTime; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.codechallenge.application.dto.TransactionDto; import com.codechallenge.application.dto.TransactionStatusDto; import com.codechallenge.application.entities.Account; import com.codechallenge.application.entities.Transaction; import com.codechallenge.application.exceptions.AccountNotFoundException; import com.codechallenge.application.mapper.TransactionMapper; import com.codechallenge.application.mapper.TransactionStatusMapper; import com.codechallenge.application.repositories.AccountRepository; import com.codechallenge.application.repositories.TransactionRepository; import com.codechallenge.application.services.TransactionService; import com.codechallenge.application.util.CalculateAmountComponent; @Service public class TransactionServicesImpl implements TransactionService{ private TransactionRepository repository; private TransactionMapper transactionMapper; private AccountRepository accountRepository; private CalculateAmountComponent calculateAmountComponent; private TransactionStatusMapper statusMapper; public TransactionServicesImpl(TransactionRepository repository, TransactionMapper transactionMapper, AccountRepository accountRepository, CalculateAmountComponent calculateAmountComponent, TransactionStatusMapper statusMapper) { this.repository=repository; this.transactionMapper=transactionMapper; this.accountRepository=accountRepository; this.calculateAmountComponent=calculateAmountComponent; this.statusMapper=statusMapper; } @Override @Transactional public List<TransactionDto> getTransactions(String accountIban, String order) { Sort sort = Sort.by("amount").descending(); if (order!=null && order.equalsIgnoreCase("ASC")) sort = sort.ascending(); if (accountIban!=null && !accountIban.trim().isEmpty()) return repository.findByAccountAccountIbanLike("%"+accountIban+"%", sort).stream().map(transactionMapper::entity2Dto).collect(Collectors.toList()); else return repository.findAll(sort).stream().map(transactionMapper::entity2Dto).collect(Collectors.toList()); } @Override @Transactional public TransactionDto createTransaction(TransactionDto inDto) { initDto(inDto); Account account = accountRepository.findById(inDto.getAccountIban()).orElseThrow(AccountNotFoundException::new); Double transactionAmountCalculated = calculateAmountComponent.calculateTransactionAmount(inDto.getAmount(), inDto.getFee()); Double accountAmountCalculated = calculateAmountComponent.calculateAccountAmount(transactionAmountCalculated, account.getTotalAmount()); account.setTotalAmount(accountAmountCalculated); Transaction tEntity = repository.save(transactionMapper.dto2Entity(inDto, account)); return transactionMapper.entity2Dto(tEntity); } @Override @Transactional public TransactionStatusDto statusTransaction(TransactionStatusDto inDto) { return repository.findById(inDto.getReference()) .map(entity -> statusMapper.mapStatus(entity, inDto.getChannel())) .orElseGet(()-> statusMapper.mapInvalidStatus(inDto.getReference())); } private void initDto (TransactionDto inDto) { inDto.setReference(inDto.getReference()!=null?inDto.getReference():PREFIX_UUID_REFERENCE.concat(UUID.randomUUID().toString())); inDto.setFee(inDto.getFee()!=null?inDto.getFee():new Double(0)); inDto.setDate(inDto.getDate()!=null?inDto.getDate():LocalDateTime.now()); } }
package com.casterlabs.vanishingwallapi.service.impl; import com.casterlabs.vanishingwallapi.modal.PostDetail; import com.casterlabs.vanishingwallapi.service.IPostCreateService; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.UUID; @Service public class PostCreateServiceImpl implements IPostCreateService { @Override public PostDetail createNewPost(PostDetail newPostData) { String uniquePostId = UUID.randomUUID().toString(); newPostData.setId(uniquePostId); if (newPostData.getContentType().equals("image")){ newPostData.setImageUrl(newPostData.getMediaUrl()); } newPostData.setState("show"); return newPostData; } }
package com.springBoot.dao.query; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Customer2 { private Integer id; private String lastName; // private String city; private Date createTime; public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Customer2() { // TODO Auto-generated constructor stub } public Customer2(Integer id) { super(); this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Id public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } // public String getCity() { // return city; // } // public void setCity(String city) { // this.city = city; // } }
package ru.job4j.todo.servlet; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import ru.job4j.todo.service.HibernateService; import ru.job4j.todo.service.MemService; import ru.job4j.todo.service.Service; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(HibernateService.class) public class DoneServletTest { @Test public void doPost() throws ServletException, IOException { Service stubService = MemService.instOf(); HttpServletRequest req = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); PowerMockito.mockStatic(HibernateService.class); when(HibernateService.instOf()).thenReturn(stubService); when(req.getParameter("id")).thenReturn("2"); new DoneServlet().doPost(req, resp); assertThat(stubService.getTasks(task -> !task.isDone()).size(), is(0)); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import com.tencent.mm.plugin.game.f$k; public final class avq extends a { public int dGs; public String eaZ; public String jQb; public long nlo; public int otY; public String protocol; public int rKe; public String rYA; public boolean rYB; public boolean rYC; public String rYD; public boolean rYE; public String rYF; public int rYj; public float rYk; public String rYl; public String rYm; public String rYn; public String rYo; public String rYp; public String rYq; public String rYr; public String rYs; public String rYt; public String rYu; public int rYv; public String rYw; public int rYx; public int rYy; public String rYz; public int rgC; public String rsp; public String rvP; protected final int a(int i, Object... objArr) { int fQ; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; aVar.fT(1, this.rYj); aVar.fT(2, this.rgC); if (this.rsp != null) { aVar.g(3, this.rsp); } aVar.l(4, this.rYk); if (this.rYl != null) { aVar.g(5, this.rYl); } if (this.rYm != null) { aVar.g(6, this.rYm); } if (this.rYn != null) { aVar.g(7, this.rYn); } if (this.rYo != null) { aVar.g(8, this.rYo); } if (this.rYp != null) { aVar.g(9, this.rYp); } if (this.rYq != null) { aVar.g(10, this.rYq); } if (this.rYr != null) { aVar.g(11, this.rYr); } if (this.rYs != null) { aVar.g(12, this.rYs); } if (this.rYt != null) { aVar.g(13, this.rYt); } if (this.rYu != null) { aVar.g(15, this.rYu); } if (this.jQb != null) { aVar.g(16, this.jQb); } aVar.fT(17, this.rYv); aVar.fT(18, this.rKe); if (this.rvP != null) { aVar.g(19, this.rvP); } if (this.rYw != null) { aVar.g(20, this.rYw); } aVar.fT(21, this.rYx); aVar.fT(22, this.rYy); if (this.rYz != null) { aVar.g(23, this.rYz); } aVar.T(24, this.nlo); if (this.rYA != null) { aVar.g(25, this.rYA); } aVar.av(26, this.rYB); aVar.fT(27, this.otY); aVar.av(28, this.rYC); if (this.rYD != null) { aVar.g(29, this.rYD); } aVar.fT(30, this.dGs); if (this.eaZ != null) { aVar.g(31, this.eaZ); } if (this.protocol != null) { aVar.g(32, this.protocol); } aVar.av(33, this.rYE); if (this.rYF != null) { aVar.g(34, this.rYF); } return 0; } else if (i == 1) { fQ = (f.a.a.a.fQ(1, this.rYj) + 0) + f.a.a.a.fQ(2, this.rgC); if (this.rsp != null) { fQ += f.a.a.b.b.a.h(3, this.rsp); } fQ += f.a.a.b.b.a.ec(4) + 4; if (this.rYl != null) { fQ += f.a.a.b.b.a.h(5, this.rYl); } if (this.rYm != null) { fQ += f.a.a.b.b.a.h(6, this.rYm); } if (this.rYn != null) { fQ += f.a.a.b.b.a.h(7, this.rYn); } if (this.rYo != null) { fQ += f.a.a.b.b.a.h(8, this.rYo); } if (this.rYp != null) { fQ += f.a.a.b.b.a.h(9, this.rYp); } if (this.rYq != null) { fQ += f.a.a.b.b.a.h(10, this.rYq); } if (this.rYr != null) { fQ += f.a.a.b.b.a.h(11, this.rYr); } if (this.rYs != null) { fQ += f.a.a.b.b.a.h(12, this.rYs); } if (this.rYt != null) { fQ += f.a.a.b.b.a.h(13, this.rYt); } if (this.rYu != null) { fQ += f.a.a.b.b.a.h(15, this.rYu); } if (this.jQb != null) { fQ += f.a.a.b.b.a.h(16, this.jQb); } fQ = (fQ + f.a.a.a.fQ(17, this.rYv)) + f.a.a.a.fQ(18, this.rKe); if (this.rvP != null) { fQ += f.a.a.b.b.a.h(19, this.rvP); } if (this.rYw != null) { fQ += f.a.a.b.b.a.h(20, this.rYw); } fQ = (fQ + f.a.a.a.fQ(21, this.rYx)) + f.a.a.a.fQ(22, this.rYy); if (this.rYz != null) { fQ += f.a.a.b.b.a.h(23, this.rYz); } fQ += f.a.a.a.S(24, this.nlo); if (this.rYA != null) { fQ += f.a.a.b.b.a.h(25, this.rYA); } fQ = ((fQ + (f.a.a.b.b.a.ec(26) + 1)) + f.a.a.a.fQ(27, this.otY)) + (f.a.a.b.b.a.ec(28) + 1); if (this.rYD != null) { fQ += f.a.a.b.b.a.h(29, this.rYD); } fQ += f.a.a.a.fQ(30, this.dGs); if (this.eaZ != null) { fQ += f.a.a.b.b.a.h(31, this.eaZ); } if (this.protocol != null) { fQ += f.a.a.b.b.a.h(32, this.protocol); } fQ += f.a.a.b.b.a.ec(33) + 1; if (this.rYF != null) { return fQ + f.a.a.b.b.a.h(34, this.rYF); } return fQ; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) { if (!super.a(aVar2, this, fQ)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; avq avq = (avq) objArr[1]; switch (((Integer) objArr[2]).intValue()) { case 1: avq.rYj = aVar3.vHC.rY(); return 0; case 2: avq.rgC = aVar3.vHC.rY(); return 0; case 3: avq.rsp = aVar3.vHC.readString(); return 0; case 4: avq.rYk = aVar3.vHC.readFloat(); return 0; case 5: avq.rYl = aVar3.vHC.readString(); return 0; case 6: avq.rYm = aVar3.vHC.readString(); return 0; case 7: avq.rYn = aVar3.vHC.readString(); return 0; case 8: avq.rYo = aVar3.vHC.readString(); return 0; case 9: avq.rYp = aVar3.vHC.readString(); return 0; case 10: avq.rYq = aVar3.vHC.readString(); return 0; case 11: avq.rYr = aVar3.vHC.readString(); return 0; case 12: avq.rYs = aVar3.vHC.readString(); return 0; case 13: avq.rYt = aVar3.vHC.readString(); return 0; case 15: avq.rYu = aVar3.vHC.readString(); return 0; case 16: avq.jQb = aVar3.vHC.readString(); return 0; case 17: avq.rYv = aVar3.vHC.rY(); return 0; case 18: avq.rKe = aVar3.vHC.rY(); return 0; case 19: avq.rvP = aVar3.vHC.readString(); return 0; case 20: avq.rYw = aVar3.vHC.readString(); return 0; case 21: avq.rYx = aVar3.vHC.rY(); return 0; case 22: avq.rYy = aVar3.vHC.rY(); return 0; case 23: avq.rYz = aVar3.vHC.readString(); return 0; case 24: avq.nlo = aVar3.vHC.rZ(); return 0; case 25: avq.rYA = aVar3.vHC.readString(); return 0; case 26: avq.rYB = aVar3.cJQ(); return 0; case 27: avq.otY = aVar3.vHC.rY(); return 0; case f$k.AppCompatTheme_actionModeCloseButtonStyle /*28*/: avq.rYC = aVar3.cJQ(); return 0; case f$k.AppCompatTheme_actionModeBackground /*29*/: avq.rYD = aVar3.vHC.readString(); return 0; case 30: avq.dGs = aVar3.vHC.rY(); return 0; case f$k.AppCompatTheme_actionModeCloseDrawable /*31*/: avq.eaZ = aVar3.vHC.readString(); return 0; case f$k.AppCompatTheme_actionModeCutDrawable /*32*/: avq.protocol = aVar3.vHC.readString(); return 0; case 33: avq.rYE = aVar3.cJQ(); return 0; case 34: avq.rYF = aVar3.vHC.readString(); return 0; default: return -1; } } } }
package extendedNodePositionList; import net.datastructures.Position; import net.datastructures.BoundaryViolationException; import java.io.BufferedWriter; import java.io.FileWriter; import java.lang.management.ManagementFactory; /** * This class provides methods to test your implementation of * the <code>IntegerSet</code> implementation. */ public class Tester { /** * Runs the test suite. */ public static void main(String args[]) { try { String[] ids = ManagementFactory.getRuntimeMXBean().getName() .split("@"); BufferedWriter bw = new BufferedWriter(new FileWriter("pid")); bw.write(ids[0]); bw.close(); } catch (Exception e) { System.out.println("Avisa al profesor de fallo sacando el PID"); } doTest(); } /** * Executes the test suite. */ public static void doTest() { int a0[] = {0,1,2,3,4}; ExtendedNodePositionList<Integer> l0 = mkPositionList(a0); Position<Integer> p1 = l0.nth(1); if (p1.element() != 0) { System.out.println("Position 1 should have the value 0"); throw new Error(); } Position<Integer> p3 = l0.nth(3); if (p3.element() != 2) { System.out.println("Position 3 should have the value 2"); throw new Error(); } Position<Integer> p5 = l0.nth(5); if (p5.element() != 4) { System.out.println("Position 5 should have the value 4"); throw new Error(); } try { Position<Integer> pExc = l0.nth(6); System.out.println("afterwards"); System.out.println ("Accessing position 6 should throw an "+ "exception net.datastructures.BoundaryViolationException\n"+ "but returned the value "+pExc); throw new Error(); } catch (BoundaryViolationException e) { }; int m1[] = {0,1,2,3,4}; ExtendedNodePositionList<Integer> l1 = mkPositionList(m1); int m2[] = {-1,-2,-3,-4,-5}; ExtendedNodePositionList<Integer> l2 = mkPositionList(m2); ExtendedNodePositionList<Integer> l3 = l1.fairMerge(l2); if (l3.size() != 10) { System.out.println ("The merged array should have a size of 10"+ " but has a size of "+l3.size()); throw new Error(); } Position<Integer> p6 = l3.nth(1); if (p6.element() != 0) { System.out.println ("Position 1 should have the value 0"+ " but has value "+p6.element()); throw new Error(); } Position<Integer> p7 = l3.nth(2); if (p7.element() != -1) { System.out.println ("Position 2 should have the value -1"+ " but has value "+p7.element()); throw new Error(); } ExtendedNodePositionList<Integer> l4 = l2.fairMerge(l1); if (l4.size() != 10) { System.out.println ("The merged array should have a size of 10"+ " but has a size of "+l4.size()); throw new Error(); } Position<Integer> p8 = l4.nth(1); if (p8.element() != -1) { System.out.println ("Position 1 should have the value -1"+ " but has value "+p8.element()); throw new Error(); } Position<Integer> p9 = l4.nth(2); if (p9.element() != 0) { System.out.println ("Position 2 should have the value 0"+ " but has value "+p9.element()); throw new Error(); } int m3[] = {0}; ExtendedNodePositionList<Integer> l5 = mkPositionList(m3); int m4[] = {1,2}; ExtendedNodePositionList<Integer> l6 = mkPositionList(m4); ExtendedNodePositionList<Integer> l7 = l5.fairMerge(l6); if (l7.size() != 3) { System.out.println ("The merged array should have a size of 3"+ " but has a size of "+l7.size()); throw new Error(); } Position<Integer> p10 = l7.nth(3); if (p10.element() != 2) { System.out.println ("Position 3 should have the value 2"+ " but has value "+p10.element()); throw new Error(); } System.out.println("Test finalizado correctamente."); } static ExtendedNodePositionList<Integer> mkPositionList(int arr[]) { ExtendedNodePositionList<Integer> list = new ExtendedNodePositionList<Integer>(); for (int i=0; i<arr.length; i++) list.addLast(arr[i]); return list; } }
package com.jackie.classbook.common; /** * Created with IntelliJ IDEA. * Description: * * @author liuxl * @date 2018/7/2 */ public enum MateTypeEnum { DESKMATE(1, "同桌"),ROOMMATE(2, "室友"); private int key; private String value; MateTypeEnum(int key, String value) { this.key = key; this.value = value; } public String getValue() { return value; } public int getKey() { return key; } public static String getValue(int key){ if (DESKMATE.getKey() == key){ return DESKMATE.getValue(); }else if (ROOMMATE.getKey() == key){ return ROOMMATE.getValue(); }else { return "其他"; } } public static int getKey(String value){ if (DESKMATE.getValue().equals(value)){ return DESKMATE.getKey(); }else if (ROOMMATE.getValue().equals(value)){ return ROOMMATE.getKey(); }else { return 3; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.opensoft.model.services; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.opensoft.model.entities.Colegios; import org.opensoft.model.entities.Usuarios; /** * * @author MLLERENA */ @Stateless public class ColegiosFacade extends AbstractFacade<Colegios> { @PersistenceContext(unitName = "funec-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public ColegiosFacade() { super(Colegios.class); } public Colegios findByColegio(String colegio) { Query query = em.createNamedQuery("Colegios.findByColegio"); query.setParameter("colegio", colegio); return !query.getResultList().isEmpty() ? (Colegios) query.getSingleResult() : null ; } public List<Colegios> findByEstado(String estado) { Query query = em.createNamedQuery("Colegios.findByEstado"); query.setParameter("estado", estado); return query.getResultList(); } }
package cn.gzcc.feibao.entity; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class My { @Id private int Id; private String name; private String address; private String remark; private String no; private String status; private String type; private String price; private String role; private String tele; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getTele() { return tele; } public void setTele(String tele) { this.tele = tele; } }
package com.example.strongM.mycalendarview.calendar; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.view.View; import android.view.ViewGroup; import com.example.strongM.mycalendarview.calendar.formatter.CalendarWeekDayFormatter; import com.example.strongM.mycalendarview.calendar.formatter.DateFormatDayFormatter; import com.example.strongM.mycalendarview.calendar.formatter.DayFormatter; import com.example.strongM.mycalendarview.calendar.formatter.TitleFormatter; import com.example.strongM.mycalendarview.calendar.formatter.WeekDayFormatter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; abstract class CalendarPagerAdapter<V extends CalendarPagerView> extends PagerAdapter { protected ICalendarView calendarView; private final ArrayDeque<V> currentViews; private List<CalendarDayData> selectedDates = new ArrayList<CalendarDayData>(); private final CalendarDayData today; private CalendarDayData minDate; private CalendarDayData maxDate; private DateRangeIndex rangeIndex; private TitleFormatter titleFormatter = null; private WeekDayFormatter weekDayFormatter = new CalendarWeekDayFormatter(); private DayFormatter dayFormatter = new DateFormatDayFormatter(); protected Context context; private boolean selectionEnabled = true; private boolean isShowOtherDates = false; protected CalendarPagerAdapter(ICalendarView calendarView, Context context) { this.calendarView = calendarView; this.today = CalendarDayData.today(); this.context = context; currentViews = new ArrayDeque<V>(); currentViews.iterator(); setRangeDates(null, null); } @Override public CharSequence getPageTitle(int position) { return titleFormatter == null ? "" : titleFormatter.format(getItem(position)); } @Override public int getCount() { Log.d("zpw", "count: " + rangeIndex.getCount()); return rangeIndex.getCount(); } @Override public int getItemPosition(Object object) { if (!(isInstanceOfView(object))) { return POSITION_NONE; } CalendarPagerView pagerView = (CalendarPagerView) object; CalendarDayData firstViewDay = pagerView.getFirstViewDay(); if (firstViewDay == null) { return POSITION_NONE; } int index = indexOf((V) object); if (index < 0) { return POSITION_NONE; } return index; } @Override public Object instantiateItem(ViewGroup container, int position) { V pagerView = createView(position); pagerView.setWeekDayFormatter(weekDayFormatter); pagerView.setDayFormatter(dayFormatter); pagerView.setMinimumDate(minDate); pagerView.setMaximumDate(maxDate); pagerView.setSelectedDates(selectedDates); container.addView(pagerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); currentViews.add(pagerView); return pagerView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { CalendarPagerView pagerView = (CalendarPagerView) object; currentViews.remove(pagerView); container.removeView(pagerView); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } public void setRangeDates(CalendarDayData min, CalendarDayData max) { this.minDate = min; this.maxDate = max; for (V pagerView : currentViews) { pagerView.setMinimumDate(min); pagerView.setMaximumDate(max); } if (min == null) { min = CalendarDayData.from(today.getYear() - 1, today.getMonth(), today.getDay()); } if (max == null) { max = CalendarDayData.from(today.getYear() + 1, today.getMonth(), today.getDay()); } rangeIndex = createRangeIndex(min, max); notifyDataSetChanged(); invalidateSelectedDates(); } public void setShowOtherDates(boolean isShow) { isShowOtherDates = isShow; for (V pagerView : currentViews) { pagerView.setShowOtherDates(isShow); } } public void setWeekDayFormatter(WeekDayFormatter formatter) { this.weekDayFormatter = formatter; for (V pagerView : currentViews) { pagerView.setWeekDayFormatter(formatter); } } public void setDayFormatter(DayFormatter formatter) { this.dayFormatter = formatter; for (V pagerView : currentViews) { pagerView.setDayFormatter(formatter); } } private void invalidateSelectedDates() { validateSelectedDates(); for (V pagerView : currentViews) { pagerView.setSelectedDates(selectedDates); } } private void validateSelectedDates() { for (int i = 0; i < selectedDates.size(); i++) { CalendarDayData date = selectedDates.get(i); if ((minDate != null && minDate.isAfter(date)) || (maxDate != null && maxDate.isBefore(date))) { selectedDates.remove(i); i -= 1; } } } protected abstract V createView(int position); protected abstract int indexOf(V view); protected abstract boolean isInstanceOfView(Object object); protected abstract DateRangeIndex createRangeIndex(CalendarDayData min, CalendarDayData max); public void clearSelections() { selectedDates.clear(); invalidateSelectedDates(); } public int getIndexForDay(CalendarDayData day) { if (day == null) { return getCount() / 2; } if (minDate != null && day.isBefore(minDate)) { return 0; } if (maxDate != null && day.isAfter(maxDate)) { return getCount() - 1; } return rangeIndex.indexOf(day); } public CalendarDayData getItem(int position) { return rangeIndex.getItem(position); } public DateRangeIndex getRangeIndex() { return rangeIndex; } public List<CalendarDayData> getSelectedDates() { return Collections.unmodifiableList(selectedDates); } public void setDateSelected(CalendarDayData day, boolean selected) { if (selected) { if (!selectedDates.contains(day)) { selectedDates.add(day); invalidateSelectedDates(); } } else { if (selectedDates.contains(day)) { selectedDates.remove(day); invalidateSelectedDates(); } } } }
package com.google.android.gms.common.internal; import android.accounts.Account; import android.view.View; import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.api.a; import com.google.android.gms.signin.e; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class h { public final Account aIy; public final Set<Scope> aJT; private final int aJU; private final View aJV; public final String aJW; final String aJX; final Set<Scope> aNO; public final Map<a<?>, a> aNP; public final e aNQ; public Integer aNR; public h(Account account, Set<Scope> set, Map<a<?>, a> map, int i, View view, String str, String str2, e eVar) { Map map2; this.aIy = account; this.aJT = set == null ? Collections.EMPTY_SET : Collections.unmodifiableSet(set); if (map2 == null) { map2 = Collections.EMPTY_MAP; } this.aNP = map2; this.aJV = view; this.aJU = i; this.aJW = str; this.aJX = str2; this.aNQ = eVar; Set hashSet = new HashSet(this.aJT); for (a aVar : this.aNP.values()) { hashSet.addAll(aVar.aKn); } this.aNO = Collections.unmodifiableSet(hashSet); } }
package com.yc.controllers; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yc.freemaker.DataBaseBiz; import com.yc.freemaker.DataBaseBizImpl; import com.yc.freemaker.FreeMarkerService; import com.yc.mail.SendMailService; import com.yc.mail.SendMailServiceImpl; @RestController public class MailController { @Resource(name="sendMailServiceImpl") private SendMailService sms; @Resource(name="dataBaseBizImpl") private DataBaseBiz dataBaseBiz; @Resource(name="freeMarkerServiceImpl") private FreeMarkerService fms; @RequestMapping("sendEmailtoReg.action") public boolean send(int code,String email){ Map<String,Object> map = new HashMap<String,Object>(); map.put("code", code); map.put("email", email); fms.getHtml(map,"mailTemp.html", "mail.html"); String sys = System.getProperty("user.dir"); String path = sys+"\\freeMarker\\mail.html"; String html = dataBaseBiz.readFile(path); sms.sendHtmlMail("欢迎使用淘宝贝",html,email+"@qq.com"); return true; } }
package com.example.ferdinand.travelup; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.ImageView; import android.view.View; import java.util.ArrayList; import com.example.ferdinand.travelup.adapter.*; import com.example.ferdinand.travelup.model.*; public class HotelActivity extends AppCompatActivity implements View.OnClickListener { private RecyclerView recyclerView; private ArrayList<HotelModel> lstHotel; private HotelAdapter hotelAdapter; private RecyclerView.LayoutManager layoutManager; // HotelActivity is an activity that allows the user to search for hotels by typing the name of the // hotel or by scrolling down the list. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hotel); ImageView backIcon = findViewById(R.id.backarrow); backIcon.setOnClickListener(this); createHotelList(); buildRecyclerView(); EditText editText = findViewById(R.id.hetSearch); editText.addTextChangedListener(new TextWatcher() { // These methods are made to do a filter with 's' input on the EditText @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { filter(s.toString()); } }); } // filter method is used to do a simple searching from the lstHotel ArrayList. private void filter(String text){ ArrayList<HotelModel> filteredList = new ArrayList<>(); for (HotelModel item : lstHotel){ if (item.getNameHotel().toLowerCase().contains(text.toLowerCase())){ filteredList.add(item); } } hotelAdapter.filterList(filteredList); } // createHotelList method is used to create an ArrayList containing data with six parameters on // every item. private void createHotelList(){ lstHotel = new ArrayList<>(); lstHotel.add(new HotelModel("Favehotel", "Jl. I Dewa Nyoman Oka No.30, Yogyakarta", -7.7855261,110.3677555, "4.4", R.drawable.favehotel)); lstHotel.add(new HotelModel("Marriott Hotel", "Jl. Ringroad Utara, Sleman, Yogyakarta", -7.761885, 110.3962313,"4.7", R.drawable.marriott)); lstHotel.add(new HotelModel("Platinum Hotel", "Jl. Raya Solo - Yogyakarta No.28, Sleman, Yogyakarta", -7.7830952, 110.4350722, "4.5", R.drawable.platinum)); lstHotel.add(new HotelModel("Royal Ambarrukmo Hotel", "Jl. Laksda Adisucipto No.81, Sleman, Yogyakarta", -7.7827773, 110.4006064, "4.7",R.drawable.ambarrukmo)); lstHotel.add(new HotelModel("Grand Mercure Hotel", "Jl. Laksda Adisucipto No.80, Sleman, Yogyakarta", -7.7836748, 110.3901039, "4.5", R.drawable.mercure)); lstHotel.add(new HotelModel("Sheraton Mustika Hotel", "Jl. Laksda Adisucipto No.Km 8.7, Sleman, Yogyakarta", -7.7817487, 110.4258963, "4.5", R.drawable.sheraton)); lstHotel.add(new HotelModel("Tentrem Hotel", "Jl. P. Mangkubumi No.72A, Yogyakarta", -7.7735805, 110.3664571, "4.7", R.drawable.tentrem)); lstHotel.add(new HotelModel("Grand Tjokro Hotel", "Jl. Affandi No.37, Sleman, Yogyakarta", -7.7669399, 110.3893918, "4.3", R.drawable.tjokro)); lstHotel.add(new HotelModel("Prime Plaza Hotel", "Jl. Affandi, Sleman, Yogyakarta", -7.7769294, 110.3871801, "4.5", R.drawable.prime)); lstHotel.add(new HotelModel("UC Universitas Gadjah Mada", "Jl. Pancasila Bulaksumur No.2, Sleman, Yogyakarta", -7.7731477, 110.3751633, "4.3", R.drawable.ucugm)); lstHotel.add(new HotelModel("Artotel", "Jl. Kaliurang KM 5.6 no. 14, Sleman, Yogyakarta", -7.7566449, 110.380034, "4.5", R.drawable.artotel)); lstHotel.add(new HotelModel("Indoluxe Hotel", "Jl. Palagan No.106, Sleman, Yogyakarta", -7.7504087, 110.3706192,"4.4", R.drawable.indoluxe)); lstHotel.add(new HotelModel("Sahid Rich Hotel", "Jl. Magelang No.KM.6 No.18, Sleman, Yogyakarta", -7.7524426, 110.3590168, "4.5", R.drawable.sahid)); lstHotel.add(new HotelModel("Jambuluwuk Malioboro Hotel", "Jl. Gajah Mada No.67, Yogyakarta", -7.7975533, 110.3700699, "4.3", R.drawable.jambuluwuk)); lstHotel.add(new HotelModel("Lafayette Boutique Hotel", "Jl. Ring Road Utara No. 409, Sleman, Yogyakarta", -7.7592471, 110.3852267, "4.6", R.drawable.lafayette)); } // buildRecyclerView method is used prepare the RecyclerView, to display scrolling hotel list // of elements private void buildRecyclerView() { recyclerView = findViewById(R.id.recyclerviewMenuHotel); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); hotelAdapter = new HotelAdapter(this, lstHotel); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(hotelAdapter); } // onClick method is an implementation of the OnClickListener interface, and therefore it applies // the polymorphism concept. public void onClick(View v) { if (v.getId() == R.id.backarrow) { Intent i = new Intent(this, MainActivity.class); startActivity(i); } } }
package com.headfirst.designpatterns.factory.simplefactory; public class CheesePizza extends Pizza{ public CheesePizza(){ name = "Cheese Pizza"; dough = "Cheese Dough"; sauce = "CheeseSauce"; toppings.add("Cheese Cheese"); } }
package utils; import Model.Edge; import Model.Graph; import Model.Vertex; import org.uma.jmetal.solution.IntegerSolution; import java.util.*; public class EvaluatorUtils { public ArrayList<ArrayList<Integer>> extractDispatchListsFromSolution(List<Integer> dispatchListRaw, int dispatchListVertexLength, int vertexNum) { ArrayList<ArrayList<Integer>> dispatchLists = new ArrayList<>(); for (int vertexId = 0; vertexId < vertexNum; vertexId++) { ArrayList<Integer> dispatchList = new ArrayList<>(); for (int dispatchListSlotId = 0; dispatchListSlotId < dispatchListVertexLength; dispatchListSlotId++) { dispatchList.add(dispatchListRaw.get(vertexId * dispatchListVertexLength + dispatchListSlotId)); } dispatchLists.add(vertexId, dispatchList); } return dispatchLists; } public ArrayList<ArrayList<Integer>> extractDispatchListsFromSolutionWithVariableDepot(List<Integer> dispatchListRaw, int dispatchListVertexLength, int vertexNum, int depotDispatchListLength) { ArrayList<ArrayList<Integer>> dispatchLists = new ArrayList<>(); ArrayList<Integer> dispatchList = new ArrayList<>(); for (int dispatchListSlotId = 0; dispatchListSlotId < depotDispatchListLength; dispatchListSlotId++) { dispatchList.add(dispatchListRaw.get(dispatchListSlotId)); } dispatchLists.add(0, dispatchList); for (int vertexId = 1; vertexId < vertexNum; vertexId++) { dispatchList = new ArrayList<>(); for (int dispatchListSlotId = 0; dispatchListSlotId < dispatchListVertexLength; dispatchListSlotId++) { dispatchList.add(dispatchListRaw.get(depotDispatchListLength + (vertexId-1) * dispatchListVertexLength + dispatchListSlotId)); } dispatchLists.add(vertexId, dispatchList); } return dispatchLists; } public boolean allCustomersSupplied(List<Double> customersCurrentDemand) { for (Double demand : customersCurrentDemand) { if (demand > 0.0) { return false; } } return true; } public int addEdgeCost(int currentPositionId, int nextPositionId, Map<Vertex, List<Edge>> graphStructure) { Vertex currentVertex = null; Vertex nextVertex = null; int result = 0; for (Vertex vertex : graphStructure.keySet()) { if (vertex.getId() == currentPositionId) { currentVertex = vertex; } if (vertex.getId() == nextPositionId) { nextVertex = vertex; } } List<Edge> egdes = graphStructure.get(currentVertex); for (Edge edge : egdes) { if (edge.getFirstVertexId() == currentVertex.getId() && edge.getSecondVertexId() == nextVertex.getId()) { result += edge.getCost(); } } return result; } public void saveSolution(IntegerSolution solution,ArrayList<ArrayList<Integer>> dispatchLists){ int index = 0; for(ArrayList<Integer> dispatchList : dispatchLists){ for(Integer value : dispatchList){ solution.setVariableValue(index, value); index +=1; } } } public int findClosestDemandingCustomer(int currentPositionId, Map<Vertex, List<Edge>> graphStructure, ArrayList<Double> customersCurrentDemand) { int customerId = 0; ArrayList<Integer> customersFitness = new ArrayList<>(); for(Double customerDemand : customersCurrentDemand){ if(customerDemand == 0 || customerId == currentPositionId || customerId == 0){ customersFitness.add(Integer.MAX_VALUE); } else { customersFitness.add(addEdgeCost(currentPositionId, customerId, graphStructure)); } customerId++; } return customersFitness.indexOf(Collections.min(customersFitness)); } private Random rand = new Random(); public int findRandomDemandingCustomer(int currentPositionId, Map<Vertex, List<Edge>> graphStructure, ArrayList<Double> customersCurrentDemand) { int customerId = 0; ArrayList<Integer> viableCustomers = new ArrayList<>(); for(Double customerDemand : customersCurrentDemand){ if(customerDemand != 0 && customerId != currentPositionId && customerId != 0){ viableCustomers.add(customerId); } customerId++; } return viableCustomers.get(rand.nextInt(viableCustomers.size())); } public int findBestDemandPerDistanceCustomer(int currentPositionId, Map<Vertex, List<Edge>> graphStructure, ArrayList<Double> customersCurrentDemand) { int customerId = 0; ArrayList<Double> customersFitness = new ArrayList<>(); for(Double customerDemand : customersCurrentDemand){ if(customerDemand == 0 || customerId == currentPositionId || customerId == 0){ customersFitness.add(0.0); } else { customersFitness.add(customerDemand / addEdgeCost(currentPositionId, customerId, graphStructure)); } customerId++; } return customersFitness.indexOf(Collections.max(customersFitness)); } public int findClosestDemandingNeighbour(int currentPositionId, Graph graph, ArrayList<Double> customersCurrentDemand) { Map<Integer, Double> neighbourMap = graph.getNearestNeighbours().get(currentPositionId); int bestNeighbourIndex = 0; double lowestDistance = Double.MAX_VALUE; for(Map.Entry<Integer, Double> neighbour : neighbourMap.entrySet()) { if(neighbour.getValue() < lowestDistance && customersCurrentDemand.get(neighbour.getKey()) != 0) { lowestDistance = neighbour.getValue(); bestNeighbourIndex = neighbour.getKey(); } } //returning 0 means every neighbour has no demand return bestNeighbourIndex; } public int findBestDemandPerDistanceNeighbour(int currentPositionId, Graph graph, ArrayList<Double> customersCurrentDemand) { Map<Integer, Double> neighbourMap = graph.getNearestNeighbours().get(currentPositionId); int bestNeighbourIndex = 0; double bestFitness = 0; for(Map.Entry<Integer, Double> neighbour : neighbourMap.entrySet()) { if((customersCurrentDemand.get(bestNeighbourIndex) / neighbour.getValue()) > bestFitness && customersCurrentDemand.get(neighbour.getKey()) != 0) { bestNeighbourIndex = neighbour.getKey(); bestFitness = customersCurrentDemand.get(bestNeighbourIndex) / neighbour.getValue(); } } //returning 0 means every neighbour has no demand return bestNeighbourIndex; } public Integer findClosestDemandingCustomerWithinTime(int currentPositionId, Map<Vertex, List<Edge>> graphStructure, ArrayList<Double> customersCurrentDemand, int step, List<Double> readyTimes, List<Double> dueTimes) { int customerId = 0; ArrayList<Double> customersFitness = new ArrayList<>(); for(Double customerDemand : customersCurrentDemand){ if(customerDemand == 0 || customerId == currentPositionId || customerId == 0 || step + addEdgeCost(currentPositionId, customerId, graphStructure) > dueTimes.get(customerId) || step + addEdgeCost(currentPositionId, customerId, graphStructure) < readyTimes.get(customerId)){ customersFitness.add(Double.MAX_VALUE); } else { customersFitness.add(readyTimes.get(customerId) + addEdgeCost(currentPositionId, customerId, graphStructure)); } customerId++; } return customersFitness.indexOf(Collections.min(customersFitness)); } }
public class DistList { private String label; private double [] dist; public DistList(String label, double[] dist) { super(); this.label = label; this.dist = dist; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public double[] getDist() { return dist; } public void setDist(double[] dist) { this.dist = dist; } }
package com.demo.thread; import java.util.ArrayList; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class AsyncTaskDemo extends Activity { private ListView list = null; private ProgressDialog m_pDialog=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Button) findViewById(R.id.load)) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { data = null; data = new ArrayList<String>(); //adapter = null; // showDialog(PROGRESS_DIALOG); // new ProgressThread(handler, data).start(); new ProgressTask().execute(data); } }); list = (ListView) findViewById(R.id.listView1); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: m_pDialog = new ProgressDialog(AsyncTaskDemo.this); // 设置进度条风格,风格为长形 m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置ProgressDialog 标题 m_pDialog.setTitle("提示"); // 设置ProgressDialog 提示信息 m_pDialog.setMessage("数据加载中..."); // 设置ProgressDialog 标题图标 m_pDialog.setIcon(R.drawable.load); // 设置ProgressDialog 进度条进度 m_pDialog.setMax(1000); // 设置ProgressDialog 的进度条是否不明确 m_pDialog.setIndeterminate(false); // 让ProgressDialog显示 m_pDialog.show(); return m_pDialog; //return ProgressDialog.show(this, "", "正在加载,请稍侯...", true); default: return null; } } private class ProgressTask extends AsyncTask<ArrayList<String>, Integer, Integer> { /* 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。 */ @Override protected void onPreExecute() { // 先显示ProgressDialog showDialog(PROGRESS_DIALOG); } /* 执行那些很耗时的后台计算工作。可以调用publishProgress方法来更新实时的任务进度。 */ @Override protected Integer doInBackground(ArrayList<String>... datas) { ArrayList<String> data = datas[0]; for (int i = 0; i < 1000; i++) { data.add("项目"+Integer.toString(i)); publishProgress(i); } return STATE_FINISH; } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onProgressUpdate(Integer... values) { // 更新进度 m_pDialog.setProgress(values[0]); } /* * 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用, * * 后台的计算结果将通过该方法传递到UI thread. */ @Override protected void onPostExecute(Integer result) { int state = result.intValue(); switch (state) { case STATE_FINISH: dismissDialog(PROGRESS_DIALOG); Toast.makeText(getApplicationContext(), "加载完成!", Toast.LENGTH_LONG) .show(); adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, data); list.setAdapter(adapter); break; case STATE_ERROR: dismissDialog(PROGRESS_DIALOG); Toast.makeText(getApplicationContext(), "处理过程发生错误!", Toast.LENGTH_LONG) .show(); adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, data); list.setAdapter(adapter); break; default: } } } private ArrayAdapter<String> adapter; private ArrayList<String> data; private static final int PROGRESS_DIALOG = 1; private static final int STATE_FINISH = 1; private static final int STATE_ERROR = -1; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package learnjava; import java.util.Scanner; /** * * @author CongThanh */ public class Unit2 { public static boolean checkPrimeShow (int n){ int x = n; for(int i=2; i<x; i++){ if(n%i==0) return false; } return true; } public static boolean checkPrime(int n) { if (n < 2) { return false; } if (n == 2 || n == 3) { return true; } if (n % 2 == 0 || n % 3 == 0) { return false; } int x = (int) Math.sqrt(n); for (int i = 5; i <= x; i += 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } int number_1; int number_2; public void setNumber_1(int number_1) { this.number_1 = number_1; } public void setNumber_2(int number_2) { this.number_2 = number_2; } public void setNumber() { Scanner inputNumber = new Scanner(System.in); System.out.print("Nhap so thu nhat: "); setNumber_1(inputNumber.nextInt()); System.out.print("Nhap so thu hai: "); setNumber_2(inputNumber.nextInt()); } public void add() { System.out.print("Tong hai so la: "); System.out.println(number_1 + number_2); } public void sub() { System.out.print("Hieu hai so la: "); System.out.println(number_1 - number_2); } public void mux() { System.out.print("Tich hai so la: "); System.out.println(number_1 * number_2); } public void div() { System.out.print("Thuong hai so la: "); System.out.println((float) number_1 / number_2); } public int UCLN(int a, int b) { do { if (a > b) { a = a - b; } else { b = b - a; } } while (a != b); return a; } public int BCNN(int a, int b) { return a * b / UCLN(a, b); } public static void numMax(int[] arrayNum) { int max = arrayNum[0]; for (int x : arrayNum) { if (x > max) { max = x; } } System.out.println(max); } public static void main(String[] args) { Unit2 test = new Unit2(); long startTime = System.currentTimeMillis(); boolean c = false; for(int i =0; i< 100000; i++){ c = checkPrime(i); } System.out.println(c); System.out.println("Thoi gian xu ly nhanh: "+(System.currentTimeMillis()-startTime) +"ms"); long startTime2 = System.currentTimeMillis(); for(int i =0; i< 100000; i++){ c = checkPrimeShow(i); } System.out.println(c); System.out.println("Thoi gian xu ly cham: "+(System.currentTimeMillis()- startTime2) +"ms"); // System.out.println(test.UCLN(a,b)); // System.out.println(test.BCNN(a,b)); } }
/* * VTB Group. Do not reproduce without permission in writing. * Copyright (c) 2017 VTB Group. All rights reserved. */ package com.resource.integration; import com.Application; import com.dto.DispatcherDto; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.json.JacksonTester; import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; import org.springframework.restdocs.payload.JsonFieldType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.io.UnsupportedEncodingException; import java.util.List; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureRestDocs(outputDir = "target/generated-snippets") @AutoConfigureMockMvc @AutoConfigureJsonTesters public class DispatcherResourceImplTest { @Autowired private MockMvc mockMvc; private JacksonTester<DispatcherDto> dispatcherMapper; private JacksonTester<List<DispatcherDto>> dispatcherListMapper; @Before public void setup() { ObjectMapper objectMappper = new ObjectMapper(); JacksonTester.initFields(this, objectMappper); } @Test public void getDispatchers() throws Exception { List<DispatcherDto> dispatcherDtoList = getDispatchersList(); dispatcherDtoList.forEach( System.out::println ); } private List<DispatcherDto> getDispatchersList() throws UnsupportedEncodingException, Exception { String dispatchers = mockMvc .perform(RestDocumentationRequestBuilders.get("/dispatcher")) .andExpect(status().isOk()) .andDo(document("dispatchers list", responseFields( fieldWithPath("[].dispatcherName").type(JsonFieldType.STRING) .description("Dispatcher name"), fieldWithPath("[].dispatcherFrase").type(JsonFieldType.STRING).description("Dispatcher frase"), fieldWithPath("[].createTime").type(JsonFieldType.NUMBER).optional() .description("Dispatchers creation time")))) .andReturn().getResponse().getContentAsString(); return dispatcherListMapper.parseObject(dispatchers); } }
package ass1.PQueue; import ass1.PQueue.IPriorityQueue; import ass1.PQueue.PQNode; public class LinearPQ<T> implements IPriorityQueue<T> { private PQNode<T> front; private int size; private int running = 0; public LinearPQ() { this.front = null; this.size = 0; } @Override public void add(T element, double priority) { if(element == null) throw new IllegalArgumentException("Null pointer denied!"); else { PQNode<T> n = new PQNode<T>(element, priority, ++running); PQNode<T> current = front; if (size == 0) // if the queue is empty then the first element inserted will be the front one front = n; else { if (current.getPriority() > n.getPriority()) { // if the priority of the item to be inserted is less than the first element in n.setNext(front); // the queue then the item will be placed in the front front = n; } else { // all magic stuff happens here :D // find the right position where the new item should pe placed; while (current.getPriority() <= n.getPriority() && current.getNext() != null) { if(current.getNext().getPriority() <= n.getPriority()) current = current.getNext(); else break; } // place the element in the queue n.setNext(current.getNext()); current.setNext(n); // magic stuff ends here :D } } size++; //increment the size of the priority queue; } } @Override public T getNext() { T temp = null; if(size > 0) { temp = front.getElement(); front = front.getNext(); size--; } return temp; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public void printPQ() { PQNode<T> current = front; while(current != null) { System.out.print("(" + current.getElement() + ", " + current.getPriority() + ")"); if(current.getNext() != null) System.out.print(" "); else System.out.print(";"); System.out.println(); current = current.getNext(); } } @Override public boolean contains(T element) { if (element == null) throw new IllegalArgumentException("Null pointer is not allowed"); else { PQNode<T> current = front; while (current != null) { if (current.getElement().equals(element)) return true; current = current.getNext(); } return false; } } @Override public void clear() { front = null; size = 0; running = 0; } }
package Algorithm; public class DistanceFunction { public static double calcDistance(Point p1, Point p2){ return Math.sqrt(Math.pow(p1.getX()-p2.getX(),2)+Math.pow(p1.getY()-p2.getY(),2)+Math.pow(p1.getZ()-p2.getZ(),2)); } }
package com.web.servlet; import com.domain.Book; import com.service.BookService; import com.service.impl.BookServiceImpl; import com.utils.Scanner; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/DeleteServlet") public class DeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().append("Served at: ").append(request.getContextPath()); Book book = null; Object obj = Scanner.dealInfo(); if (obj instanceof Book) { book = (Book) obj; BookService bs = new BookServiceImpl(); if(bs.deleteBook(book.getBook_id())) { response.getWriter().write("Delete Successfully! Jumping after 5 seconds!"); response.setHeader("refresh", "5;url=" + request.getContextPath() + "/index2.jsp"); } else { response.getWriter().write("Delete Failed! Jumping after 5 seconds!"); response.setHeader("refresh", "5;url=" + request.getContextPath() + "/delete.jsp"); } } else { response.getWriter().write("Wrong Scanning! Please scan again!"); response.setHeader("refresh", "5;url=" + request.getContextPath() + "/delete.jsp"); } } }
package org.foobarspam.MarcHernadezCabot_proxy; public interface DoSomethingSimple<T, R> { public T doRequest(T accion, R objeto); }
package com.sibilante.shortner.config; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; import com.sibilante.shortner.controller.ShortnerResource; @Component @ApplicationPath("/") public class JerseyConfiguration extends ResourceConfig { public JerseyConfiguration() { register(ShortnerResource.class); } }
package com.plivo.utilities; import com.jayway.jsonpath.JsonPath; import java.io.File; public class JsonReader { public String fileName; private File jsonFile; public JsonReader(String fileName) { this.fileName = fileName; } public String getTestData(String data) { try { jsonFile = new File(fileName); return JsonPath.read(jsonFile, "$." + data); } catch (Exception e) { return null; } } }
package pl.cwanix.opensun.agentserver.packets.processors.sync; import io.netty.channel.ChannelHandlerContext; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import pl.cwanix.opensun.agentserver.packets.c2s.sync.C2SAskKeyboardMovePacket; import pl.cwanix.opensun.agentserver.server.AgentServerChannelHandler; import pl.cwanix.opensun.agentserver.server.session.AgentServerSession; import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessor; import pl.cwanix.opensun.commonserver.packets.annotations.PacketProcessor; import pl.cwanix.opensun.model.character.CharacterDataSource; @Slf4j @RequiredArgsConstructor @PacketProcessor(packetClass = C2SAskKeyboardMovePacket.class) public class C2SAskKeyboardMoveProcessor implements SUNPacketProcessor<C2SAskKeyboardMovePacket> { private static final Marker MARKER = MarkerFactory.getMarker("C2S -> KEYBOARD MOVE"); private final CharacterDataSource characterDataSource; @Override public void process(final ChannelHandlerContext ctx, final C2SAskKeyboardMovePacket packet) { AgentServerSession session = ctx.channel().attr(AgentServerChannelHandler.SESSION_ATTRIBUTE).get(); log.trace(MARKER, "Updating character position: {} {} {} {}", packet.getCurrentPosition().getX(), packet.getCurrentPosition().getY(), packet.getCurrentPosition().getZ(), packet.getAngle()); characterDataSource.updateCharacterPosition( session.getCharacter().getId(), packet.getCurrentPosition().getX(), packet.getCurrentPosition().getY(), packet.getCurrentPosition().getZ(), packet.getAngle().toShort()); } }
public class Node<T> { T i; Node left; Node right; public Node(T i){ this.i = i; } public Node(){ i = null; } public void setLeft(Node n){ left =n; } public void setRight(Node n){ right = n; } public Node getRight(){ return right; } public Node getLeft(){ return left; } public boolean hasLeft(){ if(left!=null) return true; else return false; } public boolean hasRight(){ if(right!=null) return true; else return false; } public int getValue(){ return i; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dominio; import java.util.ArrayList; import java.util.Date; /** * * @author josdan */ public class Empleado { private int idEmpleado; private String apellido; private String nombre; private int legajo; private Date fechaIngreso; private int dni; private String cuil; private Date fechaNacimiento; private boolean esActivo; private int telefono; private String email; private String domicilio; private char sexo; private ArrayList<Puesto> puestos; public Empleado(int idEmpleado, String apellido, String nombre, int legajo, Date fechaIngreso, int dni, String cuil, Date fechaNacimiento, boolean esActivo, int telefono, String email, String domicilio, char sexo, ArrayList<Puesto> puestos) { this.idEmpleado = idEmpleado; this.apellido = apellido; this.nombre = nombre; this.legajo = legajo; this.fechaIngreso = fechaIngreso; this.dni = dni; this.cuil = cuil; this.fechaNacimiento = fechaNacimiento; this.esActivo = esActivo; this.telefono = telefono; this.email = email; this.domicilio = domicilio; this.sexo = sexo; this.puestos = puestos; } public int getIdEmpleado() { return idEmpleado; } public void setIdEmpleado(int idEmpleado) { this.idEmpleado = idEmpleado; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getLegajo() { return legajo; } public void setLegajo(int legajo) { this.legajo = legajo; } public Date getFechaIngreso() { return fechaIngreso; } public void setFechaIngreso(Date fechaIngreso) { this.fechaIngreso = fechaIngreso; } public int getDni() { return dni; } public void setDni(int dni) { this.dni = dni; } public String getCuil() { return cuil; } public void setCuil(String cuil) { this.cuil = cuil; } public Date getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Date fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public boolean isEsActivo() { return esActivo; } public void setEsActivo(boolean esActivo) { this.esActivo = esActivo; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDomicilio() { return domicilio; } public void setDomicilio(String domicilio) { this.domicilio = domicilio; } public char getSexo() { return sexo; } public void setSexo(char sexo) { this.sexo = sexo; } public ArrayList<Puesto> getPuestos() { return puestos; } public void setPuestos(ArrayList<Puesto> puestos) { this.puestos = puestos; } }
package com.javarush.task.task32.task3204; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /* Генератор паролей */ public class Solution { public static void main(String[] args) throws IOException { ByteArrayOutputStream password = getPassword(); System.out.println(password.toString()); } public static ByteArrayOutputStream getPassword() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String LOWER = "abcdefghijklmnopqrstuvwxyz"; String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String DIGITS = "0123456789"; String shuffle = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; ArrayList<String> list = new ArrayList(); list.add(LOWER); list.add(UPPER); list.add(DIGITS); list.add(shuffle); Random random = new Random(); for (int i=0;i<2;i++) { for (int j=0;j<list.size();j++){ String symbols = list.get(j); int pos = random.nextInt(symbols.length()); outputStream.write(symbols.charAt(pos)); } } return outputStream; } }
package model; import java.io.File; public class DownlaodFile { private int status; private String statuss=getStatus_str(); public int getStatus() { return status; } public String getStatuss() { return statuss; } public void setStatuss(String statuss) { this.statuss = statuss; } private String name; private String file_type; private String file_path; private long file_size = Long.MAX_VALUE ; private long last_downloaded_byte = 0; private File file; private String url; private double persent; public double getPersent() { return persent; } public void setPersent(double persent) { this.persent = persent; } private DownloadManager dm; public DownloadManager getDm() { return dm; } public void setDm(DownloadManager dm) { this.dm = dm; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } /** * get file of download * */ public File getFile() { return file; } /** * Set file to save downloading to it ! * */ public void setFile(File file) { this.file = file; } /**How much of file has downloaded till now .. * */ public double get_download_persent (){ return (double) (last_downloaded_byte/ (double) (file_size)); } public String getName() { return name; } public void setFile_type(String file_type) { this.file_type = file_type; } public void setFile_path(String file_path) { this.file_path = file_path; } public String getFile_type() { return file_type; } public String getFile_path() { return file_path; } public void setName(String name) { this.name = name; } public long getFile_size() { return file_size; } /* statuss download_ST = statuss.downloadin; enum statuss {downloadin , finished}*/ /** * set status of file*/ //should add switch case for adding in Arraylist public void setStatus(int status) { this.status = status; switch (status){ case 0:this.statuss="downloading"; break; case 1:this.statuss="pause"; break; case 2:this.statuss="finished"; break; case 3:this.statuss="failed"; break; } } /** * status of file*/ static final String[] stat = {"downloading" , "pause" , "finished" ,"failed"}; /** 0. downloading * 1. pause * 2. finished * 3.failed * */ public int getStatus_int() { return status; } public String getStatus_str (){ return stat[getStatus_int() % 4]; } /** * to get last byte downloaded*/ public long getLast_downloaded_byte() { return last_downloaded_byte; } /** * to set last byte downloaded*/ public void setLast_downloaded_byte(long last_downloaded_byte) { this.last_downloaded_byte = last_downloaded_byte; } /** * to set size of file*/ public void setFile_size(long file_size) { this.file_size = file_size; } // public String[] to_item() { // return new String[] {name , file_size + "" , getStatus_str() , get_download_persent(last_downloaded_byte , file_size) + ""}; // } }
package com.lera.vehicle.reservation.domain.customer; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CustomerTypeTest { @Test public void testGetName() { assertEquals("Client", CustomerType.CLIENT.toString()); assertEquals("Retail", CustomerType.RETAIL.toString()); } }
package com.redbus.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; public class NavBar { // ---------------Page Factory-------------------- @FindBy(how = How.XPATH, using = "//*[@class = \"redbus-logo home-redirect\"]") private WebElement redBusLogo; @FindBy(how = How.ID, using = "redBus") private WebElement busTickets; @FindBy(how = How.ID, using = "cars") private WebElement rPool; @FindBy(how = How.ID, using = "redBus Bus Hire") private WebElement busHire; public WebDriver driver; public NavBar(WebDriver driver) { PageFactory.initElements(driver, this); this.driver = driver; } // ----------------------------PAGE ACTIONS---------------------- // to click on reb dus logo public void click_RedBusLogo() { redBusLogo.click(); } // To click on bus ticket logo public void click_BusTicketsLink() { busTickets.click(); } // To click on bus hire public void click_BusHireLink() { busHire.click(); } // To click on rpool public void click_RPoolLink() { rPool.click(); } }